const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-Bosv7AtB.js","assets/useLeadSiteSearchSuggestions-BXV_m37-.js","assets/AgentReviewsSection-DqzOTuA1.js","assets/ListingCarouselModule-CfQ0Biyg.js","assets/imageOptimization-Csrlnz8M.js","assets/ExchangeListingsSection-DJgABwjK.js","assets/ScrollLivingHero-BZnYJClF.js","assets/LeadSiteLuxuryHome-DOY4B8Is.js","assets/LeadSiteExchangeListings-DNtbtfVh.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-T6TTkKPM.js","assets/LeadSiteSearch-Dfi2LYJE.js","assets/LeadSiteListingCardImage-BilJCpET.js","assets/LeadSiteMap-B-saTKPe.js","assets/LeadSiteLuxurySearch-Bk8iGsRS.js","assets/LeadSiteListingDetail-2uulafxI.js","assets/ListingVideoTour-Df9byhHh.js","assets/useListingVideos-aYVbWp1j.js","assets/LeadSiteLuxuryListingDetail-BNz8juzn.js","assets/LeadSiteCityPage-squvG6pq.js","assets/CityFaqSection-CZy6QlRu.js","assets/LeadSiteSubdivisionPage-BpHdDQUe.js","assets/LeadSiteFocusPage-gqvy6DJu.js","assets/OrgSiteAgents-bZ5w6CpS.js","assets/OrgSiteHome-Ccf6s0AW.js","assets/OrgSitePages-TVg7GYtY.js","assets/OrgSiteListings-CVdcBbF-.js","assets/PublicLiveEvent-DJhscxGT.js","assets/useLiveEngagement-COBVwXBW.js","assets/LiveEventConsole-7YeR8nqS.js","assets/StagingStudio-D6xMGAYy.js","assets/presets-DMYdD8gR.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-BDgT6cgf.js","assets/BuyCreditsDialog-3X2zypjQ.js","assets/StagingLibrary-BjTOHYBR.js","assets/StagingCredits-Bktu2FYl.js","assets/StagingSharePage-CkH9rQmx.js","assets/StagingStudioAdmin-DWgMwYu3.js","assets/PostcardManager-CQH9b6i0.js","assets/usePostcardZones-ByywVWli.js","assets/MailStudio-BMJn9T5G.js","assets/LeadSiteEditor-cnYQbjBP.js","assets/ImageUrlField-Go048UFN.js","assets/HomepageModuleManager-hiCO8_YO.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-Bb3IsY8Y.js","assets/AdminFreeWebsiteOfferStudio-C-VA8WiQ.js","assets/MLSListingDetail-CQF8gjQV.js","assets/EmailCampaigns-Bcj6W0GX.js","assets/sesRequest-BwLylBuV.js","assets/EmailCampaignComposer-RCkA33Os.js","assets/EditorModeSelector-Dijaqjhl.js","assets/SharedCampaignTemplates-EoINRdI5.js","assets/TemplateEditorDialog-BTZIDn1a.js","assets/AgentTemplates-Bg_KRAfe.js","assets/TheLocalMoveHome-CS2AYBJC.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BM_dzk3q.js"])))=>i.map(i=>d[i]); var gms=Object.defineProperty;var Zut=s=>{throw TypeError(s)};var yms=(s,t,n)=>t in s?gms(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var zr=(s,t,n)=>yms(s,typeof t!="symbol"?t+"":t,n),NFe=(s,t,n)=>t.has(s)||Zut("Cannot "+n);var ye=(s,t,n)=>(NFe(s,t,"read from private field"),n?n.call(s):t.get(s)),ps=(s,t,n)=>t.has(s)?Zut("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Ht=(s,t,n,r)=>(NFe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),ss=(s,t,n)=>(NFe(s,t,"access private method"),n);var Jy=(s,t,n,r)=>({set _(a){Ht(s,t,a,n)},get _(){return ye(s,t,r)}});function vms(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)}})();var Pp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function kd(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function bms(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 XEt={exports:{}},vMe={},QEt={exports:{}},Vd={};/** * @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 Nre=Symbol.for("react.element"),_ms=Symbol.for("react.portal"),wms=Symbol.for("react.fragment"),jms=Symbol.for("react.strict_mode"),Nms=Symbol.for("react.profiler"),kms=Symbol.for("react.provider"),Sms=Symbol.for("react.context"),Cms=Symbol.for("react.forward_ref"),Ams=Symbol.for("react.suspense"),Ems=Symbol.for("react.memo"),Tms=Symbol.for("react.lazy"),Xut=Symbol.iterator;function Mms(s){return s===null||typeof s!="object"?null:(s=Xut&&s[Xut]||s["@@iterator"],typeof s=="function"?s:null)}var JEt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},eTt=Object.assign,tTt={};function QG(s,t,n){this.props=s,this.context=t,this.refs=tTt,this.updater=n||JEt}QG.prototype.isReactComponent={};QG.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")};QG.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function sTt(){}sTt.prototype=QG.prototype;function cXe(s,t,n){this.props=s,this.context=t,this.refs=tTt,this.updater=n||JEt}var dXe=cXe.prototype=new sTt;dXe.constructor=cXe;eTt(dXe,QG.prototype);dXe.isPureReactComponent=!0;var Qut=Array.isArray,nTt=Object.prototype.hasOwnProperty,uXe={current:null},rTt={key:!0,ref:!0,__self:!0,__source:!0};function aTt(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)nTt.call(t,r)&&!rTt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,te=oe[J];if(0>>1;Ja(me,ae))hea(ge,me)?(oe[J]=ge,oe[he]=ae,J=he):(oe[J]=me,oe[ve]=ae,J=ve);else if(hea(ge,ae))oe[J]=ge,oe[he]=ae,J=he;else break e}}return re}function a(oe,re){var ae=oe.sortIndex-re.sortIndex;return ae!==0?ae:oe.id-re.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,p=!1,f=!1,g=!1,v=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(oe){for(var re=n(d);re!==null;){if(re.callback===null)r(d);else if(re.startTime<=oe)r(d),re.sortIndex=re.expirationTime,t(c,re);else break;re=n(d)}}function S(oe){if(g=!1,w(oe),!f)if(n(c)!==null)f=!0,K(C);else{var re=n(d);re!==null&&Z(S,re.startTime-oe)}}function C(oe,re){f=!1,g&&(g=!1,y(M),M=-1),p=!0;var ae=m;try{for(w(re),h=n(c);h!==null&&(!(h.expirationTime>re)||oe&&!F());){var J=h.callback;if(typeof J=="function"){h.callback=null,m=h.priorityLevel;var te=J(h.expirationTime<=re);re=s.unstable_now(),typeof te=="function"?h.callback=te:h===n(c)&&r(c),w(re)}else r(c);h=n(c)}if(h!==null)var ce=!0;else{var ve=n(d);ve!==null&&Z(S,ve.startTime-re),ce=!1}return ce}finally{h=null,m=ae,p=!1}}var E=!1,P=null,M=-1,I=5,D=-1;function F(){return!(s.unstable_now()-Doe||125J?(oe.sortIndex=ae,t(d,oe),n(c)===null&&oe===n(d)&&(g?(y(M),M=-1):g=!0,Z(S,ae-J))):(oe.sortIndex=te,t(c,oe),f||p||(f=!0,K(C))),oe},s.unstable_shouldYield=F,s.unstable_wrapCallback=function(oe){var re=m;return function(){var ae=m;m=re;try{return oe.apply(this,arguments)}finally{m=ae}}}})(dTt);cTt.exports=dTt;var xQ=cTt.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 Ums=_,Lj=xQ;function ri(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"),dUe=Object.prototype.hasOwnProperty,qms=/^[: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]*$/,eht={},tht={};function Vms(s){return dUe.call(tht,s)?!0:dUe.call(eht,s)?!1:qms.test(s)?tht[s]=!0:(eht[s]=!0,!1)}function Hms(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 Gms(s,t,n,r){if(t===null||typeof t>"u"||Hms(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 Ib(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 Av={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Av[s]=new Ib(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Av[t]=new Ib(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Av[s]=new Ib(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Av[s]=new Ib(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){Av[s]=new Ib(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Av[s]=new Ib(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Av[s]=new Ib(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Av[s]=new Ib(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Av[s]=new Ib(s,5,!1,s.toLowerCase(),null,!1,!1)});var pXe=/[\-:]([a-z])/g;function fXe(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(pXe,fXe);Av[t]=new Ib(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(pXe,fXe);Av[t]=new Ib(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(pXe,fXe);Av[t]=new Ib(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Av[s]=new Ib(s,1,!1,s.toLowerCase(),null,!1,!1)});Av.xlinkHref=new Ib("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Av[s]=new Ib(s,1,!1,s.toLowerCase(),null,!0,!0)});function xXe(s,t,n,r){var a=Av.hasOwnProperty(t)?Av[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{CFe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?mX(s):""}function Wms(s){switch(s.tag){case 5:return mX(s.type);case 16:return mX("Lazy");case 13:return mX("Suspense");case 19:return mX("SuspenseList");case 0:case 2:case 15:return s=AFe(s.type,!1),s;case 11:return s=AFe(s.type.render,!1),s;case 1:return s=AFe(s.type,!0),s;default:return""}}function pUe(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 H$:return"Fragment";case V$:return"Portal";case uUe:return"Profiler";case gXe:return"StrictMode";case hUe:return"Suspense";case mUe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case mTt:return(s.displayName||"Context")+".Consumer";case hTt:return(s._context.displayName||"Context")+".Provider";case yXe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case vXe:return t=s.displayName||null,t!==null?t:pUe(s.type)||"Memo";case d6:t=s._payload,s=s._init;try{return pUe(s(t))}catch{}}return null}function Kms(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 pUe(t);case 8:return t===gXe?"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 RP(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function fTt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Yms(s){var t=fTt(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 qoe(s){s._valueTracker||(s._valueTracker=Yms(s))}function xTt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=fTt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function N3e(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 fUe(s,t){var n=t.checked;return ex({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function nht(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=RP(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 gTt(s,t){t=t.checked,t!=null&&xXe(s,"checked",t,!1)}function xUe(s,t){gTt(s,t);var n=RP(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")?gUe(s,t.type,n):t.hasOwnProperty("defaultValue")&&gUe(s,t.type,RP(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function rht(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 gUe(s,t,n){(t!=="number"||N3e(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var pX=Array.isArray;function TU(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Voe.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function Oee(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var gQ={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},Zms=["Webkit","ms","Moz","O"];Object.keys(gQ).forEach(function(s){Zms.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),gQ[t]=gQ[s]})});function _Tt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||gQ.hasOwnProperty(s)&&gQ[s]?(""+t).trim():t+"px"}function wTt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=_Tt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var Xms=ex({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 bUe(s,t){if(t){if(Xms[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ri(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ri(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ri(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ri(62))}}function _Ue(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 wUe=null;function bXe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var jUe=null,MU=null,PU=null;function oht(s){if(s=Cre(s)){if(typeof jUe!="function")throw Error(ri(280));var t=s.stateNode;t&&(t=NMe(t),jUe(s.stateNode,s.type,t))}}function jTt(s){MU?PU?PU.push(s):PU=[s]:MU=s}function NTt(){if(MU){var s=MU,t=PU;if(PU=MU=null,oht(s),t)for(s=0;s>>=0,s===0?32:31-(lps(s)/cps|0)|0}var Hoe=64,Goe=4194304;function fX(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 A3e(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=fX(o):(i&=l,i!==0&&(r=fX(i)))}else l=n&~a,l!==0?r=fX(l):i!==0&&(r=fX(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 kre(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-hS(t),s[t]=n}function mps(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=vQ),xht=" ",ght=!1;function VTt(s,t){switch(s){case"keyup":return $ps.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function HTt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var G$=!1;function qps(s,t){switch(s){case"compositionend":return HTt(t);case"keypress":return t.which!==32?null:(ght=!0,xht);case"textInput":return s=t.data,s===xht&&ght?null:s;default:return null}}function Vps(s,t){if(G$)return s==="compositionend"||!AXe&&VTt(s,t)?(s=UTt(),Gue=kXe=SM=null,G$=!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=_ht(n)}}function YTt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?YTt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function ZTt(){for(var s=window,t=N3e();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=N3e(s.document)}return t}function EXe(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 Jps(s){var t=ZTt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&YTt(n.ownerDocument.documentElement,n)){if(r!==null&&EXe(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=wht(n,i);var l=wht(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,W$=null,EUe=null,_Q=null,TUe=!1;function jht(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;TUe||W$==null||W$!==N3e(r)||(r=W$,"selectionStart"in r&&EXe(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}),_Q&&Vee(_Q,r)||(_Q=r,r=M3e(EUe,"onSelect"),0Z$||(s.current=RUe[Z$],RUe[Z$]=null,Z$--)}function sp(s,t){Z$++,RUe[Z$]=s.current,s.current=t}var FP={},y1=hL(FP),L_=hL(!1),W7=FP;function bH(s,t){var n=s.type.contextTypes;if(!n)return FP;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 I_(s){return s=s.childContextTypes,s!=null}function L3e(){Lp(L_),Lp(y1)}function Tht(s,t,n){if(y1.current!==FP)throw Error(ri(168));sp(y1,t),sp(L_,n)}function a6t(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(ri(108,Kms(s)||"Unknown",a));return ex({},n,r)}function I3e(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||FP,W7=y1.current,sp(y1,s),sp(L_,L_.current),!0}function Mht(s,t,n){var r=s.stateNode;if(!r)throw Error(ri(169));n?(s=a6t(s,t,W7),r.__reactInternalMemoizedMergedChildContext=s,Lp(L_),Lp(y1),sp(y1,s)):Lp(L_),sp(L_,n)}var J3=null,kMe=!1,UFe=!1;function i6t(s){J3===null?J3=[s]:J3.push(s)}function ufs(s){kMe=!0,i6t(s)}function mL(){if(!UFe&&J3!==null){UFe=!0;var s=0,t=Zh;try{var n=J3;for(Zh=1;s>=l,a-=l,DA=1<<32-hS(t)+a|n<M?(I=P,P=null):I=P.sibling;var D=m(y,P,w[M],S);if(D===null){P===null&&(P=I);break}s&&P&&D.alternate===null&&t(y,P),b=i(D,b,M),E===null?C=D:E.sibling=D,E=D,P=I}if(M===w.length)return n(y,P),rf&&HI(y,M),C;if(P===null){for(;MM?(I=P,P=null):I=P.sibling;var F=m(y,P,D.value,S);if(F===null){P===null&&(P=I);break}s&&P&&F.alternate===null&&t(y,P),b=i(F,b,M),E===null?C=F:E.sibling=F,E=F,P=I}if(D.done)return n(y,P),rf&&HI(y,M),C;if(P===null){for(;!D.done;M++,D=w.next())D=h(y,D.value,S),D!==null&&(b=i(D,b,M),E===null?C=D:E.sibling=D,E=D);return rf&&HI(y,M),C}for(P=r(y,P);!D.done;M++,D=w.next())D=p(P,y,M,D.value,S),D!==null&&(s&&D.alternate!==null&&P.delete(D.key===null?M:D.key),b=i(D,b,M),E===null?C=D:E.sibling=D,E=D);return s&&P.forEach(function(q){return t(y,q)}),rf&&HI(y,M),C}function v(y,b,w,S){if(typeof w=="object"&&w!==null&&w.type===H$&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Uoe:e:{for(var C=w.key,E=b;E!==null;){if(E.key===C){if(C=w.type,C===H$){if(E.tag===7){n(y,E.sibling),b=a(E,w.props.children),b.return=y,y=b;break e}}else if(E.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===d6&&Iht(C)===E.type){n(y,E.sibling),b=a(E,w.props),b.ref=LY(y,E,w),b.return=y,y=b;break e}n(y,E);break}else t(y,E);E=E.sibling}w.type===H$?(b=XO(w.props.children,y.mode,S,w.key),b.return=y,y=b):(S=ehe(w.type,w.key,w.props,null,y.mode,S),S.ref=LY(y,b,w),S.return=y,y=S)}return l(y);case V$:e:{for(E=w.key;b!==null;){if(b.key===E)if(b.tag===4&&b.stateNode.containerInfo===w.containerInfo&&b.stateNode.implementation===w.implementation){n(y,b.sibling),b=a(b,w.children||[]),b.return=y,y=b;break e}else{n(y,b);break}else t(y,b);b=b.sibling}b=ZFe(w,y.mode,S),b.return=y,y=b}return l(y);case d6:return E=w._init,v(y,b,E(w._payload),S)}if(pX(w))return f(y,b,w,S);if(AY(w))return g(y,b,w,S);Joe(y,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,b!==null&&b.tag===6?(n(y,b.sibling),b=a(b,w),b.return=y,y=b):(n(y,b),b=YFe(w,y.mode,S),b.return=y,y=b),l(y)):n(y,b)}return v}var wH=d6t(!0),u6t=d6t(!1),F3e=hL(null),O3e=null,J$=null,LXe=null;function IXe(){LXe=J$=O3e=null}function DXe(s){var t=F3e.current;Lp(F3e),s._currentValue=t}function zUe(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 IU(s,t){O3e=s,LXe=J$=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(S_=!0),s.firstContext=null)}function TN(s){var t=s._currentValue;if(LXe!==s)if(s={context:s,memoizedValue:t,next:null},J$===null){if(O3e===null)throw Error(ri(308));J$=s,O3e.dependencies={lanes:0,firstContext:s}}else J$=J$.next=s;return t}var gF=null;function RXe(s){gF===null?gF=[s]:gF.push(s)}function h6t(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,RXe(t)):(n.next=a.next,a.next=n),t.interleaved=n,_E(s,r)}function _E(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 u6=!1;function FXe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function m6t(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 VA(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function WM(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Fu&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,_E(s,n)}return a=r.interleaved,a===null?(t.next=t,RXe(r)):(t.next=a.next,a.next=t),r.interleaved=t,_E(s,n)}function Kue(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,wXe(s,n)}}function Dht(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 z3e(s,t,n,r){var a=s.updateQueue;u6=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,p=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var f=s,g=o;switch(m=t,p=n,g.tag){case 1:if(f=g.payload,typeof f=="function"){h=f.call(p,h,m);break e}h=f;break e;case 3:f.flags=f.flags&-65537|128;case 0:if(f=g.payload,m=typeof f=="function"?f.call(p,h,m):f,m==null)break e;h=ex({},h,m);break e;case 2:u6=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,m=a.effects,m===null?a.effects=[o]:m.push(o))}else p={eventTime:p,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=p,c=h):u=u.next=p,l|=m;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;m=o,o=m.next,m.next=null,a.lastBaseUpdate=m,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);Z7|=l,s.lanes=l,s.memoizedState=h}}function Rht(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=VFe.transition;VFe.transition={};try{s(!1),t()}finally{Zh=n,VFe.transition=r}}function T6t(){return MN().memoizedState}function ffs(s,t,n){var r=YM(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},M6t(s))P6t(t,n);else if(n=h6t(s,t,n,r),n!==null){var a=_b();mS(n,s,r,a),L6t(n,t,r)}}function xfs(s,t,n){var r=YM(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(M6t(s))P6t(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,ES(o,l)){var c=t.interleaved;c===null?(a.next=a,RXe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=h6t(s,t,a,r),n!==null&&(a=_b(),mS(n,s,r,a),L6t(n,t,r))}}function M6t(s){var t=s.alternate;return s===qf||t!==null&&t===qf}function P6t(s,t){wQ=$3e=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function L6t(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,wXe(s,n)}}var U3e={readContext:TN,useCallback:Vv,useContext:Vv,useEffect:Vv,useImperativeHandle:Vv,useInsertionEffect:Vv,useLayoutEffect:Vv,useMemo:Vv,useReducer:Vv,useRef:Vv,useState:Vv,useDebugValue:Vv,useDeferredValue:Vv,useTransition:Vv,useMutableSource:Vv,useSyncExternalStore:Vv,useId:Vv,unstable_isNewReconciler:!1},gfs={readContext:TN,useCallback:function(s,t){return U5().memoizedState=[s,t===void 0?null:t],s},useContext:TN,useEffect:Oht,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,Zue(4194308,4,k6t.bind(null,t,s),n)},useLayoutEffect:function(s,t){return Zue(4194308,4,s,t)},useInsertionEffect:function(s,t){return Zue(4,2,s,t)},useMemo:function(s,t){var n=U5();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=U5();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=ffs.bind(null,qf,s),[r.memoizedState,s]},useRef:function(s){var t=U5();return s={current:s},t.memoizedState=s},useState:Fht,useDebugValue:HXe,useDeferredValue:function(s){return U5().memoizedState=s},useTransition:function(){var s=Fht(!1),t=s[0];return s=pfs.bind(null,s[1]),U5().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=qf,a=U5();if(rf){if(n===void 0)throw Error(ri(407));n=n()}else{if(n=t(),_0===null)throw Error(ri(349));Y7&30||g6t(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,Oht(v6t.bind(null,r,i,s),[s]),r.flags|=2048,Qee(9,y6t.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=U5(),t=_0.identifierPrefix;if(rf){var n=RA,r=DA;n=(r&~(1<<32-hS(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Zee++,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[k4]=t,s[Wee]=r,q6t(s,t,!1,!1),t.stateNode=s;e:{switch(l=_Ue(n,r),n){case"dialog":Np("cancel",s),Np("close",s),a=r;break;case"iframe":case"object":case"embed":Np("load",s),a=r;break;case"video":case"audio":for(a=0;akH&&(t.flags|=128,r=!0,IY(i,!1),t.lanes=4194304)}else{if(!r)if(s=B3e(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),IY(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!rf)return Hv(t),null}else 2*sg()-i.renderingStartTime>kH&&n!==1073741824&&(t.flags|=128,r=!0,IY(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=sg(),t.sibling=null,n=If.current,sp(If,r?n&1|2:n&1),t):(Hv(t),null);case 22:case 23:return XXe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ww&1073741824&&(Hv(t),t.subtreeFlags&6&&(t.flags|=8192)):Hv(t),null;case 24:return null;case 25:return null}throw Error(ri(156,t.tag))}function kfs(s,t){switch(MXe(t),t.tag){case 1:return I_(t.type)&&L3e(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return jH(),Lp(L_),Lp(y1),BXe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return zXe(t),null;case 13:if(Lp(If),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(ri(340));_H()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Lp(If),null;case 4:return jH(),null;case 10:return DXe(t.type._context),null;case 22:case 23:return XXe(),null;case 24:return null;default:return null}}var tle=!1,o1=!1,Sfs=typeof WeakSet=="function"?WeakSet:Set,go=null;function eU(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){_x(s,t,r)}else n.current=null}function KUe(s,t,n){try{n()}catch(r){_x(s,t,r)}}var Yht=!1;function Cfs(s,t){if(MUe=E3e,s=ZTt(),EXe(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,m=null;t:for(;;){for(var p;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(p=h.firstChild)!==null;)m=h,h=p;for(;;){if(h===s)break t;if(m===n&&++d===a&&(o=l),m===i&&++u===r&&(c=l),(p=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=p}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(PUe={focusedElem:s,selectionRange:n},E3e=!1,go=t;go!==null;)if(t=go,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,go=s;else for(;go!==null;){t=go;try{var f=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(f!==null){var g=f.memoizedProps,v=f.memoizedState,y=t.stateNode,b=y.getSnapshotBeforeUpdate(t.elementType===t.type?g:Lk(t.type,g),v);y.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ri(163))}}catch(S){_x(t,t.return,S)}if(s=t.sibling,s!==null){s.return=t.return,go=s;break}go=t.return}return f=Yht,Yht=!1,f}function jQ(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&&KUe(t,n,i)}a=a.next}while(a!==r)}}function AMe(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 YUe(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 G6t(s){var t=s.alternate;t!==null&&(s.alternate=null,G6t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[k4],delete t[Wee],delete t[DUe],delete t[cfs],delete t[dfs])),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 W6t(s){return s.tag===5||s.tag===3||s.tag===4}function Zht(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||W6t(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 ZUe(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=P3e));else if(r!==4&&(s=s.child,s!==null))for(ZUe(s,t,n),s=s.sibling;s!==null;)ZUe(s,t,n),s=s.sibling}function XUe(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(XUe(s,t,n),s=s.sibling;s!==null;)XUe(s,t,n),s=s.sibling}var rv=null,Zk=!1;function wT(s,t,n){for(n=n.child;n!==null;)K6t(s,t,n),n=n.sibling}function K6t(s,t,n){if(V4&&typeof V4.onCommitFiberUnmount=="function")try{V4.onCommitFiberUnmount(bMe,n)}catch{}switch(n.tag){case 5:o1||eU(n,t);case 6:var r=rv,a=Zk;rv=null,wT(s,t,n),rv=r,Zk=a,rv!==null&&(Zk?(s=rv,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):rv.removeChild(n.stateNode));break;case 18:rv!==null&&(Zk?(s=rv,n=n.stateNode,s.nodeType===8?$Fe(s.parentNode,n):s.nodeType===1&&$Fe(s,n),Uee(s)):$Fe(rv,n.stateNode));break;case 4:r=rv,a=Zk,rv=n.stateNode.containerInfo,Zk=!0,wT(s,t,n),rv=r,Zk=a;break;case 0:case 11:case 14:case 15:if(!o1&&(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)&&KUe(n,t,l),a=a.next}while(a!==r)}wT(s,t,n);break;case 1:if(!o1&&(eU(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){_x(n,t,o)}wT(s,t,n);break;case 21:wT(s,t,n);break;case 22:n.mode&1?(o1=(r=o1)||n.memoizedState!==null,wT(s,t,n),o1=r):wT(s,t,n);break;default:wT(s,t,n)}}function Xht(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new Sfs),t.forEach(function(r){var a=Rfs.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function vk(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=sg()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Efs(r/1960))-r,10s?16:s,CM===null)var r=!1;else{if(s=CM,CM=null,H3e=0,Fu&6)throw Error(ri(331));var a=Fu;for(Fu|=4,go=s.current;go!==null;){var i=go,l=i.child;if(go.flags&16){var o=i.deletions;if(o!==null){for(var c=0;csg()-YXe?ZO(s,0):KXe|=n),D_(s,t)}function sMt(s,t){t===0&&(s.mode&1?(t=Goe,Goe<<=1,!(Goe&130023424)&&(Goe=4194304)):t=1);var n=_b();s=_E(s,t),s!==null&&(kre(s,t,n),D_(s,n))}function Dfs(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),sMt(s,n)}function Rfs(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(ri(314))}r!==null&&r.delete(t),sMt(s,n)}var nMt;nMt=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||L_.current)S_=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return S_=!1,jfs(s,t,n);S_=!!(s.flags&131072)}else S_=!1,rf&&t.flags&1048576&&o6t(t,R3e,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Xue(s,t),s=t.pendingProps;var a=bH(t,y1.current);IU(t,n),a=UXe(null,t,r,s,a,n);var i=qXe();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,I_(r)?(i=!0,I3e(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,FXe(t),a.updater=CMe,t.stateNode=a,a._reactInternals=t,$Ue(t,r,s,n),t=VUe(null,t,r,!0,i,n)):(t.tag=0,rf&&i&&TXe(t),rb(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Xue(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Ofs(r),s=Lk(r,s),a){case 0:t=qUe(null,t,r,s,n);break e;case 1:t=Ght(null,t,r,s,n);break e;case 11:t=Vht(null,t,r,s,n);break e;case 14:t=Hht(null,t,r,Lk(r.type,s),n);break e}throw Error(ri(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Lk(r,a),qUe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Lk(r,a),Ght(s,t,r,a,n);case 3:e:{if(B6t(t),s===null)throw Error(ri(387));r=t.pendingProps,i=t.memoizedState,a=i.element,m6t(s,t),z3e(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=NH(Error(ri(423)),t),t=Wht(s,t,r,n,a);break e}else if(r!==a){a=NH(Error(ri(424)),t),t=Wht(s,t,r,n,a);break e}else for(rj=GM(t.stateNode.containerInfo.firstChild),hj=t,rf=!0,sS=null,n=u6t(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(_H(),r===a){t=wE(s,t,n);break e}rb(s,t,r,n)}t=t.child}return t;case 5:return p6t(t),s===null&&OUe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,LUe(r,a)?l=null:i!==null&&LUe(r,i)&&(t.flags|=32),z6t(s,t),rb(s,t,l,n),t.child;case 6:return s===null&&OUe(t),null;case 13:return $6t(s,t,n);case 4:return OXe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=wH(t,null,r,n):rb(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Lk(r,a),Vht(s,t,r,a,n);case 7:return rb(s,t,t.pendingProps,n),t.child;case 8:return rb(s,t,t.pendingProps.children,n),t.child;case 12:return rb(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,sp(F3e,r._currentValue),r._currentValue=l,i!==null)if(ES(i.value,l)){if(i.children===a.children&&!L_.current){t=wE(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=VA(-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),zUe(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(ri(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),zUe(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}rb(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,IU(t,n),a=TN(a),r=r(a),t.flags|=1,rb(s,t,r,n),t.child;case 14:return r=t.type,a=Lk(r,t.pendingProps),a=Lk(r.type,a),Hht(s,t,r,a,n);case 15:return F6t(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Lk(r,a),Xue(s,t),t.tag=1,I_(r)?(s=!0,I3e(t)):s=!1,IU(t,n),I6t(t,r,a),$Ue(t,r,a,n),VUe(null,t,r,!0,s,n);case 19:return U6t(s,t,n);case 22:return O6t(s,t,n)}throw Error(ri(156,t.tag))};function rMt(s,t){return MTt(s,t)}function Ffs(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 lN(s,t,n,r){return new Ffs(s,t,n,r)}function JXe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Ofs(s){if(typeof s=="function")return JXe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===yXe)return 11;if(s===vXe)return 14}return 2}function ZM(s,t){var n=s.alternate;return n===null?(n=lN(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 ehe(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")JXe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case H$:return XO(n.children,a,i,t);case gXe:l=8,a|=8;break;case uUe:return s=lN(12,n,t,a|2),s.elementType=uUe,s.lanes=i,s;case hUe:return s=lN(13,n,t,a),s.elementType=hUe,s.lanes=i,s;case mUe:return s=lN(19,n,t,a),s.elementType=mUe,s.lanes=i,s;case pTt:return TMe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case hTt:l=10;break e;case mTt:l=9;break e;case yXe:l=11;break e;case vXe:l=14;break e;case d6:l=16,r=null;break e}throw Error(ri(130,s==null?s:typeof s,""))}return t=lN(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function XO(s,t,n,r){return s=lN(7,s,r,t),s.lanes=n,s}function TMe(s,t,n,r){return s=lN(22,s,r,t),s.elementType=pTt,s.lanes=n,s.stateNode={isHidden:!1},s}function YFe(s,t,n){return s=lN(6,s,null,t),s.lanes=n,s}function ZFe(s,t,n){return t=lN(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function zfs(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=TFe(0),this.expirationTimes=TFe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=TFe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function eQe(s,t,n,r,a,i,l,o,c){return s=new zfs(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=lN(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},FXe(i),s}function Bfs(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(lMt)}catch(s){console.error(s)}}lMt(),lTt.exports=Vj;var pv=lTt.exports;const rQe=kd(pv);var cMt,amt=pv;cMt=amt.createRoot,amt.hydrateRoot;const Hfs="modulepreload",Gfs=function(s){return"/"+s},imt={},Fa=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=Gfs(c),c in imt)return;imt[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":Hfs,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((m,p)=>{h.addEventListener("load",m),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})},Wfs=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),Kfs=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function Yfs(s){return!!(s==="localhost"||s.endsWith(".localhost")||/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||s.endsWith(".lovable.app")||s.endsWith(".lovableproject.com")||s.endsWith(".lovable.dev")||s.endsWith(".vercel.app")||s==="relevelup.com"||s.endsWith(".relevelup.com")||s==="thelocalmove.com"||s.endsWith(".thelocalmove.com")||Wfs.has(s))}function dMt(s){return uMt(s)!==null}function uMt(s){const t=Kfs(s);return Yfs(t)?null:t}const Zfs=1,Xfs=1e6;let XFe=0;function Qfs(){return XFe=(XFe+1)%Number.MAX_SAFE_INTEGER,XFe.toString()}const QFe=new Map,omt=s=>{if(QFe.has(s))return;const t=setTimeout(()=>{QFe.delete(s),SQ({type:"REMOVE_TOAST",toastId:s})},Xfs);QFe.set(s,t)},Jfs=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,Zfs)};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?omt(n):s.toasts.forEach(r=>{omt(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)}}},the=[];let she={toasts:[]};function SQ(s){she=Jfs(she,s),the.forEach(t=>{t(she)})}function la({...s}){const t=Qfs(),n=a=>SQ({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>SQ({type:"DISMISS_TOAST",toastId:t});return SQ({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function _i(){const[s,t]=_.useState(she);return _.useEffect(()=>(the.push(t),()=>{const n=the.indexOf(t);n>-1&&the.splice(n,1)}),[s]),{...s,toast:la,dismiss:n=>SQ({type:"DISMISS_TOAST",toastId:n})}}function wa(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 lmt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function jE(...s){return t=>{let n=!1;const r=s.map(a=>{const i=lmt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=_.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=_.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 uf(s,t=[]){let n=[];function r(i,l){const o=_.createContext(l),c=n.length;n=[...n,l];const d=h=>{var y;const{scope:m,children:p,...f}=h,g=((y=m==null?void 0:m[s])==null?void 0:y[c])||o,v=_.useMemo(()=>f,Object.values(f));return e.jsx(g.Provider,{value:v,children:p})};d.displayName=i+"Provider";function u(h,m){var g;const p=((g=m==null?void 0:m[s])==null?void 0:g[c])||o,f=_.useContext(p);if(f)return f;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=>_.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return _.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,txs(a,...t)]}function txs(...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 _.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function OP(s){const t=sxs(s),n=_.forwardRef((r,a)=>{const{children:i,...l}=r,o=_.Children.toArray(i),c=o.find(nxs);if(c){const d=c.props.children,u=o.map(h=>h===c?_.Children.count(d)>1?_.Children.only(null):_.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:_.isValidElement(d)?_.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var aQe=OP("Slot");function sxs(s){const t=_.forwardRef((n,r)=>{const{children:a,...i}=n;if(_.isValidElement(a)){const l=axs(a),o=rxs(i,a.props);return a.type!==_.Fragment&&(o.ref=r?jE(r,l):l),_.cloneElement(a,o)}return _.Children.count(a)>1?_.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var hMt=Symbol("radix.slottable");function mMt(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=hMt,t}function nxs(s){return _.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===hMt}function rxs(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 axs(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 tW(s){const t=s+"CollectionProvider",[n,r]=uf(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=g=>{const{scope:v,children:y}=g,b=Ft.useRef(null),w=Ft.useRef(new Map).current;return e.jsx(a,{scope:v,itemMap:w,collectionRef:b,children:y})};l.displayName=t;const o=s+"CollectionSlot",c=OP(o),d=Ft.forwardRef((g,v)=>{const{scope:y,children:b}=g,w=i(o,y),S=el(v,w.collectionRef);return e.jsx(c,{ref:S,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=OP(u),p=Ft.forwardRef((g,v)=>{const{scope:y,children:b,...w}=g,S=Ft.useRef(null),C=el(v,S),E=i(u,y);return Ft.useEffect(()=>(E.itemMap.set(S,{ref:S,...w}),()=>void E.itemMap.delete(S))),e.jsx(m,{[h]:"",ref:C,children:b})});p.displayName=u;function f(g){const v=i(s+"CollectionConsumer",g);return Ft.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(v.itemMap.values()).sort((E,P)=>w.indexOf(E.ref.current)-w.indexOf(P.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:l,Slot:d,ItemSlot:p},f,r]}var ixs=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ci=ixs.reduce((s,t)=>{const n=OP(`Primitive.${t}`),r=_.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 iQe(s,t){s&&pv.flushSync(()=>s.dispatchEvent(t))}function Ax(s){const t=_.useRef(s);return _.useEffect(()=>{t.current=s}),_.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function oxs(s,t=globalThis==null?void 0:globalThis.document){const n=Ax(s);_.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 lxs="DismissableLayer",sqe="dismissableLayer.update",cxs="dismissableLayer.pointerDownOutside",dxs="dismissableLayer.focusOutside",cmt,pMt=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),pL=_.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=_.useContext(pMt),[u,h]=_.useState(null),m=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=_.useState({}),f=el(t,P=>h(P)),g=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),y=g.indexOf(v),b=u?g.indexOf(u):-1,w=d.layersWithOutsidePointerEventsDisabled.size>0,S=b>=y,C=hxs(P=>{const M=P.target,I=[...d.branches].some(D=>D.contains(M));!S||I||(a==null||a(P),l==null||l(P),P.defaultPrevented||o==null||o())},m),E=mxs(P=>{const M=P.target;[...d.branches].some(D=>D.contains(M))||(i==null||i(P),l==null||l(P),P.defaultPrevented||o==null||o())},m);return oxs(P=>{b===d.layers.size-1&&(r==null||r(P),!P.defaultPrevented&&o&&(P.preventDefault(),o()))},m),_.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(cmt=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),dmt(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=cmt)}},[u,m,n,d]),_.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),dmt())},[u,d]),_.useEffect(()=>{const P=()=>p({});return document.addEventListener(sqe,P),()=>document.removeEventListener(sqe,P)},[]),e.jsx(ci.div,{...c,ref:f,style:{pointerEvents:w?S?"auto":"none":void 0,...s.style},onFocusCapture:wa(s.onFocusCapture,E.onFocusCapture),onBlurCapture:wa(s.onBlurCapture,E.onBlurCapture),onPointerDownCapture:wa(s.onPointerDownCapture,C.onPointerDownCapture)})});pL.displayName=lxs;var uxs="DismissableLayerBranch",fMt=_.forwardRef((s,t)=>{const n=_.useContext(pMt),r=_.useRef(null),a=el(t,r);return _.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(ci.div,{...s,ref:a})});fMt.displayName=uxs;function hxs(s,t=globalThis==null?void 0:globalThis.document){const n=Ax(s),r=_.useRef(!1),a=_.useRef(()=>{});return _.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){xMt(cxs,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 mxs(s,t=globalThis==null?void 0:globalThis.document){const n=Ax(s),r=_.useRef(!1);return _.useEffect(()=>{const a=i=>{i.target&&!r.current&&xMt(dxs,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 dmt(){const s=new CustomEvent(sqe);document.dispatchEvent(s)}function xMt(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?iQe(a,i):a.dispatchEvent(i)}var pxs=pL,fxs=fMt,Rx=globalThis!=null&&globalThis.document?_.useLayoutEffect:()=>{},xxs="Portal",sW=_.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=_.useState(!1);Rx(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?rQe.createPortal(e.jsx(ci.div,{...r,ref:t}),l):null});sW.displayName=xxs;function gxs(s,t){return _.useReducer((n,r)=>t[n][r]??n,s)}var vg=s=>{const{present:t,children:n}=s,r=yxs(t),a=typeof n=="function"?n({present:r.isPresent}):_.Children.only(n),i=el(r.ref,vxs(a));return typeof n=="function"||r.isPresent?_.cloneElement(a,{ref:i}):null};vg.displayName="Presence";function yxs(s){const[t,n]=_.useState(),r=_.useRef(null),a=_.useRef(s),i=_.useRef("none"),l=s?"mounted":"unmounted",[o,c]=gxs(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const d=rle(r.current);i.current=o==="mounted"?d:"none"},[o]),Rx(()=>{const d=r.current,u=a.current;if(u!==s){const m=i.current,p=rle(d);s?c("MOUNT"):p==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&m!==p?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),Rx(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=p=>{const g=rle(r.current).includes(p.animationName);if(p.target===t&&g&&(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)})}},m=p=>{p.target===t&&(i.current=rle(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:_.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function rle(s){return(s==null?void 0:s.animationName)||"none"}function vxs(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 bxs=mXe[" useInsertionEffect ".trim().toString()]||Rx;function Gg({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=_xs({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=_.useRef(s!==void 0);_.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=_.useCallback(u=>{var h;if(o){const m=wxs(u)?u(s):u;m!==s&&((h=l.current)==null||h.call(l,m))}else i(u)},[o,s,i,l]);return[c,d]}function _xs({defaultProp:s,onChange:t}){const[n,r]=_.useState(s),a=_.useRef(n),i=_.useRef(t);return bxs(()=>{i.current=t},[t]),_.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function wxs(s){return typeof s=="function"}var gMt=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"}),jxs="VisuallyHidden",DMe=_.forwardRef((s,t)=>e.jsx(ci.span,{...s,ref:t,style:{...gMt,...s.style}}));DMe.displayName=jxs;var Nxs=DMe,oQe="ToastProvider",[lQe,kxs,Sxs]=tW("Toast"),[yMt,L_r]=uf("Toast",[Sxs]),[Cxs,RMe]=yMt(oQe),vMt=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=_.useState(null),[d,u]=_.useState(0),h=_.useRef(!1),m=_.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${oQe}\`. Expected non-empty \`string\`.`),e.jsx(lQe.Provider,{scope:t,children:e.jsx(Cxs,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:_.useCallback(()=>u(p=>p+1),[]),onToastRemove:_.useCallback(()=>u(p=>p-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:m,children:l})})};vMt.displayName=oQe;var bMt="ToastViewport",Axs=["F8"],nqe="toast.viewportPause",rqe="toast.viewportResume",_Mt=_.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=Axs,label:a="Notifications ({hotkey})",...i}=s,l=RMe(bMt,n),o=kxs(n),c=_.useRef(null),d=_.useRef(null),u=_.useRef(null),h=_.useRef(null),m=el(t,h,l.onViewportChange),p=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),f=l.toastCount>0;_.useEffect(()=>{const v=y=>{var w;r.length!==0&&r.every(S=>y[S]||y.code===S)&&((w=h.current)==null||w.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),_.useEffect(()=>{const v=c.current,y=h.current;if(f&&v&&y){const b=()=>{if(!l.isClosePausedRef.current){const E=new CustomEvent(nqe);y.dispatchEvent(E),l.isClosePausedRef.current=!0}},w=()=>{if(l.isClosePausedRef.current){const E=new CustomEvent(rqe);y.dispatchEvent(E),l.isClosePausedRef.current=!1}},S=E=>{!v.contains(E.relatedTarget)&&w()},C=()=>{v.contains(document.activeElement)||w()};return v.addEventListener("focusin",b),v.addEventListener("focusout",S),v.addEventListener("pointermove",b),v.addEventListener("pointerleave",C),window.addEventListener("blur",b),window.addEventListener("focus",w),()=>{v.removeEventListener("focusin",b),v.removeEventListener("focusout",S),v.removeEventListener("pointermove",b),v.removeEventListener("pointerleave",C),window.removeEventListener("blur",b),window.removeEventListener("focus",w)}}},[f,l.isClosePausedRef]);const g=_.useCallback(({tabbingDirection:v})=>{const b=o().map(w=>{const S=w.ref.current,C=[S,...$xs(S)];return v==="forwards"?C:C.reverse()});return(v==="forwards"?b.reverse():b).flat()},[o]);return _.useEffect(()=>{const v=h.current;if(v){const y=b=>{var C,E,P;const w=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!w){const M=document.activeElement,I=b.shiftKey;if(b.target===v&&I){(C=d.current)==null||C.focus();return}const q=g({tabbingDirection:I?"backwards":"forwards"}),G=q.findIndex(V=>V===M);JFe(q.slice(G+1))?b.preventDefault():I?(E=d.current)==null||E.focus():(P=u.current)==null||P.focus()}};return v.addEventListener("keydown",y),()=>v.removeEventListener("keydown",y)}},[o,g]),e.jsxs(fxs,{ref:c,role:"region","aria-label":a.replace("{hotkey}",p),tabIndex:-1,style:{pointerEvents:f?void 0:"none"},children:[f&&e.jsx(aqe,{ref:d,onFocusFromOutsideViewport:()=>{const v=g({tabbingDirection:"forwards"});JFe(v)}}),e.jsx(lQe.Slot,{scope:n,children:e.jsx(ci.ol,{tabIndex:-1,...i,ref:m})}),f&&e.jsx(aqe,{ref:u,onFocusFromOutsideViewport:()=>{const v=g({tabbingDirection:"backwards"});JFe(v)}})]})});_Mt.displayName=bMt;var wMt="ToastFocusProxy",aqe=_.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=RMe(wMt,n);return e.jsx(DMe,{"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()}})});aqe.displayName=wMt;var Ere="Toast",Exs="toast.swipeStart",Txs="toast.swipeMove",Mxs="toast.swipeCancel",Pxs="toast.swipeEnd",jMt=_.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Gg({prop:r,defaultProp:a??!0,onChange:i,caller:Ere});return e.jsx(vg,{present:n||o,children:e.jsx(Dxs,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:Ax(s.onPause),onResume:Ax(s.onResume),onSwipeStart:wa(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:wa(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:wa(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:wa(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)})})})});jMt.displayName=Ere;var[Lxs,Ixs]=yMt(Ere,{onClose(){}}),Dxs=_.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:m,onSwipeEnd:p,...f}=s,g=RMe(Ere,n),[v,y]=_.useState(null),b=el(t,V=>y(V)),w=_.useRef(null),S=_.useRef(null),C=a||g.duration,E=_.useRef(0),P=_.useRef(C),M=_.useRef(0),{onToastAdd:I,onToastRemove:D}=g,F=Ax(()=>{var H;(v==null?void 0:v.contains(document.activeElement))&&((H=g.viewport)==null||H.focus()),l()}),q=_.useCallback(V=>{!V||V===1/0||(window.clearTimeout(M.current),E.current=new Date().getTime(),M.current=window.setTimeout(F,V))},[F]);_.useEffect(()=>{const V=g.viewport;if(V){const H=()=>{q(P.current),d==null||d()},K=()=>{const Z=new Date().getTime()-E.current;P.current=P.current-Z,window.clearTimeout(M.current),c==null||c()};return V.addEventListener(nqe,K),V.addEventListener(rqe,H),()=>{V.removeEventListener(nqe,K),V.removeEventListener(rqe,H)}}},[g.viewport,C,c,d,q]),_.useEffect(()=>{i&&!g.isClosePausedRef.current&&q(C)},[i,C,g.isClosePausedRef,q]),_.useEffect(()=>(I(),()=>D()),[I,D]);const G=_.useMemo(()=>v?TMt(v):null,[v]);return g.viewport?e.jsxs(e.Fragment,{children:[G&&e.jsx(Rxs,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:G}),e.jsx(Lxs,{scope:n,onClose:F,children:pv.createPortal(e.jsx(lQe.ItemSlot,{scope:n,children:e.jsx(pxs,{asChild:!0,onEscapeKeyDown:wa(o,()=>{g.isFocusedToastEscapeKeyDownRef.current||F(),g.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(ci.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":g.swipeDirection,...f,ref:b,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:wa(s.onKeyDown,V=>{V.key==="Escape"&&(o==null||o(V.nativeEvent),V.nativeEvent.defaultPrevented||(g.isFocusedToastEscapeKeyDownRef.current=!0,F()))}),onPointerDown:wa(s.onPointerDown,V=>{V.button===0&&(w.current={x:V.clientX,y:V.clientY})}),onPointerMove:wa(s.onPointerMove,V=>{if(!w.current)return;const H=V.clientX-w.current.x,K=V.clientY-w.current.y,Z=!!S.current,oe=["left","right"].includes(g.swipeDirection),re=["left","up"].includes(g.swipeDirection)?Math.min:Math.max,ae=oe?re(0,H):0,J=oe?0:re(0,K),te=V.pointerType==="touch"?10:2,ce={x:ae,y:J},ve={originalEvent:V,delta:ce};Z?(S.current=ce,ale(Txs,h,ve,{discrete:!1})):umt(ce,g.swipeDirection,te)?(S.current=ce,ale(Exs,u,ve,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(H)>te||Math.abs(K)>te)&&(w.current=null)}),onPointerUp:wa(s.onPointerUp,V=>{const H=S.current,K=V.target;if(K.hasPointerCapture(V.pointerId)&&K.releasePointerCapture(V.pointerId),S.current=null,w.current=null,H){const Z=V.currentTarget,oe={originalEvent:V,delta:H};umt(H,g.swipeDirection,g.swipeThreshold)?ale(Pxs,p,oe,{discrete:!0}):ale(Mxs,m,oe,{discrete:!0}),Z.addEventListener("click",re=>re.preventDefault(),{once:!0})}})})})}),g.viewport)})]}):null}),Rxs=s=>{const{__scopeToast:t,children:n,...r}=s,a=RMe(Ere,t),[i,l]=_.useState(!1),[o,c]=_.useState(!1);return zxs(()=>l(!0)),_.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(sW,{asChild:!0,children:e.jsx(DMe,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},Fxs="ToastTitle",NMt=_.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(ci.div,{...r,ref:t})});NMt.displayName=Fxs;var Oxs="ToastDescription",kMt=_.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(ci.div,{...r,ref:t})});kMt.displayName=Oxs;var SMt="ToastAction",CMt=_.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(EMt,{altText:n,asChild:!0,children:e.jsx(cQe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${SMt}\`. Expected non-empty \`string\`.`),null)});CMt.displayName=SMt;var AMt="ToastClose",cQe=_.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=Ixs(AMt,n);return e.jsx(EMt,{asChild:!0,children:e.jsx(ci.button,{type:"button",...r,ref:t,onClick:wa(s.onClick,a.onClose)})})});cQe.displayName=AMt;var EMt=_.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(ci.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function TMt(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Bxs(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(...TMt(r))}}),t}function ale(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?iQe(a,i):a.dispatchEvent(i)}var umt=(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 zxs(s=()=>{}){const t=Ax(s);Rx(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Bxs(s){return s.nodeType===s.ELEMENT_NODE}function $xs(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 JFe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var Uxs=vMt,MMt=_Mt,PMt=jMt,LMt=NMt,IMt=kMt,DMt=CMt,RMt=cQe;function FMt(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,mmt=Sc,G9=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return mmt(s,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const u=n==null?void 0:n[d],h=i==null?void 0:i[d];if(u===null)return null;const m=hmt(u)||hmt(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...p}=u;return Object.entries(p).every(f=>{let[g,v]=f;return Array.isArray(v)?v.includes({...i,...o}[g]):{...i,...o}[g]===v})?[...d,h,m]:d},[]);return mmt(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 qxs=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),OMt=(...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 Vxs={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 zMt=_.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>_.createElement("svg",{ref:c,...Vxs,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:OMt("lucide",a),...o},[...l.map(([d,u])=>_.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 fe=(s,t)=>{const n=_.forwardRef(({className:r,...a},i)=>_.createElement(zMt,{ref:i,iconNode:t,className:OMt(`lucide-${qxs(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 nhe=fe("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 rhe=fe("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 ahe=fe("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 ihe=fe("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 pm=fe("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 ohe=fe("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 lhe=fe("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 WI=fe("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 KI=fe("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 che=fe("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 YI=fe("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 dhe=fe("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 uhe=fe("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 hhe=fe("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 mhe=fe("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 phe=fe("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 XM=fe("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 fhe=fe("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 xhe=fe("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 ghe=fe("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 yhe=fe("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 vhe=fe("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 bhe=fe("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 _he=fe("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 whe=fe("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 jhe=fe("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 Nhe=fe("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 khe=fe("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 QM=fe("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 JM=fe("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 She=fe("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 Che=fe("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 Ahe=fe("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 Ehe=fe("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 The=fe("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 Mhe=fe("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 Phe=fe("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 Lhe=fe("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 Ihe=fe("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 Dhe=fe("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 Rhe=fe("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 Fhe=fe("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 Ohe=fe("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 zhe=fe("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 Bhe=fe("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 $he=fe("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 Uhe=fe("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 qhe=fe("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 Vhe=fe("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 Hhe=fe("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 Ghe=fe("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 Whe=fe("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 Khe=fe("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 eP=fe("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 Yhe=fe("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 w0=fe("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 Zhe=fe("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 Xhe=fe("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 Qhe=fe("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 Jhe=fe("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 eme=fe("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 tme=fe("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 sme=fe("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 nme=fe("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 rme=fe("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 ame=fe("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 ime=fe("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 ZI=fe("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 ome=fe("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 lme=fe("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 cme=fe("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 CQ=fe("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 dme=fe("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 ume=fe("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 hme=fe("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 XI=fe("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 QI=fe("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 Vf=fe("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 mme=fe("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 AQ=fe("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 pme=fe("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 ka=fe("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 fme=fe("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 G4=fe("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 xme=fe("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 Da=fe("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 gme=fe("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 yme=fe("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 JI=fe("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 Og=fe("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 vme=fe("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 bme=fe("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 _me=fe("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 e8=fe("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 QO=fe("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 wme=fe("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 jme=fe("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 t8=fe("ArrowUpZA",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ap=fe("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 Nme=fe("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 kme=fe("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 Sme=fe("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 Cme=fe("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 Ame=fe("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 Eme=fe("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 Kh=fe("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 Tme=fe("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 s8=fe("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 Mme=fe("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 Pme=fe("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 Lme=fe("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 Ime=fe("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 eA=fe("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 Dme=fe("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 Rme=fe("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 Fme=fe("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 Ome=fe("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 zme=fe("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 Bme=fe("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 $me=fe("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 Ume=fe("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 qme=fe("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 Vme=fe("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 Hme=fe("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 Gme=fe("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 Wme=fe("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 Kme=fe("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 Yme=fe("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 JO=fe("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 Zme=fe("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 Xme=fe("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 Qme=fe("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 Jme=fe("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 epe=fe("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 Ey=fe("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 tpe=fe("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 spe=fe("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 npe=fe("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 rpe=fe("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 ape=fe("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 ipe=fe("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 EQ=fe("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 ope=fe("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 lpe=fe("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 W4=fe("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 cpe=fe("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 mj=fe("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 dpe=fe("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 upe=fe("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 hpe=fe("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 mpe=fe("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 ppe=fe("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 fpe=fe("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 pS=fe("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 xpe=fe("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 fS=fe("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 $g=fe("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 n8=fe("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 r8=fe("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 gpe=fe("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 ype=fe("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 vpe=fe("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 bpe=fe("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 _pe=fe("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 wpe=fe("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 jpe=fe("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 Npe=fe("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 kpe=fe("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 Spe=fe("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 Cpe=fe("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 Ape=fe("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 Epe=fe("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 Tpe=fe("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 Mpe=fe("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 Ppe=fe("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 HA=fe("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 Lpe=fe("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 Ipe=fe("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 Dpe=fe("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 Rpe=fe("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 Fpe=fe("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 Ope=fe("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 zpe=fe("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 a8=fe("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 Bpe=fe("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 $pe=fe("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 Upe=fe("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 qpe=fe("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 Vpe=fe("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 Hpe=fe("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 Gpe=fe("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 Wpe=fe("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 Kpe=fe("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 Ype=fe("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 ip=fe("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 Zpe=fe("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 Xpe=fe("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 Qpe=fe("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 Jpe=fe("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 efe=fe("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 tfe=fe("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 sfe=fe("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 nfe=fe("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 rfe=fe("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 afe=fe("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 tP=fe("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 ife=fe("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 Ty=fe("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 ofe=fe("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 lfe=fe("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 cfe=fe("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 K4=fe("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 TQ=fe("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 dfe=fe("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 h6=fe("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 ufe=fe("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 hfe=fe("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 mfe=fe("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 MQ=fe("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 pfe=fe("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 ffe=fe("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 xfe=fe("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 gfe=fe("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 Px=fe("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 yfe=fe("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 vfe=fe("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 bfe=fe("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 _fe=fe("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 wfe=fe("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 oi=fe("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 sP=fe("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 jfe=fe("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 Nfe=fe("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 kfe=fe("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 Sfe=fe("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 Cfe=fe("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 Hf=fe("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 pj=fe("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 Afe=fe("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 Efe=fe("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 Tfe=fe("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 Mfe=fe("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 _v=fe("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 Ud=fe("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 Pfe=fe("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 gc=fe("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 Lfe=fe("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 xS=fe("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 Ife=fe("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 Dfe=fe("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 RU=fe("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 Rfe=fe("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 v0=fe("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 Ffe=fe("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 Ofe=fe("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 zfe=fe("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 Bfe=fe("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 PQ=fe("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 ya=fe("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 $fe=fe("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 Lx=fe("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 Ufe=fe("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 qfe=fe("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 Vfe=fe("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 Hfe=fe("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 Gfe=fe("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 i8=fe("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 Wfe=fe("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 Kfe=fe("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 Yfe=fe("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 Zfe=fe("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 Xfe=fe("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 Qfe=fe("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 Jfe=fe("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 exe=fe("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 txe=fe("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 sxe=fe("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 nxe=fe("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 rxe=fe("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 axe=fe("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 o8=fe("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 l8=fe("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 ixe=fe("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 oxe=fe("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 lxe=fe("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 c8=fe("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 d8=fe("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 u8=fe("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 cxe=fe("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 h8=fe("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 dxe=fe("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 wl=fe("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 uxe=fe("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 m8=fe("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 hxe=fe("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 mxe=fe("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 p8=fe("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 f8=fe("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 pxe=fe("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 x8=fe("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 g8=fe("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 y8=fe("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 fxe=fe("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 e7=fe("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 Wr=fe("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 xxe=fe("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 gxe=fe("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 cl=fe("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 yxe=fe("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 vxe=fe("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 Wc=fe("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 yi=fe("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 h1=fe("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 bxe=fe("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 _xe=fe("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 wxe=fe("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 jxe=fe("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 Nxe=fe("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 kxe=fe("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 Sxe=fe("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 R_=fe("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 Cxe=fe("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 t7=fe("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 Axe=fe("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 Exe=fe("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 Txe=fe("Cigarette",[["path",{d:"M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14",key:"1mb5g1"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"1yl5r7"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ho=fe("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 v8=fe("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 b8=fe("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 _8=fe("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 w8=fe("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 j8=fe("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 N8=fe("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 k8=fe("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 S8=fe("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 Xl=fe("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 Mr=fe("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 C8=fe("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 A8=fe("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 E8=fe("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 T8=fe("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 Mxe=fe("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 M8=fe("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 Pxe=fe("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 Lxe=fe("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 Ixe=fe("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 Dxe=fe("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 Rxe=fe("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 Fxe=fe("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 Oxe=fe("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 P8=fe("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 v4=fe("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 L8=fe("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 zxe=fe("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 I8=fe("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 D8=fe("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 R8=fe("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 F8=fe("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 dm=fe("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 O8=fe("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 z8=fe("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 B8=fe("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 Bxe=fe("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 $8=fe("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 U8=fe("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 q8=fe("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 Bd=fe("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 Gf=fe("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 $xe=fe("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 Uxe=fe("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 FU=fe("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 fN=fe("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 qxe=fe("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 Wf=fe("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 Vxe=fe("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 Hxe=fe("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 V8=fe("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 H8=fe("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 Gxe=fe("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 Wxe=fe("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 Kxe=fe("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 Yxe=fe("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 Zxe=fe("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 Xxe=fe("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 Qxe=fe("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 Jxe=fe("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 ege=fe("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 OU=fe("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 tge=fe("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 sge=fe("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 nge=fe("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 rge=fe("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 age=fe("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 ige=fe("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 oge=fe("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 lge=fe("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 cge=fe("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 Zr=fe("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 dge=fe("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 uge=fe("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 G8=fe("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 hge=fe("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 mge=fe("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 pge=fe("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 fge=fe("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 xge=fe("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 gge=fe("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 yge=fe("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 vge=fe("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 bge=fe("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 _ge=fe("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 wge=fe("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 jge=fe("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 m6=fe("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 Nge=fe("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 kge=fe("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 FA=fe("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 Sge=fe("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 b4=fe("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 GA=fe("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 Cge=fe("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 Age=fe("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 Y4=fe("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 Ege=fe("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 LQ=fe("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 W8=fe("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 p6=fe("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 Tge=fe("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 Mge=fe("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 Pge=fe("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 s7=fe("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 Lge=fe("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 Ige=fe("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 Dge=fe("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 Rge=fe("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 Fge=fe("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 K8=fe("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 nP=fe("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 Oge=fe("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 zge=fe("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 Bge=fe("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 $ge=fe("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 Uge=fe("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 qge=fe("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 Vge=fe("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 Hge=fe("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 Gge=fe("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 Sa=fe("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 Wge=fe("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 Kge=fe("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 Yge=fe("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 IQ=fe("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 Zge=fe("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 Xge=fe("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 Qge=fe("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 Jge=fe("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 eye=fe("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 tye=fe("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 sye=fe("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 nye=fe("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 j0=fe("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 rye=fe("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 aye=fe("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 iye=fe("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 oye=fe("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 Kf=fe("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 lye=fe("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 cye=fe("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 dye=fe("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 uye=fe("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 hye=fe("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 mye=fe("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 pye=fe("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 zU=fe("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 fye=fe("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 xye=fe("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 gye=fe("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 yye=fe("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 Y8=fe("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 vye=fe("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 bye=fe("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 _ye=fe("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 wye=fe("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 jye=fe("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 Nye=fe("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 kye=fe("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 Sye=fe("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 Cye=fe("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 Aye=fe("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 Eye=fe("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 Tye=fe("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 Mye=fe("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 Pye=fe("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 Lye=fe("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 Iye=fe("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 Dye=fe("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 Rye=fe("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 Fye=fe("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 Nd=fe("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 Oye=fe("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 zye=fe("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 fj=fe("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 Bye=fe("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 Ga=fe("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 $ye=fe("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 Uye=fe("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 qye=fe("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 Vye=fe("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 Hye=fe("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 m1=fe("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 Gye=fe("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 Wye=fe("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 Kye=fe("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 Yye=fe("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 Zye=fe("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 Xye=fe("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 K2=fe("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 Qye=fe("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 Jye=fe("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 e0e=fe("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 BU=fe("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 ng=fe("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 lb=fe("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 t0e=fe("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 s0e=fe("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 n0e=fe("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 $U=fe("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 r0e=fe("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 a0e=fe("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 i0e=fe("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 mr=fe("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 o0e=fe("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 Yf=fe("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 xa=fe("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 of=fe("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 l0e=fe("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 c0e=fe("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 d0e=fe("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 u0e=fe("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 h0e=fe("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 m0e=fe("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 p0e=fe("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 f0e=fe("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 x0e=fe("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 g0e=fe("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 Z8=fe("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 y0e=fe("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 v0e=fe("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 b0e=fe("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 X8=fe("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 Q8=fe("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 J8=fe("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 eD=fe("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 n7=fe("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 DQ=fe("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 _0e=fe("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 w0e=fe("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 j0e=fe("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 tD=fe("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 N0e=fe("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 k0e=fe("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 xj=fe("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 S0e=fe("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 rP=fe("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 C0e=fe("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 A0e=fe("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 E0e=fe("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 T0e=fe("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 M0e=fe("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 P0e=fe("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 L0e=fe("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 I0e=fe("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 D0e=fe("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 R0e=fe("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 F0e=fe("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 cb=fe("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 sD=fe("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 UU=fe("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 O0e=fe("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 z0e=fe("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 B0e=fe("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 $0e=fe("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 RQ=fe("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 U0e=fe("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 xN=fe("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 FQ=fe("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 q0e=fe("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 V0e=fe("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 $r=fe("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 H0e=fe("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 G0e=fe("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 OQ=fe("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 W0e=fe("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 K0e=fe("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 zQ=fe("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 Y0e=fe("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 Z0e=fe("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 X0e=fe("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 Q0e=fe("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 J0e=fe("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 qU=fe("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 eve=fe("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 Yh=fe("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 tve=fe("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 F_=fe("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 sve=fe("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 nve=fe("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 rve=fe("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 ave=fe("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 ive=fe("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 ove=fe("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 lve=fe("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 cve=fe("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 WA=fe("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 dve=fe("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 vu=fe("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 uve=fe("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 hve=fe("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 mve=fe("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 Z4=fe("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 pve=fe("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 fve=fe("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 BQ=fe("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 xve=fe("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 gve=fe("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 cS=fe("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 yve=fe("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 vve=fe("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 bve=fe("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 _ve=fe("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 wve=fe("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 jve=fe("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 Nve=fe("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 kve=fe("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 Sve=fe("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 nD=fe("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 Cve=fe("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 Ave=fe("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 Eve=fe("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 Tve=fe("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 Mve=fe("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 Pve=fe("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 Lve=fe("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 Ive=fe("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 Dve=fe("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 Rve=fe("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 Fve=fe("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 wv=fe("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 Ove=fe("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 rD=fe("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 $Q=fe("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 zve=fe("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 Bve=fe("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 $ve=fe("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 Uve=fe("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 qve=fe("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 Vve=fe("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 Hve=fe("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 Gve=fe("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 VU=fe("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 Wve=fe("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 Kve=fe("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 Yve=fe("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 Zve=fe("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 Xve=fe("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 Qve=fe("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 Jve=fe("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 e1e=fe("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 t1e=fe("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 s1e=fe("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 n1e=fe("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 r1e=fe("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 a1e=fe("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 i1e=fe("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 o1e=fe("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 l1e=fe("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 c1e=fe("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 d1e=fe("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 u1e=fe("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 r7=fe("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 Ko=fe("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 h1e=fe("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 m1e=fe("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 aD=fe("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 p1e=fe("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 f1e=fe("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 x1e=fe("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 g1e=fe("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 y1e=fe("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 v1e=fe("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 b1e=fe("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 _1e=fe("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 w1e=fe("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 j1e=fe("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 N1e=fe("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 k1e=fe("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 S1e=fe("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 C1e=fe("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 A1e=fe("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 E1e=fe("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 T1e=fe("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 Wo=fe("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 M1e=fe("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 P1e=fe("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 fm=fe("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 L1e=fe("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 I1e=fe("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 iD=fe("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 D1e=fe("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 oD=fe("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 Vw=fe("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 R1e=fe("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 Zf=fe("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 F1e=fe("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 O1e=fe("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 z1e=fe("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 B1e=fe("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 UQ=fe("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 $1e=fe("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 qQ=fe("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 _4=fe("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 U1e=fe("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 q1e=fe("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 HU=fe("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 jv=fe("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 V1e=fe("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 H1e=fe("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 VQ=fe("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 G1e=fe("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 aP=fe("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 W1e=fe("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 K1e=fe("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 GU=fe("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 a7=fe("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 WU=fe("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 Y1e=fe("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 Z1e=fe("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 X1e=fe("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 Q1e=fe("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 J1e=fe("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 ebe=fe("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 tbe=fe("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 sbe=fe("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 HQ=fe("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 nbe=fe("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 rbe=fe("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 Fo=fe("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 abe=fe("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 ibe=fe("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 obe=fe("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 O_=fe("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 lbe=fe("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 cbe=fe("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 dbe=fe("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 ube=fe("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 GQ=fe("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 hbe=fe("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 mbe=fe("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 sa=fe("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 lD=fe("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 cD=fe("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 WQ=fe("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 pbe=fe("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 fbe=fe("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 xbe=fe("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 gbe=fe("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 N0=fe("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 ybe=fe("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 vbe=fe("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 nc=fe("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 bbe=fe("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 _be=fe("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 i7=fe("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 dD=fe("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 uD=fe("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 wbe=fe("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 KU=fe("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 gS=fe("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 jbe=fe("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 Fm=fe("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 KA=fe("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 Nbe=fe("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 kbe=fe("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 Sbe=fe("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 Cbe=fe("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 gj=fe("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 iP=fe("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 Abe=fe("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 wb=fe("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 Ebe=fe("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 Tbe=fe("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 Mbe=fe("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 Pbe=fe("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 Lbe=fe("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 Ibe=fe("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 Dbe=fe("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 Rbe=fe("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 Fbe=fe("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 Obe=fe("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 YU=fe("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 zbe=fe("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 Bbe=fe("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 hD=fe("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 $be=fe("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 Ube=fe("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 qbe=fe("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 Vbe=fe("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 Hbe=fe("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 Gbe=fe("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 X4=fe("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 oP=fe("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 op=fe("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 Wbe=fe("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 Kbe=fe("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 Ybe=fe("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 yj=fe("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 Zbe=fe("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 Xbe=fe("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 Qbe=fe("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 Jbe=fe("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 e_e=fe("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 vj=fe("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 ZU=fe("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 t_e=fe("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 s_e=fe("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 yS=fe("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 n_e=fe("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 Oc=fe("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 Kc=fe("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 fg=fe("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 r_e=fe("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 k0=fe("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 a_e=fe("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 i_e=fe("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 KQ=fe("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 o_e=fe("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 l_e=fe("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 bj=fe("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 YQ=fe("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 c_e=fe("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 d_e=fe("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 u_e=fe("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 h_e=fe("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 m_e=fe("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 p_e=fe("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 My=fe("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 bt=fe("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 f_e=fe("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 x_e=fe("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 g_e=fe("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 y_e=fe("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 XU=fe("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 mD=fe("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 ZQ=fe("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 pD=fe("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 Hl=fe("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 lP=fe("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 o7=fe("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 v_e=fe("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 b_e=fe("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 __e=fe("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 w_e=fe("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 l7=fe("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 j_e=fe("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 QU=fe("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 JU=fe("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 N_e=fe("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 k_e=fe("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 S_e=fe("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 cP=fe("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 on=fe("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 C_e=fe("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 A_e=fe("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 E_e=fe("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 T_e=fe("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 M_e=fe("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 P_e=fe("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 L_e=fe("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 I_e=fe("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 D_e=fe("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 R_e=fe("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 F_e=fe("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 O_e=fe("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 Ha=fe("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 XQ=fe("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 c7=fe("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 z_e=fe("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 QQ=fe("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 d7=fe("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 YA=fe("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 B_e=fe("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 Nh=fe("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 $_e=fe("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 U_e=fe("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 ZA=fe("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 u7=fe("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 q_e=fe("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 V_e=fe("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 eq=fe("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 H_e=fe("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 G_e=fe("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 W_e=fe("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 JQ=fe("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 K_e=fe("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 Y_e=fe("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 Z_e=fe("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 Bu=fe("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 X_e=fe("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 Q_e=fe("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 J_e=fe("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 ewe=fe("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 twe=fe("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 swe=fe("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 eJ=fe("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 nwe=fe("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 I4=fe("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 XA=fe("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 tJ=fe("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 rwe=fe("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 awe=fe("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 sJ=fe("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 iwe=fe("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 qi=fe("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 nJ=fe("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 owe=fe("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 fD=fe("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 h7=fe("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 lwe=fe("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 cwe=fe("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 dwe=fe("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 uwe=fe("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 hwe=fe("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 mwe=fe("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 pwe=fe("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 fwe=fe("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 gN=fe("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 xwe=fe("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 gwe=fe("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 ywe=fe("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 vwe=fe("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 bwe=fe("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 _we=fe("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 tq=fe("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 wwe=fe("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 jwe=fe("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 Nwe=fe("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 m7=fe("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 kwe=fe("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 yN=fe("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 Swe=fe("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 Cwe=fe("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 Awe=fe("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 Ewe=fe("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 Twe=fe("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 rJ=fe("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 Mwe=fe("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 Gh=fe("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 wy=fe("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 Pwe=fe("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 xD=fe("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 Lwe=fe("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 Iwe=fe("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 Dwe=fe("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 Rwe=fe("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 Fwe=fe("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 Owe=fe("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 zwe=fe("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 Bwe=fe("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 $we=fe("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 Uwe=fe("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 qwe=fe("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 Vwe=fe("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 aJ=fe("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 Hwe=fe("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 Gwe=fe("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 Wwe=fe("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 sq=fe("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 Kwe=fe("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 Ywe=fe("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 Zwe=fe("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 iJ=fe("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 Xwe=fe("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 vN=fe("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 Qwe=fe("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 Jwe=fe("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 eje=fe("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 tje=fe("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 sje=fe("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 nje=fe("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 rje=fe("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 aje=fe("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 ije=fe("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 nS=fe("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 oje=fe("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 gD=fe("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 yD=fe("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 lje=fe("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 cje=fe("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 dje=fe("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 uje=fe("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 hje=fe("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 mje=fe("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 pje=fe("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 fje=fe("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 xje=fe("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 gje=fe("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 yje=fe("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 vje=fe("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 Sh=fe("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 bje=fe("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 _je=fe("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 vD=fe("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 wje=fe("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 yc=fe("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 jje=fe("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 bD=fe("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 Nje=fe("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 kje=fe("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 _D=fe("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 wD=fe("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 jD=fe("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 ND=fe("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 Sje=fe("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 kD=fe("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 Cje=fe("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 Aje=fe("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 Eje=fe("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 SD=fe("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 Tje=fe("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 Mje=fe("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 Pje=fe("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 Lje=fe("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 tA=fe("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 dP=fe("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 Ije=fe("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 Dje=fe("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 Ix=fe("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 S0=fe("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 Rje=fe("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 Fje=fe("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 Mm=fe("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 Oje=fe("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 QA=fe("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 Y2=fe("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 nq=fe("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 zje=fe("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 Bje=fe("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 Wa=fe("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 $je=fe("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 z_=fe("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 Uje=fe("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 qje=fe("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 oJ=fe("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 Vje=fe("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 Hje=fe("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 Gje=fe("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 Wje=fe("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 Kje=fe("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 va=fe("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 Yje=fe("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 Zje=fe("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 Xje=fe("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 Qje=fe("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 Jje=fe("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 lJ=fe("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 e2e=fe("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 t2e=fe("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 s2e=fe("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 n2e=fe("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 r2e=fe("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 cJ=fe("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 JA=fe("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 a2e=fe("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 i2e=fe("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 o2e=fe("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 l2e=fe("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 dJ=fe("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 su=fe("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 c2e=fe("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 CD=fe("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 _j=fe("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 sn=fe("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 d2e=fe("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 u2e=fe("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 h2e=fe("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 m2e=fe("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 p2e=fe("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 f2e=fe("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 x2e=fe("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 g2e=fe("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 y2e=fe("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 uJ=fe("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 C0=fe("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 v2e=fe("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 eE=fe("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 b2e=fe("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 _2e=fe("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 w2e=fe("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 j2e=fe("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 lf=fe("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 wj=fe("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 N2e=fe("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 rq=fe("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 k2e=fe("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 S2e=fe("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 C2e=fe("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 A2e=fe("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 Nv=fe("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 E2e=fe("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 T2e=fe("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 M2e=fe("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 P2e=fe("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 L2e=fe("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 I2e=fe("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 D2e=fe("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 R2e=fe("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 F2e=fe("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 O2e=fe("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 z2e=fe("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 B2e=fe("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 $2e=fe("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 aq=fe("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 AD=fe("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 U2e=fe("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 q2e=fe("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 V2e=fe("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 H2e=fe("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 G2e=fe("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 tE=fe("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 W2e=fe("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 iq=fe("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 K2e=fe("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 Gi=fe("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 Y2e=fe("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 Z2e=fe("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 X2e=fe("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 Q2e=fe("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 hJ=fe("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 sE=fe("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 J2e=fe("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 eNe=fe("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 tNe=fe("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 oq=fe("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 sNe=fe("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 nNe=fe("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 Xf=fe("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 rNe=fe("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 aNe=fe("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 ED=fe("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 iNe=fe("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 Dx=fe("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 oNe=fe("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 p7=fe("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 lNe=fe("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 lq=fe("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 cNe=fe("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 TD=fe("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 MD=fe("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 dNe=fe("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 uNe=fe("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 Q4=fe("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 hNe=fe("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 mNe=fe("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 pNe=fe("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 fNe=fe("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 xNe=fe("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 gNe=fe("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 yNe=fe("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 vNe=fe("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 Bo=fe("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 PD=fe("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 bNe=fe("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 _Ne=fe("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 wNe=fe("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 jNe=fe("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 NNe=fe("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 kNe=fe("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 SNe=fe("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 CNe=fe("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 ANe=fe("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 ENe=fe("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 TNe=fe("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 MNe=fe("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 PNe=fe("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 LNe=fe("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 INe=fe("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 cq=fe("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 DNe=fe("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 RNe=fe("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 FNe=fe("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 ONe=fe("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 dq=fe("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 Rr=fe("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 zNe=fe("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 LD=fe("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 BNe=fe("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 Fr=fe("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 $Ne=fe("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 UNe=fe("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 qNe=fe("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 VNe=fe("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 HNe=fe("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 GNe=fe("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 vS=fe("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 Gc=fe("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 WNe=fe("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 sd=fe("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 mJ=fe("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 KNe=fe("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 YNe=fe("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 uq=fe("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 ZNe=fe("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 Ch=fe("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 XNe=fe("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 QNe=fe("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 JNe=fe("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 f7=fe("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 eke=fe("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 x7=fe("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 ID=fe("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 Om=fe("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 tke=fe("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 ske=fe("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 nke=fe("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 J4=fe("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 rke=fe("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 bS=fe("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 ake=fe("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 ike=fe("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 oke=fe("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 lke=fe("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 g7=fe("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 cke=fe("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 dke=fe("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 uke=fe("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 hke=fe("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 mke=fe("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 pke=fe("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 fke=fe("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 xke=fe("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 pJ=fe("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 gke=fe("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 yke=fe("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 fJ=fe("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 vke=fe("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 bke=fe("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 _ke=fe("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 wke=fe("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 uP=fe("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 DD=fe("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 jke=fe("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 Nke=fe("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 p1=fe("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 kke=fe("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 Ske=fe("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 Cke=fe("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 aj=fe("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 hq=fe("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 Ake=fe("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 Eke=fe("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 Tke=fe("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 hP=fe("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=fe("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 Mke=fe("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 Pke=fe("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 Lke=fe("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 Ike=fe("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 Dke=fe("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 Rke=fe("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 Fke=fe("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 mP=fe("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 RD=fe("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 FD=fe("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 OD=fe("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 zD=fe("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 BD=fe("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 $D=fe("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 UD=fe("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 qD=fe("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 VD=fe("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 HD=fe("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 GD=fe("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 WD=fe("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 KD=fe("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 YD=fe("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 ZD=fe("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 F5=fe("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 Zw=fe("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 XD=fe("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 QD=fe("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 JD=fe("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 eR=fe("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 tR=fe("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 sR=fe("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 Oke=fe("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 zke=fe("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 nR=fe("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 rR=fe("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 aR=fe("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 iR=fe("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 oR=fe("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 lR=fe("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 cR=fe("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 dR=fe("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 uR=fe("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 hR=fe("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 mR=fe("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 pR=fe("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 fR=fe("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 xR=fe("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 gR=fe("SquareParking",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cp=fe("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 yR=fe("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 vR=fe("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 bR=fe("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 _R=fe("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 wR=fe("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 jR=fe("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 Bke=fe("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 NR=fe("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 kR=fe("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 SR=fe("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 CR=fe("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 AR=fe("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 $ke=fe("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 Uke=fe("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 ER=fe("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 TR=fe("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 MR=fe("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 PR=fe("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 jb=fe("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 qke=fe("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 Vke=fe("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 Hke=fe("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 Gke=fe("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 Wke=fe("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 Ia=fe("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 Kke=fe("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 Yke=fe("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 Zke=fe("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 Xke=fe("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 y7=fe("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 mq=fe("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 Qke=fe("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 Jke=fe("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 xJ=fe("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 eSe=fe("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 tSe=fe("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 sSe=fe("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 nSe=fe("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 rSe=fe("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 bN=fe("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 aSe=fe("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 iSe=fe("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 oSe=fe("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 lSe=fe("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 cSe=fe("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 dSe=fe("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 uSe=fe("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 hSe=fe("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 mSe=fe("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 pq=fe("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 pSe=fe("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 fSe=fe("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 xSe=fe("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 gSe=fe("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 ySe=fe("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 vSe=fe("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 fq=fe("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 bSe=fe("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 xq=fe("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 _Se=fe("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 Ip=fe("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 gJ=fe("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 wSe=fe("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 jSe=fe("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 NSe=fe("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 kSe=fe("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 SSe=fe("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 CSe=fe("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 bu=fe("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 ASe=fe("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 ESe=fe("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 TSe=fe("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 MSe=fe("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 LR=fe("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 PSe=fe("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 LSe=fe("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 gq=fe("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 ISe=fe("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 DSe=fe("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 RSe=fe("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 IR=fe("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 FSe=fe("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 OSe=fe("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 zSe=fe("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 BSe=fe("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 $Se=fe("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 yJ=fe("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 Ug=fe("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 USe=fe("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 qSe=fe("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 VSe=fe("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 HSe=fe("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 GSe=fe("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 WSe=fe("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 v7=fe("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 KSe=fe("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 YSe=fe("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 ZSe=fe("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 XSe=fe("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 QSe=fe("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 JSe=fe("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 e5e=fe("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 t5e=fe("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 s5e=fe("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 n5e=fe("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 r5e=fe("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 a5e=fe("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 i5e=fe("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 o5e=fe("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 l5e=fe("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 c5e=fe("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 d5e=fe("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 u5e=fe("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 h5e=fe("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 DR=fe("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 Cn=fe("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 m5e=fe("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 p5e=fe("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 RR=fe("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 pP=fe("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 f5e=fe("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 x5e=fe("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 _S=fe("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 g5e=fe("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 kl=fe("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 nl=fe("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 y5e=fe("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 v5e=fe("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 jl=fe("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 vJ=fe("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 b5e=fe("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 _5e=fe("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 FR=fe("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 w5e=fe("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 j5e=fe("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 bJ=fe("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 N5e=fe("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 yq=fe("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 k5e=fe("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 S5e=fe("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 b7=fe("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 _J=fe("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 C5e=fe("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 nE=fe("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 A5e=fe("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 E5e=fe("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 T5e=fe("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 OR=fe("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 M5e=fe("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 rE=fe("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 _7=fe("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 Ra=fe("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 P5e=fe("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 jj=fe("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 wJ=fe("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 vq=fe("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 L5e=fe("UserPen",[["path",{d:"M11.5 15H7a4 4 0 0 0-4 4v2",key:"15lzij"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pl=fe("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 f6=fe("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 zR=fe("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 BR=fe("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 I5e=fe("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 $R=fe("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 bq=fe("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 UR=fe("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 x6=fe("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 D5e=fe("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 _q=fe("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 Oo=fe("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 vy=fe("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 On=fe("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 qR=fe("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 VR=fe("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 R5e=fe("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 wq=fe("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 F5e=fe("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 O5e=fe("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 z5e=fe("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 B5e=fe("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 $5e=fe("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 U5e=fe("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 Xr=fe("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 q5e=fe("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 V5e=fe("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 H5e=fe("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 G5e=fe("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 W5e=fe("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 jJ=fe("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 K5e=fe("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 NJ=fe("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 Y5e=fe("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 Z5e=fe("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 X5e=fe("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 HR=fe("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 w7=fe("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 Q5e=fe("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 rg=fe("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 J5e=fe("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 e4e=fe("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 t4e=fe("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 s4e=fe("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 n4e=fe("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 r4e=fe("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 a4e=fe("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 i4e=fe("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 o4e=fe("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 l4e=fe("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 c4e=fe("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 d4e=fe("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 u4e=fe("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 h4e=fe("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 m4e=fe("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 p4e=fe("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 f4e=fe("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 x4e=fe("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 g4e=fe("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 y4e=fe("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 v4e=fe("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 b4e=fe("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 j7=fe("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 _4e=fe("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 w4e=fe("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 eC=fe("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 er=fe("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 jq=fe("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 j4e=fe("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 cf=fe("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 fP=fe("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 Nq=fe("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 Hxs=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:nhe,AArrowUp:rhe,ALargeSmall:ahe,Accessibility:ihe,Activity:pm,AirVent:ohe,Airplay:lhe,AlarmClock:dhe,AlarmClockCheck:WI,AlarmClockMinus:KI,AlarmClockOff:che,AlarmClockPlus:YI,AlarmSmoke:uhe,Album:hhe,AlignCenter:XM,AlignCenterHorizontal:mhe,AlignCenterVertical:phe,AlignEndHorizontal:fhe,AlignEndVertical:xhe,AlignHorizontalDistributeCenter:ghe,AlignHorizontalDistributeEnd:yhe,AlignHorizontalDistributeStart:vhe,AlignHorizontalJustifyCenter:bhe,AlignHorizontalJustifyEnd:_he,AlignHorizontalJustifyStart:whe,AlignHorizontalSpaceAround:jhe,AlignHorizontalSpaceBetween:Nhe,AlignJustify:khe,AlignLeft:QM,AlignRight:JM,AlignStartHorizontal:She,AlignStartVertical:Che,AlignVerticalDistributeCenter:Ahe,AlignVerticalDistributeEnd:Ehe,AlignVerticalDistributeStart:The,AlignVerticalJustifyCenter:Mhe,AlignVerticalJustifyEnd:Phe,AlignVerticalJustifyStart:Lhe,AlignVerticalSpaceAround:Ihe,AlignVerticalSpaceBetween:Dhe,Ambulance:Rhe,Ampersand:Fhe,Ampersands:Ohe,Amphora:zhe,Anchor:Bhe,Angry:$he,Annoyed:Uhe,Antenna:qhe,Anvil:Vhe,Aperture:Hhe,AppWindow:Whe,AppWindowMac:Ghe,Apple:Khe,Archive:w0,ArchiveRestore:eP,ArchiveX:Yhe,Armchair:Zhe,ArrowBigDown:Qhe,ArrowBigDownDash:Xhe,ArrowBigLeft:eme,ArrowBigLeftDash:Jhe,ArrowBigRight:sme,ArrowBigRightDash:tme,ArrowBigUp:rme,ArrowBigUpDash:nme,ArrowDown:Vf,ArrowDown01:ame,ArrowDown10:ime,ArrowDownAZ:ZI,ArrowDownFromLine:ome,ArrowDownLeft:lme,ArrowDownNarrowWide:cme,ArrowDownRight:CQ,ArrowDownToDot:dme,ArrowDownToLine:ume,ArrowDownUp:hme,ArrowDownWideNarrow:XI,ArrowDownZA:QI,ArrowLeft:ka,ArrowLeftFromLine:mme,ArrowLeftRight:AQ,ArrowLeftToLine:pme,ArrowRight:Da,ArrowRightFromLine:fme,ArrowRightLeft:G4,ArrowRightToLine:xme,ArrowUp:ap,ArrowUp01:gme,ArrowUp10:yme,ArrowUpAZ:JI,ArrowUpDown:Og,ArrowUpFromDot:vme,ArrowUpFromLine:bme,ArrowUpLeft:_me,ArrowUpNarrowWide:e8,ArrowUpRight:QO,ArrowUpToLine:wme,ArrowUpWideNarrow:jme,ArrowUpZA:t8,ArrowsUpFromLine:Nme,Asterisk:kme,AtSign:Sme,Atom:Cme,AudioLines:Ame,AudioWaveform:Eme,Award:Kh,Axe:Tme,Axis3d:s8,Baby:Mme,Backpack:Pme,Badge:Kme,BadgeAlert:Lme,BadgeCent:Ime,BadgeCheck:eA,BadgeDollarSign:Dme,BadgeEuro:Rme,BadgeHelp:Fme,BadgeIndianRupee:Ome,BadgeInfo:zme,BadgeJapaneseYen:Bme,BadgeMinus:$me,BadgePercent:Ume,BadgePlus:qme,BadgePoundSterling:Vme,BadgeRussianRuble:Hme,BadgeSwissFranc:Gme,BadgeX:Wme,BaggageClaim:Yme,Ban:JO,Banana:Zme,Bandage:Xme,Banknote:Qme,Barcode:Jme,Baseline:epe,Bath:Ey,Battery:ipe,BatteryCharging:tpe,BatteryFull:spe,BatteryLow:npe,BatteryMedium:rpe,BatteryWarning:ape,Beaker:EQ,Bean:lpe,BeanOff:ope,Bed:mj,BedDouble:W4,BedSingle:cpe,Beef:dpe,Beer:hpe,BeerOff:upe,Bell:$g,BellDot:mpe,BellElectric:ppe,BellMinus:fpe,BellOff:pS,BellPlus:xpe,BellRing:fS,BetweenHorizontalEnd:n8,BetweenHorizontalStart:r8,BetweenVerticalEnd:gpe,BetweenVerticalStart:ype,BicepsFlexed:vpe,Bike:bpe,Binary:_pe,Binoculars:wpe,Biohazard:jpe,Bird:Npe,Bitcoin:kpe,Blend:Spe,Blinds:Cpe,Blocks:Ape,Bluetooth:Ppe,BluetoothConnected:Epe,BluetoothOff:Tpe,BluetoothSearching:Mpe,Bold:HA,Bolt:Lpe,Bomb:Ipe,Bone:Dpe,Book:nfe,BookA:Rpe,BookAudio:Fpe,BookCheck:Ope,BookCopy:zpe,BookDashed:a8,BookDown:Bpe,BookHeadphones:$pe,BookHeart:Upe,BookImage:qpe,BookKey:Vpe,BookLock:Hpe,BookMarked:Gpe,BookMinus:Wpe,BookOpen:ip,BookOpenCheck:Kpe,BookOpenText:Ype,BookPlus:Zpe,BookText:Xpe,BookType:Qpe,BookUp:efe,BookUp2:Jpe,BookUser:tfe,BookX:sfe,Bookmark:Ty,BookmarkCheck:rfe,BookmarkMinus:afe,BookmarkPlus:tP,BookmarkX:ife,BoomBox:ofe,Bot:K4,BotMessageSquare:lfe,BotOff:cfe,Box:TQ,Boxes:dfe,Braces:h6,Brackets:ufe,Brain:MQ,BrainCircuit:hfe,BrainCog:mfe,BrickWall:pfe,Briefcase:Px,BriefcaseBusiness:ffe,BriefcaseConveyorBelt:xfe,BriefcaseMedical:gfe,BringToFront:yfe,Brush:vfe,Bug:wfe,BugOff:bfe,BugPlay:_fe,Building:sP,Building2:oi,Bus:Nfe,BusFront:jfe,Cable:Sfe,CableCar:kfe,Cake:Hf,CakeSlice:Cfe,Calculator:pj,Calendar:ya,Calendar1:Afe,CalendarArrowDown:Efe,CalendarArrowUp:Tfe,CalendarCheck:_v,CalendarCheck2:Mfe,CalendarClock:Ud,CalendarCog:Pfe,CalendarDays:gc,CalendarFold:Lfe,CalendarHeart:xS,CalendarMinus:Dfe,CalendarMinus2:Ife,CalendarOff:RU,CalendarPlus:v0,CalendarPlus2:Rfe,CalendarRange:Ffe,CalendarSearch:Ofe,CalendarSync:zfe,CalendarX:PQ,CalendarX2:Bfe,Camera:Lx,CameraOff:$fe,Candy:Vfe,CandyCane:Ufe,CandyOff:qfe,Cannabis:Hfe,Captions:i8,CaptionsOff:Gfe,Car:Yfe,CarFront:Wfe,CarTaxiFront:Kfe,Caravan:Zfe,Carrot:Xfe,CaseLower:Qfe,CaseSensitive:Jfe,CaseUpper:exe,CassetteTape:txe,Cast:sxe,Castle:nxe,Cat:rxe,Cctv:axe,ChartArea:o8,ChartBar:c8,ChartBarBig:l8,ChartBarDecreasing:ixe,ChartBarIncreasing:oxe,ChartBarStacked:lxe,ChartCandlestick:d8,ChartColumn:wl,ChartColumnBig:u8,ChartColumnDecreasing:cxe,ChartColumnIncreasing:h8,ChartColumnStacked:dxe,ChartGantt:uxe,ChartLine:m8,ChartNetwork:hxe,ChartNoAxesColumn:f8,ChartNoAxesColumnDecreasing:mxe,ChartNoAxesColumnIncreasing:p8,ChartNoAxesCombined:pxe,ChartNoAxesGantt:x8,ChartPie:g8,ChartScatter:y8,ChartSpline:fxe,Check:Wr,CheckCheck:e7,ChefHat:xxe,Cherry:gxe,ChevronDown:cl,ChevronFirst:yxe,ChevronLast:vxe,ChevronLeft:Wc,ChevronRight:yi,ChevronUp:h1,ChevronsDown:_xe,ChevronsDownUp:bxe,ChevronsLeft:Nxe,ChevronsLeftRight:jxe,ChevronsLeftRightEllipsis:wxe,ChevronsRight:Sxe,ChevronsRightLeft:kxe,ChevronsUp:Cxe,ChevronsUpDown:R_,Chrome:t7,Church:Axe,Cigarette:Txe,CigaretteOff:Exe,Circle:Gf,CircleAlert:Ho,CircleArrowDown:v8,CircleArrowLeft:b8,CircleArrowOutDownLeft:_8,CircleArrowOutDownRight:w8,CircleArrowOutUpLeft:j8,CircleArrowOutUpRight:N8,CircleArrowRight:k8,CircleArrowUp:S8,CircleCheck:Mr,CircleCheckBig:Xl,CircleChevronDown:C8,CircleChevronLeft:A8,CircleChevronRight:E8,CircleChevronUp:T8,CircleDashed:Mxe,CircleDivide:M8,CircleDollarSign:Pxe,CircleDot:Ixe,CircleDotDashed:Lxe,CircleEllipsis:Dxe,CircleEqual:Rxe,CircleFadingArrowUp:Fxe,CircleFadingPlus:Oxe,CircleGauge:P8,CircleHelp:v4,CircleMinus:L8,CircleOff:zxe,CircleParking:D8,CircleParkingOff:I8,CirclePause:R8,CirclePercent:F8,CirclePlay:dm,CirclePlus:O8,CirclePower:z8,CircleSlash:Bxe,CircleSlash2:B8,CircleStop:$8,CircleUser:q8,CircleUserRound:U8,CircleX:Bd,CircuitBoard:$xe,Citrus:Uxe,Clapperboard:FU,Clipboard:Yxe,ClipboardCheck:fN,ClipboardCopy:qxe,ClipboardList:Wf,ClipboardMinus:Vxe,ClipboardPaste:Hxe,ClipboardPen:H8,ClipboardPenLine:V8,ClipboardPlus:Gxe,ClipboardType:Wxe,ClipboardX:Kxe,Clock:Zr,Clock1:Zxe,Clock10:Xxe,Clock11:Qxe,Clock12:Jxe,Clock2:ege,Clock3:OU,Clock4:tge,Clock5:sge,Clock6:nge,Clock7:rge,Clock8:age,Clock9:ige,ClockAlert:oge,ClockArrowDown:lge,ClockArrowUp:cge,Cloud:Nge,CloudAlert:dge,CloudCog:uge,CloudDownload:G8,CloudDrizzle:hge,CloudFog:mge,CloudHail:pge,CloudLightning:fge,CloudMoon:gge,CloudMoonRain:xge,CloudOff:yge,CloudRain:bge,CloudRainWind:vge,CloudSnow:_ge,CloudSun:jge,CloudSunRain:wge,CloudUpload:m6,Cloudy:kge,Clover:FA,Club:Sge,Code:GA,CodeXml:b4,Codepen:Cge,Codesandbox:Age,Coffee:Y4,Cog:Ege,Coins:LQ,Columns2:W8,Columns3:p6,Columns4:Tge,Combine:Mge,Command:Pge,Compass:s7,Component:Lge,Computer:Ige,ConciergeBell:Dge,Cone:Rge,Construction:Fge,Contact:nP,ContactRound:K8,Container:Oge,Contrast:zge,Cookie:Bge,CookingPot:$ge,Copy:Sa,CopyCheck:Uge,CopyMinus:qge,CopyPlus:Vge,CopySlash:Hge,CopyX:Gge,Copyleft:Wge,Copyright:Kge,CornerDownLeft:Yge,CornerDownRight:IQ,CornerLeftDown:Zge,CornerLeftUp:Xge,CornerRightDown:Qge,CornerRightUp:Jge,CornerUpLeft:eye,CornerUpRight:tye,Cpu:sye,CreativeCommons:nye,CreditCard:j0,Croissant:rye,Crop:aye,Cross:iye,Crosshair:oye,Crown:Kf,Cuboid:lye,CupSoda:cye,Currency:dye,Cylinder:uye,Dam:hye,Database:zU,DatabaseBackup:mye,DatabaseZap:pye,Delete:fye,Dessert:xye,Diameter:gye,Diamond:bye,DiamondMinus:yye,DiamondPercent:Y8,DiamondPlus:vye,Dice1:_ye,Dice2:wye,Dice3:jye,Dice4:Nye,Dice5:kye,Dice6:Sye,Dices:Cye,Diff:Aye,Disc:Pye,Disc2:Eye,Disc3:Tye,DiscAlbum:Mye,Divide:Lye,Dna:Dye,DnaOff:Iye,Dock:Rye,Dog:Fye,DollarSign:Nd,Donut:Oye,DoorClosed:zye,DoorOpen:fj,Dot:Bye,Download:Ga,DraftingCompass:$ye,Drama:Uye,Dribbble:qye,Drill:Vye,Droplet:Hye,Droplets:m1,Drum:Gye,Drumstick:Wye,Dumbbell:Kye,Ear:Zye,EarOff:Yye,Earth:K2,EarthLock:Xye,Eclipse:Qye,Egg:BU,EggFried:Jye,EggOff:e0e,Ellipsis:lb,EllipsisVertical:ng,Equal:n0e,EqualApproximately:t0e,EqualNot:s0e,Eraser:$U,EthernetPort:r0e,Euro:a0e,Expand:i0e,ExternalLink:mr,Eye:xa,EyeClosed:o0e,EyeOff:Yf,Facebook:of,Factory:l0e,Fan:c0e,FastForward:d0e,Feather:u0e,Fence:h0e,FerrisWheel:m0e,Figma:p0e,File:qU,FileArchive:f0e,FileAudio:g0e,FileAudio2:x0e,FileAxis3d:Z8,FileBadge:v0e,FileBadge2:y0e,FileBox:b0e,FileChartColumn:Q8,FileChartColumnIncreasing:X8,FileChartLine:J8,FileChartPie:eD,FileCheck:DQ,FileCheck2:n7,FileClock:_0e,FileCode:j0e,FileCode2:w0e,FileCog:tD,FileDiff:N0e,FileDigit:k0e,FileDown:xj,FileHeart:S0e,FileImage:rP,FileInput:C0e,FileJson:E0e,FileJson2:A0e,FileKey:M0e,FileKey2:T0e,FileLock:L0e,FileLock2:P0e,FileMinus:D0e,FileMinus2:I0e,FileMusic:R0e,FileOutput:F0e,FilePen:sD,FilePenLine:cb,FilePlus:O0e,FilePlus2:UU,FileQuestion:z0e,FileScan:B0e,FileSearch:RQ,FileSearch2:$0e,FileSliders:U0e,FileSpreadsheet:xN,FileStack:FQ,FileSymlink:q0e,FileTerminal:V0e,FileText:$r,FileType:G0e,FileType2:H0e,FileUp:OQ,FileUser:W0e,FileVideo:zQ,FileVideo2:K0e,FileVolume:Z0e,FileVolume2:Y0e,FileWarning:X0e,FileX:J0e,FileX2:Q0e,Files:eve,Film:Yh,Filter:F_,FilterX:tve,Fingerprint:sve,FireExtinguisher:nve,Fish:ive,FishOff:rve,FishSymbol:ave,Flag:WA,FlagOff:ove,FlagTriangleLeft:lve,FlagTriangleRight:cve,Flame:vu,FlameKindling:dve,Flashlight:hve,FlashlightOff:uve,FlaskConical:Z4,FlaskConicalOff:mve,FlaskRound:pve,FlipHorizontal:BQ,FlipHorizontal2:fve,FlipVertical:gve,FlipVertical2:xve,Flower:yve,Flower2:cS,Focus:vve,FoldHorizontal:bve,FoldVertical:_ve,Folder:VU,FolderArchive:wve,FolderCheck:jve,FolderClock:Nve,FolderClosed:kve,FolderCode:Sve,FolderCog:nD,FolderDot:Cve,FolderDown:Ave,FolderGit:Tve,FolderGit2:Eve,FolderHeart:Mve,FolderInput:Pve,FolderKanban:Lve,FolderKey:Ive,FolderLock:Dve,FolderMinus:Rve,FolderOpen:wv,FolderOpenDot:Fve,FolderOutput:Ove,FolderPen:rD,FolderPlus:$Q,FolderRoot:zve,FolderSearch:$ve,FolderSearch2:Bve,FolderSymlink:Uve,FolderSync:qve,FolderTree:Vve,FolderUp:Hve,FolderX:Gve,Folders:Wve,Footprints:Kve,Forklift:Yve,Forward:Zve,Frame:Xve,Framer:Qve,Frown:Jve,Fuel:e1e,Fullscreen:t1e,GalleryHorizontal:n1e,GalleryHorizontalEnd:s1e,GalleryThumbnails:r1e,GalleryVertical:i1e,GalleryVerticalEnd:a1e,Gamepad:l1e,Gamepad2:o1e,Gauge:c1e,Gavel:d1e,Gem:u1e,Ghost:r7,Gift:Ko,GitBranch:m1e,GitBranchPlus:h1e,GitCommitHorizontal:aD,GitCommitVertical:p1e,GitCompare:x1e,GitCompareArrows:f1e,GitFork:g1e,GitGraph:y1e,GitMerge:v1e,GitPullRequest:k1e,GitPullRequestArrow:b1e,GitPullRequestClosed:_1e,GitPullRequestCreate:j1e,GitPullRequestCreateArrow:w1e,GitPullRequestDraft:N1e,Github:S1e,Gitlab:C1e,GlassWater:A1e,Glasses:E1e,Globe:Wo,GlobeLock:T1e,Goal:M1e,Grab:P1e,GraduationCap:fm,Grape:L1e,Grid2x2:oD,Grid2x2Check:I1e,Grid2x2Plus:iD,Grid2x2X:D1e,Grid3x3:Vw,Grip:F1e,GripHorizontal:R1e,GripVertical:Zf,Group:O1e,Guitar:z1e,Ham:B1e,Hammer:UQ,Hand:HU,HandCoins:$1e,HandHeart:qQ,HandHelping:_4,HandMetal:U1e,HandPlatter:q1e,Handshake:jv,HardDrive:VQ,HardDriveDownload:V1e,HardDriveUpload:H1e,HardHat:G1e,Hash:aP,Haze:W1e,HdmiPort:K1e,Heading:Q1e,Heading1:GU,Heading2:a7,Heading3:WU,Heading4:Y1e,Heading5:Z1e,Heading6:X1e,HeadphoneOff:J1e,Headphones:ebe,Headset:tbe,Heart:Fo,HeartCrack:sbe,HeartHandshake:HQ,HeartOff:nbe,HeartPulse:rbe,Heater:abe,Hexagon:ibe,Highlighter:obe,History:O_,Hop:cbe,HopOff:lbe,Hospital:dbe,Hotel:ube,Hourglass:GQ,House:sa,HousePlug:hbe,HousePlus:mbe,IceCreamBowl:lD,IceCreamCone:cD,IdCard:WQ,Image:nc,ImageDown:pbe,ImageMinus:fbe,ImageOff:xbe,ImagePlay:gbe,ImagePlus:N0,ImageUp:ybe,ImageUpscale:vbe,Images:bbe,Import:_be,Inbox:i7,IndentDecrease:dD,IndentIncrease:uD,IndianRupee:wbe,Infinity:KU,Info:gS,InspectionPanel:jbe,Instagram:Fm,Italic:KA,IterationCcw:Nbe,IterationCw:kbe,JapaneseYen:Sbe,Joystick:Cbe,Kanban:gj,Key:wb,KeyRound:iP,KeySquare:Abe,Keyboard:Mbe,KeyboardMusic:Ebe,KeyboardOff:Tbe,Lamp:Fbe,LampCeiling:Pbe,LampDesk:Lbe,LampFloor:Ibe,LampWallDown:Dbe,LampWallUp:Rbe,LandPlot:Obe,Landmark:YU,Languages:zbe,Laptop:$be,LaptopMinimal:hD,LaptopMinimalCheck:Bbe,Lasso:qbe,LassoSelect:Ube,Laugh:Vbe,Layers:X4,Layers2:Hbe,Layers3:Gbe,LayoutDashboard:oP,LayoutGrid:op,LayoutList:Wbe,LayoutPanelLeft:Kbe,LayoutPanelTop:Ybe,LayoutTemplate:yj,Leaf:Zbe,LeafyGreen:Xbe,Lectern:Qbe,LetterText:Jbe,Library:vj,LibraryBig:e_e,LifeBuoy:ZU,Ligature:t_e,Lightbulb:yS,LightbulbOff:s_e,Link:Kc,Link2:Oc,Link2Off:n_e,Linkedin:fg,List:My,ListCheck:r_e,ListChecks:k0,ListCollapse:a_e,ListEnd:i_e,ListFilter:KQ,ListMinus:o_e,ListMusic:l_e,ListOrdered:bj,ListPlus:YQ,ListRestart:c_e,ListStart:d_e,ListTodo:u_e,ListTree:h_e,ListVideo:m_e,ListX:p_e,Loader:x_e,LoaderCircle:bt,LoaderPinwheel:f_e,Locate:XU,LocateFixed:g_e,LocateOff:y_e,Lock:Hl,LockKeyhole:ZQ,LockKeyholeOpen:mD,LockOpen:pD,LogIn:lP,LogOut:o7,Logs:v_e,Lollipop:b_e,Luggage:__e,Magnet:w_e,Mail:on,MailCheck:l7,MailMinus:j_e,MailOpen:QU,MailPlus:JU,MailQuestion:N_e,MailSearch:k_e,MailWarning:S_e,MailX:cP,Mailbox:C_e,Mails:A_e,Map:c7,MapPin:Ha,MapPinCheck:T_e,MapPinCheckInside:E_e,MapPinHouse:M_e,MapPinMinus:L_e,MapPinMinusInside:P_e,MapPinOff:I_e,MapPinPlus:R_e,MapPinPlusInside:D_e,MapPinX:O_e,MapPinXInside:F_e,MapPinned:XQ,Martini:z_e,Maximize:d7,Maximize2:QQ,Medal:YA,Megaphone:Nh,MegaphoneOff:B_e,Meh:$_e,MemoryStick:U_e,Menu:ZA,Merge:u7,MessageCircle:Bu,MessageCircleCode:q_e,MessageCircleDashed:V_e,MessageCircleHeart:eq,MessageCircleMore:H_e,MessageCircleOff:G_e,MessageCirclePlus:W_e,MessageCircleQuestion:JQ,MessageCircleReply:K_e,MessageCircleWarning:Y_e,MessageCircleX:Z_e,MessageSquare:qi,MessageSquareCode:X_e,MessageSquareDashed:Q_e,MessageSquareDiff:J_e,MessageSquareDot:ewe,MessageSquareHeart:twe,MessageSquareLock:swe,MessageSquareMore:eJ,MessageSquareOff:nwe,MessageSquarePlus:I4,MessageSquareQuote:XA,MessageSquareReply:tJ,MessageSquareShare:rwe,MessageSquareText:awe,MessageSquareWarning:sJ,MessageSquareX:iwe,MessagesSquare:nJ,Mic:h7,MicOff:owe,MicVocal:fD,Microchip:lwe,Microscope:cwe,Microwave:dwe,Milestone:uwe,Milk:mwe,MilkOff:hwe,Minimize:fwe,Minimize2:pwe,Minus:gN,Monitor:yN,MonitorCheck:xwe,MonitorCog:gwe,MonitorDot:ywe,MonitorDown:vwe,MonitorOff:bwe,MonitorPause:_we,MonitorPlay:tq,MonitorSmartphone:wwe,MonitorSpeaker:jwe,MonitorStop:Nwe,MonitorUp:m7,MonitorX:kwe,Moon:Cwe,MoonStar:Swe,Mountain:Ewe,MountainSnow:Awe,Mouse:Pwe,MouseOff:Twe,MousePointer:wy,MousePointer2:rJ,MousePointerBan:Mwe,MousePointerClick:Gh,Move:aJ,Move3d:xD,MoveDiagonal:Iwe,MoveDiagonal2:Lwe,MoveDown:Fwe,MoveDownLeft:Dwe,MoveDownRight:Rwe,MoveHorizontal:Owe,MoveLeft:zwe,MoveRight:Bwe,MoveUp:qwe,MoveUpLeft:$we,MoveUpRight:Uwe,MoveVertical:Vwe,Music:sq,Music2:Hwe,Music3:Gwe,Music4:Wwe,Navigation:iJ,Navigation2:Ywe,Navigation2Off:Kwe,NavigationOff:Zwe,Network:Xwe,Newspaper:vN,Nfc:Qwe,Notebook:sje,NotebookPen:Jwe,NotebookTabs:eje,NotebookText:tje,NotepadText:rje,NotepadTextDashed:nje,Nut:ije,NutOff:aje,Octagon:lje,OctagonAlert:nS,OctagonMinus:oje,OctagonPause:gD,OctagonX:yD,Omega:cje,Option:dje,Orbit:uje,Origami:hje,Package:Sh,Package2:mje,PackageCheck:pje,PackageMinus:fje,PackageOpen:xje,PackagePlus:gje,PackageSearch:yje,PackageX:vje,PaintBucket:bje,PaintRoller:_je,Paintbrush:wje,PaintbrushVertical:vD,Palette:yc,PanelBottom:kje,PanelBottomClose:jje,PanelBottomDashed:bD,PanelBottomOpen:Nje,PanelLeft:ND,PanelLeftClose:_D,PanelLeftDashed:wD,PanelLeftOpen:jD,PanelRight:Aje,PanelRightClose:Sje,PanelRightDashed:kD,PanelRightOpen:Cje,PanelTop:Mje,PanelTopClose:Eje,PanelTopDashed:SD,PanelTopOpen:Tje,PanelsLeftBottom:Pje,PanelsRightBottom:Lje,PanelsTopLeft:tA,Paperclip:dP,Parentheses:Ije,ParkingMeter:Dje,PartyPopper:Ix,Pause:S0,PawPrint:Rje,PcCase:Fje,Pen:Y2,PenLine:Mm,PenOff:Oje,PenTool:QA,Pencil:Wa,PencilLine:nq,PencilOff:zje,PencilRuler:Bje,Pentagon:$je,Percent:z_,PersonStanding:Uje,PhilippinePeso:qje,Phone:va,PhoneCall:oJ,PhoneForwarded:Vje,PhoneIncoming:Hje,PhoneMissed:Gje,PhoneOff:Wje,PhoneOutgoing:Kje,Pi:Yje,Piano:Zje,Pickaxe:Xje,PictureInPicture:Jje,PictureInPicture2:Qje,PiggyBank:lJ,Pilcrow:s2e,PilcrowLeft:e2e,PilcrowRight:t2e,Pill:r2e,PillBottle:n2e,Pin:JA,PinOff:cJ,Pipette:a2e,Pizza:i2e,Plane:dJ,PlaneLanding:o2e,PlaneTakeoff:l2e,Play:su,Plug:_j,Plug2:c2e,PlugZap:CD,Plus:sn,Pocket:u2e,PocketKnife:d2e,Podcast:h2e,Pointer:p2e,PointerOff:m2e,Popcorn:f2e,Popsicle:x2e,PoundSterling:g2e,Power:uJ,PowerOff:y2e,Presentation:C0,Printer:eE,PrinterCheck:v2e,Projector:b2e,Proportions:_2e,Puzzle:w2e,Pyramid:j2e,QrCode:lf,Quote:wj,Rabbit:N2e,Radar:rq,Radiation:k2e,Radical:S2e,Radio:Nv,RadioReceiver:C2e,RadioTower:A2e,Radius:E2e,RailSymbol:T2e,Rainbow:M2e,Rat:P2e,Ratio:L2e,Receipt:aq,ReceiptCent:I2e,ReceiptEuro:D2e,ReceiptIndianRupee:R2e,ReceiptJapaneseYen:F2e,ReceiptPoundSterling:O2e,ReceiptRussianRuble:z2e,ReceiptSwissFranc:B2e,ReceiptText:$2e,RectangleEllipsis:AD,RectangleHorizontal:U2e,RectangleVertical:q2e,Recycle:V2e,Redo:tE,Redo2:H2e,RedoDot:G2e,RefreshCcw:iq,RefreshCcwDot:W2e,RefreshCw:Gi,RefreshCwOff:K2e,Refrigerator:Y2e,Regex:Z2e,RemoveFormatting:X2e,Repeat:sE,Repeat1:Q2e,Repeat2:hJ,Replace:eNe,ReplaceAll:J2e,Reply:oq,ReplyAll:tNe,Rewind:sNe,Ribbon:nNe,Rocket:Xf,RockingChair:rNe,RollerCoaster:aNe,Rotate3d:ED,RotateCcw:Dx,RotateCcwSquare:iNe,RotateCw:p7,RotateCwSquare:oNe,Route:lq,RouteOff:lNe,Router:cNe,Rows2:TD,Rows3:MD,Rows4:dNe,Rss:uNe,Ruler:Q4,RussianRuble:hNe,Sailboat:mNe,Salad:pNe,Sandwich:fNe,Satellite:gNe,SatelliteDish:xNe,Save:Bo,SaveAll:yNe,SaveOff:vNe,Scale:bNe,Scale3d:PD,Scaling:_Ne,Scan:ENe,ScanBarcode:wNe,ScanEye:jNe,ScanFace:NNe,ScanLine:kNe,ScanQrCode:SNe,ScanSearch:CNe,ScanText:ANe,School:TNe,Scissors:PNe,ScissorsLineDashed:MNe,ScreenShare:INe,ScreenShareOff:LNe,Scroll:DNe,ScrollText:cq,Search:Rr,SearchCheck:RNe,SearchCode:FNe,SearchSlash:ONe,SearchX:dq,Section:zNe,Send:Fr,SendHorizontal:LD,SendToBack:BNe,SeparatorHorizontal:$Ne,SeparatorVertical:UNe,Server:GNe,ServerCog:qNe,ServerCrash:VNe,ServerOff:HNe,Settings:Gc,Settings2:vS,Shapes:WNe,Share:mJ,Share2:sd,Sheet:KNe,Shell:YNe,Shield:Om,ShieldAlert:uq,ShieldBan:ZNe,ShieldCheck:Ch,ShieldEllipsis:XNe,ShieldHalf:QNe,ShieldMinus:JNe,ShieldOff:f7,ShieldPlus:eke,ShieldQuestion:x7,ShieldX:ID,Ship:ske,ShipWheel:tke,Shirt:nke,ShoppingBag:J4,ShoppingBasket:rke,ShoppingCart:bS,Shovel:ake,ShowerHead:ike,Shrink:oke,Shrub:lke,Shuffle:g7,Sigma:cke,Signal:pke,SignalHigh:dke,SignalLow:uke,SignalMedium:hke,SignalZero:mke,Signature:fke,Signpost:pJ,SignpostBig:xke,Siren:gke,SkipBack:yke,SkipForward:fJ,Skull:vke,Slack:bke,Slash:_ke,Slice:wke,SlidersHorizontal:uP,SlidersVertical:DD,Smartphone:p1,SmartphoneCharging:jke,SmartphoneNfc:Nke,Smile:Ske,SmilePlus:kke,Snail:Cke,Snowflake:aj,Sofa:hq,Soup:Ake,Space:Eke,Spade:Tke,Sparkle:hP,Sparkles:un,Speaker:Mke,Speech:Pke,SpellCheck:Ike,SpellCheck2:Lke,Spline:Dke,Split:Rke,SprayCan:Fke,Sprout:mP,Square:jb,SquareActivity:RD,SquareArrowDown:zD,SquareArrowDownLeft:FD,SquareArrowDownRight:OD,SquareArrowLeft:BD,SquareArrowOutDownLeft:$D,SquareArrowOutDownRight:UD,SquareArrowOutUpLeft:qD,SquareArrowOutUpRight:VD,SquareArrowRight:HD,SquareArrowUp:KD,SquareArrowUpLeft:GD,SquareArrowUpRight:WD,SquareAsterisk:YD,SquareBottomDashedScissors:ZD,SquareChartGantt:F5,SquareCheck:XD,SquareCheckBig:Zw,SquareChevronDown:QD,SquareChevronLeft:JD,SquareChevronRight:eR,SquareChevronUp:tR,SquareCode:sR,SquareDashed:aR,SquareDashedBottom:zke,SquareDashedBottomCode:Oke,SquareDashedKanban:nR,SquareDashedMousePointer:rR,SquareDivide:iR,SquareDot:oR,SquareEqual:lR,SquareFunction:cR,SquareKanban:dR,SquareLibrary:uR,SquareM:hR,SquareMenu:mR,SquareMinus:pR,SquareMousePointer:fR,SquareParking:gR,SquareParkingOff:xR,SquarePen:Cp,SquarePercent:yR,SquarePi:vR,SquarePilcrow:bR,SquarePlay:_R,SquarePlus:wR,SquarePower:jR,SquareRadical:Bke,SquareScissors:NR,SquareSigma:kR,SquareSlash:SR,SquareSplitHorizontal:CR,SquareSplitVertical:AR,SquareSquare:$ke,SquareStack:Uke,SquareTerminal:ER,SquareUser:MR,SquareUserRound:TR,SquareX:PR,Squircle:qke,Squirrel:Vke,Stamp:Hke,Star:Ia,StarHalf:Gke,StarOff:Wke,StepBack:Kke,StepForward:Yke,Stethoscope:Zke,Sticker:Xke,StickyNote:y7,Store:mq,StretchHorizontal:Qke,StretchVertical:Jke,Strikethrough:xJ,Subscript:eSe,Sun:bN,SunDim:tSe,SunMedium:sSe,SunMoon:nSe,SunSnow:rSe,Sunrise:aSe,Sunset:iSe,Superscript:oSe,SwatchBook:lSe,SwissFranc:cSe,SwitchCamera:dSe,Sword:uSe,Swords:hSe,Syringe:mSe,Table:fq,Table2:pq,TableCellsMerge:pSe,TableCellsSplit:fSe,TableColumnsSplit:xSe,TableOfContents:gSe,TableProperties:ySe,TableRowsSplit:vSe,Tablet:xq,TabletSmartphone:bSe,Tablets:_Se,Tag:Ip,Tags:gJ,Tally1:wSe,Tally2:jSe,Tally3:NSe,Tally4:kSe,Tally5:SSe,Tangent:CSe,Target:bu,Telescope:ASe,Tent:TSe,TentTree:ESe,Terminal:MSe,TestTube:PSe,TestTubeDiagonal:LR,TestTubes:LSe,Text:FSe,TextCursor:ISe,TextCursorInput:gq,TextQuote:DSe,TextSearch:RSe,TextSelect:IR,Theater:OSe,Thermometer:$Se,ThermometerSnowflake:zSe,ThermometerSun:BSe,ThumbsDown:yJ,ThumbsUp:Ug,Ticket:v7,TicketCheck:USe,TicketMinus:qSe,TicketPercent:VSe,TicketPlus:HSe,TicketSlash:GSe,TicketX:WSe,Tickets:YSe,TicketsPlane:KSe,Timer:QSe,TimerOff:ZSe,TimerReset:XSe,ToggleLeft:JSe,ToggleRight:e5e,Toilet:t5e,Tornado:s5e,Torus:n5e,Touchpad:a5e,TouchpadOff:r5e,TowerControl:i5e,ToyBrick:o5e,Tractor:l5e,TrafficCone:c5e,TrainFront:u5e,TrainFrontTunnel:d5e,TrainTrack:h5e,TramFront:DR,Trash:m5e,Trash2:Cn,TreeDeciduous:p5e,TreePalm:RR,TreePine:pP,Trees:f5e,Trello:x5e,TrendingDown:_S,TrendingUp:kl,TrendingUpDown:g5e,Triangle:v5e,TriangleAlert:nl,TriangleRight:y5e,Trophy:jl,Truck:vJ,Turtle:b5e,Tv:w5e,TvMinimal:FR,TvMinimalPlay:_5e,Twitch:j5e,Twitter:bJ,Type:yq,TypeOutline:N5e,Umbrella:S5e,UmbrellaOff:k5e,Underline:b7,Undo:nE,Undo2:_J,UndoDot:C5e,UnfoldHorizontal:A5e,UnfoldVertical:E5e,Ungroup:T5e,University:OR,Unlink:rE,Unlink2:M5e,Unplug:_7,Upload:Ra,Usb:P5e,User:Oo,UserCheck:jj,UserCog:wJ,UserMinus:vq,UserPen:L5e,UserPlus:Pl,UserRound:x6,UserRoundCheck:f6,UserRoundCog:zR,UserRoundMinus:BR,UserRoundPen:I5e,UserRoundPlus:$R,UserRoundSearch:bq,UserRoundX:UR,UserSearch:D5e,UserX:_q,Users:On,UsersRound:vy,Utensils:VR,UtensilsCrossed:qR,UtilityPole:R5e,Variable:wq,Vault:F5e,Vegan:O5e,VenetianMask:z5e,Vibrate:$5e,VibrateOff:B5e,Video:Xr,VideoOff:U5e,Videotape:q5e,View:V5e,Voicemail:H5e,Volleyball:G5e,Volume:Y5e,Volume1:W5e,Volume2:jJ,VolumeOff:K5e,VolumeX:NJ,Vote:Z5e,Wallet:w7,WalletCards:X5e,WalletMinimal:HR,Wallpaper:Q5e,Wand:J5e,WandSparkles:rg,Warehouse:e4e,WashingMachine:t4e,Watch:s4e,Waves:n4e,Waypoints:r4e,Webcam:a4e,Webhook:o4e,WebhookOff:i4e,Weight:l4e,Wheat:d4e,WheatOff:c4e,WholeWord:u4e,Wifi:x4e,WifiHigh:h4e,WifiLow:m4e,WifiOff:p4e,WifiZero:f4e,Wind:y4e,WindArrowDown:g4e,Wine:b4e,WineOff:v4e,Workflow:j7,Worm:_4e,WrapText:w4e,Wrench:eC,X:er,Youtube:jq,Zap:cf,ZapOff:j4e,ZoomIn:fP,ZoomOut:Nq},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 FMe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:nhe,AArrowDownIcon:nhe,AArrowUp:rhe,AArrowUpIcon:rhe,ALargeSmall:ahe,ALargeSmallIcon:ahe,Accessibility:ihe,AccessibilityIcon:ihe,Activity:pm,ActivityIcon:pm,ActivitySquare:RD,ActivitySquareIcon:RD,AirVent:ohe,AirVentIcon:ohe,Airplay:lhe,AirplayIcon:lhe,AlarmCheck:WI,AlarmCheckIcon:WI,AlarmClock:dhe,AlarmClockCheck:WI,AlarmClockCheckIcon:WI,AlarmClockIcon:dhe,AlarmClockMinus:KI,AlarmClockMinusIcon:KI,AlarmClockOff:che,AlarmClockOffIcon:che,AlarmClockPlus:YI,AlarmClockPlusIcon:YI,AlarmMinus:KI,AlarmMinusIcon:KI,AlarmPlus:YI,AlarmPlusIcon:YI,AlarmSmoke:uhe,AlarmSmokeIcon:uhe,Album:hhe,AlbumIcon:hhe,AlertCircle:Ho,AlertCircleIcon:Ho,AlertOctagon:nS,AlertOctagonIcon:nS,AlertTriangle:nl,AlertTriangleIcon:nl,AlignCenter:XM,AlignCenterHorizontal:mhe,AlignCenterHorizontalIcon:mhe,AlignCenterIcon:XM,AlignCenterVertical:phe,AlignCenterVerticalIcon:phe,AlignEndHorizontal:fhe,AlignEndHorizontalIcon:fhe,AlignEndVertical:xhe,AlignEndVerticalIcon:xhe,AlignHorizontalDistributeCenter:ghe,AlignHorizontalDistributeCenterIcon:ghe,AlignHorizontalDistributeEnd:yhe,AlignHorizontalDistributeEndIcon:yhe,AlignHorizontalDistributeStart:vhe,AlignHorizontalDistributeStartIcon:vhe,AlignHorizontalJustifyCenter:bhe,AlignHorizontalJustifyCenterIcon:bhe,AlignHorizontalJustifyEnd:_he,AlignHorizontalJustifyEndIcon:_he,AlignHorizontalJustifyStart:whe,AlignHorizontalJustifyStartIcon:whe,AlignHorizontalSpaceAround:jhe,AlignHorizontalSpaceAroundIcon:jhe,AlignHorizontalSpaceBetween:Nhe,AlignHorizontalSpaceBetweenIcon:Nhe,AlignJustify:khe,AlignJustifyIcon:khe,AlignLeft:QM,AlignLeftIcon:QM,AlignRight:JM,AlignRightIcon:JM,AlignStartHorizontal:She,AlignStartHorizontalIcon:She,AlignStartVertical:Che,AlignStartVerticalIcon:Che,AlignVerticalDistributeCenter:Ahe,AlignVerticalDistributeCenterIcon:Ahe,AlignVerticalDistributeEnd:Ehe,AlignVerticalDistributeEndIcon:Ehe,AlignVerticalDistributeStart:The,AlignVerticalDistributeStartIcon:The,AlignVerticalJustifyCenter:Mhe,AlignVerticalJustifyCenterIcon:Mhe,AlignVerticalJustifyEnd:Phe,AlignVerticalJustifyEndIcon:Phe,AlignVerticalJustifyStart:Lhe,AlignVerticalJustifyStartIcon:Lhe,AlignVerticalSpaceAround:Ihe,AlignVerticalSpaceAroundIcon:Ihe,AlignVerticalSpaceBetween:Dhe,AlignVerticalSpaceBetweenIcon:Dhe,Ambulance:Rhe,AmbulanceIcon:Rhe,Ampersand:Fhe,AmpersandIcon:Fhe,Ampersands:Ohe,AmpersandsIcon:Ohe,Amphora:zhe,AmphoraIcon:zhe,Anchor:Bhe,AnchorIcon:Bhe,Angry:$he,AngryIcon:$he,Annoyed:Uhe,AnnoyedIcon:Uhe,Antenna:qhe,AntennaIcon:qhe,Anvil:Vhe,AnvilIcon:Vhe,Aperture:Hhe,ApertureIcon:Hhe,AppWindow:Whe,AppWindowIcon:Whe,AppWindowMac:Ghe,AppWindowMacIcon:Ghe,Apple:Khe,AppleIcon:Khe,Archive:w0,ArchiveIcon:w0,ArchiveRestore:eP,ArchiveRestoreIcon:eP,ArchiveX:Yhe,ArchiveXIcon:Yhe,AreaChart:o8,AreaChartIcon:o8,Armchair:Zhe,ArmchairIcon:Zhe,ArrowBigDown:Qhe,ArrowBigDownDash:Xhe,ArrowBigDownDashIcon:Xhe,ArrowBigDownIcon:Qhe,ArrowBigLeft:eme,ArrowBigLeftDash:Jhe,ArrowBigLeftDashIcon:Jhe,ArrowBigLeftIcon:eme,ArrowBigRight:sme,ArrowBigRightDash:tme,ArrowBigRightDashIcon:tme,ArrowBigRightIcon:sme,ArrowBigUp:rme,ArrowBigUpDash:nme,ArrowBigUpDashIcon:nme,ArrowBigUpIcon:rme,ArrowDown:Vf,ArrowDown01:ame,ArrowDown01Icon:ame,ArrowDown10:ime,ArrowDown10Icon:ime,ArrowDownAZ:ZI,ArrowDownAZIcon:ZI,ArrowDownAz:ZI,ArrowDownAzIcon:ZI,ArrowDownCircle:v8,ArrowDownCircleIcon:v8,ArrowDownFromLine:ome,ArrowDownFromLineIcon:ome,ArrowDownIcon:Vf,ArrowDownLeft:lme,ArrowDownLeftFromCircle:_8,ArrowDownLeftFromCircleIcon:_8,ArrowDownLeftFromSquare:$D,ArrowDownLeftFromSquareIcon:$D,ArrowDownLeftIcon:lme,ArrowDownLeftSquare:FD,ArrowDownLeftSquareIcon:FD,ArrowDownNarrowWide:cme,ArrowDownNarrowWideIcon:cme,ArrowDownRight:CQ,ArrowDownRightFromCircle:w8,ArrowDownRightFromCircleIcon:w8,ArrowDownRightFromSquare:UD,ArrowDownRightFromSquareIcon:UD,ArrowDownRightIcon:CQ,ArrowDownRightSquare:OD,ArrowDownRightSquareIcon:OD,ArrowDownSquare:zD,ArrowDownSquareIcon:zD,ArrowDownToDot:dme,ArrowDownToDotIcon:dme,ArrowDownToLine:ume,ArrowDownToLineIcon:ume,ArrowDownUp:hme,ArrowDownUpIcon:hme,ArrowDownWideNarrow:XI,ArrowDownWideNarrowIcon:XI,ArrowDownZA:QI,ArrowDownZAIcon:QI,ArrowDownZa:QI,ArrowDownZaIcon:QI,ArrowLeft:ka,ArrowLeftCircle:b8,ArrowLeftCircleIcon:b8,ArrowLeftFromLine:mme,ArrowLeftFromLineIcon:mme,ArrowLeftIcon:ka,ArrowLeftRight:AQ,ArrowLeftRightIcon:AQ,ArrowLeftSquare:BD,ArrowLeftSquareIcon:BD,ArrowLeftToLine:pme,ArrowLeftToLineIcon:pme,ArrowRight:Da,ArrowRightCircle:k8,ArrowRightCircleIcon:k8,ArrowRightFromLine:fme,ArrowRightFromLineIcon:fme,ArrowRightIcon:Da,ArrowRightLeft:G4,ArrowRightLeftIcon:G4,ArrowRightSquare:HD,ArrowRightSquareIcon:HD,ArrowRightToLine:xme,ArrowRightToLineIcon:xme,ArrowUp:ap,ArrowUp01:gme,ArrowUp01Icon:gme,ArrowUp10:yme,ArrowUp10Icon:yme,ArrowUpAZ:JI,ArrowUpAZIcon:JI,ArrowUpAz:JI,ArrowUpAzIcon:JI,ArrowUpCircle:S8,ArrowUpCircleIcon:S8,ArrowUpDown:Og,ArrowUpDownIcon:Og,ArrowUpFromDot:vme,ArrowUpFromDotIcon:vme,ArrowUpFromLine:bme,ArrowUpFromLineIcon:bme,ArrowUpIcon:ap,ArrowUpLeft:_me,ArrowUpLeftFromCircle:j8,ArrowUpLeftFromCircleIcon:j8,ArrowUpLeftFromSquare:qD,ArrowUpLeftFromSquareIcon:qD,ArrowUpLeftIcon:_me,ArrowUpLeftSquare:GD,ArrowUpLeftSquareIcon:GD,ArrowUpNarrowWide:e8,ArrowUpNarrowWideIcon:e8,ArrowUpRight:QO,ArrowUpRightFromCircle:N8,ArrowUpRightFromCircleIcon:N8,ArrowUpRightFromSquare:VD,ArrowUpRightFromSquareIcon:VD,ArrowUpRightIcon:QO,ArrowUpRightSquare:WD,ArrowUpRightSquareIcon:WD,ArrowUpSquare:KD,ArrowUpSquareIcon:KD,ArrowUpToLine:wme,ArrowUpToLineIcon:wme,ArrowUpWideNarrow:jme,ArrowUpWideNarrowIcon:jme,ArrowUpZA:t8,ArrowUpZAIcon:t8,ArrowUpZa:t8,ArrowUpZaIcon:t8,ArrowsUpFromLine:Nme,ArrowsUpFromLineIcon:Nme,Asterisk:kme,AsteriskIcon:kme,AsteriskSquare:YD,AsteriskSquareIcon:YD,AtSign:Sme,AtSignIcon:Sme,Atom:Cme,AtomIcon:Cme,AudioLines:Ame,AudioLinesIcon:Ame,AudioWaveform:Eme,AudioWaveformIcon:Eme,Award:Kh,AwardIcon:Kh,Axe:Tme,AxeIcon:Tme,Axis3D:s8,Axis3DIcon:s8,Axis3d:s8,Axis3dIcon:s8,Baby:Mme,BabyIcon:Mme,Backpack:Pme,BackpackIcon:Pme,Badge:Kme,BadgeAlert:Lme,BadgeAlertIcon:Lme,BadgeCent:Ime,BadgeCentIcon:Ime,BadgeCheck:eA,BadgeCheckIcon:eA,BadgeDollarSign:Dme,BadgeDollarSignIcon:Dme,BadgeEuro:Rme,BadgeEuroIcon:Rme,BadgeHelp:Fme,BadgeHelpIcon:Fme,BadgeIcon:Kme,BadgeIndianRupee:Ome,BadgeIndianRupeeIcon:Ome,BadgeInfo:zme,BadgeInfoIcon:zme,BadgeJapaneseYen:Bme,BadgeJapaneseYenIcon:Bme,BadgeMinus:$me,BadgeMinusIcon:$me,BadgePercent:Ume,BadgePercentIcon:Ume,BadgePlus:qme,BadgePlusIcon:qme,BadgePoundSterling:Vme,BadgePoundSterlingIcon:Vme,BadgeRussianRuble:Hme,BadgeRussianRubleIcon:Hme,BadgeSwissFranc:Gme,BadgeSwissFrancIcon:Gme,BadgeX:Wme,BadgeXIcon:Wme,BaggageClaim:Yme,BaggageClaimIcon:Yme,Ban:JO,BanIcon:JO,Banana:Zme,BananaIcon:Zme,Bandage:Xme,BandageIcon:Xme,Banknote:Qme,BanknoteIcon:Qme,BarChart:p8,BarChart2:f8,BarChart2Icon:f8,BarChart3:wl,BarChart3Icon:wl,BarChart4:h8,BarChart4Icon:h8,BarChartBig:u8,BarChartBigIcon:u8,BarChartHorizontal:c8,BarChartHorizontalBig:l8,BarChartHorizontalBigIcon:l8,BarChartHorizontalIcon:c8,BarChartIcon:p8,Barcode:Jme,BarcodeIcon:Jme,Baseline:epe,BaselineIcon:epe,Bath:Ey,BathIcon:Ey,Battery:ipe,BatteryCharging:tpe,BatteryChargingIcon:tpe,BatteryFull:spe,BatteryFullIcon:spe,BatteryIcon:ipe,BatteryLow:npe,BatteryLowIcon:npe,BatteryMedium:rpe,BatteryMediumIcon:rpe,BatteryWarning:ape,BatteryWarningIcon:ape,Beaker:EQ,BeakerIcon:EQ,Bean:lpe,BeanIcon:lpe,BeanOff:ope,BeanOffIcon:ope,Bed:mj,BedDouble:W4,BedDoubleIcon:W4,BedIcon:mj,BedSingle:cpe,BedSingleIcon:cpe,Beef:dpe,BeefIcon:dpe,Beer:hpe,BeerIcon:hpe,BeerOff:upe,BeerOffIcon:upe,Bell:$g,BellDot:mpe,BellDotIcon:mpe,BellElectric:ppe,BellElectricIcon:ppe,BellIcon:$g,BellMinus:fpe,BellMinusIcon:fpe,BellOff:pS,BellOffIcon:pS,BellPlus:xpe,BellPlusIcon:xpe,BellRing:fS,BellRingIcon:fS,BetweenHorizonalEnd:n8,BetweenHorizonalEndIcon:n8,BetweenHorizonalStart:r8,BetweenHorizonalStartIcon:r8,BetweenHorizontalEnd:n8,BetweenHorizontalEndIcon:n8,BetweenHorizontalStart:r8,BetweenHorizontalStartIcon:r8,BetweenVerticalEnd:gpe,BetweenVerticalEndIcon:gpe,BetweenVerticalStart:ype,BetweenVerticalStartIcon:ype,BicepsFlexed:vpe,BicepsFlexedIcon:vpe,Bike:bpe,BikeIcon:bpe,Binary:_pe,BinaryIcon:_pe,Binoculars:wpe,BinocularsIcon:wpe,Biohazard:jpe,BiohazardIcon:jpe,Bird:Npe,BirdIcon:Npe,Bitcoin:kpe,BitcoinIcon:kpe,Blend:Spe,BlendIcon:Spe,Blinds:Cpe,BlindsIcon:Cpe,Blocks:Ape,BlocksIcon:Ape,Bluetooth:Ppe,BluetoothConnected:Epe,BluetoothConnectedIcon:Epe,BluetoothIcon:Ppe,BluetoothOff:Tpe,BluetoothOffIcon:Tpe,BluetoothSearching:Mpe,BluetoothSearchingIcon:Mpe,Bold:HA,BoldIcon:HA,Bolt:Lpe,BoltIcon:Lpe,Bomb:Ipe,BombIcon:Ipe,Bone:Dpe,BoneIcon:Dpe,Book:nfe,BookA:Rpe,BookAIcon:Rpe,BookAudio:Fpe,BookAudioIcon:Fpe,BookCheck:Ope,BookCheckIcon:Ope,BookCopy:zpe,BookCopyIcon:zpe,BookDashed:a8,BookDashedIcon:a8,BookDown:Bpe,BookDownIcon:Bpe,BookHeadphones:$pe,BookHeadphonesIcon:$pe,BookHeart:Upe,BookHeartIcon:Upe,BookIcon:nfe,BookImage:qpe,BookImageIcon:qpe,BookKey:Vpe,BookKeyIcon:Vpe,BookLock:Hpe,BookLockIcon:Hpe,BookMarked:Gpe,BookMarkedIcon:Gpe,BookMinus:Wpe,BookMinusIcon:Wpe,BookOpen:ip,BookOpenCheck:Kpe,BookOpenCheckIcon:Kpe,BookOpenIcon:ip,BookOpenText:Ype,BookOpenTextIcon:Ype,BookPlus:Zpe,BookPlusIcon:Zpe,BookTemplate:a8,BookTemplateIcon:a8,BookText:Xpe,BookTextIcon:Xpe,BookType:Qpe,BookTypeIcon:Qpe,BookUp:efe,BookUp2:Jpe,BookUp2Icon:Jpe,BookUpIcon:efe,BookUser:tfe,BookUserIcon:tfe,BookX:sfe,BookXIcon:sfe,Bookmark:Ty,BookmarkCheck:rfe,BookmarkCheckIcon:rfe,BookmarkIcon:Ty,BookmarkMinus:afe,BookmarkMinusIcon:afe,BookmarkPlus:tP,BookmarkPlusIcon:tP,BookmarkX:ife,BookmarkXIcon:ife,BoomBox:ofe,BoomBoxIcon:ofe,Bot:K4,BotIcon:K4,BotMessageSquare:lfe,BotMessageSquareIcon:lfe,BotOff:cfe,BotOffIcon:cfe,Box:TQ,BoxIcon:TQ,BoxSelect:aR,BoxSelectIcon:aR,Boxes:dfe,BoxesIcon:dfe,Braces:h6,BracesIcon:h6,Brackets:ufe,BracketsIcon:ufe,Brain:MQ,BrainCircuit:hfe,BrainCircuitIcon:hfe,BrainCog:mfe,BrainCogIcon:mfe,BrainIcon:MQ,BrickWall:pfe,BrickWallIcon:pfe,Briefcase:Px,BriefcaseBusiness:ffe,BriefcaseBusinessIcon:ffe,BriefcaseConveyorBelt:xfe,BriefcaseConveyorBeltIcon:xfe,BriefcaseIcon:Px,BriefcaseMedical:gfe,BriefcaseMedicalIcon:gfe,BringToFront:yfe,BringToFrontIcon:yfe,Brush:vfe,BrushIcon:vfe,Bug:wfe,BugIcon:wfe,BugOff:bfe,BugOffIcon:bfe,BugPlay:_fe,BugPlayIcon:_fe,Building:sP,Building2:oi,Building2Icon:oi,BuildingIcon:sP,Bus:Nfe,BusFront:jfe,BusFrontIcon:jfe,BusIcon:Nfe,Cable:Sfe,CableCar:kfe,CableCarIcon:kfe,CableIcon:Sfe,Cake:Hf,CakeIcon:Hf,CakeSlice:Cfe,CakeSliceIcon:Cfe,Calculator:pj,CalculatorIcon:pj,Calendar:ya,Calendar1:Afe,Calendar1Icon:Afe,CalendarArrowDown:Efe,CalendarArrowDownIcon:Efe,CalendarArrowUp:Tfe,CalendarArrowUpIcon:Tfe,CalendarCheck:_v,CalendarCheck2:Mfe,CalendarCheck2Icon:Mfe,CalendarCheckIcon:_v,CalendarClock:Ud,CalendarClockIcon:Ud,CalendarCog:Pfe,CalendarCogIcon:Pfe,CalendarDays:gc,CalendarDaysIcon:gc,CalendarFold:Lfe,CalendarFoldIcon:Lfe,CalendarHeart:xS,CalendarHeartIcon:xS,CalendarIcon:ya,CalendarMinus:Dfe,CalendarMinus2:Ife,CalendarMinus2Icon:Ife,CalendarMinusIcon:Dfe,CalendarOff:RU,CalendarOffIcon:RU,CalendarPlus:v0,CalendarPlus2:Rfe,CalendarPlus2Icon:Rfe,CalendarPlusIcon:v0,CalendarRange:Ffe,CalendarRangeIcon:Ffe,CalendarSearch:Ofe,CalendarSearchIcon:Ofe,CalendarSync:zfe,CalendarSyncIcon:zfe,CalendarX:PQ,CalendarX2:Bfe,CalendarX2Icon:Bfe,CalendarXIcon:PQ,Camera:Lx,CameraIcon:Lx,CameraOff:$fe,CameraOffIcon:$fe,CandlestickChart:d8,CandlestickChartIcon:d8,Candy:Vfe,CandyCane:Ufe,CandyCaneIcon:Ufe,CandyIcon:Vfe,CandyOff:qfe,CandyOffIcon:qfe,Cannabis:Hfe,CannabisIcon:Hfe,Captions:i8,CaptionsIcon:i8,CaptionsOff:Gfe,CaptionsOffIcon:Gfe,Car:Yfe,CarFront:Wfe,CarFrontIcon:Wfe,CarIcon:Yfe,CarTaxiFront:Kfe,CarTaxiFrontIcon:Kfe,Caravan:Zfe,CaravanIcon:Zfe,Carrot:Xfe,CarrotIcon:Xfe,CaseLower:Qfe,CaseLowerIcon:Qfe,CaseSensitive:Jfe,CaseSensitiveIcon:Jfe,CaseUpper:exe,CaseUpperIcon:exe,CassetteTape:txe,CassetteTapeIcon:txe,Cast:sxe,CastIcon:sxe,Castle:nxe,CastleIcon:nxe,Cat:rxe,CatIcon:rxe,Cctv:axe,CctvIcon:axe,ChartArea:o8,ChartAreaIcon:o8,ChartBar:c8,ChartBarBig:l8,ChartBarBigIcon:l8,ChartBarDecreasing:ixe,ChartBarDecreasingIcon:ixe,ChartBarIcon:c8,ChartBarIncreasing:oxe,ChartBarIncreasingIcon:oxe,ChartBarStacked:lxe,ChartBarStackedIcon:lxe,ChartCandlestick:d8,ChartCandlestickIcon:d8,ChartColumn:wl,ChartColumnBig:u8,ChartColumnBigIcon:u8,ChartColumnDecreasing:cxe,ChartColumnDecreasingIcon:cxe,ChartColumnIcon:wl,ChartColumnIncreasing:h8,ChartColumnIncreasingIcon:h8,ChartColumnStacked:dxe,ChartColumnStackedIcon:dxe,ChartGantt:uxe,ChartGanttIcon:uxe,ChartLine:m8,ChartLineIcon:m8,ChartNetwork:hxe,ChartNetworkIcon:hxe,ChartNoAxesColumn:f8,ChartNoAxesColumnDecreasing:mxe,ChartNoAxesColumnDecreasingIcon:mxe,ChartNoAxesColumnIcon:f8,ChartNoAxesColumnIncreasing:p8,ChartNoAxesColumnIncreasingIcon:p8,ChartNoAxesCombined:pxe,ChartNoAxesCombinedIcon:pxe,ChartNoAxesGantt:x8,ChartNoAxesGanttIcon:x8,ChartPie:g8,ChartPieIcon:g8,ChartScatter:y8,ChartScatterIcon:y8,ChartSpline:fxe,ChartSplineIcon:fxe,Check:Wr,CheckCheck:e7,CheckCheckIcon:e7,CheckCircle:Xl,CheckCircle2:Mr,CheckCircle2Icon:Mr,CheckCircleIcon:Xl,CheckIcon:Wr,CheckSquare:Zw,CheckSquare2:XD,CheckSquare2Icon:XD,CheckSquareIcon:Zw,ChefHat:xxe,ChefHatIcon:xxe,Cherry:gxe,CherryIcon:gxe,ChevronDown:cl,ChevronDownCircle:C8,ChevronDownCircleIcon:C8,ChevronDownIcon:cl,ChevronDownSquare:QD,ChevronDownSquareIcon:QD,ChevronFirst:yxe,ChevronFirstIcon:yxe,ChevronLast:vxe,ChevronLastIcon:vxe,ChevronLeft:Wc,ChevronLeftCircle:A8,ChevronLeftCircleIcon:A8,ChevronLeftIcon:Wc,ChevronLeftSquare:JD,ChevronLeftSquareIcon:JD,ChevronRight:yi,ChevronRightCircle:E8,ChevronRightCircleIcon:E8,ChevronRightIcon:yi,ChevronRightSquare:eR,ChevronRightSquareIcon:eR,ChevronUp:h1,ChevronUpCircle:T8,ChevronUpCircleIcon:T8,ChevronUpIcon:h1,ChevronUpSquare:tR,ChevronUpSquareIcon:tR,ChevronsDown:_xe,ChevronsDownIcon:_xe,ChevronsDownUp:bxe,ChevronsDownUpIcon:bxe,ChevronsLeft:Nxe,ChevronsLeftIcon:Nxe,ChevronsLeftRight:jxe,ChevronsLeftRightEllipsis:wxe,ChevronsLeftRightEllipsisIcon:wxe,ChevronsLeftRightIcon:jxe,ChevronsRight:Sxe,ChevronsRightIcon:Sxe,ChevronsRightLeft:kxe,ChevronsRightLeftIcon:kxe,ChevronsUp:Cxe,ChevronsUpDown:R_,ChevronsUpDownIcon:R_,ChevronsUpIcon:Cxe,Chrome:t7,ChromeIcon:t7,Church:Axe,ChurchIcon:Axe,Cigarette:Txe,CigaretteIcon:Txe,CigaretteOff:Exe,CigaretteOffIcon:Exe,Circle:Gf,CircleAlert:Ho,CircleAlertIcon:Ho,CircleArrowDown:v8,CircleArrowDownIcon:v8,CircleArrowLeft:b8,CircleArrowLeftIcon:b8,CircleArrowOutDownLeft:_8,CircleArrowOutDownLeftIcon:_8,CircleArrowOutDownRight:w8,CircleArrowOutDownRightIcon:w8,CircleArrowOutUpLeft:j8,CircleArrowOutUpLeftIcon:j8,CircleArrowOutUpRight:N8,CircleArrowOutUpRightIcon:N8,CircleArrowRight:k8,CircleArrowRightIcon:k8,CircleArrowUp:S8,CircleArrowUpIcon:S8,CircleCheck:Mr,CircleCheckBig:Xl,CircleCheckBigIcon:Xl,CircleCheckIcon:Mr,CircleChevronDown:C8,CircleChevronDownIcon:C8,CircleChevronLeft:A8,CircleChevronLeftIcon:A8,CircleChevronRight:E8,CircleChevronRightIcon:E8,CircleChevronUp:T8,CircleChevronUpIcon:T8,CircleDashed:Mxe,CircleDashedIcon:Mxe,CircleDivide:M8,CircleDivideIcon:M8,CircleDollarSign:Pxe,CircleDollarSignIcon:Pxe,CircleDot:Ixe,CircleDotDashed:Lxe,CircleDotDashedIcon:Lxe,CircleDotIcon:Ixe,CircleEllipsis:Dxe,CircleEllipsisIcon:Dxe,CircleEqual:Rxe,CircleEqualIcon:Rxe,CircleFadingArrowUp:Fxe,CircleFadingArrowUpIcon:Fxe,CircleFadingPlus:Oxe,CircleFadingPlusIcon:Oxe,CircleGauge:P8,CircleGaugeIcon:P8,CircleHelp:v4,CircleHelpIcon:v4,CircleIcon:Gf,CircleMinus:L8,CircleMinusIcon:L8,CircleOff:zxe,CircleOffIcon:zxe,CircleParking:D8,CircleParkingIcon:D8,CircleParkingOff:I8,CircleParkingOffIcon:I8,CirclePause:R8,CirclePauseIcon:R8,CirclePercent:F8,CirclePercentIcon:F8,CirclePlay:dm,CirclePlayIcon:dm,CirclePlus:O8,CirclePlusIcon:O8,CirclePower:z8,CirclePowerIcon:z8,CircleSlash:Bxe,CircleSlash2:B8,CircleSlash2Icon:B8,CircleSlashIcon:Bxe,CircleSlashed:B8,CircleSlashedIcon:B8,CircleStop:$8,CircleStopIcon:$8,CircleUser:q8,CircleUserIcon:q8,CircleUserRound:U8,CircleUserRoundIcon:U8,CircleX:Bd,CircleXIcon:Bd,CircuitBoard:$xe,CircuitBoardIcon:$xe,Citrus:Uxe,CitrusIcon:Uxe,Clapperboard:FU,ClapperboardIcon:FU,Clipboard:Yxe,ClipboardCheck:fN,ClipboardCheckIcon:fN,ClipboardCopy:qxe,ClipboardCopyIcon:qxe,ClipboardEdit:H8,ClipboardEditIcon:H8,ClipboardIcon:Yxe,ClipboardList:Wf,ClipboardListIcon:Wf,ClipboardMinus:Vxe,ClipboardMinusIcon:Vxe,ClipboardPaste:Hxe,ClipboardPasteIcon:Hxe,ClipboardPen:H8,ClipboardPenIcon:H8,ClipboardPenLine:V8,ClipboardPenLineIcon:V8,ClipboardPlus:Gxe,ClipboardPlusIcon:Gxe,ClipboardSignature:V8,ClipboardSignatureIcon:V8,ClipboardType:Wxe,ClipboardTypeIcon:Wxe,ClipboardX:Kxe,ClipboardXIcon:Kxe,Clock:Zr,Clock1:Zxe,Clock10:Xxe,Clock10Icon:Xxe,Clock11:Qxe,Clock11Icon:Qxe,Clock12:Jxe,Clock12Icon:Jxe,Clock1Icon:Zxe,Clock2:ege,Clock2Icon:ege,Clock3:OU,Clock3Icon:OU,Clock4:tge,Clock4Icon:tge,Clock5:sge,Clock5Icon:sge,Clock6:nge,Clock6Icon:nge,Clock7:rge,Clock7Icon:rge,Clock8:age,Clock8Icon:age,Clock9:ige,Clock9Icon:ige,ClockAlert:oge,ClockAlertIcon:oge,ClockArrowDown:lge,ClockArrowDownIcon:lge,ClockArrowUp:cge,ClockArrowUpIcon:cge,ClockIcon:Zr,Cloud:Nge,CloudAlert:dge,CloudAlertIcon:dge,CloudCog:uge,CloudCogIcon:uge,CloudDownload:G8,CloudDownloadIcon:G8,CloudDrizzle:hge,CloudDrizzleIcon:hge,CloudFog:mge,CloudFogIcon:mge,CloudHail:pge,CloudHailIcon:pge,CloudIcon:Nge,CloudLightning:fge,CloudLightningIcon:fge,CloudMoon:gge,CloudMoonIcon:gge,CloudMoonRain:xge,CloudMoonRainIcon:xge,CloudOff:yge,CloudOffIcon:yge,CloudRain:bge,CloudRainIcon:bge,CloudRainWind:vge,CloudRainWindIcon:vge,CloudSnow:_ge,CloudSnowIcon:_ge,CloudSun:jge,CloudSunIcon:jge,CloudSunRain:wge,CloudSunRainIcon:wge,CloudUpload:m6,CloudUploadIcon:m6,Cloudy:kge,CloudyIcon:kge,Clover:FA,CloverIcon:FA,Club:Sge,ClubIcon:Sge,Code:GA,Code2:b4,Code2Icon:b4,CodeIcon:GA,CodeSquare:sR,CodeSquareIcon:sR,CodeXml:b4,CodeXmlIcon:b4,Codepen:Cge,CodepenIcon:Cge,Codesandbox:Age,CodesandboxIcon:Age,Coffee:Y4,CoffeeIcon:Y4,Cog:Ege,CogIcon:Ege,Coins:LQ,CoinsIcon:LQ,Columns:W8,Columns2:W8,Columns2Icon:W8,Columns3:p6,Columns3Icon:p6,Columns4:Tge,Columns4Icon:Tge,ColumnsIcon:W8,Combine:Mge,CombineIcon:Mge,Command:Pge,CommandIcon:Pge,Compass:s7,CompassIcon:s7,Component:Lge,ComponentIcon:Lge,Computer:Ige,ComputerIcon:Ige,ConciergeBell:Dge,ConciergeBellIcon:Dge,Cone:Rge,ConeIcon:Rge,Construction:Fge,ConstructionIcon:Fge,Contact:nP,Contact2:K8,Contact2Icon:K8,ContactIcon:nP,ContactRound:K8,ContactRoundIcon:K8,Container:Oge,ContainerIcon:Oge,Contrast:zge,ContrastIcon:zge,Cookie:Bge,CookieIcon:Bge,CookingPot:$ge,CookingPotIcon:$ge,Copy:Sa,CopyCheck:Uge,CopyCheckIcon:Uge,CopyIcon:Sa,CopyMinus:qge,CopyMinusIcon:qge,CopyPlus:Vge,CopyPlusIcon:Vge,CopySlash:Hge,CopySlashIcon:Hge,CopyX:Gge,CopyXIcon:Gge,Copyleft:Wge,CopyleftIcon:Wge,Copyright:Kge,CopyrightIcon:Kge,CornerDownLeft:Yge,CornerDownLeftIcon:Yge,CornerDownRight:IQ,CornerDownRightIcon:IQ,CornerLeftDown:Zge,CornerLeftDownIcon:Zge,CornerLeftUp:Xge,CornerLeftUpIcon:Xge,CornerRightDown:Qge,CornerRightDownIcon:Qge,CornerRightUp:Jge,CornerRightUpIcon:Jge,CornerUpLeft:eye,CornerUpLeftIcon:eye,CornerUpRight:tye,CornerUpRightIcon:tye,Cpu:sye,CpuIcon:sye,CreativeCommons:nye,CreativeCommonsIcon:nye,CreditCard:j0,CreditCardIcon:j0,Croissant:rye,CroissantIcon:rye,Crop:aye,CropIcon:aye,Cross:iye,CrossIcon:iye,Crosshair:oye,CrosshairIcon:oye,Crown:Kf,CrownIcon:Kf,Cuboid:lye,CuboidIcon:lye,CupSoda:cye,CupSodaIcon:cye,CurlyBraces:h6,CurlyBracesIcon:h6,Currency:dye,CurrencyIcon:dye,Cylinder:uye,CylinderIcon:uye,Dam:hye,DamIcon:hye,Database:zU,DatabaseBackup:mye,DatabaseBackupIcon:mye,DatabaseIcon:zU,DatabaseZap:pye,DatabaseZapIcon:pye,Delete:fye,DeleteIcon:fye,Dessert:xye,DessertIcon:xye,Diameter:gye,DiameterIcon:gye,Diamond:bye,DiamondIcon:bye,DiamondMinus:yye,DiamondMinusIcon:yye,DiamondPercent:Y8,DiamondPercentIcon:Y8,DiamondPlus:vye,DiamondPlusIcon:vye,Dice1:_ye,Dice1Icon:_ye,Dice2:wye,Dice2Icon:wye,Dice3:jye,Dice3Icon:jye,Dice4:Nye,Dice4Icon:Nye,Dice5:kye,Dice5Icon:kye,Dice6:Sye,Dice6Icon:Sye,Dices:Cye,DicesIcon:Cye,Diff:Aye,DiffIcon:Aye,Disc:Pye,Disc2:Eye,Disc2Icon:Eye,Disc3:Tye,Disc3Icon:Tye,DiscAlbum:Mye,DiscAlbumIcon:Mye,DiscIcon:Pye,Divide:Lye,DivideCircle:M8,DivideCircleIcon:M8,DivideIcon:Lye,DivideSquare:iR,DivideSquareIcon:iR,Dna:Dye,DnaIcon:Dye,DnaOff:Iye,DnaOffIcon:Iye,Dock:Rye,DockIcon:Rye,Dog:Fye,DogIcon:Fye,DollarSign:Nd,DollarSignIcon:Nd,Donut:Oye,DonutIcon:Oye,DoorClosed:zye,DoorClosedIcon:zye,DoorOpen:fj,DoorOpenIcon:fj,Dot:Bye,DotIcon:Bye,DotSquare:oR,DotSquareIcon:oR,Download:Ga,DownloadCloud:G8,DownloadCloudIcon:G8,DownloadIcon:Ga,DraftingCompass:$ye,DraftingCompassIcon:$ye,Drama:Uye,DramaIcon:Uye,Dribbble:qye,DribbbleIcon:qye,Drill:Vye,DrillIcon:Vye,Droplet:Hye,DropletIcon:Hye,Droplets:m1,DropletsIcon:m1,Drum:Gye,DrumIcon:Gye,Drumstick:Wye,DrumstickIcon:Wye,Dumbbell:Kye,DumbbellIcon:Kye,Ear:Zye,EarIcon:Zye,EarOff:Yye,EarOffIcon:Yye,Earth:K2,EarthIcon:K2,EarthLock:Xye,EarthLockIcon:Xye,Eclipse:Qye,EclipseIcon:Qye,Edit:Cp,Edit2:Y2,Edit2Icon:Y2,Edit3:Mm,Edit3Icon:Mm,EditIcon:Cp,Egg:BU,EggFried:Jye,EggFriedIcon:Jye,EggIcon:BU,EggOff:e0e,EggOffIcon:e0e,Ellipsis:lb,EllipsisIcon:lb,EllipsisVertical:ng,EllipsisVerticalIcon:ng,Equal:n0e,EqualApproximately:t0e,EqualApproximatelyIcon:t0e,EqualIcon:n0e,EqualNot:s0e,EqualNotIcon:s0e,EqualSquare:lR,EqualSquareIcon:lR,Eraser:$U,EraserIcon:$U,EthernetPort:r0e,EthernetPortIcon:r0e,Euro:a0e,EuroIcon:a0e,Expand:i0e,ExpandIcon:i0e,ExternalLink:mr,ExternalLinkIcon:mr,Eye:xa,EyeClosed:o0e,EyeClosedIcon:o0e,EyeIcon:xa,EyeOff:Yf,EyeOffIcon:Yf,Facebook:of,FacebookIcon:of,Factory:l0e,FactoryIcon:l0e,Fan:c0e,FanIcon:c0e,FastForward:d0e,FastForwardIcon:d0e,Feather:u0e,FeatherIcon:u0e,Fence:h0e,FenceIcon:h0e,FerrisWheel:m0e,FerrisWheelIcon:m0e,Figma:p0e,FigmaIcon:p0e,File:qU,FileArchive:f0e,FileArchiveIcon:f0e,FileAudio:g0e,FileAudio2:x0e,FileAudio2Icon:x0e,FileAudioIcon:g0e,FileAxis3D:Z8,FileAxis3DIcon:Z8,FileAxis3d:Z8,FileAxis3dIcon:Z8,FileBadge:v0e,FileBadge2:y0e,FileBadge2Icon:y0e,FileBadgeIcon:v0e,FileBarChart:X8,FileBarChart2:Q8,FileBarChart2Icon:Q8,FileBarChartIcon:X8,FileBox:b0e,FileBoxIcon:b0e,FileChartColumn:Q8,FileChartColumnIcon:Q8,FileChartColumnIncreasing:X8,FileChartColumnIncreasingIcon:X8,FileChartLine:J8,FileChartLineIcon:J8,FileChartPie:eD,FileChartPieIcon:eD,FileCheck:DQ,FileCheck2:n7,FileCheck2Icon:n7,FileCheckIcon:DQ,FileClock:_0e,FileClockIcon:_0e,FileCode:j0e,FileCode2:w0e,FileCode2Icon:w0e,FileCodeIcon:j0e,FileCog:tD,FileCog2:tD,FileCog2Icon:tD,FileCogIcon:tD,FileDiff:N0e,FileDiffIcon:N0e,FileDigit:k0e,FileDigitIcon:k0e,FileDown:xj,FileDownIcon:xj,FileEdit:sD,FileEditIcon:sD,FileHeart:S0e,FileHeartIcon:S0e,FileIcon:qU,FileImage:rP,FileImageIcon:rP,FileInput:C0e,FileInputIcon:C0e,FileJson:E0e,FileJson2:A0e,FileJson2Icon:A0e,FileJsonIcon:E0e,FileKey:M0e,FileKey2:T0e,FileKey2Icon:T0e,FileKeyIcon:M0e,FileLineChart:J8,FileLineChartIcon:J8,FileLock:L0e,FileLock2:P0e,FileLock2Icon:P0e,FileLockIcon:L0e,FileMinus:D0e,FileMinus2:I0e,FileMinus2Icon:I0e,FileMinusIcon:D0e,FileMusic:R0e,FileMusicIcon:R0e,FileOutput:F0e,FileOutputIcon:F0e,FilePen:sD,FilePenIcon:sD,FilePenLine:cb,FilePenLineIcon:cb,FilePieChart:eD,FilePieChartIcon:eD,FilePlus:O0e,FilePlus2:UU,FilePlus2Icon:UU,FilePlusIcon:O0e,FileQuestion:z0e,FileQuestionIcon:z0e,FileScan:B0e,FileScanIcon:B0e,FileSearch:RQ,FileSearch2:$0e,FileSearch2Icon:$0e,FileSearchIcon:RQ,FileSignature:cb,FileSignatureIcon:cb,FileSliders:U0e,FileSlidersIcon:U0e,FileSpreadsheet:xN,FileSpreadsheetIcon:xN,FileStack:FQ,FileStackIcon:FQ,FileSymlink:q0e,FileSymlinkIcon:q0e,FileTerminal:V0e,FileTerminalIcon:V0e,FileText:$r,FileTextIcon:$r,FileType:G0e,FileType2:H0e,FileType2Icon:H0e,FileTypeIcon:G0e,FileUp:OQ,FileUpIcon:OQ,FileUser:W0e,FileUserIcon:W0e,FileVideo:zQ,FileVideo2:K0e,FileVideo2Icon:K0e,FileVideoIcon:zQ,FileVolume:Z0e,FileVolume2:Y0e,FileVolume2Icon:Y0e,FileVolumeIcon:Z0e,FileWarning:X0e,FileWarningIcon:X0e,FileX:J0e,FileX2:Q0e,FileX2Icon:Q0e,FileXIcon:J0e,Files:eve,FilesIcon:eve,Film:Yh,FilmIcon:Yh,Filter:F_,FilterIcon:F_,FilterX:tve,FilterXIcon:tve,Fingerprint:sve,FingerprintIcon:sve,FireExtinguisher:nve,FireExtinguisherIcon:nve,Fish:ive,FishIcon:ive,FishOff:rve,FishOffIcon:rve,FishSymbol:ave,FishSymbolIcon:ave,Flag:WA,FlagIcon:WA,FlagOff:ove,FlagOffIcon:ove,FlagTriangleLeft:lve,FlagTriangleLeftIcon:lve,FlagTriangleRight:cve,FlagTriangleRightIcon:cve,Flame:vu,FlameIcon:vu,FlameKindling:dve,FlameKindlingIcon:dve,Flashlight:hve,FlashlightIcon:hve,FlashlightOff:uve,FlashlightOffIcon:uve,FlaskConical:Z4,FlaskConicalIcon:Z4,FlaskConicalOff:mve,FlaskConicalOffIcon:mve,FlaskRound:pve,FlaskRoundIcon:pve,FlipHorizontal:BQ,FlipHorizontal2:fve,FlipHorizontal2Icon:fve,FlipHorizontalIcon:BQ,FlipVertical:gve,FlipVertical2:xve,FlipVertical2Icon:xve,FlipVerticalIcon:gve,Flower:yve,Flower2:cS,Flower2Icon:cS,FlowerIcon:yve,Focus:vve,FocusIcon:vve,FoldHorizontal:bve,FoldHorizontalIcon:bve,FoldVertical:_ve,FoldVerticalIcon:_ve,Folder:VU,FolderArchive:wve,FolderArchiveIcon:wve,FolderCheck:jve,FolderCheckIcon:jve,FolderClock:Nve,FolderClockIcon:Nve,FolderClosed:kve,FolderClosedIcon:kve,FolderCode:Sve,FolderCodeIcon:Sve,FolderCog:nD,FolderCog2:nD,FolderCog2Icon:nD,FolderCogIcon:nD,FolderDot:Cve,FolderDotIcon:Cve,FolderDown:Ave,FolderDownIcon:Ave,FolderEdit:rD,FolderEditIcon:rD,FolderGit:Tve,FolderGit2:Eve,FolderGit2Icon:Eve,FolderGitIcon:Tve,FolderHeart:Mve,FolderHeartIcon:Mve,FolderIcon:VU,FolderInput:Pve,FolderInputIcon:Pve,FolderKanban:Lve,FolderKanbanIcon:Lve,FolderKey:Ive,FolderKeyIcon:Ive,FolderLock:Dve,FolderLockIcon:Dve,FolderMinus:Rve,FolderMinusIcon:Rve,FolderOpen:wv,FolderOpenDot:Fve,FolderOpenDotIcon:Fve,FolderOpenIcon:wv,FolderOutput:Ove,FolderOutputIcon:Ove,FolderPen:rD,FolderPenIcon:rD,FolderPlus:$Q,FolderPlusIcon:$Q,FolderRoot:zve,FolderRootIcon:zve,FolderSearch:$ve,FolderSearch2:Bve,FolderSearch2Icon:Bve,FolderSearchIcon:$ve,FolderSymlink:Uve,FolderSymlinkIcon:Uve,FolderSync:qve,FolderSyncIcon:qve,FolderTree:Vve,FolderTreeIcon:Vve,FolderUp:Hve,FolderUpIcon:Hve,FolderX:Gve,FolderXIcon:Gve,Folders:Wve,FoldersIcon:Wve,Footprints:Kve,FootprintsIcon:Kve,ForkKnife:VR,ForkKnifeCrossed:qR,ForkKnifeCrossedIcon:qR,ForkKnifeIcon:VR,Forklift:Yve,ForkliftIcon:Yve,FormInput:AD,FormInputIcon:AD,Forward:Zve,ForwardIcon:Zve,Frame:Xve,FrameIcon:Xve,Framer:Qve,FramerIcon:Qve,Frown:Jve,FrownIcon:Jve,Fuel:e1e,FuelIcon:e1e,Fullscreen:t1e,FullscreenIcon:t1e,FunctionSquare:cR,FunctionSquareIcon:cR,GalleryHorizontal:n1e,GalleryHorizontalEnd:s1e,GalleryHorizontalEndIcon:s1e,GalleryHorizontalIcon:n1e,GalleryThumbnails:r1e,GalleryThumbnailsIcon:r1e,GalleryVertical:i1e,GalleryVerticalEnd:a1e,GalleryVerticalEndIcon:a1e,GalleryVerticalIcon:i1e,Gamepad:l1e,Gamepad2:o1e,Gamepad2Icon:o1e,GamepadIcon:l1e,GanttChart:x8,GanttChartIcon:x8,GanttChartSquare:F5,GanttChartSquareIcon:F5,Gauge:c1e,GaugeCircle:P8,GaugeCircleIcon:P8,GaugeIcon:c1e,Gavel:d1e,GavelIcon:d1e,Gem:u1e,GemIcon:u1e,Ghost:r7,GhostIcon:r7,Gift:Ko,GiftIcon:Ko,GitBranch:m1e,GitBranchIcon:m1e,GitBranchPlus:h1e,GitBranchPlusIcon:h1e,GitCommit:aD,GitCommitHorizontal:aD,GitCommitHorizontalIcon:aD,GitCommitIcon:aD,GitCommitVertical:p1e,GitCommitVerticalIcon:p1e,GitCompare:x1e,GitCompareArrows:f1e,GitCompareArrowsIcon:f1e,GitCompareIcon:x1e,GitFork:g1e,GitForkIcon:g1e,GitGraph:y1e,GitGraphIcon:y1e,GitMerge:v1e,GitMergeIcon:v1e,GitPullRequest:k1e,GitPullRequestArrow:b1e,GitPullRequestArrowIcon:b1e,GitPullRequestClosed:_1e,GitPullRequestClosedIcon:_1e,GitPullRequestCreate:j1e,GitPullRequestCreateArrow:w1e,GitPullRequestCreateArrowIcon:w1e,GitPullRequestCreateIcon:j1e,GitPullRequestDraft:N1e,GitPullRequestDraftIcon:N1e,GitPullRequestIcon:k1e,Github:S1e,GithubIcon:S1e,Gitlab:C1e,GitlabIcon:C1e,GlassWater:A1e,GlassWaterIcon:A1e,Glasses:E1e,GlassesIcon:E1e,Globe:Wo,Globe2:K2,Globe2Icon:K2,GlobeIcon:Wo,GlobeLock:T1e,GlobeLockIcon:T1e,Goal:M1e,GoalIcon:M1e,Grab:P1e,GrabIcon:P1e,GraduationCap:fm,GraduationCapIcon:fm,Grape:L1e,GrapeIcon:L1e,Grid:Vw,Grid2X2:oD,Grid2X2Icon:oD,Grid2X2Plus:iD,Grid2X2PlusIcon:iD,Grid2x2:oD,Grid2x2Check:I1e,Grid2x2CheckIcon:I1e,Grid2x2Icon:oD,Grid2x2Plus:iD,Grid2x2PlusIcon:iD,Grid2x2X:D1e,Grid2x2XIcon:D1e,Grid3X3:Vw,Grid3X3Icon:Vw,Grid3x3:Vw,Grid3x3Icon:Vw,GridIcon:Vw,Grip:F1e,GripHorizontal:R1e,GripHorizontalIcon:R1e,GripIcon:F1e,GripVertical:Zf,GripVerticalIcon:Zf,Group:O1e,GroupIcon:O1e,Guitar:z1e,GuitarIcon:z1e,Ham:B1e,HamIcon:B1e,Hammer:UQ,HammerIcon:UQ,Hand:HU,HandCoins:$1e,HandCoinsIcon:$1e,HandHeart:qQ,HandHeartIcon:qQ,HandHelping:_4,HandHelpingIcon:_4,HandIcon:HU,HandMetal:U1e,HandMetalIcon:U1e,HandPlatter:q1e,HandPlatterIcon:q1e,Handshake:jv,HandshakeIcon:jv,HardDrive:VQ,HardDriveDownload:V1e,HardDriveDownloadIcon:V1e,HardDriveIcon:VQ,HardDriveUpload:H1e,HardDriveUploadIcon:H1e,HardHat:G1e,HardHatIcon:G1e,Hash:aP,HashIcon:aP,Haze:W1e,HazeIcon:W1e,HdmiPort:K1e,HdmiPortIcon:K1e,Heading:Q1e,Heading1:GU,Heading1Icon:GU,Heading2:a7,Heading2Icon:a7,Heading3:WU,Heading3Icon:WU,Heading4:Y1e,Heading4Icon:Y1e,Heading5:Z1e,Heading5Icon:Z1e,Heading6:X1e,Heading6Icon:X1e,HeadingIcon:Q1e,HeadphoneOff:J1e,HeadphoneOffIcon:J1e,Headphones:ebe,HeadphonesIcon:ebe,Headset:tbe,HeadsetIcon:tbe,Heart:Fo,HeartCrack:sbe,HeartCrackIcon:sbe,HeartHandshake:HQ,HeartHandshakeIcon:HQ,HeartIcon:Fo,HeartOff:nbe,HeartOffIcon:nbe,HeartPulse:rbe,HeartPulseIcon:rbe,Heater:abe,HeaterIcon:abe,HelpCircle:v4,HelpCircleIcon:v4,HelpingHand:_4,HelpingHandIcon:_4,Hexagon:ibe,HexagonIcon:ibe,Highlighter:obe,HighlighterIcon:obe,History:O_,HistoryIcon:O_,Home:sa,HomeIcon:sa,Hop:cbe,HopIcon:cbe,HopOff:lbe,HopOffIcon:lbe,Hospital:dbe,HospitalIcon:dbe,Hotel:ube,HotelIcon:ube,Hourglass:GQ,HourglassIcon:GQ,House:sa,HouseIcon:sa,HousePlug:hbe,HousePlugIcon:hbe,HousePlus:mbe,HousePlusIcon:mbe,IceCream:cD,IceCream2:lD,IceCream2Icon:lD,IceCreamBowl:lD,IceCreamBowlIcon:lD,IceCreamCone:cD,IceCreamConeIcon:cD,IceCreamIcon:cD,Icon:zMt,IdCard:WQ,IdCardIcon:WQ,Image:nc,ImageDown:pbe,ImageDownIcon:pbe,ImageIcon:nc,ImageMinus:fbe,ImageMinusIcon:fbe,ImageOff:xbe,ImageOffIcon:xbe,ImagePlay:gbe,ImagePlayIcon:gbe,ImagePlus:N0,ImagePlusIcon:N0,ImageUp:ybe,ImageUpIcon:ybe,ImageUpscale:vbe,ImageUpscaleIcon:vbe,Images:bbe,ImagesIcon:bbe,Import:_be,ImportIcon:_be,Inbox:i7,InboxIcon:i7,Indent:uD,IndentDecrease:dD,IndentDecreaseIcon:dD,IndentIcon:uD,IndentIncrease:uD,IndentIncreaseIcon:uD,IndianRupee:wbe,IndianRupeeIcon:wbe,Infinity:KU,InfinityIcon:KU,Info:gS,InfoIcon:gS,Inspect:fR,InspectIcon:fR,InspectionPanel:jbe,InspectionPanelIcon:jbe,Instagram:Fm,InstagramIcon:Fm,Italic:KA,ItalicIcon:KA,IterationCcw:Nbe,IterationCcwIcon:Nbe,IterationCw:kbe,IterationCwIcon:kbe,JapaneseYen:Sbe,JapaneseYenIcon:Sbe,Joystick:Cbe,JoystickIcon:Cbe,Kanban:gj,KanbanIcon:gj,KanbanSquare:dR,KanbanSquareDashed:nR,KanbanSquareDashedIcon:nR,KanbanSquareIcon:dR,Key:wb,KeyIcon:wb,KeyRound:iP,KeyRoundIcon:iP,KeySquare:Abe,KeySquareIcon:Abe,Keyboard:Mbe,KeyboardIcon:Mbe,KeyboardMusic:Ebe,KeyboardMusicIcon:Ebe,KeyboardOff:Tbe,KeyboardOffIcon:Tbe,Lamp:Fbe,LampCeiling:Pbe,LampCeilingIcon:Pbe,LampDesk:Lbe,LampDeskIcon:Lbe,LampFloor:Ibe,LampFloorIcon:Ibe,LampIcon:Fbe,LampWallDown:Dbe,LampWallDownIcon:Dbe,LampWallUp:Rbe,LampWallUpIcon:Rbe,LandPlot:Obe,LandPlotIcon:Obe,Landmark:YU,LandmarkIcon:YU,Languages:zbe,LanguagesIcon:zbe,Laptop:$be,Laptop2:hD,Laptop2Icon:hD,LaptopIcon:$be,LaptopMinimal:hD,LaptopMinimalCheck:Bbe,LaptopMinimalCheckIcon:Bbe,LaptopMinimalIcon:hD,Lasso:qbe,LassoIcon:qbe,LassoSelect:Ube,LassoSelectIcon:Ube,Laugh:Vbe,LaughIcon:Vbe,Layers:X4,Layers2:Hbe,Layers2Icon:Hbe,Layers3:Gbe,Layers3Icon:Gbe,LayersIcon:X4,Layout:tA,LayoutDashboard:oP,LayoutDashboardIcon:oP,LayoutGrid:op,LayoutGridIcon:op,LayoutIcon:tA,LayoutList:Wbe,LayoutListIcon:Wbe,LayoutPanelLeft:Kbe,LayoutPanelLeftIcon:Kbe,LayoutPanelTop:Ybe,LayoutPanelTopIcon:Ybe,LayoutTemplate:yj,LayoutTemplateIcon:yj,Leaf:Zbe,LeafIcon:Zbe,LeafyGreen:Xbe,LeafyGreenIcon:Xbe,Lectern:Qbe,LecternIcon:Qbe,LetterText:Jbe,LetterTextIcon:Jbe,Library:vj,LibraryBig:e_e,LibraryBigIcon:e_e,LibraryIcon:vj,LibrarySquare:uR,LibrarySquareIcon:uR,LifeBuoy:ZU,LifeBuoyIcon:ZU,Ligature:t_e,LigatureIcon:t_e,Lightbulb:yS,LightbulbIcon:yS,LightbulbOff:s_e,LightbulbOffIcon:s_e,LineChart:m8,LineChartIcon:m8,Link:Kc,Link2:Oc,Link2Icon:Oc,Link2Off:n_e,Link2OffIcon:n_e,LinkIcon:Kc,Linkedin:fg,LinkedinIcon:fg,List:My,ListCheck:r_e,ListCheckIcon:r_e,ListChecks:k0,ListChecksIcon:k0,ListCollapse:a_e,ListCollapseIcon:a_e,ListEnd:i_e,ListEndIcon:i_e,ListFilter:KQ,ListFilterIcon:KQ,ListIcon:My,ListMinus:o_e,ListMinusIcon:o_e,ListMusic:l_e,ListMusicIcon:l_e,ListOrdered:bj,ListOrderedIcon:bj,ListPlus:YQ,ListPlusIcon:YQ,ListRestart:c_e,ListRestartIcon:c_e,ListStart:d_e,ListStartIcon:d_e,ListTodo:u_e,ListTodoIcon:u_e,ListTree:h_e,ListTreeIcon:h_e,ListVideo:m_e,ListVideoIcon:m_e,ListX:p_e,ListXIcon:p_e,Loader:x_e,Loader2:bt,Loader2Icon:bt,LoaderCircle:bt,LoaderCircleIcon:bt,LoaderIcon:x_e,LoaderPinwheel:f_e,LoaderPinwheelIcon:f_e,Locate:XU,LocateFixed:g_e,LocateFixedIcon:g_e,LocateIcon:XU,LocateOff:y_e,LocateOffIcon:y_e,Lock:Hl,LockIcon:Hl,LockKeyhole:ZQ,LockKeyholeIcon:ZQ,LockKeyholeOpen:mD,LockKeyholeOpenIcon:mD,LockOpen:pD,LockOpenIcon:pD,LogIn:lP,LogInIcon:lP,LogOut:o7,LogOutIcon:o7,Logs:v_e,LogsIcon:v_e,Lollipop:b_e,LollipopIcon:b_e,LucideAArrowDown:nhe,LucideAArrowUp:rhe,LucideALargeSmall:ahe,LucideAccessibility:ihe,LucideActivity:pm,LucideActivitySquare:RD,LucideAirVent:ohe,LucideAirplay:lhe,LucideAlarmCheck:WI,LucideAlarmClock:dhe,LucideAlarmClockCheck:WI,LucideAlarmClockMinus:KI,LucideAlarmClockOff:che,LucideAlarmClockPlus:YI,LucideAlarmMinus:KI,LucideAlarmPlus:YI,LucideAlarmSmoke:uhe,LucideAlbum:hhe,LucideAlertCircle:Ho,LucideAlertOctagon:nS,LucideAlertTriangle:nl,LucideAlignCenter:XM,LucideAlignCenterHorizontal:mhe,LucideAlignCenterVertical:phe,LucideAlignEndHorizontal:fhe,LucideAlignEndVertical:xhe,LucideAlignHorizontalDistributeCenter:ghe,LucideAlignHorizontalDistributeEnd:yhe,LucideAlignHorizontalDistributeStart:vhe,LucideAlignHorizontalJustifyCenter:bhe,LucideAlignHorizontalJustifyEnd:_he,LucideAlignHorizontalJustifyStart:whe,LucideAlignHorizontalSpaceAround:jhe,LucideAlignHorizontalSpaceBetween:Nhe,LucideAlignJustify:khe,LucideAlignLeft:QM,LucideAlignRight:JM,LucideAlignStartHorizontal:She,LucideAlignStartVertical:Che,LucideAlignVerticalDistributeCenter:Ahe,LucideAlignVerticalDistributeEnd:Ehe,LucideAlignVerticalDistributeStart:The,LucideAlignVerticalJustifyCenter:Mhe,LucideAlignVerticalJustifyEnd:Phe,LucideAlignVerticalJustifyStart:Lhe,LucideAlignVerticalSpaceAround:Ihe,LucideAlignVerticalSpaceBetween:Dhe,LucideAmbulance:Rhe,LucideAmpersand:Fhe,LucideAmpersands:Ohe,LucideAmphora:zhe,LucideAnchor:Bhe,LucideAngry:$he,LucideAnnoyed:Uhe,LucideAntenna:qhe,LucideAnvil:Vhe,LucideAperture:Hhe,LucideAppWindow:Whe,LucideAppWindowMac:Ghe,LucideApple:Khe,LucideArchive:w0,LucideArchiveRestore:eP,LucideArchiveX:Yhe,LucideAreaChart:o8,LucideArmchair:Zhe,LucideArrowBigDown:Qhe,LucideArrowBigDownDash:Xhe,LucideArrowBigLeft:eme,LucideArrowBigLeftDash:Jhe,LucideArrowBigRight:sme,LucideArrowBigRightDash:tme,LucideArrowBigUp:rme,LucideArrowBigUpDash:nme,LucideArrowDown:Vf,LucideArrowDown01:ame,LucideArrowDown10:ime,LucideArrowDownAZ:ZI,LucideArrowDownAz:ZI,LucideArrowDownCircle:v8,LucideArrowDownFromLine:ome,LucideArrowDownLeft:lme,LucideArrowDownLeftFromCircle:_8,LucideArrowDownLeftFromSquare:$D,LucideArrowDownLeftSquare:FD,LucideArrowDownNarrowWide:cme,LucideArrowDownRight:CQ,LucideArrowDownRightFromCircle:w8,LucideArrowDownRightFromSquare:UD,LucideArrowDownRightSquare:OD,LucideArrowDownSquare:zD,LucideArrowDownToDot:dme,LucideArrowDownToLine:ume,LucideArrowDownUp:hme,LucideArrowDownWideNarrow:XI,LucideArrowDownZA:QI,LucideArrowDownZa:QI,LucideArrowLeft:ka,LucideArrowLeftCircle:b8,LucideArrowLeftFromLine:mme,LucideArrowLeftRight:AQ,LucideArrowLeftSquare:BD,LucideArrowLeftToLine:pme,LucideArrowRight:Da,LucideArrowRightCircle:k8,LucideArrowRightFromLine:fme,LucideArrowRightLeft:G4,LucideArrowRightSquare:HD,LucideArrowRightToLine:xme,LucideArrowUp:ap,LucideArrowUp01:gme,LucideArrowUp10:yme,LucideArrowUpAZ:JI,LucideArrowUpAz:JI,LucideArrowUpCircle:S8,LucideArrowUpDown:Og,LucideArrowUpFromDot:vme,LucideArrowUpFromLine:bme,LucideArrowUpLeft:_me,LucideArrowUpLeftFromCircle:j8,LucideArrowUpLeftFromSquare:qD,LucideArrowUpLeftSquare:GD,LucideArrowUpNarrowWide:e8,LucideArrowUpRight:QO,LucideArrowUpRightFromCircle:N8,LucideArrowUpRightFromSquare:VD,LucideArrowUpRightSquare:WD,LucideArrowUpSquare:KD,LucideArrowUpToLine:wme,LucideArrowUpWideNarrow:jme,LucideArrowUpZA:t8,LucideArrowUpZa:t8,LucideArrowsUpFromLine:Nme,LucideAsterisk:kme,LucideAsteriskSquare:YD,LucideAtSign:Sme,LucideAtom:Cme,LucideAudioLines:Ame,LucideAudioWaveform:Eme,LucideAward:Kh,LucideAxe:Tme,LucideAxis3D:s8,LucideAxis3d:s8,LucideBaby:Mme,LucideBackpack:Pme,LucideBadge:Kme,LucideBadgeAlert:Lme,LucideBadgeCent:Ime,LucideBadgeCheck:eA,LucideBadgeDollarSign:Dme,LucideBadgeEuro:Rme,LucideBadgeHelp:Fme,LucideBadgeIndianRupee:Ome,LucideBadgeInfo:zme,LucideBadgeJapaneseYen:Bme,LucideBadgeMinus:$me,LucideBadgePercent:Ume,LucideBadgePlus:qme,LucideBadgePoundSterling:Vme,LucideBadgeRussianRuble:Hme,LucideBadgeSwissFranc:Gme,LucideBadgeX:Wme,LucideBaggageClaim:Yme,LucideBan:JO,LucideBanana:Zme,LucideBandage:Xme,LucideBanknote:Qme,LucideBarChart:p8,LucideBarChart2:f8,LucideBarChart3:wl,LucideBarChart4:h8,LucideBarChartBig:u8,LucideBarChartHorizontal:c8,LucideBarChartHorizontalBig:l8,LucideBarcode:Jme,LucideBaseline:epe,LucideBath:Ey,LucideBattery:ipe,LucideBatteryCharging:tpe,LucideBatteryFull:spe,LucideBatteryLow:npe,LucideBatteryMedium:rpe,LucideBatteryWarning:ape,LucideBeaker:EQ,LucideBean:lpe,LucideBeanOff:ope,LucideBed:mj,LucideBedDouble:W4,LucideBedSingle:cpe,LucideBeef:dpe,LucideBeer:hpe,LucideBeerOff:upe,LucideBell:$g,LucideBellDot:mpe,LucideBellElectric:ppe,LucideBellMinus:fpe,LucideBellOff:pS,LucideBellPlus:xpe,LucideBellRing:fS,LucideBetweenHorizonalEnd:n8,LucideBetweenHorizonalStart:r8,LucideBetweenHorizontalEnd:n8,LucideBetweenHorizontalStart:r8,LucideBetweenVerticalEnd:gpe,LucideBetweenVerticalStart:ype,LucideBicepsFlexed:vpe,LucideBike:bpe,LucideBinary:_pe,LucideBinoculars:wpe,LucideBiohazard:jpe,LucideBird:Npe,LucideBitcoin:kpe,LucideBlend:Spe,LucideBlinds:Cpe,LucideBlocks:Ape,LucideBluetooth:Ppe,LucideBluetoothConnected:Epe,LucideBluetoothOff:Tpe,LucideBluetoothSearching:Mpe,LucideBold:HA,LucideBolt:Lpe,LucideBomb:Ipe,LucideBone:Dpe,LucideBook:nfe,LucideBookA:Rpe,LucideBookAudio:Fpe,LucideBookCheck:Ope,LucideBookCopy:zpe,LucideBookDashed:a8,LucideBookDown:Bpe,LucideBookHeadphones:$pe,LucideBookHeart:Upe,LucideBookImage:qpe,LucideBookKey:Vpe,LucideBookLock:Hpe,LucideBookMarked:Gpe,LucideBookMinus:Wpe,LucideBookOpen:ip,LucideBookOpenCheck:Kpe,LucideBookOpenText:Ype,LucideBookPlus:Zpe,LucideBookTemplate:a8,LucideBookText:Xpe,LucideBookType:Qpe,LucideBookUp:efe,LucideBookUp2:Jpe,LucideBookUser:tfe,LucideBookX:sfe,LucideBookmark:Ty,LucideBookmarkCheck:rfe,LucideBookmarkMinus:afe,LucideBookmarkPlus:tP,LucideBookmarkX:ife,LucideBoomBox:ofe,LucideBot:K4,LucideBotMessageSquare:lfe,LucideBotOff:cfe,LucideBox:TQ,LucideBoxSelect:aR,LucideBoxes:dfe,LucideBraces:h6,LucideBrackets:ufe,LucideBrain:MQ,LucideBrainCircuit:hfe,LucideBrainCog:mfe,LucideBrickWall:pfe,LucideBriefcase:Px,LucideBriefcaseBusiness:ffe,LucideBriefcaseConveyorBelt:xfe,LucideBriefcaseMedical:gfe,LucideBringToFront:yfe,LucideBrush:vfe,LucideBug:wfe,LucideBugOff:bfe,LucideBugPlay:_fe,LucideBuilding:sP,LucideBuilding2:oi,LucideBus:Nfe,LucideBusFront:jfe,LucideCable:Sfe,LucideCableCar:kfe,LucideCake:Hf,LucideCakeSlice:Cfe,LucideCalculator:pj,LucideCalendar:ya,LucideCalendar1:Afe,LucideCalendarArrowDown:Efe,LucideCalendarArrowUp:Tfe,LucideCalendarCheck:_v,LucideCalendarCheck2:Mfe,LucideCalendarClock:Ud,LucideCalendarCog:Pfe,LucideCalendarDays:gc,LucideCalendarFold:Lfe,LucideCalendarHeart:xS,LucideCalendarMinus:Dfe,LucideCalendarMinus2:Ife,LucideCalendarOff:RU,LucideCalendarPlus:v0,LucideCalendarPlus2:Rfe,LucideCalendarRange:Ffe,LucideCalendarSearch:Ofe,LucideCalendarSync:zfe,LucideCalendarX:PQ,LucideCalendarX2:Bfe,LucideCamera:Lx,LucideCameraOff:$fe,LucideCandlestickChart:d8,LucideCandy:Vfe,LucideCandyCane:Ufe,LucideCandyOff:qfe,LucideCannabis:Hfe,LucideCaptions:i8,LucideCaptionsOff:Gfe,LucideCar:Yfe,LucideCarFront:Wfe,LucideCarTaxiFront:Kfe,LucideCaravan:Zfe,LucideCarrot:Xfe,LucideCaseLower:Qfe,LucideCaseSensitive:Jfe,LucideCaseUpper:exe,LucideCassetteTape:txe,LucideCast:sxe,LucideCastle:nxe,LucideCat:rxe,LucideCctv:axe,LucideChartArea:o8,LucideChartBar:c8,LucideChartBarBig:l8,LucideChartBarDecreasing:ixe,LucideChartBarIncreasing:oxe,LucideChartBarStacked:lxe,LucideChartCandlestick:d8,LucideChartColumn:wl,LucideChartColumnBig:u8,LucideChartColumnDecreasing:cxe,LucideChartColumnIncreasing:h8,LucideChartColumnStacked:dxe,LucideChartGantt:uxe,LucideChartLine:m8,LucideChartNetwork:hxe,LucideChartNoAxesColumn:f8,LucideChartNoAxesColumnDecreasing:mxe,LucideChartNoAxesColumnIncreasing:p8,LucideChartNoAxesCombined:pxe,LucideChartNoAxesGantt:x8,LucideChartPie:g8,LucideChartScatter:y8,LucideChartSpline:fxe,LucideCheck:Wr,LucideCheckCheck:e7,LucideCheckCircle:Xl,LucideCheckCircle2:Mr,LucideCheckSquare:Zw,LucideCheckSquare2:XD,LucideChefHat:xxe,LucideCherry:gxe,LucideChevronDown:cl,LucideChevronDownCircle:C8,LucideChevronDownSquare:QD,LucideChevronFirst:yxe,LucideChevronLast:vxe,LucideChevronLeft:Wc,LucideChevronLeftCircle:A8,LucideChevronLeftSquare:JD,LucideChevronRight:yi,LucideChevronRightCircle:E8,LucideChevronRightSquare:eR,LucideChevronUp:h1,LucideChevronUpCircle:T8,LucideChevronUpSquare:tR,LucideChevronsDown:_xe,LucideChevronsDownUp:bxe,LucideChevronsLeft:Nxe,LucideChevronsLeftRight:jxe,LucideChevronsLeftRightEllipsis:wxe,LucideChevronsRight:Sxe,LucideChevronsRightLeft:kxe,LucideChevronsUp:Cxe,LucideChevronsUpDown:R_,LucideChrome:t7,LucideChurch:Axe,LucideCigarette:Txe,LucideCigaretteOff:Exe,LucideCircle:Gf,LucideCircleAlert:Ho,LucideCircleArrowDown:v8,LucideCircleArrowLeft:b8,LucideCircleArrowOutDownLeft:_8,LucideCircleArrowOutDownRight:w8,LucideCircleArrowOutUpLeft:j8,LucideCircleArrowOutUpRight:N8,LucideCircleArrowRight:k8,LucideCircleArrowUp:S8,LucideCircleCheck:Mr,LucideCircleCheckBig:Xl,LucideCircleChevronDown:C8,LucideCircleChevronLeft:A8,LucideCircleChevronRight:E8,LucideCircleChevronUp:T8,LucideCircleDashed:Mxe,LucideCircleDivide:M8,LucideCircleDollarSign:Pxe,LucideCircleDot:Ixe,LucideCircleDotDashed:Lxe,LucideCircleEllipsis:Dxe,LucideCircleEqual:Rxe,LucideCircleFadingArrowUp:Fxe,LucideCircleFadingPlus:Oxe,LucideCircleGauge:P8,LucideCircleHelp:v4,LucideCircleMinus:L8,LucideCircleOff:zxe,LucideCircleParking:D8,LucideCircleParkingOff:I8,LucideCirclePause:R8,LucideCirclePercent:F8,LucideCirclePlay:dm,LucideCirclePlus:O8,LucideCirclePower:z8,LucideCircleSlash:Bxe,LucideCircleSlash2:B8,LucideCircleSlashed:B8,LucideCircleStop:$8,LucideCircleUser:q8,LucideCircleUserRound:U8,LucideCircleX:Bd,LucideCircuitBoard:$xe,LucideCitrus:Uxe,LucideClapperboard:FU,LucideClipboard:Yxe,LucideClipboardCheck:fN,LucideClipboardCopy:qxe,LucideClipboardEdit:H8,LucideClipboardList:Wf,LucideClipboardMinus:Vxe,LucideClipboardPaste:Hxe,LucideClipboardPen:H8,LucideClipboardPenLine:V8,LucideClipboardPlus:Gxe,LucideClipboardSignature:V8,LucideClipboardType:Wxe,LucideClipboardX:Kxe,LucideClock:Zr,LucideClock1:Zxe,LucideClock10:Xxe,LucideClock11:Qxe,LucideClock12:Jxe,LucideClock2:ege,LucideClock3:OU,LucideClock4:tge,LucideClock5:sge,LucideClock6:nge,LucideClock7:rge,LucideClock8:age,LucideClock9:ige,LucideClockAlert:oge,LucideClockArrowDown:lge,LucideClockArrowUp:cge,LucideCloud:Nge,LucideCloudAlert:dge,LucideCloudCog:uge,LucideCloudDownload:G8,LucideCloudDrizzle:hge,LucideCloudFog:mge,LucideCloudHail:pge,LucideCloudLightning:fge,LucideCloudMoon:gge,LucideCloudMoonRain:xge,LucideCloudOff:yge,LucideCloudRain:bge,LucideCloudRainWind:vge,LucideCloudSnow:_ge,LucideCloudSun:jge,LucideCloudSunRain:wge,LucideCloudUpload:m6,LucideCloudy:kge,LucideClover:FA,LucideClub:Sge,LucideCode:GA,LucideCode2:b4,LucideCodeSquare:sR,LucideCodeXml:b4,LucideCodepen:Cge,LucideCodesandbox:Age,LucideCoffee:Y4,LucideCog:Ege,LucideCoins:LQ,LucideColumns:W8,LucideColumns2:W8,LucideColumns3:p6,LucideColumns4:Tge,LucideCombine:Mge,LucideCommand:Pge,LucideCompass:s7,LucideComponent:Lge,LucideComputer:Ige,LucideConciergeBell:Dge,LucideCone:Rge,LucideConstruction:Fge,LucideContact:nP,LucideContact2:K8,LucideContactRound:K8,LucideContainer:Oge,LucideContrast:zge,LucideCookie:Bge,LucideCookingPot:$ge,LucideCopy:Sa,LucideCopyCheck:Uge,LucideCopyMinus:qge,LucideCopyPlus:Vge,LucideCopySlash:Hge,LucideCopyX:Gge,LucideCopyleft:Wge,LucideCopyright:Kge,LucideCornerDownLeft:Yge,LucideCornerDownRight:IQ,LucideCornerLeftDown:Zge,LucideCornerLeftUp:Xge,LucideCornerRightDown:Qge,LucideCornerRightUp:Jge,LucideCornerUpLeft:eye,LucideCornerUpRight:tye,LucideCpu:sye,LucideCreativeCommons:nye,LucideCreditCard:j0,LucideCroissant:rye,LucideCrop:aye,LucideCross:iye,LucideCrosshair:oye,LucideCrown:Kf,LucideCuboid:lye,LucideCupSoda:cye,LucideCurlyBraces:h6,LucideCurrency:dye,LucideCylinder:uye,LucideDam:hye,LucideDatabase:zU,LucideDatabaseBackup:mye,LucideDatabaseZap:pye,LucideDelete:fye,LucideDessert:xye,LucideDiameter:gye,LucideDiamond:bye,LucideDiamondMinus:yye,LucideDiamondPercent:Y8,LucideDiamondPlus:vye,LucideDice1:_ye,LucideDice2:wye,LucideDice3:jye,LucideDice4:Nye,LucideDice5:kye,LucideDice6:Sye,LucideDices:Cye,LucideDiff:Aye,LucideDisc:Pye,LucideDisc2:Eye,LucideDisc3:Tye,LucideDiscAlbum:Mye,LucideDivide:Lye,LucideDivideCircle:M8,LucideDivideSquare:iR,LucideDna:Dye,LucideDnaOff:Iye,LucideDock:Rye,LucideDog:Fye,LucideDollarSign:Nd,LucideDonut:Oye,LucideDoorClosed:zye,LucideDoorOpen:fj,LucideDot:Bye,LucideDotSquare:oR,LucideDownload:Ga,LucideDownloadCloud:G8,LucideDraftingCompass:$ye,LucideDrama:Uye,LucideDribbble:qye,LucideDrill:Vye,LucideDroplet:Hye,LucideDroplets:m1,LucideDrum:Gye,LucideDrumstick:Wye,LucideDumbbell:Kye,LucideEar:Zye,LucideEarOff:Yye,LucideEarth:K2,LucideEarthLock:Xye,LucideEclipse:Qye,LucideEdit:Cp,LucideEdit2:Y2,LucideEdit3:Mm,LucideEgg:BU,LucideEggFried:Jye,LucideEggOff:e0e,LucideEllipsis:lb,LucideEllipsisVertical:ng,LucideEqual:n0e,LucideEqualApproximately:t0e,LucideEqualNot:s0e,LucideEqualSquare:lR,LucideEraser:$U,LucideEthernetPort:r0e,LucideEuro:a0e,LucideExpand:i0e,LucideExternalLink:mr,LucideEye:xa,LucideEyeClosed:o0e,LucideEyeOff:Yf,LucideFacebook:of,LucideFactory:l0e,LucideFan:c0e,LucideFastForward:d0e,LucideFeather:u0e,LucideFence:h0e,LucideFerrisWheel:m0e,LucideFigma:p0e,LucideFile:qU,LucideFileArchive:f0e,LucideFileAudio:g0e,LucideFileAudio2:x0e,LucideFileAxis3D:Z8,LucideFileAxis3d:Z8,LucideFileBadge:v0e,LucideFileBadge2:y0e,LucideFileBarChart:X8,LucideFileBarChart2:Q8,LucideFileBox:b0e,LucideFileChartColumn:Q8,LucideFileChartColumnIncreasing:X8,LucideFileChartLine:J8,LucideFileChartPie:eD,LucideFileCheck:DQ,LucideFileCheck2:n7,LucideFileClock:_0e,LucideFileCode:j0e,LucideFileCode2:w0e,LucideFileCog:tD,LucideFileCog2:tD,LucideFileDiff:N0e,LucideFileDigit:k0e,LucideFileDown:xj,LucideFileEdit:sD,LucideFileHeart:S0e,LucideFileImage:rP,LucideFileInput:C0e,LucideFileJson:E0e,LucideFileJson2:A0e,LucideFileKey:M0e,LucideFileKey2:T0e,LucideFileLineChart:J8,LucideFileLock:L0e,LucideFileLock2:P0e,LucideFileMinus:D0e,LucideFileMinus2:I0e,LucideFileMusic:R0e,LucideFileOutput:F0e,LucideFilePen:sD,LucideFilePenLine:cb,LucideFilePieChart:eD,LucideFilePlus:O0e,LucideFilePlus2:UU,LucideFileQuestion:z0e,LucideFileScan:B0e,LucideFileSearch:RQ,LucideFileSearch2:$0e,LucideFileSignature:cb,LucideFileSliders:U0e,LucideFileSpreadsheet:xN,LucideFileStack:FQ,LucideFileSymlink:q0e,LucideFileTerminal:V0e,LucideFileText:$r,LucideFileType:G0e,LucideFileType2:H0e,LucideFileUp:OQ,LucideFileUser:W0e,LucideFileVideo:zQ,LucideFileVideo2:K0e,LucideFileVolume:Z0e,LucideFileVolume2:Y0e,LucideFileWarning:X0e,LucideFileX:J0e,LucideFileX2:Q0e,LucideFiles:eve,LucideFilm:Yh,LucideFilter:F_,LucideFilterX:tve,LucideFingerprint:sve,LucideFireExtinguisher:nve,LucideFish:ive,LucideFishOff:rve,LucideFishSymbol:ave,LucideFlag:WA,LucideFlagOff:ove,LucideFlagTriangleLeft:lve,LucideFlagTriangleRight:cve,LucideFlame:vu,LucideFlameKindling:dve,LucideFlashlight:hve,LucideFlashlightOff:uve,LucideFlaskConical:Z4,LucideFlaskConicalOff:mve,LucideFlaskRound:pve,LucideFlipHorizontal:BQ,LucideFlipHorizontal2:fve,LucideFlipVertical:gve,LucideFlipVertical2:xve,LucideFlower:yve,LucideFlower2:cS,LucideFocus:vve,LucideFoldHorizontal:bve,LucideFoldVertical:_ve,LucideFolder:VU,LucideFolderArchive:wve,LucideFolderCheck:jve,LucideFolderClock:Nve,LucideFolderClosed:kve,LucideFolderCode:Sve,LucideFolderCog:nD,LucideFolderCog2:nD,LucideFolderDot:Cve,LucideFolderDown:Ave,LucideFolderEdit:rD,LucideFolderGit:Tve,LucideFolderGit2:Eve,LucideFolderHeart:Mve,LucideFolderInput:Pve,LucideFolderKanban:Lve,LucideFolderKey:Ive,LucideFolderLock:Dve,LucideFolderMinus:Rve,LucideFolderOpen:wv,LucideFolderOpenDot:Fve,LucideFolderOutput:Ove,LucideFolderPen:rD,LucideFolderPlus:$Q,LucideFolderRoot:zve,LucideFolderSearch:$ve,LucideFolderSearch2:Bve,LucideFolderSymlink:Uve,LucideFolderSync:qve,LucideFolderTree:Vve,LucideFolderUp:Hve,LucideFolderX:Gve,LucideFolders:Wve,LucideFootprints:Kve,LucideForkKnife:VR,LucideForkKnifeCrossed:qR,LucideForklift:Yve,LucideFormInput:AD,LucideForward:Zve,LucideFrame:Xve,LucideFramer:Qve,LucideFrown:Jve,LucideFuel:e1e,LucideFullscreen:t1e,LucideFunctionSquare:cR,LucideGalleryHorizontal:n1e,LucideGalleryHorizontalEnd:s1e,LucideGalleryThumbnails:r1e,LucideGalleryVertical:i1e,LucideGalleryVerticalEnd:a1e,LucideGamepad:l1e,LucideGamepad2:o1e,LucideGanttChart:x8,LucideGanttChartSquare:F5,LucideGauge:c1e,LucideGaugeCircle:P8,LucideGavel:d1e,LucideGem:u1e,LucideGhost:r7,LucideGift:Ko,LucideGitBranch:m1e,LucideGitBranchPlus:h1e,LucideGitCommit:aD,LucideGitCommitHorizontal:aD,LucideGitCommitVertical:p1e,LucideGitCompare:x1e,LucideGitCompareArrows:f1e,LucideGitFork:g1e,LucideGitGraph:y1e,LucideGitMerge:v1e,LucideGitPullRequest:k1e,LucideGitPullRequestArrow:b1e,LucideGitPullRequestClosed:_1e,LucideGitPullRequestCreate:j1e,LucideGitPullRequestCreateArrow:w1e,LucideGitPullRequestDraft:N1e,LucideGithub:S1e,LucideGitlab:C1e,LucideGlassWater:A1e,LucideGlasses:E1e,LucideGlobe:Wo,LucideGlobe2:K2,LucideGlobeLock:T1e,LucideGoal:M1e,LucideGrab:P1e,LucideGraduationCap:fm,LucideGrape:L1e,LucideGrid:Vw,LucideGrid2X2:oD,LucideGrid2X2Plus:iD,LucideGrid2x2:oD,LucideGrid2x2Check:I1e,LucideGrid2x2Plus:iD,LucideGrid2x2X:D1e,LucideGrid3X3:Vw,LucideGrid3x3:Vw,LucideGrip:F1e,LucideGripHorizontal:R1e,LucideGripVertical:Zf,LucideGroup:O1e,LucideGuitar:z1e,LucideHam:B1e,LucideHammer:UQ,LucideHand:HU,LucideHandCoins:$1e,LucideHandHeart:qQ,LucideHandHelping:_4,LucideHandMetal:U1e,LucideHandPlatter:q1e,LucideHandshake:jv,LucideHardDrive:VQ,LucideHardDriveDownload:V1e,LucideHardDriveUpload:H1e,LucideHardHat:G1e,LucideHash:aP,LucideHaze:W1e,LucideHdmiPort:K1e,LucideHeading:Q1e,LucideHeading1:GU,LucideHeading2:a7,LucideHeading3:WU,LucideHeading4:Y1e,LucideHeading5:Z1e,LucideHeading6:X1e,LucideHeadphoneOff:J1e,LucideHeadphones:ebe,LucideHeadset:tbe,LucideHeart:Fo,LucideHeartCrack:sbe,LucideHeartHandshake:HQ,LucideHeartOff:nbe,LucideHeartPulse:rbe,LucideHeater:abe,LucideHelpCircle:v4,LucideHelpingHand:_4,LucideHexagon:ibe,LucideHighlighter:obe,LucideHistory:O_,LucideHome:sa,LucideHop:cbe,LucideHopOff:lbe,LucideHospital:dbe,LucideHotel:ube,LucideHourglass:GQ,LucideHouse:sa,LucideHousePlug:hbe,LucideHousePlus:mbe,LucideIceCream:cD,LucideIceCream2:lD,LucideIceCreamBowl:lD,LucideIceCreamCone:cD,LucideIdCard:WQ,LucideImage:nc,LucideImageDown:pbe,LucideImageMinus:fbe,LucideImageOff:xbe,LucideImagePlay:gbe,LucideImagePlus:N0,LucideImageUp:ybe,LucideImageUpscale:vbe,LucideImages:bbe,LucideImport:_be,LucideInbox:i7,LucideIndent:uD,LucideIndentDecrease:dD,LucideIndentIncrease:uD,LucideIndianRupee:wbe,LucideInfinity:KU,LucideInfo:gS,LucideInspect:fR,LucideInspectionPanel:jbe,LucideInstagram:Fm,LucideItalic:KA,LucideIterationCcw:Nbe,LucideIterationCw:kbe,LucideJapaneseYen:Sbe,LucideJoystick:Cbe,LucideKanban:gj,LucideKanbanSquare:dR,LucideKanbanSquareDashed:nR,LucideKey:wb,LucideKeyRound:iP,LucideKeySquare:Abe,LucideKeyboard:Mbe,LucideKeyboardMusic:Ebe,LucideKeyboardOff:Tbe,LucideLamp:Fbe,LucideLampCeiling:Pbe,LucideLampDesk:Lbe,LucideLampFloor:Ibe,LucideLampWallDown:Dbe,LucideLampWallUp:Rbe,LucideLandPlot:Obe,LucideLandmark:YU,LucideLanguages:zbe,LucideLaptop:$be,LucideLaptop2:hD,LucideLaptopMinimal:hD,LucideLaptopMinimalCheck:Bbe,LucideLasso:qbe,LucideLassoSelect:Ube,LucideLaugh:Vbe,LucideLayers:X4,LucideLayers2:Hbe,LucideLayers3:Gbe,LucideLayout:tA,LucideLayoutDashboard:oP,LucideLayoutGrid:op,LucideLayoutList:Wbe,LucideLayoutPanelLeft:Kbe,LucideLayoutPanelTop:Ybe,LucideLayoutTemplate:yj,LucideLeaf:Zbe,LucideLeafyGreen:Xbe,LucideLectern:Qbe,LucideLetterText:Jbe,LucideLibrary:vj,LucideLibraryBig:e_e,LucideLibrarySquare:uR,LucideLifeBuoy:ZU,LucideLigature:t_e,LucideLightbulb:yS,LucideLightbulbOff:s_e,LucideLineChart:m8,LucideLink:Kc,LucideLink2:Oc,LucideLink2Off:n_e,LucideLinkedin:fg,LucideList:My,LucideListCheck:r_e,LucideListChecks:k0,LucideListCollapse:a_e,LucideListEnd:i_e,LucideListFilter:KQ,LucideListMinus:o_e,LucideListMusic:l_e,LucideListOrdered:bj,LucideListPlus:YQ,LucideListRestart:c_e,LucideListStart:d_e,LucideListTodo:u_e,LucideListTree:h_e,LucideListVideo:m_e,LucideListX:p_e,LucideLoader:x_e,LucideLoader2:bt,LucideLoaderCircle:bt,LucideLoaderPinwheel:f_e,LucideLocate:XU,LucideLocateFixed:g_e,LucideLocateOff:y_e,LucideLock:Hl,LucideLockKeyhole:ZQ,LucideLockKeyholeOpen:mD,LucideLockOpen:pD,LucideLogIn:lP,LucideLogOut:o7,LucideLogs:v_e,LucideLollipop:b_e,LucideLuggage:__e,LucideMSquare:hR,LucideMagnet:w_e,LucideMail:on,LucideMailCheck:l7,LucideMailMinus:j_e,LucideMailOpen:QU,LucideMailPlus:JU,LucideMailQuestion:N_e,LucideMailSearch:k_e,LucideMailWarning:S_e,LucideMailX:cP,LucideMailbox:C_e,LucideMails:A_e,LucideMap:c7,LucideMapPin:Ha,LucideMapPinCheck:T_e,LucideMapPinCheckInside:E_e,LucideMapPinHouse:M_e,LucideMapPinMinus:L_e,LucideMapPinMinusInside:P_e,LucideMapPinOff:I_e,LucideMapPinPlus:R_e,LucideMapPinPlusInside:D_e,LucideMapPinX:O_e,LucideMapPinXInside:F_e,LucideMapPinned:XQ,LucideMartini:z_e,LucideMaximize:d7,LucideMaximize2:QQ,LucideMedal:YA,LucideMegaphone:Nh,LucideMegaphoneOff:B_e,LucideMeh:$_e,LucideMemoryStick:U_e,LucideMenu:ZA,LucideMenuSquare:mR,LucideMerge:u7,LucideMessageCircle:Bu,LucideMessageCircleCode:q_e,LucideMessageCircleDashed:V_e,LucideMessageCircleHeart:eq,LucideMessageCircleMore:H_e,LucideMessageCircleOff:G_e,LucideMessageCirclePlus:W_e,LucideMessageCircleQuestion:JQ,LucideMessageCircleReply:K_e,LucideMessageCircleWarning:Y_e,LucideMessageCircleX:Z_e,LucideMessageSquare:qi,LucideMessageSquareCode:X_e,LucideMessageSquareDashed:Q_e,LucideMessageSquareDiff:J_e,LucideMessageSquareDot:ewe,LucideMessageSquareHeart:twe,LucideMessageSquareLock:swe,LucideMessageSquareMore:eJ,LucideMessageSquareOff:nwe,LucideMessageSquarePlus:I4,LucideMessageSquareQuote:XA,LucideMessageSquareReply:tJ,LucideMessageSquareShare:rwe,LucideMessageSquareText:awe,LucideMessageSquareWarning:sJ,LucideMessageSquareX:iwe,LucideMessagesSquare:nJ,LucideMic:h7,LucideMic2:fD,LucideMicOff:owe,LucideMicVocal:fD,LucideMicrochip:lwe,LucideMicroscope:cwe,LucideMicrowave:dwe,LucideMilestone:uwe,LucideMilk:mwe,LucideMilkOff:hwe,LucideMinimize:fwe,LucideMinimize2:pwe,LucideMinus:gN,LucideMinusCircle:L8,LucideMinusSquare:pR,LucideMonitor:yN,LucideMonitorCheck:xwe,LucideMonitorCog:gwe,LucideMonitorDot:ywe,LucideMonitorDown:vwe,LucideMonitorOff:bwe,LucideMonitorPause:_we,LucideMonitorPlay:tq,LucideMonitorSmartphone:wwe,LucideMonitorSpeaker:jwe,LucideMonitorStop:Nwe,LucideMonitorUp:m7,LucideMonitorX:kwe,LucideMoon:Cwe,LucideMoonStar:Swe,LucideMoreHorizontal:lb,LucideMoreVertical:ng,LucideMountain:Ewe,LucideMountainSnow:Awe,LucideMouse:Pwe,LucideMouseOff:Twe,LucideMousePointer:wy,LucideMousePointer2:rJ,LucideMousePointerBan:Mwe,LucideMousePointerClick:Gh,LucideMousePointerSquareDashed:rR,LucideMove:aJ,LucideMove3D:xD,LucideMove3d:xD,LucideMoveDiagonal:Iwe,LucideMoveDiagonal2:Lwe,LucideMoveDown:Fwe,LucideMoveDownLeft:Dwe,LucideMoveDownRight:Rwe,LucideMoveHorizontal:Owe,LucideMoveLeft:zwe,LucideMoveRight:Bwe,LucideMoveUp:qwe,LucideMoveUpLeft:$we,LucideMoveUpRight:Uwe,LucideMoveVertical:Vwe,LucideMusic:sq,LucideMusic2:Hwe,LucideMusic3:Gwe,LucideMusic4:Wwe,LucideNavigation:iJ,LucideNavigation2:Ywe,LucideNavigation2Off:Kwe,LucideNavigationOff:Zwe,LucideNetwork:Xwe,LucideNewspaper:vN,LucideNfc:Qwe,LucideNotebook:sje,LucideNotebookPen:Jwe,LucideNotebookTabs:eje,LucideNotebookText:tje,LucideNotepadText:rje,LucideNotepadTextDashed:nje,LucideNut:ije,LucideNutOff:aje,LucideOctagon:lje,LucideOctagonAlert:nS,LucideOctagonMinus:oje,LucideOctagonPause:gD,LucideOctagonX:yD,LucideOmega:cje,LucideOption:dje,LucideOrbit:uje,LucideOrigami:hje,LucideOutdent:dD,LucidePackage:Sh,LucidePackage2:mje,LucidePackageCheck:pje,LucidePackageMinus:fje,LucidePackageOpen:xje,LucidePackagePlus:gje,LucidePackageSearch:yje,LucidePackageX:vje,LucidePaintBucket:bje,LucidePaintRoller:_je,LucidePaintbrush:wje,LucidePaintbrush2:vD,LucidePaintbrushVertical:vD,LucidePalette:yc,LucidePalmtree:RR,LucidePanelBottom:kje,LucidePanelBottomClose:jje,LucidePanelBottomDashed:bD,LucidePanelBottomInactive:bD,LucidePanelBottomOpen:Nje,LucidePanelLeft:ND,LucidePanelLeftClose:_D,LucidePanelLeftDashed:wD,LucidePanelLeftInactive:wD,LucidePanelLeftOpen:jD,LucidePanelRight:Aje,LucidePanelRightClose:Sje,LucidePanelRightDashed:kD,LucidePanelRightInactive:kD,LucidePanelRightOpen:Cje,LucidePanelTop:Mje,LucidePanelTopClose:Eje,LucidePanelTopDashed:SD,LucidePanelTopInactive:SD,LucidePanelTopOpen:Tje,LucidePanelsLeftBottom:Pje,LucidePanelsLeftRight:p6,LucidePanelsRightBottom:Lje,LucidePanelsTopBottom:MD,LucidePanelsTopLeft:tA,LucidePaperclip:dP,LucideParentheses:Ije,LucideParkingCircle:D8,LucideParkingCircleOff:I8,LucideParkingMeter:Dje,LucideParkingSquare:gR,LucideParkingSquareOff:xR,LucidePartyPopper:Ix,LucidePause:S0,LucidePauseCircle:R8,LucidePauseOctagon:gD,LucidePawPrint:Rje,LucidePcCase:Fje,LucidePen:Y2,LucidePenBox:Cp,LucidePenLine:Mm,LucidePenOff:Oje,LucidePenSquare:Cp,LucidePenTool:QA,LucidePencil:Wa,LucidePencilLine:nq,LucidePencilOff:zje,LucidePencilRuler:Bje,LucidePentagon:$je,LucidePercent:z_,LucidePercentCircle:F8,LucidePercentDiamond:Y8,LucidePercentSquare:yR,LucidePersonStanding:Uje,LucidePhilippinePeso:qje,LucidePhone:va,LucidePhoneCall:oJ,LucidePhoneForwarded:Vje,LucidePhoneIncoming:Hje,LucidePhoneMissed:Gje,LucidePhoneOff:Wje,LucidePhoneOutgoing:Kje,LucidePi:Yje,LucidePiSquare:vR,LucidePiano:Zje,LucidePickaxe:Xje,LucidePictureInPicture:Jje,LucidePictureInPicture2:Qje,LucidePieChart:g8,LucidePiggyBank:lJ,LucidePilcrow:s2e,LucidePilcrowLeft:e2e,LucidePilcrowRight:t2e,LucidePilcrowSquare:bR,LucidePill:r2e,LucidePillBottle:n2e,LucidePin:JA,LucidePinOff:cJ,LucidePipette:a2e,LucidePizza:i2e,LucidePlane:dJ,LucidePlaneLanding:o2e,LucidePlaneTakeoff:l2e,LucidePlay:su,LucidePlayCircle:dm,LucidePlaySquare:_R,LucidePlug:_j,LucidePlug2:c2e,LucidePlugZap:CD,LucidePlugZap2:CD,LucidePlus:sn,LucidePlusCircle:O8,LucidePlusSquare:wR,LucidePocket:u2e,LucidePocketKnife:d2e,LucidePodcast:h2e,LucidePointer:p2e,LucidePointerOff:m2e,LucidePopcorn:f2e,LucidePopsicle:x2e,LucidePoundSterling:g2e,LucidePower:uJ,LucidePowerCircle:z8,LucidePowerOff:y2e,LucidePowerSquare:jR,LucidePresentation:C0,LucidePrinter:eE,LucidePrinterCheck:v2e,LucideProjector:b2e,LucideProportions:_2e,LucidePuzzle:w2e,LucidePyramid:j2e,LucideQrCode:lf,LucideQuote:wj,LucideRabbit:N2e,LucideRadar:rq,LucideRadiation:k2e,LucideRadical:S2e,LucideRadio:Nv,LucideRadioReceiver:C2e,LucideRadioTower:A2e,LucideRadius:E2e,LucideRailSymbol:T2e,LucideRainbow:M2e,LucideRat:P2e,LucideRatio:L2e,LucideReceipt:aq,LucideReceiptCent:I2e,LucideReceiptEuro:D2e,LucideReceiptIndianRupee:R2e,LucideReceiptJapaneseYen:F2e,LucideReceiptPoundSterling:O2e,LucideReceiptRussianRuble:z2e,LucideReceiptSwissFranc:B2e,LucideReceiptText:$2e,LucideRectangleEllipsis:AD,LucideRectangleHorizontal:U2e,LucideRectangleVertical:q2e,LucideRecycle:V2e,LucideRedo:tE,LucideRedo2:H2e,LucideRedoDot:G2e,LucideRefreshCcw:iq,LucideRefreshCcwDot:W2e,LucideRefreshCw:Gi,LucideRefreshCwOff:K2e,LucideRefrigerator:Y2e,LucideRegex:Z2e,LucideRemoveFormatting:X2e,LucideRepeat:sE,LucideRepeat1:Q2e,LucideRepeat2:hJ,LucideReplace:eNe,LucideReplaceAll:J2e,LucideReply:oq,LucideReplyAll:tNe,LucideRewind:sNe,LucideRibbon:nNe,LucideRocket:Xf,LucideRockingChair:rNe,LucideRollerCoaster:aNe,LucideRotate3D:ED,LucideRotate3d:ED,LucideRotateCcw:Dx,LucideRotateCcwSquare:iNe,LucideRotateCw:p7,LucideRotateCwSquare:oNe,LucideRoute:lq,LucideRouteOff:lNe,LucideRouter:cNe,LucideRows:TD,LucideRows2:TD,LucideRows3:MD,LucideRows4:dNe,LucideRss:uNe,LucideRuler:Q4,LucideRussianRuble:hNe,LucideSailboat:mNe,LucideSalad:pNe,LucideSandwich:fNe,LucideSatellite:gNe,LucideSatelliteDish:xNe,LucideSave:Bo,LucideSaveAll:yNe,LucideSaveOff:vNe,LucideScale:bNe,LucideScale3D:PD,LucideScale3d:PD,LucideScaling:_Ne,LucideScan:ENe,LucideScanBarcode:wNe,LucideScanEye:jNe,LucideScanFace:NNe,LucideScanLine:kNe,LucideScanQrCode:SNe,LucideScanSearch:CNe,LucideScanText:ANe,LucideScatterChart:y8,LucideSchool:TNe,LucideSchool2:OR,LucideScissors:PNe,LucideScissorsLineDashed:MNe,LucideScissorsSquare:NR,LucideScissorsSquareDashedBottom:ZD,LucideScreenShare:INe,LucideScreenShareOff:LNe,LucideScroll:DNe,LucideScrollText:cq,LucideSearch:Rr,LucideSearchCheck:RNe,LucideSearchCode:FNe,LucideSearchSlash:ONe,LucideSearchX:dq,LucideSection:zNe,LucideSend:Fr,LucideSendHorizonal:LD,LucideSendHorizontal:LD,LucideSendToBack:BNe,LucideSeparatorHorizontal:$Ne,LucideSeparatorVertical:UNe,LucideServer:GNe,LucideServerCog:qNe,LucideServerCrash:VNe,LucideServerOff:HNe,LucideSettings:Gc,LucideSettings2:vS,LucideShapes:WNe,LucideShare:mJ,LucideShare2:sd,LucideSheet:KNe,LucideShell:YNe,LucideShield:Om,LucideShieldAlert:uq,LucideShieldBan:ZNe,LucideShieldCheck:Ch,LucideShieldClose:ID,LucideShieldEllipsis:XNe,LucideShieldHalf:QNe,LucideShieldMinus:JNe,LucideShieldOff:f7,LucideShieldPlus:eke,LucideShieldQuestion:x7,LucideShieldX:ID,LucideShip:ske,LucideShipWheel:tke,LucideShirt:nke,LucideShoppingBag:J4,LucideShoppingBasket:rke,LucideShoppingCart:bS,LucideShovel:ake,LucideShowerHead:ike,LucideShrink:oke,LucideShrub:lke,LucideShuffle:g7,LucideSidebar:ND,LucideSidebarClose:_D,LucideSidebarOpen:jD,LucideSigma:cke,LucideSigmaSquare:kR,LucideSignal:pke,LucideSignalHigh:dke,LucideSignalLow:uke,LucideSignalMedium:hke,LucideSignalZero:mke,LucideSignature:fke,LucideSignpost:pJ,LucideSignpostBig:xke,LucideSiren:gke,LucideSkipBack:yke,LucideSkipForward:fJ,LucideSkull:vke,LucideSlack:bke,LucideSlash:_ke,LucideSlashSquare:SR,LucideSlice:wke,LucideSliders:DD,LucideSlidersHorizontal:uP,LucideSlidersVertical:DD,LucideSmartphone:p1,LucideSmartphoneCharging:jke,LucideSmartphoneNfc:Nke,LucideSmile:Ske,LucideSmilePlus:kke,LucideSnail:Cke,LucideSnowflake:aj,LucideSofa:hq,LucideSortAsc:e8,LucideSortDesc:XI,LucideSoup:Ake,LucideSpace:Eke,LucideSpade:Tke,LucideSparkle:hP,LucideSparkles:un,LucideSpeaker:Mke,LucideSpeech:Pke,LucideSpellCheck:Ike,LucideSpellCheck2:Lke,LucideSpline:Dke,LucideSplit:Rke,LucideSplitSquareHorizontal:CR,LucideSplitSquareVertical:AR,LucideSprayCan:Fke,LucideSprout:mP,LucideSquare:jb,LucideSquareActivity:RD,LucideSquareArrowDown:zD,LucideSquareArrowDownLeft:FD,LucideSquareArrowDownRight:OD,LucideSquareArrowLeft:BD,LucideSquareArrowOutDownLeft:$D,LucideSquareArrowOutDownRight:UD,LucideSquareArrowOutUpLeft:qD,LucideSquareArrowOutUpRight:VD,LucideSquareArrowRight:HD,LucideSquareArrowUp:KD,LucideSquareArrowUpLeft:GD,LucideSquareArrowUpRight:WD,LucideSquareAsterisk:YD,LucideSquareBottomDashedScissors:ZD,LucideSquareChartGantt:F5,LucideSquareCheck:XD,LucideSquareCheckBig:Zw,LucideSquareChevronDown:QD,LucideSquareChevronLeft:JD,LucideSquareChevronRight:eR,LucideSquareChevronUp:tR,LucideSquareCode:sR,LucideSquareDashed:aR,LucideSquareDashedBottom:zke,LucideSquareDashedBottomCode:Oke,LucideSquareDashedKanban:nR,LucideSquareDashedMousePointer:rR,LucideSquareDivide:iR,LucideSquareDot:oR,LucideSquareEqual:lR,LucideSquareFunction:cR,LucideSquareGanttChart:F5,LucideSquareKanban:dR,LucideSquareLibrary:uR,LucideSquareM:hR,LucideSquareMenu:mR,LucideSquareMinus:pR,LucideSquareMousePointer:fR,LucideSquareParking:gR,LucideSquareParkingOff:xR,LucideSquarePen:Cp,LucideSquarePercent:yR,LucideSquarePi:vR,LucideSquarePilcrow:bR,LucideSquarePlay:_R,LucideSquarePlus:wR,LucideSquarePower:jR,LucideSquareRadical:Bke,LucideSquareScissors:NR,LucideSquareSigma:kR,LucideSquareSlash:SR,LucideSquareSplitHorizontal:CR,LucideSquareSplitVertical:AR,LucideSquareSquare:$ke,LucideSquareStack:Uke,LucideSquareTerminal:ER,LucideSquareUser:MR,LucideSquareUserRound:TR,LucideSquareX:PR,LucideSquircle:qke,LucideSquirrel:Vke,LucideStamp:Hke,LucideStar:Ia,LucideStarHalf:Gke,LucideStarOff:Wke,LucideStars:un,LucideStepBack:Kke,LucideStepForward:Yke,LucideStethoscope:Zke,LucideSticker:Xke,LucideStickyNote:y7,LucideStopCircle:$8,LucideStore:mq,LucideStretchHorizontal:Qke,LucideStretchVertical:Jke,LucideStrikethrough:xJ,LucideSubscript:eSe,LucideSubtitles:i8,LucideSun:bN,LucideSunDim:tSe,LucideSunMedium:sSe,LucideSunMoon:nSe,LucideSunSnow:rSe,LucideSunrise:aSe,LucideSunset:iSe,LucideSuperscript:oSe,LucideSwatchBook:lSe,LucideSwissFranc:cSe,LucideSwitchCamera:dSe,LucideSword:uSe,LucideSwords:hSe,LucideSyringe:mSe,LucideTable:fq,LucideTable2:pq,LucideTableCellsMerge:pSe,LucideTableCellsSplit:fSe,LucideTableColumnsSplit:xSe,LucideTableOfContents:gSe,LucideTableProperties:ySe,LucideTableRowsSplit:vSe,LucideTablet:xq,LucideTabletSmartphone:bSe,LucideTablets:_Se,LucideTag:Ip,LucideTags:gJ,LucideTally1:wSe,LucideTally2:jSe,LucideTally3:NSe,LucideTally4:kSe,LucideTally5:SSe,LucideTangent:CSe,LucideTarget:bu,LucideTelescope:ASe,LucideTent:TSe,LucideTentTree:ESe,LucideTerminal:MSe,LucideTerminalSquare:ER,LucideTestTube:PSe,LucideTestTube2:LR,LucideTestTubeDiagonal:LR,LucideTestTubes:LSe,LucideText:FSe,LucideTextCursor:ISe,LucideTextCursorInput:gq,LucideTextQuote:DSe,LucideTextSearch:RSe,LucideTextSelect:IR,LucideTextSelection:IR,LucideTheater:OSe,LucideThermometer:$Se,LucideThermometerSnowflake:zSe,LucideThermometerSun:BSe,LucideThumbsDown:yJ,LucideThumbsUp:Ug,LucideTicket:v7,LucideTicketCheck:USe,LucideTicketMinus:qSe,LucideTicketPercent:VSe,LucideTicketPlus:HSe,LucideTicketSlash:GSe,LucideTicketX:WSe,LucideTickets:YSe,LucideTicketsPlane:KSe,LucideTimer:QSe,LucideTimerOff:ZSe,LucideTimerReset:XSe,LucideToggleLeft:JSe,LucideToggleRight:e5e,LucideToilet:t5e,LucideTornado:s5e,LucideTorus:n5e,LucideTouchpad:a5e,LucideTouchpadOff:r5e,LucideTowerControl:i5e,LucideToyBrick:o5e,LucideTractor:l5e,LucideTrafficCone:c5e,LucideTrain:DR,LucideTrainFront:u5e,LucideTrainFrontTunnel:d5e,LucideTrainTrack:h5e,LucideTramFront:DR,LucideTrash:m5e,LucideTrash2:Cn,LucideTreeDeciduous:p5e,LucideTreePalm:RR,LucideTreePine:pP,LucideTrees:f5e,LucideTrello:x5e,LucideTrendingDown:_S,LucideTrendingUp:kl,LucideTrendingUpDown:g5e,LucideTriangle:v5e,LucideTriangleAlert:nl,LucideTriangleRight:y5e,LucideTrophy:jl,LucideTruck:vJ,LucideTurtle:b5e,LucideTv:w5e,LucideTv2:FR,LucideTvMinimal:FR,LucideTvMinimalPlay:_5e,LucideTwitch:j5e,LucideTwitter:bJ,LucideType:yq,LucideTypeOutline:N5e,LucideUmbrella:S5e,LucideUmbrellaOff:k5e,LucideUnderline:b7,LucideUndo:nE,LucideUndo2:_J,LucideUndoDot:C5e,LucideUnfoldHorizontal:A5e,LucideUnfoldVertical:E5e,LucideUngroup:T5e,LucideUniversity:OR,LucideUnlink:rE,LucideUnlink2:M5e,LucideUnlock:pD,LucideUnlockKeyhole:mD,LucideUnplug:_7,LucideUpload:Ra,LucideUploadCloud:m6,LucideUsb:P5e,LucideUser:Oo,LucideUser2:x6,LucideUserCheck:jj,LucideUserCheck2:f6,LucideUserCircle:q8,LucideUserCircle2:U8,LucideUserCog:wJ,LucideUserCog2:zR,LucideUserMinus:vq,LucideUserMinus2:BR,LucideUserPen:L5e,LucideUserPlus:Pl,LucideUserPlus2:$R,LucideUserRound:x6,LucideUserRoundCheck:f6,LucideUserRoundCog:zR,LucideUserRoundMinus:BR,LucideUserRoundPen:I5e,LucideUserRoundPlus:$R,LucideUserRoundSearch:bq,LucideUserRoundX:UR,LucideUserSearch:D5e,LucideUserSquare:MR,LucideUserSquare2:TR,LucideUserX:_q,LucideUserX2:UR,LucideUsers:On,LucideUsers2:vy,LucideUsersRound:vy,LucideUtensils:VR,LucideUtensilsCrossed:qR,LucideUtilityPole:R5e,LucideVariable:wq,LucideVault:F5e,LucideVegan:O5e,LucideVenetianMask:z5e,LucideVerified:eA,LucideVibrate:$5e,LucideVibrateOff:B5e,LucideVideo:Xr,LucideVideoOff:U5e,LucideVideotape:q5e,LucideView:V5e,LucideVoicemail:H5e,LucideVolleyball:G5e,LucideVolume:Y5e,LucideVolume1:W5e,LucideVolume2:jJ,LucideVolumeOff:K5e,LucideVolumeX:NJ,LucideVote:Z5e,LucideWallet:w7,LucideWallet2:HR,LucideWalletCards:X5e,LucideWalletMinimal:HR,LucideWallpaper:Q5e,LucideWand:J5e,LucideWand2:rg,LucideWandSparkles:rg,LucideWarehouse:e4e,LucideWashingMachine:t4e,LucideWatch:s4e,LucideWaves:n4e,LucideWaypoints:r4e,LucideWebcam:a4e,LucideWebhook:o4e,LucideWebhookOff:i4e,LucideWeight:l4e,LucideWheat:d4e,LucideWheatOff:c4e,LucideWholeWord:u4e,LucideWifi:x4e,LucideWifiHigh:h4e,LucideWifiLow:m4e,LucideWifiOff:p4e,LucideWifiZero:f4e,LucideWind:y4e,LucideWindArrowDown:g4e,LucideWine:b4e,LucideWineOff:v4e,LucideWorkflow:j7,LucideWorm:_4e,LucideWrapText:w4e,LucideWrench:eC,LucideX:er,LucideXCircle:Bd,LucideXOctagon:yD,LucideXSquare:PR,LucideYoutube:jq,LucideZap:cf,LucideZapOff:j4e,LucideZoomIn:fP,LucideZoomOut:Nq,Luggage:__e,LuggageIcon:__e,MSquare:hR,MSquareIcon:hR,Magnet:w_e,MagnetIcon:w_e,Mail:on,MailCheck:l7,MailCheckIcon:l7,MailIcon:on,MailMinus:j_e,MailMinusIcon:j_e,MailOpen:QU,MailOpenIcon:QU,MailPlus:JU,MailPlusIcon:JU,MailQuestion:N_e,MailQuestionIcon:N_e,MailSearch:k_e,MailSearchIcon:k_e,MailWarning:S_e,MailWarningIcon:S_e,MailX:cP,MailXIcon:cP,Mailbox:C_e,MailboxIcon:C_e,Mails:A_e,MailsIcon:A_e,Map:c7,MapIcon:c7,MapPin:Ha,MapPinCheck:T_e,MapPinCheckIcon:T_e,MapPinCheckInside:E_e,MapPinCheckInsideIcon:E_e,MapPinHouse:M_e,MapPinHouseIcon:M_e,MapPinIcon:Ha,MapPinMinus:L_e,MapPinMinusIcon:L_e,MapPinMinusInside:P_e,MapPinMinusInsideIcon:P_e,MapPinOff:I_e,MapPinOffIcon:I_e,MapPinPlus:R_e,MapPinPlusIcon:R_e,MapPinPlusInside:D_e,MapPinPlusInsideIcon:D_e,MapPinX:O_e,MapPinXIcon:O_e,MapPinXInside:F_e,MapPinXInsideIcon:F_e,MapPinned:XQ,MapPinnedIcon:XQ,Martini:z_e,MartiniIcon:z_e,Maximize:d7,Maximize2:QQ,Maximize2Icon:QQ,MaximizeIcon:d7,Medal:YA,MedalIcon:YA,Megaphone:Nh,MegaphoneIcon:Nh,MegaphoneOff:B_e,MegaphoneOffIcon:B_e,Meh:$_e,MehIcon:$_e,MemoryStick:U_e,MemoryStickIcon:U_e,Menu:ZA,MenuIcon:ZA,MenuSquare:mR,MenuSquareIcon:mR,Merge:u7,MergeIcon:u7,MessageCircle:Bu,MessageCircleCode:q_e,MessageCircleCodeIcon:q_e,MessageCircleDashed:V_e,MessageCircleDashedIcon:V_e,MessageCircleHeart:eq,MessageCircleHeartIcon:eq,MessageCircleIcon:Bu,MessageCircleMore:H_e,MessageCircleMoreIcon:H_e,MessageCircleOff:G_e,MessageCircleOffIcon:G_e,MessageCirclePlus:W_e,MessageCirclePlusIcon:W_e,MessageCircleQuestion:JQ,MessageCircleQuestionIcon:JQ,MessageCircleReply:K_e,MessageCircleReplyIcon:K_e,MessageCircleWarning:Y_e,MessageCircleWarningIcon:Y_e,MessageCircleX:Z_e,MessageCircleXIcon:Z_e,MessageSquare:qi,MessageSquareCode:X_e,MessageSquareCodeIcon:X_e,MessageSquareDashed:Q_e,MessageSquareDashedIcon:Q_e,MessageSquareDiff:J_e,MessageSquareDiffIcon:J_e,MessageSquareDot:ewe,MessageSquareDotIcon:ewe,MessageSquareHeart:twe,MessageSquareHeartIcon:twe,MessageSquareIcon:qi,MessageSquareLock:swe,MessageSquareLockIcon:swe,MessageSquareMore:eJ,MessageSquareMoreIcon:eJ,MessageSquareOff:nwe,MessageSquareOffIcon:nwe,MessageSquarePlus:I4,MessageSquarePlusIcon:I4,MessageSquareQuote:XA,MessageSquareQuoteIcon:XA,MessageSquareReply:tJ,MessageSquareReplyIcon:tJ,MessageSquareShare:rwe,MessageSquareShareIcon:rwe,MessageSquareText:awe,MessageSquareTextIcon:awe,MessageSquareWarning:sJ,MessageSquareWarningIcon:sJ,MessageSquareX:iwe,MessageSquareXIcon:iwe,MessagesSquare:nJ,MessagesSquareIcon:nJ,Mic:h7,Mic2:fD,Mic2Icon:fD,MicIcon:h7,MicOff:owe,MicOffIcon:owe,MicVocal:fD,MicVocalIcon:fD,Microchip:lwe,MicrochipIcon:lwe,Microscope:cwe,MicroscopeIcon:cwe,Microwave:dwe,MicrowaveIcon:dwe,Milestone:uwe,MilestoneIcon:uwe,Milk:mwe,MilkIcon:mwe,MilkOff:hwe,MilkOffIcon:hwe,Minimize:fwe,Minimize2:pwe,Minimize2Icon:pwe,MinimizeIcon:fwe,Minus:gN,MinusCircle:L8,MinusCircleIcon:L8,MinusIcon:gN,MinusSquare:pR,MinusSquareIcon:pR,Monitor:yN,MonitorCheck:xwe,MonitorCheckIcon:xwe,MonitorCog:gwe,MonitorCogIcon:gwe,MonitorDot:ywe,MonitorDotIcon:ywe,MonitorDown:vwe,MonitorDownIcon:vwe,MonitorIcon:yN,MonitorOff:bwe,MonitorOffIcon:bwe,MonitorPause:_we,MonitorPauseIcon:_we,MonitorPlay:tq,MonitorPlayIcon:tq,MonitorSmartphone:wwe,MonitorSmartphoneIcon:wwe,MonitorSpeaker:jwe,MonitorSpeakerIcon:jwe,MonitorStop:Nwe,MonitorStopIcon:Nwe,MonitorUp:m7,MonitorUpIcon:m7,MonitorX:kwe,MonitorXIcon:kwe,Moon:Cwe,MoonIcon:Cwe,MoonStar:Swe,MoonStarIcon:Swe,MoreHorizontal:lb,MoreHorizontalIcon:lb,MoreVertical:ng,MoreVerticalIcon:ng,Mountain:Ewe,MountainIcon:Ewe,MountainSnow:Awe,MountainSnowIcon:Awe,Mouse:Pwe,MouseIcon:Pwe,MouseOff:Twe,MouseOffIcon:Twe,MousePointer:wy,MousePointer2:rJ,MousePointer2Icon:rJ,MousePointerBan:Mwe,MousePointerBanIcon:Mwe,MousePointerClick:Gh,MousePointerClickIcon:Gh,MousePointerIcon:wy,MousePointerSquareDashed:rR,MousePointerSquareDashedIcon:rR,Move:aJ,Move3D:xD,Move3DIcon:xD,Move3d:xD,Move3dIcon:xD,MoveDiagonal:Iwe,MoveDiagonal2:Lwe,MoveDiagonal2Icon:Lwe,MoveDiagonalIcon:Iwe,MoveDown:Fwe,MoveDownIcon:Fwe,MoveDownLeft:Dwe,MoveDownLeftIcon:Dwe,MoveDownRight:Rwe,MoveDownRightIcon:Rwe,MoveHorizontal:Owe,MoveHorizontalIcon:Owe,MoveIcon:aJ,MoveLeft:zwe,MoveLeftIcon:zwe,MoveRight:Bwe,MoveRightIcon:Bwe,MoveUp:qwe,MoveUpIcon:qwe,MoveUpLeft:$we,MoveUpLeftIcon:$we,MoveUpRight:Uwe,MoveUpRightIcon:Uwe,MoveVertical:Vwe,MoveVerticalIcon:Vwe,Music:sq,Music2:Hwe,Music2Icon:Hwe,Music3:Gwe,Music3Icon:Gwe,Music4:Wwe,Music4Icon:Wwe,MusicIcon:sq,Navigation:iJ,Navigation2:Ywe,Navigation2Icon:Ywe,Navigation2Off:Kwe,Navigation2OffIcon:Kwe,NavigationIcon:iJ,NavigationOff:Zwe,NavigationOffIcon:Zwe,Network:Xwe,NetworkIcon:Xwe,Newspaper:vN,NewspaperIcon:vN,Nfc:Qwe,NfcIcon:Qwe,Notebook:sje,NotebookIcon:sje,NotebookPen:Jwe,NotebookPenIcon:Jwe,NotebookTabs:eje,NotebookTabsIcon:eje,NotebookText:tje,NotebookTextIcon:tje,NotepadText:rje,NotepadTextDashed:nje,NotepadTextDashedIcon:nje,NotepadTextIcon:rje,Nut:ije,NutIcon:ije,NutOff:aje,NutOffIcon:aje,Octagon:lje,OctagonAlert:nS,OctagonAlertIcon:nS,OctagonIcon:lje,OctagonMinus:oje,OctagonMinusIcon:oje,OctagonPause:gD,OctagonPauseIcon:gD,OctagonX:yD,OctagonXIcon:yD,Omega:cje,OmegaIcon:cje,Option:dje,OptionIcon:dje,Orbit:uje,OrbitIcon:uje,Origami:hje,OrigamiIcon:hje,Outdent:dD,OutdentIcon:dD,Package:Sh,Package2:mje,Package2Icon:mje,PackageCheck:pje,PackageCheckIcon:pje,PackageIcon:Sh,PackageMinus:fje,PackageMinusIcon:fje,PackageOpen:xje,PackageOpenIcon:xje,PackagePlus:gje,PackagePlusIcon:gje,PackageSearch:yje,PackageSearchIcon:yje,PackageX:vje,PackageXIcon:vje,PaintBucket:bje,PaintBucketIcon:bje,PaintRoller:_je,PaintRollerIcon:_je,Paintbrush:wje,Paintbrush2:vD,Paintbrush2Icon:vD,PaintbrushIcon:wje,PaintbrushVertical:vD,PaintbrushVerticalIcon:vD,Palette:yc,PaletteIcon:yc,Palmtree:RR,PalmtreeIcon:RR,PanelBottom:kje,PanelBottomClose:jje,PanelBottomCloseIcon:jje,PanelBottomDashed:bD,PanelBottomDashedIcon:bD,PanelBottomIcon:kje,PanelBottomInactive:bD,PanelBottomInactiveIcon:bD,PanelBottomOpen:Nje,PanelBottomOpenIcon:Nje,PanelLeft:ND,PanelLeftClose:_D,PanelLeftCloseIcon:_D,PanelLeftDashed:wD,PanelLeftDashedIcon:wD,PanelLeftIcon:ND,PanelLeftInactive:wD,PanelLeftInactiveIcon:wD,PanelLeftOpen:jD,PanelLeftOpenIcon:jD,PanelRight:Aje,PanelRightClose:Sje,PanelRightCloseIcon:Sje,PanelRightDashed:kD,PanelRightDashedIcon:kD,PanelRightIcon:Aje,PanelRightInactive:kD,PanelRightInactiveIcon:kD,PanelRightOpen:Cje,PanelRightOpenIcon:Cje,PanelTop:Mje,PanelTopClose:Eje,PanelTopCloseIcon:Eje,PanelTopDashed:SD,PanelTopDashedIcon:SD,PanelTopIcon:Mje,PanelTopInactive:SD,PanelTopInactiveIcon:SD,PanelTopOpen:Tje,PanelTopOpenIcon:Tje,PanelsLeftBottom:Pje,PanelsLeftBottomIcon:Pje,PanelsLeftRight:p6,PanelsLeftRightIcon:p6,PanelsRightBottom:Lje,PanelsRightBottomIcon:Lje,PanelsTopBottom:MD,PanelsTopBottomIcon:MD,PanelsTopLeft:tA,PanelsTopLeftIcon:tA,Paperclip:dP,PaperclipIcon:dP,Parentheses:Ije,ParenthesesIcon:Ije,ParkingCircle:D8,ParkingCircleIcon:D8,ParkingCircleOff:I8,ParkingCircleOffIcon:I8,ParkingMeter:Dje,ParkingMeterIcon:Dje,ParkingSquare:gR,ParkingSquareIcon:gR,ParkingSquareOff:xR,ParkingSquareOffIcon:xR,PartyPopper:Ix,PartyPopperIcon:Ix,Pause:S0,PauseCircle:R8,PauseCircleIcon:R8,PauseIcon:S0,PauseOctagon:gD,PauseOctagonIcon:gD,PawPrint:Rje,PawPrintIcon:Rje,PcCase:Fje,PcCaseIcon:Fje,Pen:Y2,PenBox:Cp,PenBoxIcon:Cp,PenIcon:Y2,PenLine:Mm,PenLineIcon:Mm,PenOff:Oje,PenOffIcon:Oje,PenSquare:Cp,PenSquareIcon:Cp,PenTool:QA,PenToolIcon:QA,Pencil:Wa,PencilIcon:Wa,PencilLine:nq,PencilLineIcon:nq,PencilOff:zje,PencilOffIcon:zje,PencilRuler:Bje,PencilRulerIcon:Bje,Pentagon:$je,PentagonIcon:$je,Percent:z_,PercentCircle:F8,PercentCircleIcon:F8,PercentDiamond:Y8,PercentDiamondIcon:Y8,PercentIcon:z_,PercentSquare:yR,PercentSquareIcon:yR,PersonStanding:Uje,PersonStandingIcon:Uje,PhilippinePeso:qje,PhilippinePesoIcon:qje,Phone:va,PhoneCall:oJ,PhoneCallIcon:oJ,PhoneForwarded:Vje,PhoneForwardedIcon:Vje,PhoneIcon:va,PhoneIncoming:Hje,PhoneIncomingIcon:Hje,PhoneMissed:Gje,PhoneMissedIcon:Gje,PhoneOff:Wje,PhoneOffIcon:Wje,PhoneOutgoing:Kje,PhoneOutgoingIcon:Kje,Pi:Yje,PiIcon:Yje,PiSquare:vR,PiSquareIcon:vR,Piano:Zje,PianoIcon:Zje,Pickaxe:Xje,PickaxeIcon:Xje,PictureInPicture:Jje,PictureInPicture2:Qje,PictureInPicture2Icon:Qje,PictureInPictureIcon:Jje,PieChart:g8,PieChartIcon:g8,PiggyBank:lJ,PiggyBankIcon:lJ,Pilcrow:s2e,PilcrowIcon:s2e,PilcrowLeft:e2e,PilcrowLeftIcon:e2e,PilcrowRight:t2e,PilcrowRightIcon:t2e,PilcrowSquare:bR,PilcrowSquareIcon:bR,Pill:r2e,PillBottle:n2e,PillBottleIcon:n2e,PillIcon:r2e,Pin:JA,PinIcon:JA,PinOff:cJ,PinOffIcon:cJ,Pipette:a2e,PipetteIcon:a2e,Pizza:i2e,PizzaIcon:i2e,Plane:dJ,PlaneIcon:dJ,PlaneLanding:o2e,PlaneLandingIcon:o2e,PlaneTakeoff:l2e,PlaneTakeoffIcon:l2e,Play:su,PlayCircle:dm,PlayCircleIcon:dm,PlayIcon:su,PlaySquare:_R,PlaySquareIcon:_R,Plug:_j,Plug2:c2e,Plug2Icon:c2e,PlugIcon:_j,PlugZap:CD,PlugZap2:CD,PlugZap2Icon:CD,PlugZapIcon:CD,Plus:sn,PlusCircle:O8,PlusCircleIcon:O8,PlusIcon:sn,PlusSquare:wR,PlusSquareIcon:wR,Pocket:u2e,PocketIcon:u2e,PocketKnife:d2e,PocketKnifeIcon:d2e,Podcast:h2e,PodcastIcon:h2e,Pointer:p2e,PointerIcon:p2e,PointerOff:m2e,PointerOffIcon:m2e,Popcorn:f2e,PopcornIcon:f2e,Popsicle:x2e,PopsicleIcon:x2e,PoundSterling:g2e,PoundSterlingIcon:g2e,Power:uJ,PowerCircle:z8,PowerCircleIcon:z8,PowerIcon:uJ,PowerOff:y2e,PowerOffIcon:y2e,PowerSquare:jR,PowerSquareIcon:jR,Presentation:C0,PresentationIcon:C0,Printer:eE,PrinterCheck:v2e,PrinterCheckIcon:v2e,PrinterIcon:eE,Projector:b2e,ProjectorIcon:b2e,Proportions:_2e,ProportionsIcon:_2e,Puzzle:w2e,PuzzleIcon:w2e,Pyramid:j2e,PyramidIcon:j2e,QrCode:lf,QrCodeIcon:lf,Quote:wj,QuoteIcon:wj,Rabbit:N2e,RabbitIcon:N2e,Radar:rq,RadarIcon:rq,Radiation:k2e,RadiationIcon:k2e,Radical:S2e,RadicalIcon:S2e,Radio:Nv,RadioIcon:Nv,RadioReceiver:C2e,RadioReceiverIcon:C2e,RadioTower:A2e,RadioTowerIcon:A2e,Radius:E2e,RadiusIcon:E2e,RailSymbol:T2e,RailSymbolIcon:T2e,Rainbow:M2e,RainbowIcon:M2e,Rat:P2e,RatIcon:P2e,Ratio:L2e,RatioIcon:L2e,Receipt:aq,ReceiptCent:I2e,ReceiptCentIcon:I2e,ReceiptEuro:D2e,ReceiptEuroIcon:D2e,ReceiptIcon:aq,ReceiptIndianRupee:R2e,ReceiptIndianRupeeIcon:R2e,ReceiptJapaneseYen:F2e,ReceiptJapaneseYenIcon:F2e,ReceiptPoundSterling:O2e,ReceiptPoundSterlingIcon:O2e,ReceiptRussianRuble:z2e,ReceiptRussianRubleIcon:z2e,ReceiptSwissFranc:B2e,ReceiptSwissFrancIcon:B2e,ReceiptText:$2e,ReceiptTextIcon:$2e,RectangleEllipsis:AD,RectangleEllipsisIcon:AD,RectangleHorizontal:U2e,RectangleHorizontalIcon:U2e,RectangleVertical:q2e,RectangleVerticalIcon:q2e,Recycle:V2e,RecycleIcon:V2e,Redo:tE,Redo2:H2e,Redo2Icon:H2e,RedoDot:G2e,RedoDotIcon:G2e,RedoIcon:tE,RefreshCcw:iq,RefreshCcwDot:W2e,RefreshCcwDotIcon:W2e,RefreshCcwIcon:iq,RefreshCw:Gi,RefreshCwIcon:Gi,RefreshCwOff:K2e,RefreshCwOffIcon:K2e,Refrigerator:Y2e,RefrigeratorIcon:Y2e,Regex:Z2e,RegexIcon:Z2e,RemoveFormatting:X2e,RemoveFormattingIcon:X2e,Repeat:sE,Repeat1:Q2e,Repeat1Icon:Q2e,Repeat2:hJ,Repeat2Icon:hJ,RepeatIcon:sE,Replace:eNe,ReplaceAll:J2e,ReplaceAllIcon:J2e,ReplaceIcon:eNe,Reply:oq,ReplyAll:tNe,ReplyAllIcon:tNe,ReplyIcon:oq,Rewind:sNe,RewindIcon:sNe,Ribbon:nNe,RibbonIcon:nNe,Rocket:Xf,RocketIcon:Xf,RockingChair:rNe,RockingChairIcon:rNe,RollerCoaster:aNe,RollerCoasterIcon:aNe,Rotate3D:ED,Rotate3DIcon:ED,Rotate3d:ED,Rotate3dIcon:ED,RotateCcw:Dx,RotateCcwIcon:Dx,RotateCcwSquare:iNe,RotateCcwSquareIcon:iNe,RotateCw:p7,RotateCwIcon:p7,RotateCwSquare:oNe,RotateCwSquareIcon:oNe,Route:lq,RouteIcon:lq,RouteOff:lNe,RouteOffIcon:lNe,Router:cNe,RouterIcon:cNe,Rows:TD,Rows2:TD,Rows2Icon:TD,Rows3:MD,Rows3Icon:MD,Rows4:dNe,Rows4Icon:dNe,RowsIcon:TD,Rss:uNe,RssIcon:uNe,Ruler:Q4,RulerIcon:Q4,RussianRuble:hNe,RussianRubleIcon:hNe,Sailboat:mNe,SailboatIcon:mNe,Salad:pNe,SaladIcon:pNe,Sandwich:fNe,SandwichIcon:fNe,Satellite:gNe,SatelliteDish:xNe,SatelliteDishIcon:xNe,SatelliteIcon:gNe,Save:Bo,SaveAll:yNe,SaveAllIcon:yNe,SaveIcon:Bo,SaveOff:vNe,SaveOffIcon:vNe,Scale:bNe,Scale3D:PD,Scale3DIcon:PD,Scale3d:PD,Scale3dIcon:PD,ScaleIcon:bNe,Scaling:_Ne,ScalingIcon:_Ne,Scan:ENe,ScanBarcode:wNe,ScanBarcodeIcon:wNe,ScanEye:jNe,ScanEyeIcon:jNe,ScanFace:NNe,ScanFaceIcon:NNe,ScanIcon:ENe,ScanLine:kNe,ScanLineIcon:kNe,ScanQrCode:SNe,ScanQrCodeIcon:SNe,ScanSearch:CNe,ScanSearchIcon:CNe,ScanText:ANe,ScanTextIcon:ANe,ScatterChart:y8,ScatterChartIcon:y8,School:TNe,School2:OR,School2Icon:OR,SchoolIcon:TNe,Scissors:PNe,ScissorsIcon:PNe,ScissorsLineDashed:MNe,ScissorsLineDashedIcon:MNe,ScissorsSquare:NR,ScissorsSquareDashedBottom:ZD,ScissorsSquareDashedBottomIcon:ZD,ScissorsSquareIcon:NR,ScreenShare:INe,ScreenShareIcon:INe,ScreenShareOff:LNe,ScreenShareOffIcon:LNe,Scroll:DNe,ScrollIcon:DNe,ScrollText:cq,ScrollTextIcon:cq,Search:Rr,SearchCheck:RNe,SearchCheckIcon:RNe,SearchCode:FNe,SearchCodeIcon:FNe,SearchIcon:Rr,SearchSlash:ONe,SearchSlashIcon:ONe,SearchX:dq,SearchXIcon:dq,Section:zNe,SectionIcon:zNe,Send:Fr,SendHorizonal:LD,SendHorizonalIcon:LD,SendHorizontal:LD,SendHorizontalIcon:LD,SendIcon:Fr,SendToBack:BNe,SendToBackIcon:BNe,SeparatorHorizontal:$Ne,SeparatorHorizontalIcon:$Ne,SeparatorVertical:UNe,SeparatorVerticalIcon:UNe,Server:GNe,ServerCog:qNe,ServerCogIcon:qNe,ServerCrash:VNe,ServerCrashIcon:VNe,ServerIcon:GNe,ServerOff:HNe,ServerOffIcon:HNe,Settings:Gc,Settings2:vS,Settings2Icon:vS,SettingsIcon:Gc,Shapes:WNe,ShapesIcon:WNe,Share:mJ,Share2:sd,Share2Icon:sd,ShareIcon:mJ,Sheet:KNe,SheetIcon:KNe,Shell:YNe,ShellIcon:YNe,Shield:Om,ShieldAlert:uq,ShieldAlertIcon:uq,ShieldBan:ZNe,ShieldBanIcon:ZNe,ShieldCheck:Ch,ShieldCheckIcon:Ch,ShieldClose:ID,ShieldCloseIcon:ID,ShieldEllipsis:XNe,ShieldEllipsisIcon:XNe,ShieldHalf:QNe,ShieldHalfIcon:QNe,ShieldIcon:Om,ShieldMinus:JNe,ShieldMinusIcon:JNe,ShieldOff:f7,ShieldOffIcon:f7,ShieldPlus:eke,ShieldPlusIcon:eke,ShieldQuestion:x7,ShieldQuestionIcon:x7,ShieldX:ID,ShieldXIcon:ID,Ship:ske,ShipIcon:ske,ShipWheel:tke,ShipWheelIcon:tke,Shirt:nke,ShirtIcon:nke,ShoppingBag:J4,ShoppingBagIcon:J4,ShoppingBasket:rke,ShoppingBasketIcon:rke,ShoppingCart:bS,ShoppingCartIcon:bS,Shovel:ake,ShovelIcon:ake,ShowerHead:ike,ShowerHeadIcon:ike,Shrink:oke,ShrinkIcon:oke,Shrub:lke,ShrubIcon:lke,Shuffle:g7,ShuffleIcon:g7,Sidebar:ND,SidebarClose:_D,SidebarCloseIcon:_D,SidebarIcon:ND,SidebarOpen:jD,SidebarOpenIcon:jD,Sigma:cke,SigmaIcon:cke,SigmaSquare:kR,SigmaSquareIcon:kR,Signal:pke,SignalHigh:dke,SignalHighIcon:dke,SignalIcon:pke,SignalLow:uke,SignalLowIcon:uke,SignalMedium:hke,SignalMediumIcon:hke,SignalZero:mke,SignalZeroIcon:mke,Signature:fke,SignatureIcon:fke,Signpost:pJ,SignpostBig:xke,SignpostBigIcon:xke,SignpostIcon:pJ,Siren:gke,SirenIcon:gke,SkipBack:yke,SkipBackIcon:yke,SkipForward:fJ,SkipForwardIcon:fJ,Skull:vke,SkullIcon:vke,Slack:bke,SlackIcon:bke,Slash:_ke,SlashIcon:_ke,SlashSquare:SR,SlashSquareIcon:SR,Slice:wke,SliceIcon:wke,Sliders:DD,SlidersHorizontal:uP,SlidersHorizontalIcon:uP,SlidersIcon:DD,SlidersVertical:DD,SlidersVerticalIcon:DD,Smartphone:p1,SmartphoneCharging:jke,SmartphoneChargingIcon:jke,SmartphoneIcon:p1,SmartphoneNfc:Nke,SmartphoneNfcIcon:Nke,Smile:Ske,SmileIcon:Ske,SmilePlus:kke,SmilePlusIcon:kke,Snail:Cke,SnailIcon:Cke,Snowflake:aj,SnowflakeIcon:aj,Sofa:hq,SofaIcon:hq,SortAsc:e8,SortAscIcon:e8,SortDesc:XI,SortDescIcon:XI,Soup:Ake,SoupIcon:Ake,Space:Eke,SpaceIcon:Eke,Spade:Tke,SpadeIcon:Tke,Sparkle:hP,SparkleIcon:hP,Sparkles:un,SparklesIcon:un,Speaker:Mke,SpeakerIcon:Mke,Speech:Pke,SpeechIcon:Pke,SpellCheck:Ike,SpellCheck2:Lke,SpellCheck2Icon:Lke,SpellCheckIcon:Ike,Spline:Dke,SplineIcon:Dke,Split:Rke,SplitIcon:Rke,SplitSquareHorizontal:CR,SplitSquareHorizontalIcon:CR,SplitSquareVertical:AR,SplitSquareVerticalIcon:AR,SprayCan:Fke,SprayCanIcon:Fke,Sprout:mP,SproutIcon:mP,Square:jb,SquareActivity:RD,SquareActivityIcon:RD,SquareArrowDown:zD,SquareArrowDownIcon:zD,SquareArrowDownLeft:FD,SquareArrowDownLeftIcon:FD,SquareArrowDownRight:OD,SquareArrowDownRightIcon:OD,SquareArrowLeft:BD,SquareArrowLeftIcon:BD,SquareArrowOutDownLeft:$D,SquareArrowOutDownLeftIcon:$D,SquareArrowOutDownRight:UD,SquareArrowOutDownRightIcon:UD,SquareArrowOutUpLeft:qD,SquareArrowOutUpLeftIcon:qD,SquareArrowOutUpRight:VD,SquareArrowOutUpRightIcon:VD,SquareArrowRight:HD,SquareArrowRightIcon:HD,SquareArrowUp:KD,SquareArrowUpIcon:KD,SquareArrowUpLeft:GD,SquareArrowUpLeftIcon:GD,SquareArrowUpRight:WD,SquareArrowUpRightIcon:WD,SquareAsterisk:YD,SquareAsteriskIcon:YD,SquareBottomDashedScissors:ZD,SquareBottomDashedScissorsIcon:ZD,SquareChartGantt:F5,SquareChartGanttIcon:F5,SquareCheck:XD,SquareCheckBig:Zw,SquareCheckBigIcon:Zw,SquareCheckIcon:XD,SquareChevronDown:QD,SquareChevronDownIcon:QD,SquareChevronLeft:JD,SquareChevronLeftIcon:JD,SquareChevronRight:eR,SquareChevronRightIcon:eR,SquareChevronUp:tR,SquareChevronUpIcon:tR,SquareCode:sR,SquareCodeIcon:sR,SquareDashed:aR,SquareDashedBottom:zke,SquareDashedBottomCode:Oke,SquareDashedBottomCodeIcon:Oke,SquareDashedBottomIcon:zke,SquareDashedIcon:aR,SquareDashedKanban:nR,SquareDashedKanbanIcon:nR,SquareDashedMousePointer:rR,SquareDashedMousePointerIcon:rR,SquareDivide:iR,SquareDivideIcon:iR,SquareDot:oR,SquareDotIcon:oR,SquareEqual:lR,SquareEqualIcon:lR,SquareFunction:cR,SquareFunctionIcon:cR,SquareGanttChart:F5,SquareGanttChartIcon:F5,SquareIcon:jb,SquareKanban:dR,SquareKanbanIcon:dR,SquareLibrary:uR,SquareLibraryIcon:uR,SquareM:hR,SquareMIcon:hR,SquareMenu:mR,SquareMenuIcon:mR,SquareMinus:pR,SquareMinusIcon:pR,SquareMousePointer:fR,SquareMousePointerIcon:fR,SquareParking:gR,SquareParkingIcon:gR,SquareParkingOff:xR,SquareParkingOffIcon:xR,SquarePen:Cp,SquarePenIcon:Cp,SquarePercent:yR,SquarePercentIcon:yR,SquarePi:vR,SquarePiIcon:vR,SquarePilcrow:bR,SquarePilcrowIcon:bR,SquarePlay:_R,SquarePlayIcon:_R,SquarePlus:wR,SquarePlusIcon:wR,SquarePower:jR,SquarePowerIcon:jR,SquareRadical:Bke,SquareRadicalIcon:Bke,SquareScissors:NR,SquareScissorsIcon:NR,SquareSigma:kR,SquareSigmaIcon:kR,SquareSlash:SR,SquareSlashIcon:SR,SquareSplitHorizontal:CR,SquareSplitHorizontalIcon:CR,SquareSplitVertical:AR,SquareSplitVerticalIcon:AR,SquareSquare:$ke,SquareSquareIcon:$ke,SquareStack:Uke,SquareStackIcon:Uke,SquareTerminal:ER,SquareTerminalIcon:ER,SquareUser:MR,SquareUserIcon:MR,SquareUserRound:TR,SquareUserRoundIcon:TR,SquareX:PR,SquareXIcon:PR,Squircle:qke,SquircleIcon:qke,Squirrel:Vke,SquirrelIcon:Vke,Stamp:Hke,StampIcon:Hke,Star:Ia,StarHalf:Gke,StarHalfIcon:Gke,StarIcon:Ia,StarOff:Wke,StarOffIcon:Wke,Stars:un,StarsIcon:un,StepBack:Kke,StepBackIcon:Kke,StepForward:Yke,StepForwardIcon:Yke,Stethoscope:Zke,StethoscopeIcon:Zke,Sticker:Xke,StickerIcon:Xke,StickyNote:y7,StickyNoteIcon:y7,StopCircle:$8,StopCircleIcon:$8,Store:mq,StoreIcon:mq,StretchHorizontal:Qke,StretchHorizontalIcon:Qke,StretchVertical:Jke,StretchVerticalIcon:Jke,Strikethrough:xJ,StrikethroughIcon:xJ,Subscript:eSe,SubscriptIcon:eSe,Subtitles:i8,SubtitlesIcon:i8,Sun:bN,SunDim:tSe,SunDimIcon:tSe,SunIcon:bN,SunMedium:sSe,SunMediumIcon:sSe,SunMoon:nSe,SunMoonIcon:nSe,SunSnow:rSe,SunSnowIcon:rSe,Sunrise:aSe,SunriseIcon:aSe,Sunset:iSe,SunsetIcon:iSe,Superscript:oSe,SuperscriptIcon:oSe,SwatchBook:lSe,SwatchBookIcon:lSe,SwissFranc:cSe,SwissFrancIcon:cSe,SwitchCamera:dSe,SwitchCameraIcon:dSe,Sword:uSe,SwordIcon:uSe,Swords:hSe,SwordsIcon:hSe,Syringe:mSe,SyringeIcon:mSe,Table:fq,Table2:pq,Table2Icon:pq,TableCellsMerge:pSe,TableCellsMergeIcon:pSe,TableCellsSplit:fSe,TableCellsSplitIcon:fSe,TableColumnsSplit:xSe,TableColumnsSplitIcon:xSe,TableIcon:fq,TableOfContents:gSe,TableOfContentsIcon:gSe,TableProperties:ySe,TablePropertiesIcon:ySe,TableRowsSplit:vSe,TableRowsSplitIcon:vSe,Tablet:xq,TabletIcon:xq,TabletSmartphone:bSe,TabletSmartphoneIcon:bSe,Tablets:_Se,TabletsIcon:_Se,Tag:Ip,TagIcon:Ip,Tags:gJ,TagsIcon:gJ,Tally1:wSe,Tally1Icon:wSe,Tally2:jSe,Tally2Icon:jSe,Tally3:NSe,Tally3Icon:NSe,Tally4:kSe,Tally4Icon:kSe,Tally5:SSe,Tally5Icon:SSe,Tangent:CSe,TangentIcon:CSe,Target:bu,TargetIcon:bu,Telescope:ASe,TelescopeIcon:ASe,Tent:TSe,TentIcon:TSe,TentTree:ESe,TentTreeIcon:ESe,Terminal:MSe,TerminalIcon:MSe,TerminalSquare:ER,TerminalSquareIcon:ER,TestTube:PSe,TestTube2:LR,TestTube2Icon:LR,TestTubeDiagonal:LR,TestTubeDiagonalIcon:LR,TestTubeIcon:PSe,TestTubes:LSe,TestTubesIcon:LSe,Text:FSe,TextCursor:ISe,TextCursorIcon:ISe,TextCursorInput:gq,TextCursorInputIcon:gq,TextIcon:FSe,TextQuote:DSe,TextQuoteIcon:DSe,TextSearch:RSe,TextSearchIcon:RSe,TextSelect:IR,TextSelectIcon:IR,TextSelection:IR,TextSelectionIcon:IR,Theater:OSe,TheaterIcon:OSe,Thermometer:$Se,ThermometerIcon:$Se,ThermometerSnowflake:zSe,ThermometerSnowflakeIcon:zSe,ThermometerSun:BSe,ThermometerSunIcon:BSe,ThumbsDown:yJ,ThumbsDownIcon:yJ,ThumbsUp:Ug,ThumbsUpIcon:Ug,Ticket:v7,TicketCheck:USe,TicketCheckIcon:USe,TicketIcon:v7,TicketMinus:qSe,TicketMinusIcon:qSe,TicketPercent:VSe,TicketPercentIcon:VSe,TicketPlus:HSe,TicketPlusIcon:HSe,TicketSlash:GSe,TicketSlashIcon:GSe,TicketX:WSe,TicketXIcon:WSe,Tickets:YSe,TicketsIcon:YSe,TicketsPlane:KSe,TicketsPlaneIcon:KSe,Timer:QSe,TimerIcon:QSe,TimerOff:ZSe,TimerOffIcon:ZSe,TimerReset:XSe,TimerResetIcon:XSe,ToggleLeft:JSe,ToggleLeftIcon:JSe,ToggleRight:e5e,ToggleRightIcon:e5e,Toilet:t5e,ToiletIcon:t5e,Tornado:s5e,TornadoIcon:s5e,Torus:n5e,TorusIcon:n5e,Touchpad:a5e,TouchpadIcon:a5e,TouchpadOff:r5e,TouchpadOffIcon:r5e,TowerControl:i5e,TowerControlIcon:i5e,ToyBrick:o5e,ToyBrickIcon:o5e,Tractor:l5e,TractorIcon:l5e,TrafficCone:c5e,TrafficConeIcon:c5e,Train:DR,TrainFront:u5e,TrainFrontIcon:u5e,TrainFrontTunnel:d5e,TrainFrontTunnelIcon:d5e,TrainIcon:DR,TrainTrack:h5e,TrainTrackIcon:h5e,TramFront:DR,TramFrontIcon:DR,Trash:m5e,Trash2:Cn,Trash2Icon:Cn,TrashIcon:m5e,TreeDeciduous:p5e,TreeDeciduousIcon:p5e,TreePalm:RR,TreePalmIcon:RR,TreePine:pP,TreePineIcon:pP,Trees:f5e,TreesIcon:f5e,Trello:x5e,TrelloIcon:x5e,TrendingDown:_S,TrendingDownIcon:_S,TrendingUp:kl,TrendingUpDown:g5e,TrendingUpDownIcon:g5e,TrendingUpIcon:kl,Triangle:v5e,TriangleAlert:nl,TriangleAlertIcon:nl,TriangleIcon:v5e,TriangleRight:y5e,TriangleRightIcon:y5e,Trophy:jl,TrophyIcon:jl,Truck:vJ,TruckIcon:vJ,Turtle:b5e,TurtleIcon:b5e,Tv:w5e,Tv2:FR,Tv2Icon:FR,TvIcon:w5e,TvMinimal:FR,TvMinimalIcon:FR,TvMinimalPlay:_5e,TvMinimalPlayIcon:_5e,Twitch:j5e,TwitchIcon:j5e,Twitter:bJ,TwitterIcon:bJ,Type:yq,TypeIcon:yq,TypeOutline:N5e,TypeOutlineIcon:N5e,Umbrella:S5e,UmbrellaIcon:S5e,UmbrellaOff:k5e,UmbrellaOffIcon:k5e,Underline:b7,UnderlineIcon:b7,Undo:nE,Undo2:_J,Undo2Icon:_J,UndoDot:C5e,UndoDotIcon:C5e,UndoIcon:nE,UnfoldHorizontal:A5e,UnfoldHorizontalIcon:A5e,UnfoldVertical:E5e,UnfoldVerticalIcon:E5e,Ungroup:T5e,UngroupIcon:T5e,University:OR,UniversityIcon:OR,Unlink:rE,Unlink2:M5e,Unlink2Icon:M5e,UnlinkIcon:rE,Unlock:pD,UnlockIcon:pD,UnlockKeyhole:mD,UnlockKeyholeIcon:mD,Unplug:_7,UnplugIcon:_7,Upload:Ra,UploadCloud:m6,UploadCloudIcon:m6,UploadIcon:Ra,Usb:P5e,UsbIcon:P5e,User:Oo,User2:x6,User2Icon:x6,UserCheck:jj,UserCheck2:f6,UserCheck2Icon:f6,UserCheckIcon:jj,UserCircle:q8,UserCircle2:U8,UserCircle2Icon:U8,UserCircleIcon:q8,UserCog:wJ,UserCog2:zR,UserCog2Icon:zR,UserCogIcon:wJ,UserIcon:Oo,UserMinus:vq,UserMinus2:BR,UserMinus2Icon:BR,UserMinusIcon:vq,UserPen:L5e,UserPenIcon:L5e,UserPlus:Pl,UserPlus2:$R,UserPlus2Icon:$R,UserPlusIcon:Pl,UserRound:x6,UserRoundCheck:f6,UserRoundCheckIcon:f6,UserRoundCog:zR,UserRoundCogIcon:zR,UserRoundIcon:x6,UserRoundMinus:BR,UserRoundMinusIcon:BR,UserRoundPen:I5e,UserRoundPenIcon:I5e,UserRoundPlus:$R,UserRoundPlusIcon:$R,UserRoundSearch:bq,UserRoundSearchIcon:bq,UserRoundX:UR,UserRoundXIcon:UR,UserSearch:D5e,UserSearchIcon:D5e,UserSquare:MR,UserSquare2:TR,UserSquare2Icon:TR,UserSquareIcon:MR,UserX:_q,UserX2:UR,UserX2Icon:UR,UserXIcon:_q,Users:On,Users2:vy,Users2Icon:vy,UsersIcon:On,UsersRound:vy,UsersRoundIcon:vy,Utensils:VR,UtensilsCrossed:qR,UtensilsCrossedIcon:qR,UtensilsIcon:VR,UtilityPole:R5e,UtilityPoleIcon:R5e,Variable:wq,VariableIcon:wq,Vault:F5e,VaultIcon:F5e,Vegan:O5e,VeganIcon:O5e,VenetianMask:z5e,VenetianMaskIcon:z5e,Verified:eA,VerifiedIcon:eA,Vibrate:$5e,VibrateIcon:$5e,VibrateOff:B5e,VibrateOffIcon:B5e,Video:Xr,VideoIcon:Xr,VideoOff:U5e,VideoOffIcon:U5e,Videotape:q5e,VideotapeIcon:q5e,View:V5e,ViewIcon:V5e,Voicemail:H5e,VoicemailIcon:H5e,Volleyball:G5e,VolleyballIcon:G5e,Volume:Y5e,Volume1:W5e,Volume1Icon:W5e,Volume2:jJ,Volume2Icon:jJ,VolumeIcon:Y5e,VolumeOff:K5e,VolumeOffIcon:K5e,VolumeX:NJ,VolumeXIcon:NJ,Vote:Z5e,VoteIcon:Z5e,Wallet:w7,Wallet2:HR,Wallet2Icon:HR,WalletCards:X5e,WalletCardsIcon:X5e,WalletIcon:w7,WalletMinimal:HR,WalletMinimalIcon:HR,Wallpaper:Q5e,WallpaperIcon:Q5e,Wand:J5e,Wand2:rg,Wand2Icon:rg,WandIcon:J5e,WandSparkles:rg,WandSparklesIcon:rg,Warehouse:e4e,WarehouseIcon:e4e,WashingMachine:t4e,WashingMachineIcon:t4e,Watch:s4e,WatchIcon:s4e,Waves:n4e,WavesIcon:n4e,Waypoints:r4e,WaypointsIcon:r4e,Webcam:a4e,WebcamIcon:a4e,Webhook:o4e,WebhookIcon:o4e,WebhookOff:i4e,WebhookOffIcon:i4e,Weight:l4e,WeightIcon:l4e,Wheat:d4e,WheatIcon:d4e,WheatOff:c4e,WheatOffIcon:c4e,WholeWord:u4e,WholeWordIcon:u4e,Wifi:x4e,WifiHigh:h4e,WifiHighIcon:h4e,WifiIcon:x4e,WifiLow:m4e,WifiLowIcon:m4e,WifiOff:p4e,WifiOffIcon:p4e,WifiZero:f4e,WifiZeroIcon:f4e,Wind:y4e,WindArrowDown:g4e,WindArrowDownIcon:g4e,WindIcon:y4e,Wine:b4e,WineIcon:b4e,WineOff:v4e,WineOffIcon:v4e,Workflow:j7,WorkflowIcon:j7,Worm:_4e,WormIcon:_4e,WrapText:w4e,WrapTextIcon:w4e,Wrench:eC,WrenchIcon:eC,X:er,XCircle:Bd,XCircleIcon:Bd,XIcon:er,XOctagon:yD,XOctagonIcon:yD,XSquare:PR,XSquareIcon:PR,Youtube:jq,YoutubeIcon:jq,Zap:cf,ZapIcon:cf,ZapOff:j4e,ZapOffIcon:j4e,ZoomIn:fP,ZoomInIcon:fP,ZoomOut:Nq,ZoomOutIcon:Nq,createLucideIcon:fe,icons:Hxs},Symbol.toStringTag,{value:"Module"})),dQe="-",Gxs=s=>{const t=Kxs(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(dQe);return o[0]===""&&o.length!==1&&o.shift(),BMt(o,t)||Wxs(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},BMt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?BMt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(dQe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},pmt=/^\[(.+)\]$/,Wxs=s=>{if(pmt.test(s)){const t=pmt.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},Kxs=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return Zxs(Object.entries(s.classGroups),n).forEach(([i,l])=>{iqe(l,r,i,t)}),r},iqe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:fmt(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(Yxs(a)){iqe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{iqe(l,fmt(t,i),n,r)})})},fmt=(s,t)=>{let n=s;return t.split(dQe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},Yxs=s=>s.isThemeGetter,Zxs=(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,Xxs=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)}}},$Mt="!",Qxs=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:p,baseClassName:f,maybePostfixModifierPosition:g}};return n?o=>n({className:o,parseClassName:l}):l},Jxs=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},egs=s=>({cache:Xxs(s.cacheSize),parseClassName:Qxs(s),...Gxs(s)}),tgs=/\s+/,sgs=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(tgs);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);let f=!!p,g=r(f?m.substring(0,p):m);if(!g){if(!f){o=d+(o.length>0?" "+o:o);continue}if(g=r(m),!g){o=d+(o.length>0?" "+o:o);continue}f=!1}const v=Jxs(u).join(":"),y=h?v+$Mt:v,b=y+g;if(i.includes(b))continue;i.push(b);const w=a(g,f);for(let S=0;S0?" "+o:o)}return o};function ngs(){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=egs(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=sgs(c,n);return a(c,u),u}return function(){return i(ngs.apply(null,arguments))}}const _p=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},qMt=/^\[(?:([a-z-]+):)?(.+)\]$/i,ags=/^\d+\/\d+$/,igs=new Set(["px","full","screen"]),ogs=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,lgs=/\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$/,cgs=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,dgs=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ugs=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,g3=s=>kq(s)||igs.has(s)||ags.test(s),jT=s=>nW(s,"length",vgs),kq=s=>!!s&&!Number.isNaN(Number(s)),eOe=s=>nW(s,"number",kq),RY=s=>!!s&&Number.isInteger(Number(s)),hgs=s=>s.endsWith("%")&&kq(s.slice(0,-1)),Qc=s=>qMt.test(s),NT=s=>ogs.test(s),mgs=new Set(["length","size","percentage"]),pgs=s=>nW(s,mgs,VMt),fgs=s=>nW(s,"position",VMt),xgs=new Set(["image","url"]),ggs=s=>nW(s,xgs,_gs),ygs=s=>nW(s,"",bgs),FY=()=>!0,nW=(s,t,n)=>{const r=qMt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},vgs=s=>lgs.test(s)&&!cgs.test(s),VMt=()=>!1,bgs=s=>dgs.test(s),_gs=s=>ugs.test(s),wgs=()=>{const s=_p("colors"),t=_p("spacing"),n=_p("blur"),r=_p("brightness"),a=_p("borderColor"),i=_p("borderRadius"),l=_p("borderSpacing"),o=_p("borderWidth"),c=_p("contrast"),d=_p("grayscale"),u=_p("hueRotate"),h=_p("invert"),m=_p("gap"),p=_p("gradientColorStops"),f=_p("gradientColorStopPositions"),g=_p("inset"),v=_p("margin"),y=_p("opacity"),b=_p("padding"),w=_p("saturate"),S=_p("scale"),C=_p("sepia"),E=_p("skew"),P=_p("space"),M=_p("translate"),I=()=>["auto","contain","none"],D=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto",Qc,t],q=()=>[Qc,t],G=()=>["",g3,jT],V=()=>["auto",kq,Qc],H=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],K=()=>["solid","dashed","dotted","double","none"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],oe=()=>["start","end","center","between","around","evenly","stretch"],re=()=>["","0",Qc],ae=()=>["auto","avoid","all","avoid-page","page","left","right","column"],J=()=>[kq,Qc];return{cacheSize:500,separator:":",theme:{colors:[FY],spacing:[g3,jT],blur:["none","",NT,Qc],brightness:J(),borderColor:[s],borderRadius:["none","","full",NT,Qc],borderSpacing:q(),borderWidth:G(),contrast:J(),grayscale:re(),hueRotate:J(),invert:re(),gap:q(),gradientColorStops:[s],gradientColorStopPositions:[hgs,jT],inset:F(),margin:F(),opacity:J(),padding:q(),saturate:J(),scale:J(),sepia:re(),skew:J(),space:q(),translate:q()},classGroups:{aspect:[{aspect:["auto","square","video",Qc]}],container:["container"],columns:[{columns:[NT]}],"break-after":[{"break-after":ae()}],"break-before":[{"break-before":ae()}],"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:[...H(),Qc]}],overflow:[{overflow:D()}],"overflow-x":[{"overflow-x":D()}],"overflow-y":[{"overflow-y":D()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[g]}],"inset-x":[{"inset-x":[g]}],"inset-y":[{"inset-y":[g]}],start:[{start:[g]}],end:[{end:[g]}],top:[{top:[g]}],right:[{right:[g]}],bottom:[{bottom:[g]}],left:[{left:[g]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",RY,Qc]}],basis:[{basis:F()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Qc]}],grow:[{grow:re()}],shrink:[{shrink:re()}],order:[{order:["first","last","none",RY,Qc]}],"grid-cols":[{"grid-cols":[FY]}],"col-start-end":[{col:["auto",{span:["full",RY,Qc]},Qc]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[FY]}],"row-start-end":[{row:["auto",{span:[RY,Qc]},Qc]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Qc]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Qc]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...oe()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...oe(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...oe(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],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":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Qc,t]}],"min-w":[{"min-w":[Qc,t,"min","max","fit"]}],"max-w":[{"max-w":[Qc,t,"none","full","min","max","fit","prose",{screen:[NT]},NT]}],h:[{h:[Qc,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Qc,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Qc,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Qc,t,"auto","min","max","fit"]}],"font-size":[{text:["base",NT,jT]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",eOe]}],"font-family":[{font:[FY]}],"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",Qc]}],"line-clamp":[{"line-clamp":["none",kq,eOe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",g3,Qc]}],"list-image":[{"list-image":["none",Qc]}],"list-style-type":[{list:["none","disc","decimal",Qc]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...K(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",g3,jT]}],"underline-offset":[{"underline-offset":["auto",g3,Qc]}],"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:q()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Qc]}],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",Qc]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...H(),fgs]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",pgs]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},ggs]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[f]}],"gradient-via-pos":[{via:[f]}],"gradient-to-pos":[{to:[f]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...K(),"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":[y]}],"divide-style":[{divide:K()}],"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:["",...K()]}],"outline-offset":[{"outline-offset":[g3,Qc]}],"outline-w":[{outline:[g3,jT]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:G()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[g3,jT]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",NT,ygs]}],"shadow-color":[{shadow:[FY]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...Z(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Z()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",NT,Qc]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[C]}],"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":[y]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"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",Qc]}],duration:[{duration:J()}],ease:[{ease:["linear","in","out","in-out",Qc]}],delay:[{delay:J()}],animate:[{animate:["none","spin","ping","pulse","bounce",Qc]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[RY,Qc]}],"translate-x":[{"translate-x":[M]}],"translate-y":[{"translate-y":[M]}],"skew-x":[{"skew-x":[E]}],"skew-y":[{"skew-y":[E]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Qc]}],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",Qc]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":q()}],"scroll-mx":[{"scroll-mx":q()}],"scroll-my":[{"scroll-my":q()}],"scroll-ms":[{"scroll-ms":q()}],"scroll-me":[{"scroll-me":q()}],"scroll-mt":[{"scroll-mt":q()}],"scroll-mr":[{"scroll-mr":q()}],"scroll-mb":[{"scroll-mb":q()}],"scroll-ml":[{"scroll-ml":q()}],"scroll-p":[{"scroll-p":q()}],"scroll-px":[{"scroll-px":q()}],"scroll-py":[{"scroll-py":q()}],"scroll-ps":[{"scroll-ps":q()}],"scroll-pe":[{"scroll-pe":q()}],"scroll-pt":[{"scroll-pt":q()}],"scroll-pr":[{"scroll-pr":q()}],"scroll-pb":[{"scroll-pb":q()}],"scroll-pl":[{"scroll-pl":q()}],"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",Qc]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[g3,jT,eOe]}],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"]}}},jgs=rgs(wgs);function Ct(...s){return jgs(Sc(s))}function lm(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 xmt(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function ete(s){return s?s.replace(/<[^>]*>/g,""):""}const Ngs=Uxs,HMt=_.forwardRef(({className:s,...t},n)=>e.jsx(MMt,{ref:n,className:Ct("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}));HMt.displayName=MMt.displayName;const kgs=G9("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"}}),GMt=_.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(PMt,{ref:r,className:Ct(kgs({variant:t}),s),...n}));GMt.displayName=PMt.displayName;const Sgs=_.forwardRef(({className:s,...t},n)=>e.jsx(DMt,{ref:n,className:Ct("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}));Sgs.displayName=DMt.displayName;const WMt=_.forwardRef(({className:s,...t},n)=>e.jsx(RMt,{ref:n,className:Ct("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(er,{className:"h-4 w-4"})}));WMt.displayName=RMt.displayName;const KMt=_.forwardRef(({className:s,...t},n)=>e.jsx(LMt,{ref:n,className:Ct("text-sm font-semibold",s),...t}));KMt.displayName=LMt.displayName;const YMt=_.forwardRef(({className:s,...t},n)=>e.jsx(IMt,{ref:n,className:Ct("text-sm opacity-90",s),...t}));YMt.displayName=IMt.displayName;function Cgs(){const{toasts:s}=_i();return e.jsxs(Ngs,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(GMt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(KMt,{children:n}),r&&e.jsx(YMt,{children:r})]}),a,e.jsx(WMt,{})]},t)}),e.jsx(HMt,{})]})}var gmt=["light","dark"],Ags="(prefers-color-scheme: dark)",Egs=_.createContext(void 0),Tgs={setTheme:s=>{},themes:[]},Mgs=()=>{var s;return(s=_.useContext(Egs))!=null?s:Tgs};_.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(f=>`'${f}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?gmt.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(f,g=!1,v=!0)=>{let y=l?l[f]:f,b=g?f+"|| ''":`'${y}'`,w="";return a&&v&&!g&&gmt.includes(f)&&(w+=`d.style.colorScheme = '${f}';`),n==="class"?g||y?w+=`c.add(${b})`:w+="null":y&&(w+=`d[s](n,${b})`),w},p=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${Ags}',m=window.matchMedia(t);if(m.media!==t||m.matches){${m("dark")}}else{${m("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}${d?"":"else{"+m(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}else{${m(i,!1,!1)};}${h}}catch(t){}}();`;return _.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:p}})});var Pgs=s=>{switch(s){case"success":return Dgs;case"info":return Fgs;case"warning":return Rgs;case"error":return Ogs;default:return null}},Lgs=Array(12).fill(0),Igs=({visible:s,className:t})=>Ft.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Ft.createElement("div",{className:"sonner-spinner"},Lgs.map((n,r)=>Ft.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Dgs=Ft.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ft.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"})),Rgs=Ft.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Ft.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"})),Fgs=Ft.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ft.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"})),Ogs=Ft.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ft.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"})),zgs=Ft.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"},Ft.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Ft.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Bgs=()=>{let[s,t]=Ft.useState(document.hidden);return Ft.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},oqe=1,$gs=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:oqe++,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],Ft.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(qgs(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)||oqe++;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}},g_=new $gs,Ugs=(s,t)=>{let n=(t==null?void 0:t.id)||oqe++;return g_.addToast({title:s,...t,id:n}),n},qgs=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Vgs=Ugs,Hgs=()=>g_.toasts,Ggs=()=>g_.getActiveToasts(),ne=Object.assign(Vgs,{success:g_.success,info:g_.info,warning:g_.warning,error:g_.error,custom:g_.custom,message:g_.message,promise:g_.promise,dismiss:g_.dismiss,loading:g_.loading},{getHistory:Hgs,getToasts:Ggs});function Wgs(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))}Wgs(`: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 ile(s){return s.label!==void 0}var Kgs=3,Ygs="32px",Zgs="16px",ymt=4e3,Xgs=356,Qgs=14,Jgs=20,eys=200;function bk(...s){return s.filter(Boolean).join(" ")}function tys(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var sys=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:p,unstyled:f,interacting:g,setHeights:v,visibleToasts:y,heights:b,index:w,toasts:S,expanded:C,removeToast:E,defaultRichColors:P,closeButton:M,style:I,cancelButtonStyle:D,actionButtonStyle:F,className:q="",descriptionClassName:G="",duration:V,position:H,gap:K,loadingIcon:Z,expandByDefault:oe,classNames:re,icons:ae,closeButtonAriaLabel:J="Close toast",pauseWhenPageIsHidden:te}=s,[ce,ve]=Ft.useState(null),[me,he]=Ft.useState(null),[ge,Ee]=Ft.useState(!1),[Ne,Pe]=Ft.useState(!1),[Oe,ke]=Ft.useState(!1),[Ve,_e]=Ft.useState(!1),[Ae,Se]=Ft.useState(!1),[We,qe]=Ft.useState(0),[Be,Ze]=Ft.useState(0),$e=Ft.useRef(p.duration||V||ymt),Xe=Ft.useRef(null),nt=Ft.useRef(null),Ge=w===0,Je=w+1<=y,ut=p.type,lt=p.dismissible!==!1,qt=p.className||"",zt=p.descriptionClassName||"",Zt=Ft.useMemo(()=>b.findIndex(Tn=>Tn.toastId===p.id)||0,[b,p.id]),ms=Ft.useMemo(()=>{var Tn;return(Tn=p.closeButton)!=null?Tn:M},[p.closeButton,M]),Dt=Ft.useMemo(()=>p.duration||V||ymt,[p.duration,V]),It=Ft.useRef(0),qs=Ft.useRef(0),wt=Ft.useRef(0),Us=Ft.useRef(null),[Es,kn]=H.split("-"),Sn=Ft.useMemo(()=>b.reduce((Tn,Yn,fs)=>fs>=Zt?Tn:Tn+Yn.height,0),[b,Zt]),bn=Bgs(),cr=p.invert||m,Fs=ut==="loading";qs.current=Ft.useMemo(()=>Zt*K+Sn,[Zt,Sn]),Ft.useEffect(()=>{$e.current=Dt},[Dt]),Ft.useEffect(()=>{Ee(!0)},[]),Ft.useEffect(()=>{let Tn=nt.current;if(Tn){let Yn=Tn.getBoundingClientRect().height;return Ze(Yn),v(fs=>[{toastId:p.id,height:Yn,position:p.position},...fs]),()=>v(fs=>fs.filter(wn=>wn.toastId!==p.id))}},[v,p.id]),Ft.useLayoutEffect(()=>{if(!ge)return;let Tn=nt.current,Yn=Tn.style.height;Tn.style.height="auto";let fs=Tn.getBoundingClientRect().height;Tn.style.height=Yn,Ze(fs),v(wn=>wn.find(As=>As.toastId===p.id)?wn.map(As=>As.toastId===p.id?{...As,height:fs}:As):[{toastId:p.id,height:fs,position:p.position},...wn])},[ge,p.title,p.description,v,p.id]);let cn=Ft.useCallback(()=>{Pe(!0),qe(qs.current),v(Tn=>Tn.filter(Yn=>Yn.toastId!==p.id)),setTimeout(()=>{E(p)},eys)},[p,E,v,qs]);Ft.useEffect(()=>{if(p.promise&&ut==="loading"||p.duration===1/0||p.type==="loading")return;let Tn;return C||g||te&&bn?(()=>{if(wt.current{var Yn;(Yn=p.onAutoClose)==null||Yn.call(p,p),cn()},$e.current)),()=>clearTimeout(Tn)},[C,g,p,ut,te,bn,cn]),Ft.useEffect(()=>{p.delete&&cn()},[cn,p.delete]);function lr(){var Tn,Yn,fs;return ae!=null&&ae.loading?Ft.createElement("div",{className:bk(re==null?void 0:re.loader,(Tn=p==null?void 0:p.classNames)==null?void 0:Tn.loader,"sonner-loader"),"data-visible":ut==="loading"},ae.loading):Z?Ft.createElement("div",{className:bk(re==null?void 0:re.loader,(Yn=p==null?void 0:p.classNames)==null?void 0:Yn.loader,"sonner-loader"),"data-visible":ut==="loading"},Z):Ft.createElement(Igs,{className:bk(re==null?void 0:re.loader,(fs=p==null?void 0:p.classNames)==null?void 0:fs.loader),visible:ut==="loading"})}return Ft.createElement("li",{tabIndex:0,ref:nt,className:bk(q,qt,re==null?void 0:re.toast,(t=p==null?void 0:p.classNames)==null?void 0:t.toast,re==null?void 0:re.default,re==null?void 0:re[ut],(n=p==null?void 0:p.classNames)==null?void 0:n[ut]),"data-sonner-toast":"","data-rich-colors":(r=p.richColors)!=null?r:P,"data-styled":!(p.jsx||p.unstyled||f),"data-mounted":ge,"data-promise":!!p.promise,"data-swiped":Ae,"data-removed":Ne,"data-visible":Je,"data-y-position":Es,"data-x-position":kn,"data-index":w,"data-front":Ge,"data-swiping":Oe,"data-dismissible":lt,"data-type":ut,"data-invert":cr,"data-swipe-out":Ve,"data-swipe-direction":me,"data-expanded":!!(C||oe&&ge),style:{"--index":w,"--toasts-before":w,"--z-index":S.length-w,"--offset":`${Ne?We:qs.current}px`,"--initial-height":oe?"auto":`${Be}px`,...I,...p.style},onDragEnd:()=>{ke(!1),ve(null),Us.current=null},onPointerDown:Tn=>{Fs||!lt||(Xe.current=new Date,qe(qs.current),Tn.target.setPointerCapture(Tn.pointerId),Tn.target.tagName!=="BUTTON"&&(ke(!0),Us.current={x:Tn.clientX,y:Tn.clientY}))},onPointerUp:()=>{var Tn,Yn,fs,wn;if(Ve||!lt)return;Us.current=null;let As=Number(((Tn=nt.current)==null?void 0:Tn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ss=Number(((Yn=nt.current)==null?void 0:Yn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),pr=new Date().getTime()-((fs=Xe.current)==null?void 0:fs.getTime()),hn=ce==="x"?As:Ss,Pn=Math.abs(hn)/pr;if(Math.abs(hn)>=Jgs||Pn>.11){qe(qs.current),(wn=p.onDismiss)==null||wn.call(p,p),he(ce==="x"?As>0?"right":"left":Ss>0?"down":"up"),cn(),_e(!0),Se(!1);return}ke(!1),ve(null)},onPointerMove:Tn=>{var Yn,fs,wn,As;if(!Us.current||!lt||((Yn=window.getSelection())==null?void 0:Yn.toString().length)>0)return;let Ss=Tn.clientY-Us.current.y,pr=Tn.clientX-Us.current.x,hn=(fs=s.swipeDirections)!=null?fs:tys(H);!ce&&(Math.abs(pr)>1||Math.abs(Ss)>1)&&ve(Math.abs(pr)>Math.abs(Ss)?"x":"y");let Pn={x:0,y:0};ce==="y"?(hn.includes("top")||hn.includes("bottom"))&&(hn.includes("top")&&Ss<0||hn.includes("bottom")&&Ss>0)&&(Pn.y=Ss):ce==="x"&&(hn.includes("left")||hn.includes("right"))&&(hn.includes("left")&&pr<0||hn.includes("right")&&pr>0)&&(Pn.x=pr),(Math.abs(Pn.x)>0||Math.abs(Pn.y)>0)&&Se(!0),(wn=nt.current)==null||wn.style.setProperty("--swipe-amount-x",`${Pn.x}px`),(As=nt.current)==null||As.style.setProperty("--swipe-amount-y",`${Pn.y}px`)}},ms&&!p.jsx?Ft.createElement("button",{"aria-label":J,"data-disabled":Fs,"data-close-button":!0,onClick:Fs||!lt?()=>{}:()=>{var Tn;cn(),(Tn=p.onDismiss)==null||Tn.call(p,p)},className:bk(re==null?void 0:re.closeButton,(a=p==null?void 0:p.classNames)==null?void 0:a.closeButton)},(i=ae==null?void 0:ae.close)!=null?i:zgs):null,p.jsx||_.isValidElement(p.title)?p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title:Ft.createElement(Ft.Fragment,null,ut||p.icon||p.promise?Ft.createElement("div",{"data-icon":"",className:bk(re==null?void 0:re.icon,(l=p==null?void 0:p.classNames)==null?void 0:l.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||lr():null,p.type!=="loading"?p.icon||(ae==null?void 0:ae[ut])||Pgs(ut):null):null,Ft.createElement("div",{"data-content":"",className:bk(re==null?void 0:re.content,(o=p==null?void 0:p.classNames)==null?void 0:o.content)},Ft.createElement("div",{"data-title":"",className:bk(re==null?void 0:re.title,(c=p==null?void 0:p.classNames)==null?void 0:c.title)},typeof p.title=="function"?p.title():p.title),p.description?Ft.createElement("div",{"data-description":"",className:bk(G,zt,re==null?void 0:re.description,(d=p==null?void 0:p.classNames)==null?void 0:d.description)},typeof p.description=="function"?p.description():p.description):null),_.isValidElement(p.cancel)?p.cancel:p.cancel&&ile(p.cancel)?Ft.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||D,onClick:Tn=>{var Yn,fs;ile(p.cancel)&<&&((fs=(Yn=p.cancel).onClick)==null||fs.call(Yn,Tn),cn())},className:bk(re==null?void 0:re.cancelButton,(u=p==null?void 0:p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,_.isValidElement(p.action)?p.action:p.action&&ile(p.action)?Ft.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||F,onClick:Tn=>{var Yn,fs;ile(p.action)&&((fs=(Yn=p.action).onClick)==null||fs.call(Yn,Tn),!Tn.defaultPrevented&&cn())},className:bk(re==null?void 0:re.actionButton,(h=p==null?void 0:p.classNames)==null?void 0:h.actionButton)},p.action.label):null))};function vmt(){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 nys(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?Zgs:Ygs;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 rys=_.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:m,style:p,visibleToasts:f=Kgs,toastOptions:g,dir:v=vmt(),gap:y=Qgs,loadingIcon:b,icons:w,containerAriaLabel:S="Notifications",pauseWhenPageIsHidden:C}=s,[E,P]=Ft.useState([]),M=Ft.useMemo(()=>Array.from(new Set([r].concat(E.filter(te=>te.position).map(te=>te.position)))),[E,r]),[I,D]=Ft.useState([]),[F,q]=Ft.useState(!1),[G,V]=Ft.useState(!1),[H,K]=Ft.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Z=Ft.useRef(null),oe=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),re=Ft.useRef(null),ae=Ft.useRef(!1),J=Ft.useCallback(te=>{P(ce=>{var ve;return(ve=ce.find(me=>me.id===te.id))!=null&&ve.delete||g_.dismiss(te.id),ce.filter(({id:me})=>me!==te.id)})},[]);return Ft.useEffect(()=>g_.subscribe(te=>{if(te.dismiss){P(ce=>ce.map(ve=>ve.id===te.id?{...ve,delete:!0}:ve));return}setTimeout(()=>{rQe.flushSync(()=>{P(ce=>{let ve=ce.findIndex(me=>me.id===te.id);return ve!==-1?[...ce.slice(0,ve),{...ce[ve],...te},...ce.slice(ve+1)]:[te,...ce]})})})}),[]),Ft.useEffect(()=>{if(u!=="system"){K(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?K("dark"):K("light")),typeof window>"u")return;let te=window.matchMedia("(prefers-color-scheme: dark)");try{te.addEventListener("change",({matches:ce})=>{K(ce?"dark":"light")})}catch{te.addListener(({matches:ve})=>{try{K(ve?"dark":"light")}catch(me){console.error(me)}})}},[u]),Ft.useEffect(()=>{E.length<=1&&q(!1)},[E]),Ft.useEffect(()=>{let te=ce=>{var ve,me;a.every(he=>ce[he]||ce.code===he)&&(q(!0),(ve=Z.current)==null||ve.focus()),ce.code==="Escape"&&(document.activeElement===Z.current||(me=Z.current)!=null&&me.contains(document.activeElement))&&q(!1)};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[a]),Ft.useEffect(()=>{if(Z.current)return()=>{re.current&&(re.current.focus({preventScroll:!0}),re.current=null,ae.current=!1)}},[Z.current]),Ft.createElement("section",{ref:t,"aria-label":`${S} ${oe}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((te,ce)=>{var ve;let[me,he]=te.split("-");return E.length?Ft.createElement("ol",{key:te,dir:v==="auto"?vmt():v,tabIndex:-1,ref:Z,className:o,"data-sonner-toaster":!0,"data-theme":H,"data-y-position":me,"data-lifted":F&&E.length>1&&!i,"data-x-position":he,style:{"--front-toast-height":`${((ve=I[0])==null?void 0:ve.height)||0}px`,"--width":`${Xgs}px`,"--gap":`${y}px`,...p,...nys(c,d)},onBlur:ge=>{ae.current&&!ge.currentTarget.contains(ge.relatedTarget)&&(ae.current=!1,re.current&&(re.current.focus({preventScroll:!0}),re.current=null))},onFocus:ge=>{ge.target instanceof HTMLElement&&ge.target.dataset.dismissible==="false"||ae.current||(ae.current=!0,re.current=ge.relatedTarget)},onMouseEnter:()=>q(!0),onMouseMove:()=>q(!0),onMouseLeave:()=>{G||q(!1)},onDragEnd:()=>q(!1),onPointerDown:ge=>{ge.target instanceof HTMLElement&&ge.target.dataset.dismissible==="false"||V(!0)},onPointerUp:()=>V(!1)},E.filter(ge=>!ge.position&&ce===0||ge.position===te).map((ge,Ee)=>{var Ne,Pe;return Ft.createElement(sys,{key:ge.id,icons:w,index:Ee,toast:ge,defaultRichColors:h,duration:(Ne=g==null?void 0:g.duration)!=null?Ne:m,className:g==null?void 0:g.className,descriptionClassName:g==null?void 0:g.descriptionClassName,invert:n,visibleToasts:f,closeButton:(Pe=g==null?void 0:g.closeButton)!=null?Pe:l,interacting:G,position:te,style:g==null?void 0:g.style,unstyled:g==null?void 0:g.unstyled,classNames:g==null?void 0:g.classNames,cancelButtonStyle:g==null?void 0:g.cancelButtonStyle,actionButtonStyle:g==null?void 0:g.actionButtonStyle,removeToast:J,toasts:E.filter(Oe=>Oe.position==ge.position),heights:I.filter(Oe=>Oe.position==ge.position),setHeights:D,expandByDefault:i,gap:y,loadingIcon:b,expanded:F,pauseWhenPageIsHidden:C,swipeDirections:s.swipeDirections})})):null}))});const ays=({...s})=>{const{theme:t="system"}=Mgs();return e.jsx(rys,{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 iys=mXe[" useId ".trim().toString()]||(()=>{}),oys=0;function qg(s){const[t,n]=_.useState(iys());return Rx(()=>{n(r=>r??String(oys++))},[s]),t?`radix-${t}`:""}var tOe="focusScope.autoFocusOnMount",sOe="focusScope.autoFocusOnUnmount",bmt={bubbles:!1,cancelable:!0},lys="FocusScope",Tre=_.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=_.useState(null),d=Ax(a),u=Ax(i),h=_.useRef(null),m=el(t,g=>c(g)),p=_.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;_.useEffect(()=>{if(r){let g=function(w){if(p.paused||!o)return;const S=w.target;o.contains(S)?h.current=S:YT(h.current,{select:!0})},v=function(w){if(p.paused||!o)return;const S=w.relatedTarget;S!==null&&(o.contains(S)||YT(h.current,{select:!0}))},y=function(w){if(document.activeElement===document.body)for(const C of w)C.removedNodes.length>0&&YT(o)};document.addEventListener("focusin",g),document.addEventListener("focusout",v);const b=new MutationObserver(y);return o&&b.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",v),b.disconnect()}}},[r,o,p.paused]),_.useEffect(()=>{if(o){wmt.add(p);const g=document.activeElement;if(!o.contains(g)){const y=new CustomEvent(tOe,bmt);o.addEventListener(tOe,d),o.dispatchEvent(y),y.defaultPrevented||(cys(pys(ZMt(o)),{select:!0}),document.activeElement===g&&YT(o))}return()=>{o.removeEventListener(tOe,d),setTimeout(()=>{const y=new CustomEvent(sOe,bmt);o.addEventListener(sOe,u),o.dispatchEvent(y),y.defaultPrevented||YT(g??document.body,{select:!0}),o.removeEventListener(sOe,u),wmt.remove(p)},0)}}},[o,d,u,p]);const f=_.useCallback(g=>{if(!n&&!r||p.paused)return;const v=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,y=document.activeElement;if(v&&y){const b=g.currentTarget,[w,S]=dys(b);w&&S?!g.shiftKey&&y===S?(g.preventDefault(),n&&YT(w,{select:!0})):g.shiftKey&&y===w&&(g.preventDefault(),n&&YT(S,{select:!0})):y===b&&g.preventDefault()}},[n,r,p.paused]);return e.jsx(ci.div,{tabIndex:-1,...l,ref:m,onKeyDown:f})});Tre.displayName=lys;function cys(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(YT(r,{select:t}),document.activeElement!==n)return}function dys(s){const t=ZMt(s),n=_mt(t,s),r=_mt(t.reverse(),s);return[n,r]}function ZMt(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 _mt(s,t){for(const n of s)if(!uys(n,{upTo:t}))return n}function uys(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 hys(s){return s instanceof HTMLInputElement&&"select"in s}function YT(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&hys(s)&&t&&s.select()}}var wmt=mys();function mys(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=jmt(s,t),s.unshift(t)},remove(t){var n;s=jmt(s,t),(n=s[0])==null||n.resume()}}}function jmt(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pys(s){return s.filter(t=>t.tagName!=="A")}var nOe=0;function OMe(){_.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??Nmt()),document.body.insertAdjacentElement("beforeend",s[1]??Nmt()),nOe++,()=>{nOe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),nOe--}},[])}function Nmt(){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 S4=function(){return S4=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return Mys;var t=Pys(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])}},Iys=ePt(),Sq="data-scroll-locked",Dys=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(xys,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(Sq,`] { 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(N4e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(k4e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(N4e," .").concat(N4e,` { right: 0 `).concat(r,`; } .`).concat(k4e," .").concat(k4e,` { margin-right: 0 `).concat(r,`; } body[`).concat(Sq,`] { `).concat(gys,": ").concat(o,`px; } `)},Smt=function(){var s=parseInt(document.body.getAttribute(Sq)||"0",10);return isFinite(s)?s:0},Rys=function(){_.useEffect(function(){return document.body.setAttribute(Sq,(Smt()+1).toString()),function(){var s=Smt()-1;s<=0?document.body.removeAttribute(Sq):document.body.setAttribute(Sq,s.toString())}},[])},Fys=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;Rys();var i=_.useMemo(function(){return Lys(a)},[a]);return _.createElement(Iys,{styles:Dys(i,!t,a,n?"":"!important")})},lqe=!1;if(typeof window<"u")try{var ole=Object.defineProperty({},"passive",{get:function(){return lqe=!0,!0}});window.addEventListener("test",ole,ole),window.removeEventListener("test",ole,ole)}catch{lqe=!1}var yB=lqe?{passive:!1}:!1,Oys=function(s){return s.tagName==="TEXTAREA"},tPt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Oys(s)&&n[t]==="visible")},zys=function(s){return tPt(s,"overflowY")},Bys=function(s){return tPt(s,"overflowX")},Cmt=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=sPt(s,r);if(a){var i=nPt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},$ys=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Uys=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},sPt=function(s,t){return s==="v"?zys(t):Bys(t)},nPt=function(s,t){return s==="v"?$ys(t):Uys(t)},qys=function(s,t){return s==="h"&&t==="rtl"?-1:1},Vys=function(s,t,n,r,a){var i=qys(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,m=0;do{if(!o)break;var p=nPt(s,o),f=p[0],g=p[1],v=p[2],y=g-v-i*f;(f||y)&&sPt(s,o)&&(h+=y,m+=f);var b=o.parentNode;o=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(h)<1||!a)||!u&&(Math.abs(m)<1||!a))&&(d=!0),d},lle=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Amt=function(s){return[s.deltaX,s.deltaY]},Emt=function(s){return s&&"current"in s?s.current:s},Hys=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Gys=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},Wys=0,vB=[];function Kys(s){var t=_.useRef([]),n=_.useRef([0,0]),r=_.useRef(),a=_.useState(Wys++)[0],i=_.useState(ePt)[0],l=_.useRef(s);_.useEffect(function(){l.current=s},[s]),_.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var g=fys([s.lockRef.current],(s.shards||[]).map(Emt),!0).filter(Boolean);return g.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),g.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=_.useCallback(function(g,v){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!l.current.allowPinchZoom;var y=lle(g),b=n.current,w="deltaX"in g?g.deltaX:b[0]-y[0],S="deltaY"in g?g.deltaY:b[1]-y[1],C,E=g.target,P=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in g&&P==="h"&&E.type==="range")return!1;var M=Cmt(P,E);if(!M)return!0;if(M?C=P:(C=P==="v"?"h":"v",M=Cmt(P,E)),!M)return!1;if(!r.current&&"changedTouches"in g&&(w||S)&&(r.current=C),!C)return!0;var I=r.current||C;return Vys(I,v,g,I==="h"?w:S,!0)},[]),c=_.useCallback(function(g){var v=g;if(!(!vB.length||vB[vB.length-1]!==i)){var y="deltaY"in v?Amt(v):lle(v),b=t.current.filter(function(C){return C.name===v.type&&(C.target===v.target||v.target===C.shadowParent)&&Hys(C.delta,y)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var w=(l.current.shards||[]).map(Emt).filter(Boolean).filter(function(C){return C.contains(v.target)}),S=w.length>0?o(v,w[0]):!l.current.noIsolation;S&&v.cancelable&&v.preventDefault()}}},[]),d=_.useCallback(function(g,v,y,b){var w={name:g,delta:v,target:y,should:b,shadowParent:Yys(y)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),u=_.useCallback(function(g){n.current=lle(g),r.current=void 0},[]),h=_.useCallback(function(g){d(g.type,Amt(g),g.target,o(g,s.lockRef.current))},[]),m=_.useCallback(function(g){d(g.type,lle(g),g.target,o(g,s.lockRef.current))},[]);_.useEffect(function(){return vB.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,yB),document.addEventListener("touchmove",c,yB),document.addEventListener("touchstart",u,yB),function(){vB=vB.filter(function(g){return g!==i}),document.removeEventListener("wheel",c,yB),document.removeEventListener("touchmove",c,yB),document.removeEventListener("touchstart",u,yB)}},[]);var p=s.removeScrollBar,f=s.inert;return _.createElement(_.Fragment,null,f?_.createElement(i,{styles:Gys(a)}):null,p?_.createElement(Fys,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function Yys(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const Zys=Nys(JMt,Kys);var Mre=_.forwardRef(function(s,t){return _.createElement(zMe,S4({},s,{ref:t,sideCar:Zys}))});Mre.classNames=zMe.classNames;var Xys=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},bB=new WeakMap,cle=new WeakMap,dle={},oOe=0,rPt=function(s){return s&&(s.host||rPt(s.parentNode))},Qys=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=rPt(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})},Jys=function(s,t,n,r){var a=Qys(t,Array.isArray(s)?s:[s]);dle[n]||(dle[n]=new WeakMap);var i=dle[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(m){if(o.has(m))u(m);else try{var p=m.getAttribute(r),f=p!==null&&p!=="false",g=(bB.get(m)||0)+1,v=(i.get(m)||0)+1;bB.set(m,g),i.set(m,v),l.push(m),g===1&&f&&cle.set(m,!0),v===1&&m.setAttribute(n,"true"),f||m.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",m,y)}})};return u(t),o.clear(),oOe++,function(){l.forEach(function(h){var m=bB.get(h)-1,p=i.get(h)-1;bB.set(h,m),i.set(h,p),m||(cle.has(h)||h.removeAttribute(r),cle.delete(h)),p||h.removeAttribute(n)}),oOe--,oOe||(bB=new WeakMap,bB=new WeakMap,cle=new WeakMap,dle={})}},BMe=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=Xys(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),Jys(r,a,n,"aria-hidden")):function(){return null}},$Me="Dialog",[aPt,iPt]=uf($Me),[e0s,FS]=aPt($Me),oPt=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=_.useRef(null),c=_.useRef(null),[d,u]=Gg({prop:r,defaultProp:a??!1,onChange:i,caller:$Me});return e.jsx(e0s,{scope:t,triggerRef:o,contentRef:c,contentId:qg(),titleId:qg(),descriptionId:qg(),open:d,onOpenChange:u,onOpenToggle:_.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};oPt.displayName=$Me;var lPt="DialogTrigger",cPt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=FS(lPt,n),i=el(t,a.triggerRef);return e.jsx(ci.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":mQe(a.open),...r,ref:i,onClick:wa(s.onClick,a.onOpenToggle)})});cPt.displayName=lPt;var uQe="DialogPortal",[t0s,dPt]=aPt(uQe,{forceMount:void 0}),uPt=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=FS(uQe,t);return e.jsx(t0s,{scope:t,forceMount:n,children:_.Children.map(r,l=>e.jsx(vg,{present:n||i.open,children:e.jsx(sW,{asChild:!0,container:a,children:l})}))})};uPt.displayName=uQe;var K3e="DialogOverlay",hPt=_.forwardRef((s,t)=>{const n=dPt(K3e,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=FS(K3e,s.__scopeDialog);return i.modal?e.jsx(vg,{present:r||i.open,children:e.jsx(n0s,{...a,ref:t})}):null});hPt.displayName=K3e;var s0s=OP("DialogOverlay.RemoveScroll"),n0s=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=FS(K3e,n);return e.jsx(Mre,{as:s0s,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(ci.div,{"data-state":mQe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Q7="DialogContent",mPt=_.forwardRef((s,t)=>{const n=dPt(Q7,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=FS(Q7,s.__scopeDialog);return e.jsx(vg,{present:r||i.open,children:i.modal?e.jsx(r0s,{...a,ref:t}):e.jsx(a0s,{...a,ref:t})})});mPt.displayName=Q7;var r0s=_.forwardRef((s,t)=>{const n=FS(Q7,s.__scopeDialog),r=_.useRef(null),a=el(t,n.contentRef,r);return _.useEffect(()=>{const i=r.current;if(i)return BMe(i)},[]),e.jsx(pPt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:wa(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:wa(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:wa(s.onFocusOutside,i=>i.preventDefault())})}),a0s=_.forwardRef((s,t)=>{const n=FS(Q7,s.__scopeDialog),r=_.useRef(!1),a=_.useRef(!1);return e.jsx(pPt,{...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()}})}),pPt=_.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=FS(Q7,n),c=_.useRef(null),d=el(t,c);return OMe(),e.jsxs(e.Fragment,{children:[e.jsx(Tre,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(pL,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":mQe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(o0s,{titleId:o.titleId}),e.jsx(c0s,{contentRef:c,descriptionId:o.descriptionId})]})]})}),hQe="DialogTitle",fPt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=FS(hQe,n);return e.jsx(ci.h2,{id:a.titleId,...r,ref:t})});fPt.displayName=hQe;var xPt="DialogDescription",gPt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=FS(xPt,n);return e.jsx(ci.p,{id:a.descriptionId,...r,ref:t})});gPt.displayName=xPt;var yPt="DialogClose",vPt=_.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=FS(yPt,n);return e.jsx(ci.button,{type:"button",...r,ref:t,onClick:wa(s.onClick,()=>a.onOpenChange(!1))})});vPt.displayName=yPt;function mQe(s){return s?"open":"closed"}var bPt="DialogTitleWarning",[i0s,_Pt]=exs(bPt,{contentName:Q7,titleName:hQe,docsSlug:"dialog"}),o0s=({titleId:s})=>{const t=_Pt(bPt),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 _.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},l0s="DialogDescriptionWarning",c0s=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${_Pt(l0s).contentName}}.`;return _.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},UMe=oPt,pQe=cPt,qMe=uPt,rW=hPt,aW=mPt,Pre=fPt,Lre=gPt,Ire=vPt,wPt="AlertDialog",[d0s,D_r]=uf(wPt,[iPt]),zE=iPt(),jPt=s=>{const{__scopeAlertDialog:t,...n}=s,r=zE(t);return e.jsx(UMe,{...r,...n,modal:!0})};jPt.displayName=wPt;var u0s="AlertDialogTrigger",NPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=zE(n);return e.jsx(pQe,{...a,...r,ref:t})});NPt.displayName=u0s;var h0s="AlertDialogPortal",kPt=s=>{const{__scopeAlertDialog:t,...n}=s,r=zE(t);return e.jsx(qMe,{...r,...n})};kPt.displayName=h0s;var m0s="AlertDialogOverlay",SPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=zE(n);return e.jsx(rW,{...a,...r,ref:t})});SPt.displayName=m0s;var Cq="AlertDialogContent",[p0s,f0s]=d0s(Cq),x0s=mMt("AlertDialogContent"),CPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=zE(n),l=_.useRef(null),o=el(t,l),c=_.useRef(null);return e.jsx(i0s,{contentName:Cq,titleName:APt,docsSlug:"alert-dialog",children:e.jsx(p0s,{scope:n,cancelRef:c,children:e.jsxs(aW,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:wa(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(x0s,{children:r}),e.jsx(y0s,{contentRef:l})]})})})});CPt.displayName=Cq;var APt="AlertDialogTitle",EPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=zE(n);return e.jsx(Pre,{...a,...r,ref:t})});EPt.displayName=APt;var TPt="AlertDialogDescription",MPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=zE(n);return e.jsx(Lre,{...a,...r,ref:t})});MPt.displayName=TPt;var g0s="AlertDialogAction",PPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=zE(n);return e.jsx(Ire,{...a,...r,ref:t})});PPt.displayName=g0s;var LPt="AlertDialogCancel",IPt=_.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=f0s(LPt,n),i=zE(n),l=el(t,a);return e.jsx(Ire,{...i,...r,ref:l})});IPt.displayName=LPt;var y0s=({contentRef:s})=>{const t=`\`${Cq}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${Cq}\` by passing a \`${TPt}\` 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 \`${Cq}\`. 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 _.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},v0s=jPt,b0s=NPt,_0s=kPt,DPt=SPt,RPt=CPt,FPt=PPt,OPt=IPt,zPt=EPt,BPt=MPt;const SH=G9("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"}}),z=_.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?aQe:"button";return e.jsx(l,{className:Ct(SH({variant:t,size:n,className:s})),ref:i,...a})});z.displayName="Button";const Ql=v0s,Ex=b0s,w0s=_0s,$Pt=_.forwardRef(({className:s,...t},n)=>e.jsx(DPt,{className:Ct("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}));$Pt.displayName=DPt.displayName;const zl=_.forwardRef(({className:s,...t},n)=>e.jsxs(w0s,{children:[e.jsx($Pt,{}),e.jsx(RPt,{ref:n,className:Ct("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})]}));zl.displayName=RPt.displayName;const Bl=({className:s,...t})=>e.jsx("div",{className:Ct("flex flex-col space-y-2 text-center sm:text-left",s),...t});Bl.displayName="AlertDialogHeader";const $l=({className:s,...t})=>e.jsx("div",{className:Ct("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});$l.displayName="AlertDialogFooter";const Ul=_.forwardRef(({className:s,...t},n)=>e.jsx(zPt,{ref:n,className:Ct("text-lg font-semibold",s),...t}));Ul.displayName=zPt.displayName;const ql=_.forwardRef(({className:s,...t},n)=>e.jsx(BPt,{ref:n,className:Ct("text-sm text-muted-foreground",s),...t}));ql.displayName=BPt.displayName;const Ml=_.forwardRef(({className:s,...t},n)=>e.jsx(FPt,{ref:n,className:Ct(SH(),s),...t}));Ml.displayName=FPt.displayName;const Vl=_.forwardRef(({className:s,...t},n)=>e.jsx(OPt,{ref:n,className:Ct(SH({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Vl.displayName=OPt.displayName;let Y3e=null;const j0s=["delete","remove","revoke","cannot be undone","permanently"];function Qi(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??j0s.some(i=>r.includes(i));return new Promise(i=>{if(!Y3e){i(window.confirm(n.description??n.title??"Are you sure?"));return}Y3e({...n,destructive:a,resolve:i})})}function N0s(){const[s,t]=_.useState(null);_.useEffect(()=>(Y3e=a=>t(a),()=>{Y3e=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(Ql,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(zl,{className:"sm:max-w-md",children:[e.jsx(Bl,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ct("mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full",r?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:e.jsx(nl,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(Ul,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(ql,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs($l,{className:"gap-2 sm:gap-2",children:[e.jsx(Vl,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(Ml,{onClick:()=>n(!0),className:Ct(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const k0s=["top","right","bottom","left"],zP=Math.min,Xw=Math.max,Z3e=Math.round,ule=Math.floor,BP=s=>({x:s,y:s}),S0s={left:"right",right:"left",bottom:"top",top:"bottom"},C0s={start:"end",end:"start"};function cqe(s,t,n){return Xw(s,zP(t,n))}function NE(s,t){return typeof s=="function"?s(t):s}function kE(s){return s.split("-")[0]}function iW(s){return s.split("-")[1]}function fQe(s){return s==="x"?"y":"x"}function xQe(s){return s==="y"?"height":"width"}function $P(s){return["top","bottom"].includes(kE(s))?"y":"x"}function gQe(s){return fQe($P(s))}function A0s(s,t,n){n===void 0&&(n=!1);const r=iW(s),a=gQe(s),i=xQe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=X3e(l)),[l,X3e(l)]}function E0s(s){const t=X3e(s);return[dqe(s),t,dqe(t)]}function dqe(s){return s.replace(/start|end/g,t=>C0s[t])}function T0s(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 M0s(s,t,n,r){const a=iW(s);let i=T0s(kE(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(dqe)))),i}function X3e(s){return s.replace(/left|right|bottom|top/g,t=>S0s[t])}function P0s(s){return{top:0,right:0,bottom:0,left:0,...s}}function UPt(s){return typeof s!="number"?P0s(s):{top:s,right:s,bottom:s,left:s}}function Q3e(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 Tmt(s,t,n){let{reference:r,floating:a}=s;const i=$P(t),l=gQe(t),o=xQe(l),c=kE(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,m=r[o]/2-a[o]/2;let p;switch(c){case"top":p={x:u,y:r.y-a.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:h};break;case"left":p={x:r.x-a.width,y:h};break;default:p={x:r.x,y:r.y}}switch(iW(t)){case"start":p[l]-=m*(n&&d?-1:1);break;case"end":p[l]+=m*(n&&d?-1:1);break}return p}const L0s=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}=Tmt(d,r,c),m=r,p={},f=0;for(let g=0;g({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}=NE(s,t)||{};if(d==null)return{};const h=UPt(u),m={x:n,y:r},p=gQe(a),f=xQe(p),g=await l.getDimensions(d),v=p==="y",y=v?"top":"left",b=v?"bottom":"right",w=v?"clientHeight":"clientWidth",S=i.reference[f]+i.reference[p]-m[p]-i.floating[f],C=m[p]-i.reference[p],E=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let P=E?E[w]:0;(!P||!await(l.isElement==null?void 0:l.isElement(E)))&&(P=o.floating[w]||i.floating[f]);const M=S/2-C/2,I=P/2-g[f]/2-1,D=zP(h[y],I),F=zP(h[b],I),q=D,G=P-g[f]-F,V=P/2-g[f]/2+M,H=cqe(q,V,G),K=!c.arrow&&iW(a)!=null&&V!==H&&i.reference[f]/2-(VV<=0)){var F,q;const V=(((F=i.flip)==null?void 0:F.index)||0)+1,H=P[V];if(H)return{data:{index:V,overflows:D},reset:{placement:H}};let K=(q=D.filter(Z=>Z.overflows[0]<=0).sort((Z,oe)=>Z.overflows[1]-oe.overflows[1])[0])==null?void 0:q.placement;if(!K)switch(p){case"bestFit":{var G;const Z=(G=D.filter(oe=>{if(E){const re=$P(oe.placement);return re===b||re==="y"}return!0}).map(oe=>[oe.placement,oe.overflows.filter(re=>re>0).reduce((re,ae)=>re+ae,0)]).sort((oe,re)=>oe[1]-re[1])[0])==null?void 0:G[0];Z&&(K=Z);break}case"initialPlacement":K=o;break}if(a!==K)return{reset:{placement:K}}}return{}}}};function Mmt(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function Pmt(s){return k0s.some(t=>s[t]>=0)}const R0s=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=NE(s,t);switch(r){case"referenceHidden":{const i=await tte(t,{...a,elementContext:"reference"}),l=Mmt(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:Pmt(l)}}}case"escaped":{const i=await tte(t,{...a,altBoundary:!0}),l=Mmt(i,n.floating);return{data:{escapedOffsets:l,escaped:Pmt(l)}}}default:return{}}}}};async function F0s(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=kE(n),o=iW(n),c=$P(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=NE(t,s);let{mainAxis:m,crossAxis:p,alignmentAxis:f}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof f=="number"&&(p=o==="end"?f*-1:f),c?{x:p*u,y:m*d}:{x:m*d,y:p*u}}const O0s=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 F0s(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}}}}},z0s=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:y,y:b}=v;return{x:y,y:b}}},...c}=NE(s,t),d={x:n,y:r},u=await tte(t,c),h=$P(kE(a)),m=fQe(h);let p=d[m],f=d[h];if(i){const v=m==="y"?"top":"left",y=m==="y"?"bottom":"right",b=p+u[v],w=p-u[y];p=cqe(b,p,w)}if(l){const v=h==="y"?"top":"left",y=h==="y"?"bottom":"right",b=f+u[v],w=f-u[y];f=cqe(b,f,w)}const g=o.fn({...t,[m]:p,[h]:f});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[m]:i,[h]:l}}}}}},B0s=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}=NE(s,t),u={x:n,y:r},h=$P(a),m=fQe(h);let p=u[m],f=u[h];const g=NE(o,t),v=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const w=m==="y"?"height":"width",S=i.reference[m]-i.floating[w]+v.mainAxis,C=i.reference[m]+i.reference[w]-v.mainAxis;pC&&(p=C)}if(d){var y,b;const w=m==="y"?"width":"height",S=["top","left"].includes(kE(a)),C=i.reference[h]-i.floating[w]+(S&&((y=l.offset)==null?void 0:y[h])||0)+(S?0:v.crossAxis),E=i.reference[h]+i.reference[w]+(S?0:((b=l.offset)==null?void 0:b[h])||0)-(S?v.crossAxis:0);fE&&(f=E)}return{[m]:p,[h]:f}}}},$0s=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}=NE(s,t),u=await tte(t,d),h=kE(a),m=iW(a),p=$P(a)==="y",{width:f,height:g}=i.floating;let v,y;h==="top"||h==="bottom"?(v=h,y=m===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(y=h,v=m==="end"?"top":"bottom");const b=g-u.top-u.bottom,w=f-u.left-u.right,S=zP(g-u[v],b),C=zP(f-u[y],w),E=!t.middlewareData.shift;let P=S,M=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=w),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(P=b),E&&!m){const D=Xw(u.left,0),F=Xw(u.right,0),q=Xw(u.top,0),G=Xw(u.bottom,0);p?M=f-2*(D!==0||F!==0?D+F:Xw(u.left,u.right)):P=g-2*(q!==0||G!==0?q+G:Xw(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:P});const I=await l.getDimensions(o.floating);return f!==I.width||g!==I.height?{reset:{rects:!0}}:{}}}};function VMe(){return typeof window<"u"}function oW(s){return qPt(s)?(s.nodeName||"").toLowerCase():"#document"}function Nj(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function SC(s){var t;return(t=(qPt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function qPt(s){return VMe()?s instanceof Node||s instanceof Nj(s).Node:!1}function TS(s){return VMe()?s instanceof Element||s instanceof Nj(s).Element:!1}function uC(s){return VMe()?s instanceof HTMLElement||s instanceof Nj(s).HTMLElement:!1}function Lmt(s){return!VMe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof Nj(s).ShadowRoot}function Dre(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=MS(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function U0s(s){return["table","td","th"].includes(oW(s))}function HMe(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function yQe(s){const t=vQe(),n=TS(s)?MS(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 q0s(s){let t=UP(s);for(;uC(t)&&!CH(t);){if(yQe(t))return t;if(HMe(t))return null;t=UP(t)}return null}function vQe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function CH(s){return["html","body","#document"].includes(oW(s))}function MS(s){return Nj(s).getComputedStyle(s)}function GMe(s){return TS(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function UP(s){if(oW(s)==="html")return s;const t=s.assignedSlot||s.parentNode||Lmt(s)&&s.host||SC(s);return Lmt(t)?t.host:t}function VPt(s){const t=UP(s);return CH(t)?s.ownerDocument?s.ownerDocument.body:s.body:uC(t)&&Dre(t)?t:VPt(t)}function ste(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=VPt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=Nj(a);if(i){const o=uqe(l);return t.concat(l,l.visualViewport||[],Dre(a)?a:[],o&&n?ste(o):[])}return t.concat(a,ste(a,[],n))}function uqe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function HPt(s){const t=MS(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=uC(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=Z3e(n)!==i||Z3e(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function bQe(s){return TS(s)?s:s.contextElement}function Aq(s){const t=bQe(s);if(!uC(t))return BP(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=HPt(t);let l=(i?Z3e(n.width):n.width)/r,o=(i?Z3e(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const V0s=BP(0);function GPt(s){const t=Nj(s);return!vQe()||!t.visualViewport?V0s:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function H0s(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==Nj(s)?!1:t}function J7(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=bQe(s);let l=BP(1);t&&(r?TS(r)&&(l=Aq(r)):l=Aq(s));const o=H0s(i,n,r)?GPt(i):BP(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 m=Nj(i),p=r&&TS(r)?Nj(r):r;let f=m,g=uqe(f);for(;g&&r&&p!==f;){const v=Aq(g),y=g.getBoundingClientRect(),b=MS(g),w=y.left+(g.clientLeft+parseFloat(b.paddingLeft))*v.x,S=y.top+(g.clientTop+parseFloat(b.paddingTop))*v.y;c*=v.x,d*=v.y,u*=v.x,h*=v.y,c+=w,d+=S,f=Nj(g),g=uqe(f)}}return Q3e({width:u,height:h,x:c,y:d})}function G0s(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=SC(r),o=t?HMe(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=BP(1);const u=BP(0),h=uC(r);if((h||!h&&!i)&&((oW(r)!=="body"||Dre(l))&&(c=GMe(r)),uC(r))){const m=J7(r);d=Aq(r),u.x=m.x+r.clientLeft,u.y=m.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 W0s(s){return Array.from(s.getClientRects())}function hqe(s,t){const n=GMe(s).scrollLeft;return t?t.left+n:J7(SC(s)).left+n}function K0s(s){const t=SC(s),n=GMe(s),r=s.ownerDocument.body,a=Xw(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Xw(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+hqe(s);const o=-n.scrollTop;return MS(r).direction==="rtl"&&(l+=Xw(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function Y0s(s,t){const n=Nj(s),r=SC(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=vQe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function Z0s(s,t){const n=J7(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=uC(s)?Aq(s):BP(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 Imt(s,t,n){let r;if(t==="viewport")r=Y0s(s,n);else if(t==="document")r=K0s(SC(s));else if(TS(t))r=Z0s(t,n);else{const a=GPt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return Q3e(r)}function WPt(s,t){const n=UP(s);return n===t||!TS(n)||CH(n)?!1:MS(n).position==="fixed"||WPt(n,t)}function X0s(s,t){const n=t.get(s);if(n)return n;let r=ste(s,[],!1).filter(o=>TS(o)&&oW(o)!=="body"),a=null;const i=MS(s).position==="fixed";let l=i?UP(s):s;for(;TS(l)&&!CH(l);){const o=MS(l),c=yQe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||Dre(l)&&!c&&WPt(s,l))?r=r.filter(u=>u!==l):a=o,l=UP(l)}return t.set(s,r),r}function Q0s(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?HMe(t)?[]:X0s(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=Imt(t,u,a);return d.top=Xw(h.top,d.top),d.right=zP(h.right,d.right),d.bottom=zP(h.bottom,d.bottom),d.left=Xw(h.left,d.left),d},Imt(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function J0s(s){const{width:t,height:n}=HPt(s);return{width:t,height:n}}function evs(s,t,n){const r=uC(t),a=SC(t),i=n==="fixed",l=J7(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=BP(0);if(r||!r&&!i)if((oW(t)!=="body"||Dre(a))&&(o=GMe(t)),r){const p=J7(t,!0,i,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else a&&(c.x=hqe(a));let d=0,u=0;if(a&&!r&&!i){const p=a.getBoundingClientRect();u=p.top+o.scrollTop,d=p.left+o.scrollLeft-hqe(a,p)}const h=l.left+o.scrollLeft-c.x-d,m=l.top+o.scrollTop-c.y-u;return{x:h,y:m,width:l.width,height:l.height}}function lOe(s){return MS(s).position==="static"}function Dmt(s,t){if(!uC(s)||MS(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return SC(s)===n&&(n=n.ownerDocument.body),n}function KPt(s,t){const n=Nj(s);if(HMe(s))return n;if(!uC(s)){let a=UP(s);for(;a&&!CH(a);){if(TS(a)&&!lOe(a))return a;a=UP(a)}return n}let r=Dmt(s,t);for(;r&&U0s(r)&&lOe(r);)r=Dmt(r,t);return r&&CH(r)&&lOe(r)&&!yQe(r)?n:r||q0s(s)||n}const tvs=async function(s){const t=this.getOffsetParent||KPt,n=this.getDimensions,r=await n(s.floating);return{reference:evs(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function svs(s){return MS(s).direction==="rtl"}const nvs={convertOffsetParentRelativeRectToViewportRelativeRect:G0s,getDocumentElement:SC,getClippingRect:Q0s,getOffsetParent:KPt,getElementRects:tvs,getClientRects:W0s,getDimensions:J0s,getScale:Aq,isElement:TS,isRTL:svs};function rvs(s,t){let n=null,r;const a=SC(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:m}=s.getBoundingClientRect();if(o||t(),!h||!m)return;const p=ule(u),f=ule(a.clientWidth-(d+h)),g=ule(a.clientHeight-(u+m)),v=ule(d),b={rootMargin:-p+"px "+-f+"px "+-g+"px "+-v+"px",threshold:Xw(0,zP(1,c))||1};let w=!0;function S(C){const E=C[0].intersectionRatio;if(E!==c){if(!w)return l();E?l(!1,E):r=setTimeout(()=>{l(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(S,{...b,root:a.ownerDocument})}catch{n=new IntersectionObserver(S,b)}n.observe(s)}return l(!0),i}function avs(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=bQe(s),u=a||i?[...d?ste(d):[],...ste(t)]:[];u.forEach(y=>{a&&y.addEventListener("scroll",n,{passive:!0}),i&&y.addEventListener("resize",n)});const h=d&&o?rvs(d,n):null;let m=-1,p=null;l&&(p=new ResizeObserver(y=>{let[b]=y;b&&b.target===d&&p&&(p.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var w;(w=p)==null||w.observe(t)})),n()}),d&&!c&&p.observe(d),p.observe(t));let f,g=c?J7(s):null;c&&v();function v(){const y=J7(s);g&&(y.x!==g.x||y.y!==g.y||y.width!==g.width||y.height!==g.height)&&n(),g=y,f=requestAnimationFrame(v)}return n(),()=>{var y;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(y=p)==null||y.disconnect(),p=null,c&&cancelAnimationFrame(f)}}const ivs=O0s,ovs=z0s,lvs=D0s,cvs=$0s,dvs=R0s,Rmt=I0s,uvs=B0s,hvs=(s,t,n)=>{const r=new Map,a={platform:nvs,...n},i={...a.platform,_c:r};return L0s(s,t,{...a,platform:i})};var S4e=typeof document<"u"?_.useLayoutEffect:_.useEffect;function J3e(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(!J3e(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)&&!J3e(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function YPt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function Fmt(s,t){const n=YPt(s);return Math.round(t*n)/n}function cOe(s){const t=_.useRef(s);return S4e(()=>{t.current=s}),t}function mvs(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]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,p]=_.useState(r);J3e(m,r)||p(r);const[f,g]=_.useState(null),[v,y]=_.useState(null),b=_.useCallback(oe=>{oe!==E.current&&(E.current=oe,g(oe))},[]),w=_.useCallback(oe=>{oe!==P.current&&(P.current=oe,y(oe))},[]),S=i||f,C=l||v,E=_.useRef(null),P=_.useRef(null),M=_.useRef(u),I=c!=null,D=cOe(c),F=cOe(a),q=cOe(d),G=_.useCallback(()=>{if(!E.current||!P.current)return;const oe={placement:t,strategy:n,middleware:m};F.current&&(oe.platform=F.current),hvs(E.current,P.current,oe).then(re=>{const ae={...re,isPositioned:q.current!==!1};V.current&&!J3e(M.current,ae)&&(M.current=ae,pv.flushSync(()=>{h(ae)}))})},[m,t,n,F,q]);S4e(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(oe=>({...oe,isPositioned:!1})))},[d]);const V=_.useRef(!1);S4e(()=>(V.current=!0,()=>{V.current=!1}),[]),S4e(()=>{if(S&&(E.current=S),C&&(P.current=C),S&&C){if(D.current)return D.current(S,C,G);G()}},[S,C,G,D,I]);const H=_.useMemo(()=>({reference:E,floating:P,setReference:b,setFloating:w}),[b,w]),K=_.useMemo(()=>({reference:S,floating:C}),[S,C]),Z=_.useMemo(()=>{const oe={position:n,left:0,top:0};if(!K.floating)return oe;const re=Fmt(K.floating,u.x),ae=Fmt(K.floating,u.y);return o?{...oe,transform:"translate("+re+"px, "+ae+"px)",...YPt(K.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:re,top:ae}},[n,o,K.floating,u.x,u.y]);return _.useMemo(()=>({...u,update:G,refs:H,elements:K,floatingStyles:Z}),[u,G,H,K,Z])}const pvs=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?Rmt({element:r.current,padding:a}).fn(n):{}:r?Rmt({element:r,padding:a}).fn(n):{}}}},fvs=(s,t)=>({...ivs(s),options:[s,t]}),xvs=(s,t)=>({...ovs(s),options:[s,t]}),gvs=(s,t)=>({...uvs(s),options:[s,t]}),yvs=(s,t)=>({...lvs(s),options:[s,t]}),vvs=(s,t)=>({...cvs(s),options:[s,t]}),bvs=(s,t)=>({...dvs(s),options:[s,t]}),_vs=(s,t)=>({...pvs(s),options:[s,t]});var wvs="Arrow",ZPt=_.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(ci.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"})})});ZPt.displayName=wvs;var jvs=ZPt;function Rre(s){const[t,n]=_.useState(void 0);return Rx(()=>{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 _Qe="Popper",[XPt,CC]=uf(_Qe),[Nvs,QPt]=XPt(_Qe),JPt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=_.useState(null);return e.jsx(Nvs,{scope:t,anchor:r,onAnchorChange:a,children:n})};JPt.displayName=_Qe;var eLt="PopperAnchor",tLt=_.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=QPt(eLt,n),l=_.useRef(null),o=el(t,l);return _.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(ci.div,{...a,ref:o})});tLt.displayName=eLt;var wQe="PopperContent",[kvs,Svs]=XPt(wQe),sLt=_.forwardRef((s,t)=>{var ge,Ee,Ne,Pe,Oe,ke;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:m=!1,updatePositionStrategy:p="optimized",onPlaced:f,...g}=s,v=QPt(wQe,n),[y,b]=_.useState(null),w=el(t,Ve=>b(Ve)),[S,C]=_.useState(null),E=Rre(S),P=(E==null?void 0:E.width)??0,M=(E==null?void 0:E.height)??0,I=r+(i!=="center"?"-"+i:""),D=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},F=Array.isArray(d)?d:[d],q=F.length>0,G={padding:D,boundary:F.filter(Avs),altBoundary:q},{refs:V,floatingStyles:H,placement:K,isPositioned:Z,middlewareData:oe}=mvs({strategy:"fixed",placement:I,whileElementsMounted:(...Ve)=>avs(...Ve,{animationFrame:p==="always"}),elements:{reference:v.anchor},middleware:[fvs({mainAxis:a+M,alignmentAxis:l}),c&&xvs({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?gvs():void 0,...G}),c&&yvs({...G}),vvs({...G,apply:({elements:Ve,rects:_e,availableWidth:Ae,availableHeight:Se})=>{const{width:We,height:qe}=_e.reference,Be=Ve.floating.style;Be.setProperty("--radix-popper-available-width",`${Ae}px`),Be.setProperty("--radix-popper-available-height",`${Se}px`),Be.setProperty("--radix-popper-anchor-width",`${We}px`),Be.setProperty("--radix-popper-anchor-height",`${qe}px`)}}),S&&_vs({element:S,padding:o}),Evs({arrowWidth:P,arrowHeight:M}),m&&bvs({strategy:"referenceHidden",...G})]}),[re,ae]=aLt(K),J=Ax(f);Rx(()=>{Z&&(J==null||J())},[Z,J]);const te=(ge=oe.arrow)==null?void 0:ge.x,ce=(Ee=oe.arrow)==null?void 0:Ee.y,ve=((Ne=oe.arrow)==null?void 0:Ne.centerOffset)!==0,[me,he]=_.useState();return Rx(()=>{y&&he(window.getComputedStyle(y).zIndex)},[y]),e.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:Z?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:me,"--radix-popper-transform-origin":[(Pe=oe.transformOrigin)==null?void 0:Pe.x,(Oe=oe.transformOrigin)==null?void 0:Oe.y].join(" "),...((ke=oe.hide)==null?void 0:ke.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(kvs,{scope:n,placedSide:re,onArrowChange:C,arrowX:te,arrowY:ce,shouldHideArrow:ve,children:e.jsx(ci.div,{"data-side":re,"data-align":ae,...g,ref:w,style:{...g.style,animation:Z?void 0:"none"}})})})});sLt.displayName=wQe;var nLt="PopperArrow",Cvs={top:"bottom",right:"left",bottom:"top",left:"right"},rLt=_.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=Svs(nLt,r),l=Cvs[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(jvs,{...a,ref:n,style:{...a.style,display:"block"}})})});rLt.displayName=nLt;function Avs(s){return s!==null}var Evs=s=>({name:"transformOrigin",options:s,fn(t){var v,y,b;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]=aLt(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((y=a.arrow)==null?void 0:y.x)??0)+o/2,p=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let f="",g="";return d==="bottom"?(f=l?h:`${m}px`,g=`${-c}px`):d==="top"?(f=l?h:`${m}px`,g=`${r.floating.height+c}px`):d==="right"?(f=`${-c}px`,g=l?h:`${p}px`):d==="left"&&(f=`${r.floating.width+c}px`,g=l?h:`${p}px`),{data:{x:f,y:g}}}});function aLt(s){const[t,n="center"]=s.split("-");return[t,n]}var Fre=JPt,lW=tLt,Ore=sLt,zre=rLt,[WMe,R_r]=uf("Tooltip",[CC]),KMe=CC(),iLt="TooltipProvider",Tvs=700,mqe="tooltip.open",[Mvs,jQe]=WMe(iLt),oLt=s=>{const{__scopeTooltip:t,delayDuration:n=Tvs,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=_.useRef(!0),o=_.useRef(!1),c=_.useRef(0);return _.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(Mvs,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:_.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};oLt.displayName=iLt;var nte="Tooltip",[Pvs,YMe]=WMe(nte),lLt=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=jQe(nte,s.__scopeTooltip),d=KMe(t),[u,h]=_.useState(null),m=qg(),p=_.useRef(0),f=l??c.disableHoverableContent,g=o??c.delayDuration,v=_.useRef(!1),[y,b]=Gg({prop:r,defaultProp:a??!1,onChange:P=>{P?(c.onOpen(),document.dispatchEvent(new CustomEvent(mqe))):c.onClose(),i==null||i(P)},caller:nte}),w=_.useMemo(()=>y?v.current?"delayed-open":"instant-open":"closed",[y]),S=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,v.current=!1,b(!0)},[b]),C=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,b(!1)},[b]),E=_.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{v.current=!0,b(!0),p.current=0},g)},[g,b]);return _.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),e.jsx(Fre,{...d,children:e.jsx(Pvs,{scope:t,contentId:m,open:y,stateAttribute:w,trigger:u,onTriggerChange:h,onTriggerEnter:_.useCallback(()=>{c.isOpenDelayedRef.current?E():S()},[c.isOpenDelayedRef,E,S]),onTriggerLeave:_.useCallback(()=>{f?C():(window.clearTimeout(p.current),p.current=0)},[C,f]),onOpen:S,onClose:C,disableHoverableContent:f,children:n})})};lLt.displayName=nte;var pqe="TooltipTrigger",cLt=_.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=YMe(pqe,n),i=jQe(pqe,n),l=KMe(n),o=_.useRef(null),c=el(t,o,a.onTriggerChange),d=_.useRef(!1),u=_.useRef(!1),h=_.useCallback(()=>d.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(lW,{asChild:!0,...l,children:e.jsx(ci.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:wa(s.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:wa(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:wa(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:wa(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:wa(s.onBlur,a.onClose),onClick:wa(s.onClick,a.onClose)})})});cLt.displayName=pqe;var Lvs="TooltipPortal",[F_r,Ivs]=WMe(Lvs,{forceMount:void 0}),AH="TooltipContent",dLt=_.forwardRef((s,t)=>{const n=Ivs(AH,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=YMe(AH,s.__scopeTooltip);return e.jsx(vg,{present:r||l.open,children:l.disableHoverableContent?e.jsx(uLt,{side:a,...i,ref:t}):e.jsx(Dvs,{side:a,...i,ref:t})})}),Dvs=_.forwardRef((s,t)=>{const n=YMe(AH,s.__scopeTooltip),r=jQe(AH,s.__scopeTooltip),a=_.useRef(null),i=el(t,a),[l,o]=_.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,m=_.useCallback(()=>{o(null),h(!1)},[h]),p=_.useCallback((f,g)=>{const v=f.currentTarget,y={x:f.clientX,y:f.clientY},b=Bvs(y,v.getBoundingClientRect()),w=$vs(y,b),S=Uvs(g.getBoundingClientRect()),C=Vvs([...w,...S]);o(C),h(!0)},[h]);return _.useEffect(()=>()=>m(),[m]),_.useEffect(()=>{if(c&&u){const f=v=>p(v,u),g=v=>p(v,c);return c.addEventListener("pointerleave",f),u.addEventListener("pointerleave",g),()=>{c.removeEventListener("pointerleave",f),u.removeEventListener("pointerleave",g)}}},[c,u,p,m]),_.useEffect(()=>{if(l){const f=g=>{const v=g.target,y={x:g.clientX,y:g.clientY},b=(c==null?void 0:c.contains(v))||(u==null?void 0:u.contains(v)),w=!qvs(y,l);b?m():w&&(m(),d())};return document.addEventListener("pointermove",f),()=>document.removeEventListener("pointermove",f)}},[c,u,l,d,m]),e.jsx(uLt,{...s,ref:i})}),[Rvs,Fvs]=WMe(nte,{isInside:!1}),Ovs=mMt("TooltipContent"),uLt=_.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=YMe(AH,n),d=KMe(n),{onClose:u}=c;return _.useEffect(()=>(document.addEventListener(mqe,u),()=>document.removeEventListener(mqe,u)),[u]),_.useEffect(()=>{if(c.trigger){const h=m=>{const p=m.target;p!=null&&p.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(pL,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(Ore,{"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(Ovs,{children:r}),e.jsx(Rvs,{scope:n,isInside:!0,children:e.jsx(Nxs,{id:c.contentId,role:"tooltip",children:a||r})})]})})});dLt.displayName=AH;var hLt="TooltipArrow",zvs=_.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=KMe(n);return Fvs(hLt,n).isInside?null:e.jsx(zre,{...a,...r,ref:t})});zvs.displayName=hLt;function Bvs(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 $vs(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 Uvs(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 qvs(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=m>r&&n<(h-d)*(r-u)/(m-u)+d&&(a=!a)}return a}function Vvs(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),Hvs(t)}function Hvs(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 Gvs=oLt,Wvs=lLt,Kvs=cLt,mLt=dLt;const UN=Gvs,ug=Wvs,hg=Kvs,Tx=_.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(mLt,{ref:r,sideOffset:t,className:Ct("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}));Tx.displayName=mLt.displayName;var cW=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(){}},e9=typeof window>"u"||"Deno"in globalThis;function ab(){}function Yvs(s,t){return typeof s=="function"?s(t):s}function fqe(s){return typeof s=="number"&&s>=0&&s!==1/0}function pLt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function xP(s,t){return typeof s=="function"?s(t):s}function q2(s,t){return typeof s=="function"?s(t):s}function Omt(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==NQe(l,t.options))return!1}else if(!rte(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 zmt(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(t9(t.options.mutationKey)!==t9(i))return!1}else if(!rte(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function NQe(s,t){return((t==null?void 0:t.queryKeyHashFn)||t9)(s)}function t9(s){return JSON.stringify(s,(t,n)=>xqe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function rte(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>rte(s[n],t[n])):!1}function fLt(s,t){if(s===t)return s;const n=Bmt(s)&&Bmt(t);if(n||xqe(s)&&xqe(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 gqe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?fLt(s,t):t}function Xvs(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function Qvs(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var kQe=Symbol();function xLt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===kQe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function gLt(s,t){return typeof s=="function"?s(...t):!!s}var VF,q6,cV,BEt,Jvs=(BEt=class extends cW{constructor(){super();ps(this,VF);ps(this,q6);ps(this,cV);Ht(this,cV,t=>{if(!e9&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ye(this,q6)||this.setEventListener(ye(this,cV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,q6))==null||t.call(this),Ht(this,q6,void 0))}setEventListener(t){var n;Ht(this,cV,t),(n=ye(this,q6))==null||n.call(this),Ht(this,q6,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ye(this,VF)!==t&&(Ht(this,VF,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ye(this,VF)=="boolean"?ye(this,VF):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},VF=new WeakMap,q6=new WeakMap,cV=new WeakMap,BEt),SQe=new Jvs,dV,V6,uV,$Et,e1s=($Et=class extends cW{constructor(){super();ps(this,dV,!0);ps(this,V6);ps(this,uV);Ht(this,uV,t=>{if(!e9&&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(){ye(this,V6)||this.setEventListener(ye(this,uV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,V6))==null||t.call(this),Ht(this,V6,void 0))}setEventListener(t){var n;Ht(this,uV,t),(n=ye(this,V6))==null||n.call(this),Ht(this,V6,t(this.setOnline.bind(this)))}setOnline(t){ye(this,dV)!==t&&(Ht(this,dV,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return ye(this,dV)}},dV=new WeakMap,V6=new WeakMap,uV=new WeakMap,$Et),tAe=new e1s;function yqe(){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 t1s(s){return Math.min(1e3*2**s,3e4)}function yLt(s){return(s??"online")==="online"?tAe.isOnline():!0}var vLt=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function dOe(s){return s instanceof vLt}function bLt(s){let t=!1,n=0,r=!1,a;const i=yqe(),l=g=>{var v;r||(m(new vLt(g)),(v=s.abort)==null||v.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>SQe.isFocused()&&(s.networkMode==="always"||tAe.isOnline())&&s.canRun(),u=()=>yLt(s.networkMode)&&s.canRun(),h=g=>{var v;r||(r=!0,(v=s.onSuccess)==null||v.call(s,g),a==null||a(),i.resolve(g))},m=g=>{var v;r||(r=!0,(v=s.onError)==null||v.call(s,g),a==null||a(),i.reject(g))},p=()=>new Promise(g=>{var v;a=y=>{(r||d())&&g(y)},(v=s.onPause)==null||v.call(s)}).then(()=>{var g;a=void 0,r||(g=s.onContinue)==null||g.call(s)}),f=()=>{if(r)return;let g;const v=n===0?s.initialPromise:void 0;try{g=v??s.fn()}catch(y){g=Promise.reject(y)}Promise.resolve(g).then(h).catch(y=>{var E;if(r)return;const b=s.retry??(e9?0:3),w=s.retryDelay??t1s,S=typeof w=="function"?w(n,y):w,C=b===!0||typeof b=="number"&&nd()?void 0:p()).then(()=>{t?m(y):f()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?f():p().then(f),i)}}var s1s=s=>setTimeout(s,0);function n1s(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=s1s;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 by=n1s(),HF,UEt,_Lt=(UEt=class{constructor(){ps(this,HF)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),fqe(this.gcTime)&&Ht(this,HF,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(e9?1/0:5*60*1e3))}clearGcTimeout(){ye(this,HF)&&(clearTimeout(ye(this,HF)),Ht(this,HF,void 0))}},HF=new WeakMap,UEt),hV,GF,F2,WF,Jv,ane,KF,Dk,F3,qEt,r1s=(qEt=class extends _Lt{constructor(t){super();ps(this,Dk);ps(this,hV);ps(this,GF);ps(this,F2);ps(this,WF);ps(this,Jv);ps(this,ane);ps(this,KF);Ht(this,KF,!1),Ht(this,ane,t.defaultOptions),this.setOptions(t.options),this.observers=[],Ht(this,WF,t.client),Ht(this,F2,ye(this,WF).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Ht(this,hV,a1s(this.options)),this.state=t.state??ye(this,hV),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=ye(this,Jv))==null?void 0:t.promise}setOptions(t){this.options={...ye(this,ane),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ye(this,F2).remove(this)}setData(t,n){const r=gqe(this.state.data,t,this.options);return ss(this,Dk,F3).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){ss(this,Dk,F3).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=ye(this,Jv))==null?void 0:r.promise;return(a=ye(this,Jv))==null||a.cancel(t),n?n.then(ab).catch(ab):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(ye(this,hV))}isActive(){return this.observers.some(t=>q2(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===kQe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>xP(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:!pLt(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=ye(this,Jv))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=ye(this,Jv))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ye(this,F2).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(ye(this,Jv)&&(ye(this,KF)?ye(this,Jv).cancel({revert:!0}):ye(this,Jv).cancelRetry()),this.scheduleGc()),ye(this,F2).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ss(this,Dk,F3).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(ye(this,Jv))return ye(this,Jv).continueRetry(),ye(this,Jv).promise}if(t&&this.setOptions(t),!this.options.queryFn){const m=this.observers.find(p=>p.options.queryFn);m&&this.setOptions(m.options)}const r=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(Ht(this,KF,!0),r.signal)})},i=()=>{const m=xLt(this.options,n),f=(()=>{const g={client:ye(this,WF),queryKey:this.queryKey,meta:this.meta};return a(g),g})();return Ht(this,KF,!1),this.options.persister?this.options.persister(m,f,this):m(f)},o=(()=>{const m={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ye(this,WF),state:this.state,fetchFn:i};return a(m),m})();(d=this.options.behavior)==null||d.onFetch(o,this),Ht(this,GF,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&ss(this,Dk,F3).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=m=>{var p,f,g,v;dOe(m)&&m.silent||ss(this,Dk,F3).call(this,{type:"error",error:m}),dOe(m)||((f=(p=ye(this,F2).config).onError)==null||f.call(p,m,this),(v=(g=ye(this,F2).config).onSettled)==null||v.call(g,this.state.data,m,this)),this.scheduleGc()};return Ht(this,Jv,bLt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:m=>{var p,f,g,v;if(m===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(m)}catch(y){c(y);return}(f=(p=ye(this,F2).config).onSuccess)==null||f.call(p,m,this),(v=(g=ye(this,F2).config).onSettled)==null||v.call(g,m,this.state.error,this),this.scheduleGc()},onError:c,onFail:(m,p)=>{ss(this,Dk,F3).call(this,{type:"failed",failureCount:m,error:p})},onPause:()=>{ss(this,Dk,F3).call(this,{type:"pause"})},onContinue:()=>{ss(this,Dk,F3).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),ye(this,Jv).start()}},hV=new WeakMap,GF=new WeakMap,F2=new WeakMap,WF=new WeakMap,Jv=new WeakMap,ane=new WeakMap,KF=new WeakMap,Dk=new WeakSet,F3=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,...wLt(r.data,this.options),fetchMeta:t.meta??null};case"success":return Ht(this,GF,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 dOe(a)&&a.revert&&ye(this,GF)?{...ye(this,GF),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),by.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ye(this,F2).notify({query:this,type:"updated",action:t})})},qEt);function wLt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:yLt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function a1s(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 Q5,VEt,i1s=(VEt=class extends cW{constructor(t={}){super();ps(this,Q5);this.config=t,Ht(this,Q5,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??NQe(a,n);let l=this.get(i);return l||(l=new r1s({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){ye(this,Q5).has(t.queryHash)||(ye(this,Q5).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=ye(this,Q5).get(t.queryHash);n&&(t.destroy(),n===t&&ye(this,Q5).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){by.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ye(this,Q5).get(t)}getAll(){return[...ye(this,Q5).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Omt(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Omt(t,r)):n}notify(t){by.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){by.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){by.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Q5=new WeakMap,VEt),J5,sb,YF,e4,ZT,HEt,o1s=(HEt=class extends _Lt{constructor(t){super();ps(this,e4);ps(this,J5);ps(this,sb);ps(this,YF);this.mutationId=t.mutationId,Ht(this,sb,t.mutationCache),Ht(this,J5,[]),this.state=t.state||jLt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){ye(this,J5).includes(t)||(ye(this,J5).push(t),this.clearGcTimeout(),ye(this,sb).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Ht(this,J5,ye(this,J5).filter(n=>n!==t)),this.scheduleGc(),ye(this,sb).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ye(this,J5).length||(this.state.status==="pending"?this.scheduleGc():ye(this,sb).remove(this))}continue(){var t;return((t=ye(this,YF))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,m,p,f,g,v,y,b,w,S,C,E,P,M;const n=()=>{ss(this,e4,ZT).call(this,{type:"continue"})};Ht(this,YF,bLt({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(I,D)=>{ss(this,e4,ZT).call(this,{type:"failed",failureCount:I,error:D})},onPause:()=>{ss(this,e4,ZT).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ye(this,sb).canRun(this)}));const r=this.state.status==="pending",a=!ye(this,YF).canStart();try{if(r)n();else{ss(this,e4,ZT).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=ye(this,sb).config).onMutate)==null?void 0:l.call(i,t,this));const D=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));D!==this.state.context&&ss(this,e4,ZT).call(this,{type:"pending",context:D,variables:t,isPaused:a})}const I=await ye(this,YF).start();return await((u=(d=ye(this,sb).config).onSuccess)==null?void 0:u.call(d,I,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,I,t,this.state.context)),await((f=(p=ye(this,sb).config).onSettled)==null?void 0:f.call(p,I,null,this.state.variables,this.state.context,this)),await((v=(g=this.options).onSettled)==null?void 0:v.call(g,I,null,t,this.state.context)),ss(this,e4,ZT).call(this,{type:"success",data:I}),I}catch(I){try{throw await((b=(y=ye(this,sb).config).onError)==null?void 0:b.call(y,I,t,this.state.context,this)),await((S=(w=this.options).onError)==null?void 0:S.call(w,I,t,this.state.context)),await((E=(C=ye(this,sb).config).onSettled)==null?void 0:E.call(C,void 0,I,this.state.variables,this.state.context,this)),await((M=(P=this.options).onSettled)==null?void 0:M.call(P,void 0,I,t,this.state.context)),I}finally{ss(this,e4,ZT).call(this,{type:"error",error:I})}}finally{ye(this,sb).runNext(this)}}},J5=new WeakMap,sb=new WeakMap,YF=new WeakMap,e4=new WeakSet,ZT=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),by.batch(()=>{ye(this,J5).forEach(r=>{r.onMutationUpdate(t)}),ye(this,sb).notify({mutation:this,type:"updated",action:t})})},HEt);function jLt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var aA,Rk,ine,GEt,l1s=(GEt=class extends cW{constructor(t={}){super();ps(this,aA);ps(this,Rk);ps(this,ine);this.config=t,Ht(this,aA,new Set),Ht(this,Rk,new Map),Ht(this,ine,0)}build(t,n,r){const a=new o1s({mutationCache:this,mutationId:++Jy(this,ine)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){ye(this,aA).add(t);const n=hle(t);if(typeof n=="string"){const r=ye(this,Rk).get(n);r?r.push(t):ye(this,Rk).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ye(this,aA).delete(t)){const n=hle(t);if(typeof n=="string"){const r=ye(this,Rk).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&ye(this,Rk).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=hle(t);if(typeof n=="string"){const r=ye(this,Rk).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=hle(t);if(typeof n=="string"){const a=(r=ye(this,Rk).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(){by.batch(()=>{ye(this,aA).forEach(t=>{this.notify({type:"removed",mutation:t})}),ye(this,aA).clear(),ye(this,Rk).clear()})}getAll(){return Array.from(ye(this,aA))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>zmt(n,r))}findAll(t={}){return this.getAll().filter(n=>zmt(t,n))}notify(t){by.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return by.batch(()=>Promise.all(t.map(n=>n.continue().catch(ab))))}},aA=new WeakMap,Rk=new WeakMap,ine=new WeakMap,GEt);function hle(s){var t;return(t=s.options.scope)==null?void 0:t.id}function sAe(s){return{onFetch:(t,n)=>{var u,h,m,p,f;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((p=t.state.data)==null?void 0:p.pages)||[],l=((f=t.state.data)==null?void 0:f.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let g=!1;const v=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(t.signal.aborted?g=!0:t.signal.addEventListener("abort",()=>{g=!0}),t.signal)})},y=xLt(t.options,t.fetchOptions),b=async(w,S,C)=>{if(g)return Promise.reject();if(S==null&&w.pages.length)return Promise.resolve(w);const P=(()=>{const F={client:t.client,queryKey:t.queryKey,pageParam:S,direction:C?"backward":"forward",meta:t.options.meta};return v(F),F})(),M=await y(P),{maxPages:I}=t.options,D=C?Qvs:Xvs;return{pages:D(w.pages,M,I),pageParams:D(w.pageParams,S,I)}};if(a&&i.length){const w=a==="backward",S=w?NLt:vqe,C={pages:i,pageParams:l},E=S(r,C);o=await b(C,E,w)}else{const w=s??i.length;do{const S=c===0?l[0]??r.initialPageParam:vqe(r,o);if(c>0&&S==null)break;o=await b(o,S),c++}while(c{var g,v;return(v=(g=t.options).persister)==null?void 0:v.call(g,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function vqe(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 NLt(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 c1s(s,t){return t?vqe(s,t)!=null:!1}function d1s(s,t){return!t||!s.getPreviousPageParam?!1:NLt(s,t)!=null}var yx,H6,G6,mV,pV,W6,fV,xV,WEt,u1s=(WEt=class{constructor(s={}){ps(this,yx);ps(this,H6);ps(this,G6);ps(this,mV);ps(this,pV);ps(this,W6);ps(this,fV);ps(this,xV);Ht(this,yx,s.queryCache||new i1s),Ht(this,H6,s.mutationCache||new l1s),Ht(this,G6,s.defaultOptions||{}),Ht(this,mV,new Map),Ht(this,pV,new Map),Ht(this,W6,0)}mount(){Jy(this,W6)._++,ye(this,W6)===1&&(Ht(this,fV,SQe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,yx).onFocus())})),Ht(this,xV,tAe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,yx).onOnline())})))}unmount(){var s,t;Jy(this,W6)._--,ye(this,W6)===0&&((s=ye(this,fV))==null||s.call(this),Ht(this,fV,void 0),(t=ye(this,xV))==null||t.call(this),Ht(this,xV,void 0))}isFetching(s){return ye(this,yx).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return ye(this,H6).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,yx).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=ye(this,yx).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(xP(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return ye(this,yx).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=ye(this,yx).get(r.queryHash),i=a==null?void 0:a.state.data,l=Yvs(t,i);if(l!==void 0)return ye(this,yx).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return by.batch(()=>ye(this,yx).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,yx).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=ye(this,yx);by.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=ye(this,yx);return by.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=by.batch(()=>ye(this,yx).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(ab).catch(ab)}invalidateQueries(s,t={}){return by.batch(()=>(ye(this,yx).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=by.batch(()=>ye(this,yx).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(ab)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(ab)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,yx).build(this,t);return n.isStaleByTime(xP(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(ab).catch(ab)}fetchInfiniteQuery(s){return s.behavior=sAe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(ab).catch(ab)}ensureInfiniteQueryData(s){return s.behavior=sAe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return tAe.isOnline()?ye(this,H6).resumePausedMutations():Promise.resolve()}getQueryCache(){return ye(this,yx)}getMutationCache(){return ye(this,H6)}getDefaultOptions(){return ye(this,G6)}setDefaultOptions(s){Ht(this,G6,s)}setQueryDefaults(s,t){ye(this,mV).set(t9(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...ye(this,mV).values()],n={};return t.forEach(r=>{rte(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){ye(this,pV).set(t9(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...ye(this,pV).values()],n={};return t.forEach(r=>{rte(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...ye(this,G6).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=NQe(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===kQe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...ye(this,G6).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){ye(this,yx).clear(),ye(this,H6).clear()}},yx=new WeakMap,H6=new WeakMap,G6=new WeakMap,mV=new WeakMap,pV=new WeakMap,W6=new WeakMap,fV=new WeakMap,xV=new WeakMap,WEt),u_,hu,one,nb,ZF,gV,K6,Y6,lne,yV,vV,XF,QF,Z6,bV,kh,gX,bqe,_qe,wqe,jqe,Nqe,kqe,Sqe,SLt,KEt,kLt=(KEt=class extends cW{constructor(t,n){super();ps(this,kh);ps(this,u_);ps(this,hu);ps(this,one);ps(this,nb);ps(this,ZF);ps(this,gV);ps(this,K6);ps(this,Y6);ps(this,lne);ps(this,yV);ps(this,vV);ps(this,XF);ps(this,QF);ps(this,Z6);ps(this,bV,new Set);this.options=n,Ht(this,u_,t),Ht(this,Y6,null),Ht(this,K6,yqe()),this.options.experimental_prefetchInRender||ye(this,K6).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&&(ye(this,hu).addObserver(this),Umt(ye(this,hu),this.options)?ss(this,kh,gX).call(this):this.updateResult(),ss(this,kh,jqe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Cqe(ye(this,hu),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Cqe(ye(this,hu),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ss(this,kh,Nqe).call(this),ss(this,kh,kqe).call(this),ye(this,hu).removeObserver(this)}setOptions(t){const n=this.options,r=ye(this,hu);if(this.options=ye(this,u_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof q2(this.options.enabled,ye(this,hu))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ss(this,kh,Sqe).call(this),ye(this,hu).setOptions(this.options),n._defaulted&&!eAe(this.options,n)&&ye(this,u_).getQueryCache().notify({type:"observerOptionsUpdated",query:ye(this,hu),observer:this});const a=this.hasListeners();a&&qmt(ye(this,hu),r,this.options,n)&&ss(this,kh,gX).call(this),this.updateResult(),a&&(ye(this,hu)!==r||q2(this.options.enabled,ye(this,hu))!==q2(n.enabled,ye(this,hu))||xP(this.options.staleTime,ye(this,hu))!==xP(n.staleTime,ye(this,hu)))&&ss(this,kh,bqe).call(this);const i=ss(this,kh,_qe).call(this);a&&(ye(this,hu)!==r||q2(this.options.enabled,ye(this,hu))!==q2(n.enabled,ye(this,hu))||i!==ye(this,Z6))&&ss(this,kh,wqe).call(this,i)}getOptimisticResult(t){const n=ye(this,u_).getQueryCache().build(ye(this,u_),t),r=this.createResult(n,t);return m1s(this,r)&&(Ht(this,nb,r),Ht(this,gV,this.options),Ht(this,ZF,ye(this,hu).state)),r}getCurrentResult(){return ye(this,nb)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){ye(this,bV).add(t)}getCurrentQuery(){return ye(this,hu)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ye(this,u_).defaultQueryOptions(t),r=ye(this,u_).getQueryCache().build(ye(this,u_),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return ss(this,kh,gX).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ye(this,nb)))}createResult(t,n){var I;const r=ye(this,hu),a=this.options,i=ye(this,nb),l=ye(this,ZF),o=ye(this,gV),d=t!==r?t.state:ye(this,one),{state:u}=t;let h={...u},m=!1,p;if(n._optimisticResults){const D=this.hasListeners(),F=!D&&Umt(t,n),q=D&&qmt(t,r,n,a);(F||q)&&(h={...h,...wLt(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:g,status:v}=h;p=h.data;let y=!1;if(n.placeholderData!==void 0&&p===void 0&&v==="pending"){let D;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(D=i.data,y=!0):D=typeof n.placeholderData=="function"?n.placeholderData((I=ye(this,vV))==null?void 0:I.state.data,ye(this,vV)):n.placeholderData,D!==void 0&&(v="success",p=gqe(i==null?void 0:i.data,D,n),m=!0)}if(n.select&&p!==void 0&&!y)if(i&&p===(l==null?void 0:l.data)&&n.select===ye(this,lne))p=ye(this,yV);else try{Ht(this,lne,n.select),p=n.select(p),p=gqe(i==null?void 0:i.data,p,n),Ht(this,yV,p),Ht(this,Y6,null)}catch(D){Ht(this,Y6,D)}ye(this,Y6)&&(f=ye(this,Y6),p=ye(this,yV),g=Date.now(),v="error");const b=h.fetchStatus==="fetching",w=v==="pending",S=v==="error",C=w&&b,E=p!==void 0,M={status:v,fetchStatus:h.fetchStatus,isPending:w,isSuccess:v==="success",isError:S,isInitialLoading:C,isLoading:C,data:p,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:g,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:b,isRefetching:b&&!w,isLoadingError:S&&!E,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:S&&E,isStale:CQe(t,n),refetch:this.refetch,promise:ye(this,K6),isEnabled:q2(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const D=G=>{M.status==="error"?G.reject(M.error):M.data!==void 0&&G.resolve(M.data)},F=()=>{const G=Ht(this,K6,M.promise=yqe());D(G)},q=ye(this,K6);switch(q.status){case"pending":t.queryHash===r.queryHash&&D(q);break;case"fulfilled":(M.status==="error"||M.data!==q.value)&&F();break;case"rejected":(M.status!=="error"||M.error!==q.reason)&&F();break}}return M}updateResult(){const t=ye(this,nb),n=this.createResult(ye(this,hu),this.options);if(Ht(this,ZF,ye(this,hu).state),Ht(this,gV,this.options),ye(this,ZF).data!==void 0&&Ht(this,vV,ye(this,hu)),eAe(n,t))return;Ht(this,nb,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!ye(this,bV).size)return!0;const l=new Set(i??ye(this,bV));return this.options.throwOnError&&l.add("error"),Object.keys(ye(this,nb)).some(o=>{const c=o;return ye(this,nb)[c]!==t[c]&&l.has(c)})};ss(this,kh,SLt).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ss(this,kh,jqe).call(this)}},u_=new WeakMap,hu=new WeakMap,one=new WeakMap,nb=new WeakMap,ZF=new WeakMap,gV=new WeakMap,K6=new WeakMap,Y6=new WeakMap,lne=new WeakMap,yV=new WeakMap,vV=new WeakMap,XF=new WeakMap,QF=new WeakMap,Z6=new WeakMap,bV=new WeakMap,kh=new WeakSet,gX=function(t){ss(this,kh,Sqe).call(this);let n=ye(this,hu).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(ab)),n},bqe=function(){ss(this,kh,Nqe).call(this);const t=xP(this.options.staleTime,ye(this,hu));if(e9||ye(this,nb).isStale||!fqe(t))return;const r=pLt(ye(this,nb).dataUpdatedAt,t)+1;Ht(this,XF,setTimeout(()=>{ye(this,nb).isStale||this.updateResult()},r))},_qe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ye(this,hu)):this.options.refetchInterval)??!1},wqe=function(t){ss(this,kh,kqe).call(this),Ht(this,Z6,t),!(e9||q2(this.options.enabled,ye(this,hu))===!1||!fqe(ye(this,Z6))||ye(this,Z6)===0)&&Ht(this,QF,setInterval(()=>{(this.options.refetchIntervalInBackground||SQe.isFocused())&&ss(this,kh,gX).call(this)},ye(this,Z6)))},jqe=function(){ss(this,kh,bqe).call(this),ss(this,kh,wqe).call(this,ss(this,kh,_qe).call(this))},Nqe=function(){ye(this,XF)&&(clearTimeout(ye(this,XF)),Ht(this,XF,void 0))},kqe=function(){ye(this,QF)&&(clearInterval(ye(this,QF)),Ht(this,QF,void 0))},Sqe=function(){const t=ye(this,u_).getQueryCache().build(ye(this,u_),this.options);if(t===ye(this,hu))return;const n=ye(this,hu);Ht(this,hu,t),Ht(this,one,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},SLt=function(t){by.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(ye(this,nb))}),ye(this,u_).getQueryCache().notify({query:ye(this,hu),type:"observerResultsUpdated"})})},KEt);function h1s(s,t){return q2(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function Umt(s,t){return h1s(s,t)||s.state.data!==void 0&&Cqe(s,t,t.refetchOnMount)}function Cqe(s,t,n){if(q2(t.enabled,s)!==!1&&xP(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&CQe(s,t)}return!1}function qmt(s,t,n,r){return(s!==t||q2(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&CQe(s,n)}function CQe(s,t){return q2(t.enabled,s)!==!1&&s.isStaleByTime(xP(t.staleTime,s))}function m1s(s,t){return!eAe(s.getCurrentResult(),t)}var p1s=class extends kLt{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:sAe()})}getOptimisticResult(s){return s.behavior=sAe(),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 f,g;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(g=(f=n.fetchMeta)==null?void 0:f.fetchMore)==null?void 0:g.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",m=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:c1s(t,n.data),hasPreviousPage:d1s(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},X6,Q6,h_,iA,xE,C4e,Aqe,YEt,f1s=(YEt=class extends cW{constructor(n,r){super();ps(this,xE);ps(this,X6);ps(this,Q6);ps(this,h_);ps(this,iA);Ht(this,X6,n),this.setOptions(r),this.bindMethods(),ss(this,xE,C4e).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=ye(this,X6).defaultMutationOptions(n),eAe(this.options,r)||ye(this,X6).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ye(this,h_),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&t9(r.mutationKey)!==t9(this.options.mutationKey)?this.reset():((a=ye(this,h_))==null?void 0:a.state.status)==="pending"&&ye(this,h_).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ye(this,h_))==null||n.removeObserver(this)}onMutationUpdate(n){ss(this,xE,C4e).call(this),ss(this,xE,Aqe).call(this,n)}getCurrentResult(){return ye(this,Q6)}reset(){var n;(n=ye(this,h_))==null||n.removeObserver(this),Ht(this,h_,void 0),ss(this,xE,C4e).call(this),ss(this,xE,Aqe).call(this)}mutate(n,r){var a;return Ht(this,iA,r),(a=ye(this,h_))==null||a.removeObserver(this),Ht(this,h_,ye(this,X6).getMutationCache().build(ye(this,X6),this.options)),ye(this,h_).addObserver(this),ye(this,h_).execute(n)}},X6=new WeakMap,Q6=new WeakMap,h_=new WeakMap,iA=new WeakMap,xE=new WeakSet,C4e=function(){var r;const n=((r=ye(this,h_))==null?void 0:r.state)??jLt();Ht(this,Q6,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Aqe=function(n){by.batch(()=>{var r,a,i,l,o,c,d,u;if(ye(this,iA)&&this.hasListeners()){const h=ye(this,Q6).variables,m=ye(this,Q6).context;(n==null?void 0:n.type)==="success"?((a=(r=ye(this,iA)).onSuccess)==null||a.call(r,n.data,h,m),(l=(i=ye(this,iA)).onSettled)==null||l.call(i,n.data,null,h,m)):(n==null?void 0:n.type)==="error"&&((c=(o=ye(this,iA)).onError)==null||c.call(o,n.error,h,m),(u=(d=ye(this,iA)).onSettled)==null||u.call(d,void 0,n.error,h,m))}this.listeners.forEach(h=>{h(ye(this,Q6))})})},YEt),CLt=_.createContext(void 0),$t=s=>{const t=_.useContext(CLt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},x1s=({client:s,children:t})=>(_.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(CLt.Provider,{value:s,children:t})),ALt=_.createContext(!1),g1s=()=>_.useContext(ALt);ALt.Provider;function y1s(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var v1s=_.createContext(y1s()),b1s=()=>_.useContext(v1s),_1s=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},w1s=s=>{_.useEffect(()=>{s.clearReset()},[s])},j1s=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||gLt(n,[s.error,r])),N1s=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))}},k1s=(s,t)=>s.isLoading&&s.isFetching&&!t,S1s=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,Vmt=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function ELt(s,t,n){var h,m,p,f,g;const r=g1s(),a=b1s(),i=$t(),l=i.defaultQueryOptions(s);(m=(h=i.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||m.call(h,l),l._optimisticResults=r?"isRestoring":"optimistic",N1s(l),_1s(l,a),w1s(a);const o=!i.getQueryCache().get(l.queryHash),[c]=_.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(_.useSyncExternalStore(_.useCallback(v=>{const y=u?c.subscribe(by.batchCalls(v)):ab;return c.updateResult(),y},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),_.useEffect(()=>{c.setOptions(l)},[l,c]),S1s(l,d))throw Vmt(l,c,a);if(j1s({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((f=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||f.call(p,l,d),l.experimental_prefetchInRender&&!e9&&k1s(d,r)){const v=o?Vmt(l,c,a):(g=i.getQueryCache().get(l.queryHash))==null?void 0:g.promise;v==null||v.catch(ab).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function rt(s,t){return ELt(s,kLt)}function mt(s,t){const n=$t(),[r]=_.useState(()=>new f1s(n,s));_.useEffect(()=>{r.setOptions(s)},[r,s]);const a=_.useSyncExternalStore(_.useCallback(l=>r.subscribe(by.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=_.useCallback((l,o)=>{r.mutate(l,o).catch(ab)},[r]);if(a.error&&gLt(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function TLt(s,t){return ELt(s,p1s)}/** * @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 ate(){return ate=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function MLt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function A1s(){return Math.random().toString(36).substr(2,8)}function Gmt(s,t){return{usr:s.state,key:s.key,idx:t}}function Eqe(s,t,n,r){return n===void 0&&(n=null),ate({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?dW(t):t,{state:n,key:t&&t.key||r||A1s()})}function nAe(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 dW(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 E1s(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=AM.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(ate({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=AM.Pop;let v=u(),y=v==null?null:v-d;d=v,c&&c({action:o,location:g.location,delta:y})}function m(v,y){o=AM.Push;let b=Eqe(g.location,v,y);d=u()+1;let w=Gmt(b,d),S=g.createHref(b);try{l.pushState(w,"",S)}catch(C){if(C instanceof DOMException&&C.name==="DataCloneError")throw C;a.location.assign(S)}i&&c&&c({action:o,location:g.location,delta:1})}function p(v,y){o=AM.Replace;let b=Eqe(g.location,v,y);d=u();let w=Gmt(b,d),S=g.createHref(b);l.replaceState(w,"",S),i&&c&&c({action:o,location:g.location,delta:0})}function f(v){let y=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof v=="string"?v:nAe(v);return b=b.replace(/ $/,"%20"),Qf(y,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,y)}let g={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(Hmt,h),c=v,()=>{a.removeEventListener(Hmt,h),c=null}},createHref(v){return t(a,v)},createURL:f,encodeLocation(v){let y=f(v);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:m,replace:p,go(v){return l.go(v)}};return g}var Wmt;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Wmt||(Wmt={}));function T1s(s,t,n){return n===void 0&&(n="/"),M1s(s,t,n,!1)}function M1s(s,t,n,r){let a=typeof t=="string"?dW(t):t,i=EH(a.pathname||"/",n);if(i==null)return null;let l=PLt(s);P1s(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("/")&&(Qf(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=gP([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Qf(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),PLt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:z1s(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 LLt(i.path))a(i,l,c)}),t}function LLt(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=LLt(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 P1s(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:B1s(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const L1s=/^:[\w-]+$/,I1s=3,D1s=2,R1s=1,F1s=10,O1s=-2,Kmt=s=>s==="*";function z1s(s,t){let n=s.split("/"),r=n.length;return n.some(Kmt)&&(r+=O1s),t&&(r+=D1s),n.filter(a=>!Kmt(a)).reduce((a,i)=>a+(L1s.test(i)?I1s:i===""?R1s:F1s),r)}function B1s(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 $1s(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:p}=u;if(m==="*"){let g=o[h]||"";l=i.slice(0,i.length-g.length).replace(/(.)\/+$/,"$1")}const f=o[h];return p&&!f?d[m]=void 0:d[m]=(f||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function U1s(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),MLt(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 q1s(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return MLt(!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 EH(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 V1s(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?dW(s):s;return{pathname:n?n.startsWith("/")?n:H1s(n,t):t,search:K1s(r),hash:Y1s(a)}}function H1s(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 uOe(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 G1s(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function AQe(s,t){let n=G1s(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function EQe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=dW(s):(a=ate({},s),Qf(!a.pathname||!a.pathname.includes("?"),uOe("?","pathname","search",a)),Qf(!a.pathname||!a.pathname.includes("#"),uOe("#","pathname","hash",a)),Qf(!a.search||!a.search.includes("#"),uOe("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),h-=1;a.pathname=m.join("/")}o=h>=0?t[h]:"/"}let c=V1s(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const gP=s=>s.join("/").replace(/\/\/+/g,"/"),W1s=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),K1s=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,Y1s=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function Z1s(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const ILt=["post","put","patch","delete"];new Set(ILt);const X1s=["get",...ILt];new Set(X1s);/** * 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 ite(){return ite=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),_.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=EQe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:gP([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const ebs=_.createContext(null);function tbs(s){let t=_.useContext(AC).outlet;return t&&_.createElement(ebs.Provider,{value:s},t)}function Mi(){let{matches:s}=_.useContext(AC),t=s[s.length-1];return t?t.params:{}}function QMe(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=_.useContext(BE),{matches:a}=_.useContext(AC),{pathname:i}=Pd(),l=JSON.stringify(AQe(a,r.v7_relativeSplatPath));return _.useMemo(()=>EQe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function sbs(s,t){return nbs(s,t)}function nbs(s,t,n,r){uW()||Qf(!1);let{navigator:a}=_.useContext(BE),{matches:i}=_.useContext(AC),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Pd(),u;if(t){var h;let v=typeof t=="string"?dW(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||Qf(!1),u=v}else u=d;let m=u.pathname||"/",p=m;if(c!=="/"){let v=c.replace(/^\//,"").split("/");p="/"+m.replace(/^\//,"").split("/").slice(v.length).join("/")}let f=T1s(s,{pathname:p}),g=lbs(f&&f.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:gP([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:gP([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&g?_.createElement(XMe.Provider,{value:{location:ite({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:AM.Pop}},g):g}function rbs(){let s=hbs(),t=Z1s(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 _.createElement(_.Fragment,null,_.createElement("h2",null,"Unexpected Application Error!"),_.createElement("h3",{style:{fontStyle:"italic"}},t),n?_.createElement("pre",{style:a},n):null,null)}const abs=_.createElement(rbs,null);class ibs extends _.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?_.createElement(AC.Provider,{value:this.props.routeContext},_.createElement(RLt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function obs(s){let{routeContext:t,match:n,children:r}=s,a=_.useContext(ZMe);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),_.createElement(AC.Provider,{value:t},r)}function lbs(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||Qf(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let p,f=!1,g=null,v=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,g=h.route.errorElement||abs,c&&(d<0&&m===0?(f=!0,v=null):d===m&&(f=!0,v=h.route.hydrateFallbackElement||null)));let y=t.concat(l.slice(0,m+1)),b=()=>{let w;return p?w=g:f?w=v:h.route.Component?w=_.createElement(h.route.Component,null):h.route.element?w=h.route.element:w=u,_.createElement(obs,{match:h,routeContext:{outlet:u,matches:y,isDataRoute:n!=null},children:w})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?_.createElement(ibs,{location:n.location,revalidation:n.revalidation,component:g,error:p,children:b(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):b()},null)}var OLt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(OLt||{}),aAe=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}(aAe||{});function cbs(s){let t=_.useContext(ZMe);return t||Qf(!1),t}function dbs(s){let t=_.useContext(DLt);return t||Qf(!1),t}function ubs(s){let t=_.useContext(AC);return t||Qf(!1),t}function zLt(s){let t=ubs(),n=t.matches[t.matches.length-1];return n.route.id||Qf(!1),n.route.id}function hbs(){var s;let t=_.useContext(RLt),n=dbs(aAe.UseRouteError),r=zLt(aAe.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function mbs(){let{router:s}=cbs(OLt.UseNavigateStable),t=zLt(aAe.UseNavigateStable),n=_.useRef(!1);return FLt(()=>{n.current=!0}),_.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,ite({fromRouteId:t},i)))},[s,t])}function pbs(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function ed(s){let{to:t,replace:n,state:r,relative:a}=s;uW()||Qf(!1);let{future:i,static:l}=_.useContext(BE),{matches:o}=_.useContext(AC),{pathname:c}=Pd(),d=zn(),u=EQe(t,AQe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return _.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function TQe(s){return tbs(s.context)}function Jt(s){Qf(!1)}function fbs(s){let{basename:t="/",children:n=null,location:r,navigationType:a=AM.Pop,navigator:i,static:l=!1,future:o}=s;uW()&&Qf(!1);let c=t.replace(/^\/*/,"/"),d=_.useMemo(()=>({basename:c,navigator:i,static:l,future:ite({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=dW(r));let{pathname:u="/",search:h="",hash:m="",state:p=null,key:f="default"}=r,g=_.useMemo(()=>{let v=EH(u,c);return v==null?null:{location:{pathname:v,search:h,hash:m,state:p,key:f},navigationType:a}},[c,u,h,m,p,f,a]);return g==null?null:_.createElement(BE.Provider,{value:d},_.createElement(XMe.Provider,{children:n,value:g}))}function TH(s){let{children:t,location:n}=s;return sbs(Tqe(t),n)}new Promise(()=>{});function Tqe(s,t){t===void 0&&(t=[]);let n=[];return _.Children.forEach(s,(r,a)=>{if(!_.isValidElement(r))return;let i=[...t,a];if(r.type===_.Fragment){n.push.apply(n,Tqe(r.props.children,i));return}r.type!==Jt&&Qf(!1),!r.props.index||!r.props.children||Qf(!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=Tqe(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 iAe(){return iAe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function xbs(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function gbs(s,t){return s.button===0&&(!t||t==="_self")&&!xbs(s)}function Mqe(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 ybs(s,t){let n=Mqe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const vbs=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],bbs=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],_bs="6";try{window.__reactRouterVersion=_bs}catch{}const wbs=_.createContext({isTransitioning:!1}),jbs="startTransition",Ymt=mXe[jbs];function Nbs(s){let{basename:t,children:n,future:r,window:a}=s,i=_.useRef();i.current==null&&(i.current=C1s({window:a,v5Compat:!0}));let l=i.current,[o,c]=_.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=_.useCallback(h=>{d&&Ymt?Ymt(()=>c(h)):c(h)},[c,d]);return _.useLayoutEffect(()=>l.listen(u),[l,u]),_.useEffect(()=>pbs(r),[r]),_.createElement(fbs,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const kbs=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Sbs=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,or=_.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,m=BLt(t,vbs),{basename:p}=_.useContext(BE),f,g=!1;if(typeof d=="string"&&Sbs.test(d)&&(f=d,kbs))try{let w=new URL(window.location.href),S=d.startsWith("//")?new URL(w.protocol+d):new URL(d),C=EH(S.pathname,p);S.origin===w.origin&&C!=null?d=C+S.search+S.hash:g=!0}catch{}let v=Q1s(d,{relative:a}),y=Abs(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(w){r&&r(w),w.defaultPrevented||y(w)}return _.createElement("a",iAe({},m,{href:f||v,onClick:g||i?r:b,ref:n,target:c}))}),g6=_.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=BLt(t,bbs),m=QMe(c,{relative:h.relative}),p=Pd(),f=_.useContext(DLt),{navigator:g,basename:v}=_.useContext(BE),y=f!=null&&Ebs(m)&&d===!0,b=g.encodeLocation?g.encodeLocation(m).pathname:m.pathname,w=p.pathname,S=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;a||(w=w.toLowerCase(),S=S?S.toLowerCase():null,b=b.toLowerCase()),S&&v&&(S=EH(S,v)||S);const C=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let E=w===b||!l&&w.startsWith(b)&&w.charAt(C)==="/",P=S!=null&&(S===b||!l&&S.startsWith(b)&&S.charAt(b.length)==="/"),M={isActive:E,isPending:P,isTransitioning:y},I=E?r:void 0,D;typeof i=="function"?D=i(M):D=[i,E?"active":null,P?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let F=typeof o=="function"?o(M):o;return _.createElement(or,iAe({},h,{"aria-current":I,className:D,ref:n,style:F,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var Pqe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(Pqe||(Pqe={}));var Zmt;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Zmt||(Zmt={}));function Cbs(s){let t=_.useContext(ZMe);return t||Qf(!1),t}function Abs(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=zn(),d=Pd(),u=QMe(s,{relative:l});return _.useCallback(h=>{if(gbs(h,n)){h.preventDefault();let m=r!==void 0?r:nAe(d)===nAe(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function Gl(s){let t=_.useRef(Mqe(s)),n=_.useRef(!1),r=Pd(),a=_.useMemo(()=>ybs(r.search,n.current?null:t.current),[r.search]),i=zn(),l=_.useCallback((o,c)=>{const d=Mqe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Ebs(s,t){t===void 0&&(t={});let n=_.useContext(wbs);n==null&&Qf(!1);let{basename:r}=Cbs(Pqe.useViewTransitionState),a=QMe(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=EH(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=EH(n.nextLocation.pathname,r)||n.nextLocation.pathname;return rAe(a.pathname,l)!=null||rAe(a.pathname,i)!=null}var Tbs=typeof Element<"u",Mbs=typeof Map=="function",Pbs=typeof Set=="function",Lbs=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function A4e(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(!A4e(s[r],t[r]))return!1;return!0}var i;if(Mbs&&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(!A4e(r.value[1],t.get(r.value[0])))return!1;return!0}if(Pbs&&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(Lbs&&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(Tbs&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!A4e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var Ibs=function(t,n){try{return A4e(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 Dbs=kd(Ibs);var Rbs=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}},Fbs=Rbs;const Xmt=kd(Fbs);var Obs=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))($Lt||{}),hOe={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"]}},Qmt=Object.values($Lt),MQe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},Bbs=Object.entries(MQe).reduce((s,[t,n])=>(s[n]=t,s),{}),dS="data-rh",Eq={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},Tq=(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},$bs=s=>{let t=Tq(s,"title");const n=Tq(s,Eq.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=Tq(s,Eq.DEFAULT_TITLE);return t||r||void 0},Ubs=s=>Tq(s,Eq.ON_CHANGE_CLIENT_STATE)||(()=>{}),mOe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),qbs=(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),OY=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Vbs(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const l={};i.filter(c=>{let d;const u=Object.keys(c);for(let m=0;ma.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let n=0;n({baseTag:qbs(["href"],s),bodyAttributes:mOe("bodyAttributes",s),defer:Tq(s,Eq.DEFER),encode:Tq(s,Eq.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:mOe("htmlAttributes",s),linkTags:OY("link",["rel","href"],s),metaTags:OY("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:OY("noscript",["innerHTML"],s),onChangeClientState:Ubs(s),scriptTags:OY("script",["src","innerHTML"],s),styleTags:OY("style",["cssText"],s),title:$bs(s),titleAttributes:mOe("titleAttributes",s),prioritizeSeoTags:Hbs(s,Eq.PRIORITIZE_SEO_TAGS)}),ULt=s=>Array.isArray(s)?s.join(""):s,Wbs=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(Wbs(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Jmt=(s,t)=>({...s,[t]:void 0}),Kbs=["noscript","script","style"],Lqe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),qLt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),Ybs=(s,t,n,r)=>{const a=qLt(n),i=ULt(t);return a?`<${s} ${dS}="true" ${a}>${Lqe(i,r)}`:`<${s} ${dS}="true">${Lqe(i,r)}`},Zbs=(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}="${Lqe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=Kbs.indexOf(s)===-1;return`${r}<${s} ${dS}="true" ${l}${c?"/>":`>${o}`}`},""),VLt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=MQe[r];return n[a||r]=s[r],n},t),Xbs=(s,t,n)=>{const r={key:t,[dS]:!0},a=VLt(n,r);return[Ft.createElement("title",a,t)]},E4e=(s,t)=>t.map((n,r)=>{const a={key:r,[dS]:!0};return Object.keys(n).forEach(i=>{const o=MQe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Ft.createElement(s,a)}),R2=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>Xbs(s,t.title,t.titleAttributes),toString:()=>Ybs(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>VLt(t),toString:()=>qLt(t)};default:return{toComponent:()=>E4e(s,t),toString:()=>Zbs(s,t,n)}}},Qbs=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=pOe(s,hOe.meta),i=pOe(t,hOe.link),l=pOe(n,hOe.script);return{priorityMethods:{toComponent:()=>[...E4e("meta",a.priority),...E4e("link",i.priority),...E4e("script",l.priority)],toString:()=>`${R2("meta",a.priority,r)} ${R2("link",i.priority,r)} ${R2("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},Jbs=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:m}=s,p={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:p,linkTags:u,metaTags:h,scriptTags:m}=Qbs(s)),{priority:p,base:R2("base",t,r),bodyAttributes:R2("bodyAttributes",n,r),htmlAttributes:R2("htmlAttributes",a,r),link:R2("link",u,r),meta:R2("meta",h,r),noscript:R2("noscript",i,r),script:R2("script",m,r),style:R2("style",l,r),title:R2("title",{title:o,titleAttributes:c},r)}},Iqe=Jbs,mle=[],HLt=!!(typeof window<"u"&&window.document&&window.document.createElement),Dqe=class{constructor(s,t){zr(this,"instances",[]);zr(this,"canUseDOM",HLt);zr(this,"context");zr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?mle:this.instances,add:s=>{(this.canUseDOM?mle:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?mle:this.instances).indexOf(s);(this.canUseDOM?mle:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=Iqe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},e_s={},GLt=Ft.createContext(e_s),JF,WLt=(JF=class extends _.Component{constructor(n){super(n);zr(this,"helmetData");this.helmetData=new Dqe(this.props.context||{},JF.canUseDOM)}render(){return Ft.createElement(GLt.Provider,{value:this.helmetData.value},this.props.children)}},zr(JF,"canUseDOM",HLt),JF),_B=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${dS}]`),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(dS,"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}},Rqe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(dS),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(dS):n.getAttribute(dS)!==l.join(",")&&n.setAttribute(dS,l.join(","))},t_s=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=ULt(s)),Rqe("title",t)},ept=(s,t)=>{const{baseTag:n,bodyAttributes:r,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:h,titleAttributes:m}=s;Rqe("body",r),Rqe("html",a),t_s(h,m);const p={baseTag:_B("base",n),linkTags:_B("link",i),metaTags:_B("meta",l),noscriptTags:_B("noscript",o),scriptTags:_B("script",d),styleTags:_B("style",u)},f={},g={};Object.keys(p).forEach(v=>{const{newTags:y,oldTags:b}=p[v];y.length&&(f[v]=y),b.length&&(g[v]=p[v].oldTags)}),t&&t(),c(s,f,g)},zY=null,s_s=s=>{zY&&cancelAnimationFrame(zY),s.defer?zY=requestAnimationFrame(()=>{ept(s,()=>{zY=null})}):(ept(s),zY=null)},n_s=s_s,tpt=class extends _.Component{constructor(){super(...arguments);zr(this,"rendered",!1)}shouldComponentUpdate(t){return!zbs(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=Gbs(t.get().map(i=>{const l={...i.props};return delete l.context,l}));WLt.canUseDOM?n_s(a):Iqe&&(r=Iqe(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}},cUe,dl=(cUe=class extends _.Component{shouldComponentUpdate(s){return!Dbs(Jmt(this.props,"helmetData"),Jmt(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 Xmt(Qmt.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 ${Qmt.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),Xmt(!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 Ft.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[Bbs[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 Dqe)){const a=r;r=new Dqe(a.context,!0),delete n.helmetData}return r?Ft.createElement(tpt,{...n,context:r.value}):Ft.createElement(GLt.Consumer,null,a=>Ft.createElement(tpt,{...n,context:a}))}},zr(cUe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),cUe);const r_s=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Fa(async()=>{const{default:r}=await Promise.resolve().then(()=>hW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class PQe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class a_s extends PQe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class i_s extends PQe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Bre extends PQe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var Fqe;(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"})(Fqe||(Fqe={}));var o_s=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 l_s{constructor(t,{headers:n={},customFetch:r,region:a=Fqe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=r_s(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return o_s(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(f=>{throw new a_s(f)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new i_s(u);if(!u.ok)throw new Bre(u);let m=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return m==="application/json"?p=yield u.json():m==="application/octet-stream"?p=yield u.blob():m==="text/event-stream"?p=u:m==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(a){return{data:null,error:a}}})}}var j_={},LQe={},JMe={},$re={},ePe={},tPe={},c_s=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")},MH=c_s();const d_s=MH.fetch,KLt=MH.fetch.bind(MH),YLt=MH.Headers,u_s=MH.Request,h_s=MH.Response,hW=Object.freeze(Object.defineProperty({__proto__:null,Headers:YLt,Request:u_s,Response:h_s,default:KLt,fetch:d_s},Symbol.toStringTag,{value:"Module"})),m_s=bms(hW);var sPe={};Object.defineProperty(sPe,"__esModule",{value:!0});let p_s=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};sPe.default=p_s;var ZLt=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(tPe,"__esModule",{value:!0});const f_s=ZLt(m_s),x_s=ZLt(sPe);let g_s=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=f_s.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,m=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){const y=await i.text();y===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=y:u=JSON.parse(y))}const g=(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("/");g&&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,m=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const g=await i.text();try{d=JSON.parse(g),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,p="OK")}catch{i.status===404&&g===""?(m=204,p="No Content"):d={message:g}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,m=200,p="OK"),d&&this.shouldThrowOnError)throw new x_s.default(d)}return{error:d,data:u,count:h,status:m,statusText:p}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};tPe.default=g_s;var y_s=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ePe,"__esModule",{value:!0});const v_s=y_s(tPe);let b_s=class extends v_s.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}};ePe.default=b_s;var __s=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($re,"__esModule",{value:!0});const w_s=__s(ePe);let j_s=class extends w_s.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}};$re.default=j_s;var N_s=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(JMe,"__esModule",{value:!0});const BY=N_s($re);let k_s=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 BY.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 BY.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 BY.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 BY.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 BY.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};JMe.default=k_s;var nPe={},rPe={};Object.defineProperty(rPe,"__esModule",{value:!0});rPe.version=void 0;rPe.version="0.0.0-automated";Object.defineProperty(nPe,"__esModule",{value:!0});nPe.DEFAULT_HEADERS=void 0;const S_s=rPe;nPe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${S_s.version}`};var XLt=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(LQe,"__esModule",{value:!0});const C_s=XLt(JMe),A_s=XLt($re),E_s=nPe;let T_s=class QLt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},E_s.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new C_s.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new QLt(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 A_s.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};LQe.default=T_s;var mW=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(j_,"__esModule",{value:!0});j_.PostgrestError=j_.PostgrestBuilder=j_.PostgrestTransformBuilder=j_.PostgrestFilterBuilder=j_.PostgrestQueryBuilder=j_.PostgrestClient=void 0;const JLt=mW(LQe);j_.PostgrestClient=JLt.default;const eIt=mW(JMe);j_.PostgrestQueryBuilder=eIt.default;const tIt=mW($re);j_.PostgrestFilterBuilder=tIt.default;const sIt=mW(ePe);j_.PostgrestTransformBuilder=sIt.default;const nIt=mW(tPe);j_.PostgrestBuilder=nIt.default;const rIt=mW(sPe);j_.PostgrestError=rIt.default;var M_s=j_.default={PostgrestClient:JLt.default,PostgrestQueryBuilder:eIt.default,PostgrestFilterBuilder:tIt.default,PostgrestTransformBuilder:sIt.default,PostgrestBuilder:nIt.default,PostgrestError:rIt.default};const{PostgrestClient:P_s,PostgrestQueryBuilder:V_r,PostgrestFilterBuilder:H_r,PostgrestTransformBuilder:G_r,PostgrestBuilder:W_r,PostgrestError:K_r}=M_s;let Oqe;typeof window>"u"?Oqe=require("ws"):Oqe=window.WebSocket;const L_s=Oqe,I_s="2.11.10",D_s={"X-Client-Info":`realtime-js/${I_s}`},R_s="1.0.0",aIt=1e4,F_s=1e3;var Mq;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Mq||(Mq={}));var eb;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(eb||(eb={}));var Xk;(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"})(Xk||(Xk={}));var zqe;(function(s){s.websocket="websocket"})(zqe||(zqe={}));var oF;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(oF||(oF={}));class O_s{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 iIt{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 Ym;(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"})(Ym||(Ym={}));const spt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=z_s(l,s,t,a),i),{})},z_s=(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)?oIt(i,l):Bqe(l)},oIt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return q_s(t,n)}switch(s){case Ym.bool:return B_s(t);case Ym.float4:case Ym.float8:case Ym.int2:case Ym.int4:case Ym.int8:case Ym.numeric:case Ym.oid:return $_s(t);case Ym.json:case Ym.jsonb:return U_s(t);case Ym.timestamp:return V_s(t);case Ym.abstime:case Ym.date:case Ym.daterange:case Ym.int4range:case Ym.int8range:case Ym.money:case Ym.reltime:case Ym.text:case Ym.time:case Ym.timestamptz:case Ym.timetz:case Ym.tsrange:case Ym.tstzrange:return Bqe(t);default:return Bqe(t)}},Bqe=s=>s,B_s=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},$_s=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},U_s=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},q_s=(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=>oIt(t,o))}return s},V_s=s=>typeof s=="string"?s.replace(" ","T"):s,lIt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class fOe{constructor(t,n,r={},a=aIt){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 npt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(npt||(npt={}));class kJ{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=kJ.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=kJ.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=kJ.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const m=u.map(v=>v.presence_ref),p=h.map(v=>v.presence_ref),f=u.filter(v=>p.indexOf(v.presence_ref)<0),g=h.filter(v=>m.indexOf(v.presence_ref)<0);f.length>0&&(o[d]=f),g.length>0&&(c[d]=g)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(p=>p.presence_ref),m=u.filter(p=>h.indexOf(p.presence_ref)<0);t[o].unshift(...m)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var rpt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(rpt||(rpt={}));var apt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(apt||(apt={}));var H3;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(H3||(H3={}));class IQe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=eb.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 fOe(this,Xk.join,this.params,this.timeout),this.rejoinTimer=new iIt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=eb.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=eb.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=eb.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=eb.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Xk.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new kJ(this),this.broadcastEndpointURL=lIt(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(H3.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(H3.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(H3.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,p=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,f=[];for(let g=0;g{this.state=eb.errored,t==null||t(H3.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(H3.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=eb.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Xk.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new fOe(this,Xk.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 fOe(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}=Xk;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(p=>{var f,g,v;return((f=p.filter)===null||f===void 0?void 0:f.event)==="*"||((v=(g=p.filter)===null||g===void 0?void 0:g.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===l}).map(p=>p.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(p=>{var f,g,v,y,b,w;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in p){const S=p.id,C=(f=p.filter)===null||f===void 0?void 0:f.event;return S&&((g=n.ids)===null||g===void 0?void 0:g.includes(S))&&(C==="*"||(C==null?void 0:C.toLocaleLowerCase())===((v=n.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{const S=(b=(y=p==null?void 0:p.filter)===null||y===void 0?void 0:y.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((w=n==null?void 0:n.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===l}).map(p=>{if(typeof m=="object"&&"ids"in m){const f=m.data,{schema:g,table:v,commit_timestamp:y,type:b,errors:w}=f;m=Object.assign(Object.assign({},{schema:g,table:v,commit_timestamp:y,eventType:b,new:{},old:{},errors:w}),this._getPayloadRecords(f))}p.callback(m,r)})}_isClosed(){return this.state===eb.closed}_isJoined(){return this.state===eb.joined}_isJoining(){return this.state===eb.joining}_isLeaving(){return this.state===eb.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&&IQe.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(Xk.close,{},t)}_onError(t){this._on(Xk.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=eb.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=spt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=spt(t.columns,t.old_record)),n}}const ipt=()=>{},H_s=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class G_s{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=D_s,this.params={},this.timeout=aIt,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ipt,this.ref=0,this.logger=ipt,this.conn=null,this.sendBuffer=[],this.serializer=new O_s,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>Fa(async()=>{const{default:c}=await Promise.resolve().then(()=>hW);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${zqe.websocket}`,this.httpEndpoint=lIt(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 iIt(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=L_s),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 W_s(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:R_s}))}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 Mq.connecting:return oF.Connecting;case Mq.open:return oF.Open;case Mq.closing:return oF.Closing;default:return oF.Closed}}isConnected(){return this.connectionState()===oF.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new IQe(`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(Xk.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(F_s,"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(Xk.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([H_s],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class W_s{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Mq.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class DQe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function c0(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class K_s extends DQe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class $qe extends DQe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var Y_s=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 cIt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Fa(async()=>{const{default:r}=await Promise.resolve().then(()=>hW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Z_s=()=>Y_s(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Fa(()=>Promise.resolve().then(()=>hW),void 0)).Response:Response}),Uqe=s=>{if(Array.isArray(s))return s.map(n=>Uqe(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]=Uqe(r)}),t};var W9=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 xOe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),X_s=(s,t,n)=>W9(void 0,void 0,void 0,function*(){const r=yield Z_s();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new K_s(xOe(a),s.status||500))}).catch(a=>{t(new $qe(xOe(a),a))}):t(new $qe(xOe(s),s))}),Q_s=(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 Ure(s,t,n,r,a,i){return W9(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,Q_s(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=>X_s(c,o,r))})})}function oAe(s,t,n,r){return W9(this,void 0,void 0,function*(){return Ure(s,"GET",t,n,r)})}function y6(s,t,n,r,a){return W9(this,void 0,void 0,function*(){return Ure(s,"POST",t,r,a,n)})}function J_s(s,t,n,r,a){return W9(this,void 0,void 0,function*(){return Ure(s,"PUT",t,r,a,n)})}function ews(s,t,n,r){return W9(this,void 0,void 0,function*(){return Ure(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function dIt(s,t,n,r,a){return W9(this,void 0,void 0,function*(){return Ure(s,"DELETE",t,r,a,n)})}var t_=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 tws={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},opt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class sws{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=cIt(a)}uploadOrUpdate(t,n,r,a){return t_(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},opt),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(n),u=this._getFinalPath(d),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),m=yield h.json();return h.ok?{data:{path:d,id:m.Id,fullPath:m.Key},error:null}:{data:null,error:m}}catch(i){if(c0(i))return{data:null,error:i};throw i}})}upload(t,n,r){return t_(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return t_(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:opt.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",d.cacheControl)):(c=r,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const h=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:u}),m=yield h.json();return h.ok?{data:{path:i,fullPath:m.Key},error:null}:{data:null,error:m}}catch(c){if(c0(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return t_(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 y6(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 DQe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(c0(r))return{data:null,error:r};throw r}})}update(t,n,r){return t_(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return t_(this,void 0,void 0,function*(){try{return{data:yield y6(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(c0(a))return{data:null,error:a};throw a}})}copy(t,n,r){return t_(this,void 0,void 0,function*(){try{return{data:{path:(yield y6(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(c0(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return t_(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield y6(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(c0(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return t_(this,void 0,void 0,function*(){try{const a=yield y6(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(c0(a))return{data:null,error:a};throw a}})}download(t,n){return t_(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 oAe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(c0(o))return{data:null,error:o};throw o}})}info(t){return t_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield oAe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:Uqe(r),error:null}}catch(r){if(c0(r))return{data:null,error:r};throw r}})}exists(t){return t_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield ews(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(c0(r)&&r instanceof $qe){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 t_(this,void 0,void 0,function*(){try{return{data:yield dIt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(c0(n))return{data:null,error:n};throw n}})}list(t,n,r){return t_(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},tws),n),{prefix:t||""});return{data:yield y6(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(c0(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 nws="2.7.1",rws={"X-Client-Info":`storage-js/${nws}`};var wB=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 aws{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},rws),n),this.fetch=cIt(r)}listBuckets(){return wB(this,void 0,void 0,function*(){try{return{data:yield oAe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(c0(t))return{data:null,error:t};throw t}})}getBucket(t){return wB(this,void 0,void 0,function*(){try{return{data:yield oAe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(c0(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return wB(this,void 0,void 0,function*(){try{return{data:yield y6(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(c0(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return wB(this,void 0,void 0,function*(){try{return{data:yield J_s(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(c0(r))return{data:null,error:r};throw r}})}emptyBucket(t){return wB(this,void 0,void 0,function*(){try{return{data:yield y6(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(c0(n))return{data:null,error:n};throw n}})}deleteBucket(t){return wB(this,void 0,void 0,function*(){try{return{data:yield dIt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(c0(n))return{data:null,error:n};throw n}})}}class iws extends aws{constructor(t,n={},r){super(t,n,r)}from(t){return new sws(this.url,this.headers,t,this.fetch)}}const ows="2.49.10";let yX="";typeof Deno<"u"?yX="deno":typeof document<"u"?yX="web":typeof navigator<"u"&&navigator.product==="ReactNative"?yX="react-native":yX="node";const lws={"X-Client-Info":`supabase-js-${yX}/${ows}`},cws={headers:lws},dws={schema:"public"},uws={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},hws={};var mws=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 pws=s=>{let t;return s?t=s:typeof fetch>"u"?t=KLt:t=fetch,(...n)=>t(...n)},fws=()=>typeof Headers>"u"?YLt:Headers,xws=(s,t,n)=>{const r=pws(n),a=fws();return(i,l)=>mws(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 gws=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 yws(s){return s.endsWith("/")?s:s+"/"}function vws(s,t){var n,r;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:h}=t,m={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},u),l),global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{}),(r=o==null?void 0:o.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>gws(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const uIt="2.69.1",w$=30*1e3,qqe=3,gOe=qqe*w$,bws="http://localhost:9999",_ws="supabase.auth.token",wws={"X-Client-Info":`gotrue-js/${uIt}`},Vqe="X-Supabase-Api-Version",hIt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},jws=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Nws=6e5;class RQe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Jc(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class kws extends RQe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Sws(s){return Jc(s)&&s.name==="AuthApiError"}class mIt extends RQe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class fL extends RQe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class XT extends fL{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Cws(s){return Jc(s)&&s.name==="AuthSessionMissingError"}class yOe extends fL{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ple extends fL{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class fle extends fL{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 Aws(s){return Jc(s)&&s.name==="AuthImplicitGrantRedirectError"}class lpt extends fL{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 Hqe extends fL{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function vOe(s){return Jc(s)&&s.name==="AuthRetryableFetchError"}class cpt extends fL{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class SJ extends fL{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const dpt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),upt=` \r=`.split(""),Ews=(()=>{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 hpt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{Pws(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 Mws(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}Tws(r,t)}}function Pws(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 Lws(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function Dws(s){return Math.round(Date.now()/1e3)+s}function Rws(){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 O5=()=>typeof window<"u"&&typeof document<"u",CI={tested:!1,writable:!1},CJ=()=>{if(!O5())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(CI.tested)return CI.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),CI.tested=!0,CI.writable=!0}catch{CI.tested=!0,CI.writable=!1}return CI.writable};function Fws(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 fIt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Fa(async()=>{const{default:r}=await Promise.resolve().then(()=>hW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Ows=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",xIt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},xle=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},gle=async(s,t)=>{await s.removeItem(t)};class aPe{constructor(){this.promise=new aPe.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}aPe.promiseConstructor=Promise;function bOe(s){const t=s.split(".");if(t.length!==3)throw new SJ("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function Bws(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 $ws(s){return("0"+s.toString(16)).substr(-2)}function Uws(){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,$ws).join("")}async function qws(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 Vws(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 qws(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function jB(s,t,n=!1){const r=Uws();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await xIt(s,`${t}-code-verifier`,a);const i=await Vws(r);return[i,r===i?"plain":"s256"]}const Hws=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Gws(s){const t=s.headers.get(Vqe);if(!t||!t.match(Hws))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Wws(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 Kws(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 Yws=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),Zws=[502,503,504];async function mpt(s){var t;if(!Ows(s))throw new Hqe(GR(s),0);if(Zws.includes(s.status))throw new Hqe(GR(s),s.status);let n;try{n=await s.json()}catch(i){throw new mIt(GR(i),i)}let r;const a=Gws(s);if(a&&a.getTime()>=hIt["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 cpt(GR(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new XT}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 cpt(GR(n),s.status,n.weak_password.reasons);throw new kws(GR(n),s.status||500,r)}const Xws=(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 Jd(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[Vqe]||(i[Vqe]=hIt["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 Qws(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 Qws(s,t,n,r,a,i){const l=Xws(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new Hqe(GR(c),0)}if(o.ok||await mpt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await mpt(c)}}function QT(s){var t;let n=null;sjs(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=Dws(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function ppt(s){const t=QT(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 L6(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function Jws(s){return{data:s,error:null}}function ejs(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=Yws(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 tjs(s){return s}function sjs(s){return s.access_token&&s.refresh_token&&s.expires_in}var njs=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(p.forEach(f=>{const g=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(f.split(";")[1].split("=")[1]);d[`${v}Page`]=g}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Jc(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Jd(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:L6})}catch(n){if(Jc(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Jd(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:L6})}catch(r){if(Jc(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Jd(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:L6})}catch(r){if(Jc(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Jd(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(Jc(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Jd(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Jc(n))return{data:null,error:n};throw n}}}const ajs={getItem:s=>CJ()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{CJ()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{CJ()&&globalThis.localStorage.removeItem(s)}};function fpt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function ijs(){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 NB={debug:!!(globalThis&&CJ()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class gIt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class ojs extends gIt{}async function ljs(s,t,n){NB.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),NB.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){NB.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{NB.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw NB.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ojs(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(NB.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()}}))}ijs();const cjs={url:bws,storageKey:_ws,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:wws,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function xpt(s,t,n){return await n()}class ote{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=ote.nextInstanceID,ote.nextInstanceID+=1,this.instanceID>0&&O5()&&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({},cjs),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 rjs({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=fIt(a.fetch),this.lock=a.lock||xpt,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:O5()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=ljs:this.lock=xpt,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:CJ()?this.storage=ajs:(this.memoryStorage={},this.storage=fpt(this.memoryStorage)):(this.memoryStorage={},this.storage=fpt(this.memoryStorage)),O5()&&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} (${uIt}) ${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=Fws(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),O5()&&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),Aws(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 Jc(n)?{error:n}:{error:new mIt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Jd(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:QT}),{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(Jc(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:m}=t;let p=null,f=null;this.flowType==="pkce"&&([p,f]=await jB(this.storage,this.storageKey)),i=await Jd(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:u,password:h,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:p,code_challenge_method:f},xform:QT})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Jd(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=m==null?void 0:m.data)!==null&&r!==void 0?r:{},channel:(a=m==null?void 0:m.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:QT})}else throw new ple("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(Jc(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 Jd(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:ppt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Jd(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:ppt})}else throw new ple("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 yOe}:(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(Jc(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 xle(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Jd(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:QT});if(await gle(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new yOe}:(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(Jc(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 Jd(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:QT}),{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 yOe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Jc(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 jB(this.storage,this.storageKey));const{error:h}=await Jd(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 Jd(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 ple("You must provide either an email or phone number.")}catch(o){if(Jc(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 Jd(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:QT});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(Jc(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 jB(this.storage,this.storageKey)),await Jd(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:Jws})}catch(i){if(Jc(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 XT;const{error:a}=await Jd(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Jc(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 Jd(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 Jd(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 ple("You must provide either an email or phone number and a type")}catch(n){if(Jc(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 xle(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 Jd(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:L6}):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 XT}:await Jd(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:L6})})}catch(n){if(Jc(n))return Cws(n)&&(await this._removeSession(),await gle(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 XT;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await jB(this.storage,this.storageKey));const{data:d,error:u}=await Jd(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:L6});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(Jc(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 XT;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=bOe(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(Jc(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 XT;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(Jc(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!O5())throw new fle("No browser detected.");if(t.error||t.error_description||t.error_code)throw new fle(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 lpt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new fle("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 lpt("No code detected.");const{data:b,error:w}=await this._exchangeCodeForSession(t.code);if(w)throw w;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:b.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 fle("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let m=u+h;c&&(m=parseInt(c));const p=m-u;p*1e3<=w$&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const f=m-h;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,m,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,m,u);const{data:g,error:v}=await this._getUser(i);if(v)throw v;const y={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:t.type},error:null}}catch(r){if(Jc(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 xle(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&&!(Sws(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await gle(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=Rws(),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 jB(this.storage,this.storageKey,!0));try{return await Jd(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(Jc(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(Jc(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:m}=i;if(m)throw m;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await Jd(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return O5()&&!(!((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(Jc(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 Jd(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(Jc(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 Bws(async a=>(a>0&&await zws(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Jd(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:QT})),(a,i)=>{const l=200*Math.pow(2,a);return i&&vOe(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(),w$);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)/w$);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${w$}ms, refresh threshold is ${qqe} ticks`),a<=qqe&&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 gIt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!O5()||!(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 jB(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 Jd(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(Jc(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 Jd(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(Jc(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 Jd(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(Jc(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 Jd(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(Jc(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}=bOe(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+Nws>Date.now()))return r;const{data:a,error:i}=await Jd(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 SJ("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new SJ("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:p,error:f}=await this.getSession();if(f||!p.session)return{data:null,error:f};r=p.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=bOe(r);if(Wws(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:a,signature:l},error:null}}const d=Kws(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,Iws(`${o}.${c}`)))throw new SJ("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Jc(r))return{data:null,error:r};throw r}}}ote.nextInstanceID=0;const djs=ote;class ujs extends djs{constructor(t){super(t)}}var hjs=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 mjs{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=yws(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:dws,realtime:hws,auth:Object.assign(Object.assign({},uws),{storageKey:d}),global:cws},h=vws(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(m,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=xws(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 P_s(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new l_s(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new iws(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 hjs(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 ujs({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 G_s(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 pjs=(s,t,n)=>new mjs(s,t,n);function fjs(){var v,y;if(typeof window>"u")return;const s=location.hostname,n=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(b=>s===b||s.endsWith("."+b)),r="[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",a=n?((v=s.match(new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+r+")(?:-dev)?(?=\\.|$)","i")))==null?void 0:v[1])??((y=s.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:y[1]):void 0,i=window.parent&&window.parent!==window;if(!a||!i)return localStorage;const l=s.endsWith(".lovableproject-dev.com")||s.endsWith(".gpt-eng.com"),o=l?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,c=location.ancestorOrigins&&location.ancestorOrigins[0]||(document.referrer?new URL(document.referrer).origin:""),d=c&&o.test(c)?[c]:l?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],u="lovable-preview-auth:result",h=2e3,m=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),p=(b,w,S)=>new Promise(C=>{const E=m();let P=!1,M;const I=q=>{P||(P=!0,clearTimeout(M),window.removeEventListener("message",D),C(q))},D=q=>{if(d.indexOf(q.origin)<0)return;const G=q.data;G&&G.type===u&&G.requestId===E&&I(G)};window.addEventListener("message",D);const F={type:b,requestId:E,projectId:a,key:w};S!==void 0&&(F.value=S);for(const q of d)window.parent.postMessage(F,q);M=setTimeout(()=>I(null),h)});let f=!0;const g=250;return{getItem:async b=>{let w=await p("lovable-preview-auth:get",b);return!w&&f&&(await new Promise(S=>setTimeout(S,g)),w=await p("lovable-preview-auth:get",b)),f=!1,w&&w.ok&&typeof w.value=="string"?w.value===""?(localStorage.removeItem(b),null):w.value:localStorage.getItem(b)},setItem:(b,w)=>(localStorage.setItem(b,w),p("lovable-preview-auth:set",b,w).then(S=>{S&&S.ok&&typeof S.value=="string"&&localStorage.getItem(b)===w&&(S.value===""?localStorage.removeItem(b):localStorage.setItem(b,S.value))})),removeItem:b=>(localStorage.removeItem(b),p("lovable-preview-auth:remove",b).then(()=>{}))}}const xjs="https://relzejiswnotikjgvjhz.supabase.co",gjs="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",U=pjs(xjs,gjs,{auth:{storage:fjs(),persistSession:!0,autoRefreshToken:!0}}),yjs=Object.freeze(Object.defineProperty({__proto__:null,supabase:U},Symbol.toStringTag,{value:"Module"})),yIt=_.createContext(void 0),vjs=({children:s})=>{const[t,n]=_.useState(null),[r,a]=_.useState(null),[i,l]=_.useState(!0),[o,c]=_.useState(!0),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[g,v]=_.useState(null),[y,b]=_.useState([]),[w,S]=_.useState(null),C=_.useRef(null),E=_.useRef(!1),P=_.useRef(!1),M=zn(),I=()=>{u(!1),m(!1),f(!1),v(null),b([]),S(null),C.current=null,E.current=!1},D=async V=>{if(E.current&&C.current===V||P.current)return;P.current=!0,c(!0);const H=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),P.current=!1,c(!1)},8e3);try{console.log("Checking roles via RPC for user:",V);const[{data:K,error:Z},{data:oe,error:re},{data:ae,error:J}]=await Promise.all([U.rpc("has_role",{_user_id:V,_role:"admin"}),U.rpc("has_role",{_user_id:V,_role:"brokerage_manager"}),U.rpc("has_role",{_user_id:V,_role:"coach"})]);if(Z||re)console.error("Role RPC errors:",{isAdminError:Z,isBrokerError:re,isCoachError:J}),u(!1),m(!1),f(!1);else{const ve=!!K,me=!!oe,he=!!ae;console.log("RPC roles result:",{adminValue:ve,brokerValue:me,coachValue:he}),u(ve),m(me),f(he)}C.current=V,E.current=!0,window.clearTimeout(H),c(!1);const{data:te,error:ce}=await U.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",V).single();if(!ce&&(te!=null&&te.is_paused)){const ve=te.paused_reason;try{sessionStorage.setItem("accountPausedReason",ve||"")}catch{}await U.auth.signOut(),I(),M("/auth?paused=1",{replace:!0});return}if(v(!ce&&te?te.brokerage_id:null),oe){console.log("Fetching managed brokerages for user:",V);const{data:ve,error:me}=await U.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",V);if(console.log("Managed brokerage assignments result:",{assignments:ve,assignmentsError:me}),me||!ve){console.error("Error fetching managed brokerage assignments:",me),b([]);return}const he=Array.from(new Set(ve.map(Pe=>Pe.brokerage_id).filter(Boolean)));if(he.length===0){b([]);return}const{data:ge,error:Ee}=await U.from("brokerages").select("id, name").in("id",he);if(console.log("Managed brokerages details result:",{brokeragesData:ge,brokeragesError:Ee}),Ee||!ge){console.error("Error fetching managed brokerages details:",Ee),b([]);return}const Ne=ge.map(Pe=>({id:Pe.id,name:Pe.name})).sort((Pe,Oe)=>he.indexOf(Pe.id)-he.indexOf(Oe.id));console.log("Parsed managed brokerages:",Ne),b(Ne),Ne.length>0&&S(Pe=>Pe??Ne[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);C.current=V,E.current=!0}catch(K){console.error("Unexpected error in checkRoles:",K),I()}finally{window.clearTimeout(H),P.current=!1,c(!1)}};_.useEffect(()=>{let V=!0,H=!1;const K=()=>{!V||H||(H=!0,l(!1))},{data:{subscription:Z}}=U.auth.onAuthStateChange((re,ae)=>{console.log("Auth event:",re),V&&(a(ae),n((ae==null?void 0:ae.user)??null),K(),re==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),ae!=null&&ae.user?(!E.current||C.current!==ae.user.id)&&setTimeout(()=>{D(ae.user.id)},0):(I(),c(!1)))}),oe=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),K()},8e3);return()=>{V=!1,window.clearTimeout(oe),Z.unsubscribe()}},[]);const F=async(V,H)=>{var re;const K=(V||"").trim().toLowerCase(),{data:Z,error:oe}=await U.auth.signInWithPassword({email:K,password:H});if(oe)throw ne.error(/invalid login credentials/i.test(oe.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:oe.message),oe;if((re=Z.user)!=null&&re.id){const{data:ae}=await U.from("profiles").select("is_paused, paused_reason").eq("id",Z.user.id).maybeSingle();if(ae!=null&&ae.is_paused){const J=ae.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",J)}catch{}await U.auth.signOut(),I(),n(null),a(null);const te=new Error(J?`Your account is paused. ${J}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw te.name="AccountPaused",ne.error(te.message),te}}ne.success("Welcome back!")},q=async(V,H,K)=>{var J;const Z="https://dashboard.relevelup.com/dashboard",oe=localStorage.getItem("levelup_referral_code")||null,{data:re,error:ae}=await U.auth.signUp({email:V,password:H,options:{emailRedirectTo:Z,data:{name:K,referred_by_code:oe}}});if(ae)throw ne.error(ae.message),ae;if(oe&&((J=re.user)!=null&&J.id))try{await U.from("profiles").update({referred_by_code:oe}).eq("id",re.user.id),localStorage.removeItem("levelup_referral_code")}catch(te){console.warn("Failed to attach referral code to profile",te)}ne.success("Account created! Welcome to LevelUp."),M("/dashboard")},G=async()=>{try{const{data:{session:V}}=await U.auth.getSession();if(V){const{error:H}=await U.auth.signOut();H?H.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",H.message):(console.error("Sign out error:",H),ne.error(H.message)):ne.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),v(null),b([]),S(null),M("/auth")}catch(V){console.error("Unexpected sign out error:",V),M("/auth")}};return e.jsx(yIt.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:F,signUp:q,signOut:G,isAdmin:d,isBrokerageManager:h,isCoach:p,brokerageId:g,managedBrokerages:y,selectedBrokerageId:w,setSelectedBrokerageId:S},children:s})},hs=()=>{const s=_.useContext(yIt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},vIt=_.createContext({onlineUsers:[],totalOnline:0}),bjs=3*60*1e3,_js=45*1e3,wjs=30*1e3,jjs=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=hs(),[a,i]=_.useState([]),l=_.useRef(new Date().toISOString()),o=_.useCallback(async()=>{t&&await U.from("user_presence").upsert({user_id:t.id,last_seen_at:new Date().toISOString(),online_since:l.current,current_path:window.location.pathname},{onConflict:"user_id"})},[t==null?void 0:t.id]),c=_.useCallback(async()=>{if(!t)return;const u=new Date(Date.now()-bjs).toISOString(),{data:h}=await U.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",u).order("last_seen_at",{ascending:!1}).limit(200);if(!(h!=null&&h.length)){i([]);return}const m=h.map(g=>g.user_id),{data:p}=await U.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),f=new Map((p||[]).map(g=>[g.id,g]));i(h.map(g=>{var y;const v=f.get(g.user_id);return{id:g.user_id,name:(v==null?void 0:v.name)||((y=v==null?void 0:v.email)==null?void 0:y.split("@")[0])||"Member",avatarUrl:(v==null?void 0:v.avatar_url)||void 0,brokerageId:(v==null?void 0:v.brokerage_id)||void 0,onlineSince:g.online_since||g.last_seen_at}}))},[t==null?void 0:t.id]);_.useEffect(()=>{if(!t){i([]);return}l.current=new Date().toISOString();let u=!1;const h=async()=>{u||(await o(),await c())};h();const m=window.setInterval(()=>{o()},_js),p=window.setInterval(()=>{c()},wjs),f=()=>{document.visibilityState==="visible"&&h()};return document.addEventListener("visibilitychange",f),()=>{u=!0,window.clearInterval(m),window.clearInterval(p),document.removeEventListener("visibilitychange",f)}},[t==null?void 0:t.id,o,c]);const d=a.filter(u=>!!(u.id===(t==null?void 0:t.id)||r||n&&u.brokerageId===n||!n&&!u.brokerageId));return e.jsx(vIt.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},bIt=()=>_.useContext(vIt),_It=_.createContext(void 0),AI="levelup_admin_session",kT="levelup_impersonation",_Oe="levelup_impersonation_return",Njs=({children:s})=>{const[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState(!1);_.useEffect(()=>{const d=sessionStorage.getItem(kT);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(kT)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await U.auth.getSession();if(!h)return ne.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(AI,JSON.stringify(m)),u&&sessionStorage.setItem(_Oe,u);const p=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),f=await p.json();if(!p.ok)throw new Error(f.error||"Failed to impersonate user");const g={id:f.targetUser.id,name:f.targetUser.name,email:f.targetUser.email};if(sessionStorage.setItem(kT,JSON.stringify(g)),f.method==="session"){const{error:v}=await U.auth.setSession({access_token:f.access_token,refresh_token:f.refresh_token});if(v)throw console.error("Set session error:",v),sessionStorage.removeItem(AI),sessionStorage.removeItem(kT),new Error("Failed to establish impersonation session")}else{const v=f.type||"recovery",{error:y}=await U.auth.verifyOtp({token_hash:f.token_hash,type:v});if(y)throw console.error("Verify OTP error:",y),sessionStorage.removeItem(AI),sessionStorage.removeItem(kT),new Error("Failed to establish impersonation session")}return n(!0),a(g),ne.success(`Now viewing as ${g.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ne.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(AI),sessionStorage.removeItem(kT),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(AI);if(!d){await U.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await U.auth.signOut();const{error:h}=await U.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(AI),sessionStorage.removeItem(kT),h){console.error("Failed to restore admin session:",h),ne.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ne.success("Returned to your account");const m=sessionStorage.getItem(_Oe)||"/admin/members";sessionStorage.removeItem(_Oe),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),ne.error("Failed to restore admin session"),sessionStorage.removeItem(AI),sessionStorage.removeItem(kT),window.location.href="/auth"}finally{l(!1)}};return e.jsx(_It.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},iPe=()=>{const s=_.useContext(_It);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},kjs=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=iPe();return!s||!t?null:e.jsx("div",{className:"fixed top-0 left-0 right-0 z-[100] bg-amber-500 text-amber-950 px-4 py-2 shadow-lg",children:e.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nl,{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(z,{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(bt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(er,{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"})]})})]})})},wIt=_.createContext(void 0),kB="levelup_acting_as",yle="levelup_acting_as_self",Sjs=({children:s})=>{const{user:t}=hs(),[n,r]=_.useState(!1),[a,i]=_.useState([]),[l,o]=_.useState(null),[c,d]=_.useState({}),[u,h]=_.useState(!0),[m,p]=_.useState(()=>sessionStorage.getItem(yle)==="true");_.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:w}=await U.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!w){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:S,error:C}=await U.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(C||!S||S.length===0){i([]),h(!1);return}const E=S.map(I=>I.agent_id),{data:P}=await U.from("profiles").select("id, name, email, avatar_url").in("id",E),M=(P||[]).map(I=>({id:I.id,name:I.name||I.email||"Unknown",email:I.email||"",avatar_url:I.avatar_url}));if(i(M),sessionStorage.getItem(yle)==="true")p(!0),o(null),d({});else{const I=sessionStorage.getItem(kB);if(I){const D=M.find(F=>F.id===I);if(D){o(D);const F=S.find(q=>q.agent_id===I);d((F==null?void 0:F.permissions)||{})}else if(M.length>0){o(M[0]);const F=S.find(q=>q.agent_id===M[0].id);d((F==null?void 0:F.permissions)||{}),sessionStorage.setItem(kB,M[0].id)}}else if(M.length>0){o(M[0]);const D=S.find(F=>F.agent_id===M[0].id);d((D==null?void 0:D.permissions)||{}),sessionStorage.setItem(kB,M[0].id)}}}catch(w){console.error("Error loading assistant data:",w)}finally{h(!1)}})()},[t==null?void 0:t.id]);const f=b=>{o(b),p(!1),sessionStorage.removeItem(yle),b?(sessionStorage.setItem(kB,b.id),U.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",b.id).single().then(({data:w})=>{d((w==null?void 0:w.permissions)||{})})):(sessionStorage.removeItem(kB),d({}))},g=()=>{p(!0),o(null),d({}),sessionStorage.setItem(yle,"true"),sessionStorage.removeItem(kB)},v=b=>!n||m?!0:c[b]===!0,y=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(wIt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:f,effectiveUserId:y,permissions:c,hasPermission:v,isLoading:u,isActingAsSelf:m,setActingAsSelf:g},children:s})},qre=()=>{const s=_.useContext(wIt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},ha=()=>{const{effectiveUserId:s}=qre();return s};var jIt={exports:{}},NIt={};/** * @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 PH=_;function Cjs(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var Ajs=typeof Object.is=="function"?Object.is:Cjs,Ejs=PH.useState,Tjs=PH.useEffect,Mjs=PH.useLayoutEffect,Pjs=PH.useDebugValue;function Ljs(s,t){var n=t(),r=Ejs({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return Mjs(function(){a.value=n,a.getSnapshot=t,wOe(a)&&i({inst:a})},[s,n,t]),Tjs(function(){return wOe(a)&&i({inst:a}),s(function(){wOe(a)&&i({inst:a})})},[s]),Pjs(n),n}function wOe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!Ajs(s,n)}catch{return!0}}function Ijs(s,t){return t()}var Djs=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Ijs:Ljs;NIt.useSyncExternalStore=PH.useSyncExternalStore!==void 0?PH.useSyncExternalStore:Djs;jIt.exports=NIt;var Rjs=jIt.exports;function Fjs(){return Rjs.useSyncExternalStore(Ojs,()=>!0,()=>!1)}function Ojs(){return()=>{}}var FQe="Avatar",[zjs,Y_r]=uf(FQe),[Bjs,kIt]=zjs(FQe),SIt=_.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=_.useState("idle");return e.jsx(Bjs,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(ci.span,{...r,ref:t})})});SIt.displayName=FQe;var CIt="AvatarImage",AIt=_.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=kIt(CIt,n),o=$js(r,i),c=Ax(d=>{a(d),l.onImageLoadingStatusChange(d)});return Rx(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(ci.img,{...i,ref:t,src:r}):null});AIt.displayName=CIt;var EIt="AvatarFallback",TIt=_.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=kIt(EIt,n),[l,o]=_.useState(r===void 0);return _.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(ci.span,{...a,ref:t}):null});TIt.displayName=EIt;function gpt(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function $js(s,{referrerPolicy:t,crossOrigin:n}){const r=Fjs(),a=_.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=_.useState(()=>gpt(i,s));return Rx(()=>{o(gpt(i,s))},[i,s]),Rx(()=>{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 MIt=SIt,PIt=AIt,LIt=TIt;const ja=_.forwardRef(({className:s,...t},n)=>e.jsx(MIt,{ref:n,className:Ct("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));ja.displayName=MIt.displayName;const xi=_.forwardRef(({className:s,...t},n)=>e.jsx(PIt,{ref:n,className:Ct("aspect-square h-full w-full",s),...t}));xi.displayName=PIt.displayName;const Na=_.forwardRef(({className:s,...t},n)=>e.jsx(LIt,{ref:n,className:Ct("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Na.displayName=LIt.displayName;const Ujs=G9("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:Ct(Ujs({variant:t}),s),...n})}var qjs=_.createContext(void 0);function $E(s){const t=_.useContext(qjs);return s||t||"ltr"}var jOe="rovingFocusGroup.onEntryFocus",Vjs={bubbles:!1,cancelable:!0},Vre="RovingFocusGroup",[Gqe,IIt,Hjs]=tW(Vre),[Gjs,xL]=uf(Vre,[Hjs]),[Wjs,Kjs]=Gjs(Vre),DIt=_.forwardRef((s,t)=>e.jsx(Gqe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Gqe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Yjs,{...s,ref:t})})}));DIt.displayName=Vre;var Yjs=_.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,m=_.useRef(null),p=el(t,m),f=$E(i),[g,v]=Gg({prop:l,defaultProp:o??null,onChange:c,caller:Vre}),[y,b]=_.useState(!1),w=Ax(d),S=IIt(n),C=_.useRef(!1),[E,P]=_.useState(0);return _.useEffect(()=>{const M=m.current;if(M)return M.addEventListener(jOe,w),()=>M.removeEventListener(jOe,w)},[w]),e.jsx(Wjs,{scope:n,orientation:r,dir:f,loop:a,currentTabStopId:g,onItemFocus:_.useCallback(M=>v(M),[v]),onItemShiftTab:_.useCallback(()=>b(!0),[]),onFocusableItemAdd:_.useCallback(()=>P(M=>M+1),[]),onFocusableItemRemove:_.useCallback(()=>P(M=>M-1),[]),children:e.jsx(ci.div,{tabIndex:y||E===0?-1:0,"data-orientation":r,...h,ref:p,style:{outline:"none",...s.style},onMouseDown:wa(s.onMouseDown,()=>{C.current=!0}),onFocus:wa(s.onFocus,M=>{const I=!C.current;if(M.target===M.currentTarget&&I&&!y){const D=new CustomEvent(jOe,Vjs);if(M.currentTarget.dispatchEvent(D),!D.defaultPrevented){const F=S().filter(K=>K.focusable),q=F.find(K=>K.active),G=F.find(K=>K.id===g),H=[q,G,...F].filter(Boolean).map(K=>K.ref.current);OIt(H,u)}}C.current=!1}),onBlur:wa(s.onBlur,()=>b(!1))})})}),RIt="RovingFocusGroupItem",FIt=_.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=qg(),d=i||c,u=Kjs(RIt,n),h=u.currentTabStopId===d,m=IIt(n),{onFocusableItemAdd:p,onFocusableItemRemove:f,currentTabStopId:g}=u;return _.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),e.jsx(Gqe.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(ci.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:wa(s.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:wa(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:wa(s.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const y=Qjs(v,u.orientation,u.dir);if(y!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let w=m().filter(S=>S.focusable).map(S=>S.ref.current);if(y==="last")w.reverse();else if(y==="prev"||y==="next"){y==="prev"&&w.reverse();const S=w.indexOf(v.currentTarget);w=u.loop?Jjs(w,S+1):w.slice(S+1)}setTimeout(()=>OIt(w))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:g!=null}):l})})});FIt.displayName=RIt;var Zjs={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Xjs(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function Qjs(s,t,n){const r=Xjs(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Zjs[r]}function OIt(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Jjs(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var oPe=DIt,lPe=FIt,Wqe=["Enter"," "],e2s=["ArrowDown","PageUp","Home"],zIt=["ArrowUp","PageDown","End"],t2s=[...e2s,...zIt],s2s={ltr:[...Wqe,"ArrowRight"],rtl:[...Wqe,"ArrowLeft"]},n2s={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Hre="Menu",[lte,r2s,a2s]=tW(Hre),[K9,BIt]=uf(Hre,[a2s,CC,xL]),cPe=CC(),$It=xL(),[i2s,Y9]=K9(Hre),[o2s,Gre]=K9(Hre),UIt=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=cPe(t),[c,d]=_.useState(null),u=_.useRef(!1),h=Ax(i),m=$E(a);return _.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",f,{capture:!0,once:!0}),document.addEventListener("pointermove",f,{capture:!0,once:!0})},f=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",f,{capture:!0}),document.removeEventListener("pointermove",f,{capture:!0})}},[]),e.jsx(Fre,{...o,children:e.jsx(i2s,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(o2s,{scope:t,onClose:_.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})};UIt.displayName=Hre;var l2s="MenuAnchor",OQe=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=cPe(n);return e.jsx(lW,{...a,...r,ref:t})});OQe.displayName=l2s;var zQe="MenuPortal",[c2s,qIt]=K9(zQe,{forceMount:void 0}),VIt=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=Y9(zQe,t);return e.jsx(c2s,{scope:t,forceMount:n,children:e.jsx(vg,{present:n||i.open,children:e.jsx(sW,{asChild:!0,container:a,children:r})})})};VIt.displayName=zQe;var _N="MenuContent",[d2s,BQe]=K9(_N),HIt=_.forwardRef((s,t)=>{const n=qIt(_N,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=Y9(_N,s.__scopeMenu),l=Gre(_N,s.__scopeMenu);return e.jsx(lte.Provider,{scope:s.__scopeMenu,children:e.jsx(vg,{present:r||i.open,children:e.jsx(lte.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(u2s,{...a,ref:t}):e.jsx(h2s,{...a,ref:t})})})})}),u2s=_.forwardRef((s,t)=>{const n=Y9(_N,s.__scopeMenu),r=_.useRef(null),a=el(t,r);return _.useEffect(()=>{const i=r.current;if(i)return BMe(i)},[]),e.jsx($Qe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:wa(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),h2s=_.forwardRef((s,t)=>{const n=Y9(_N,s.__scopeMenu);return e.jsx($Qe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),m2s=OP("MenuContent.ScrollLock"),$Qe=_.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:m,onDismiss:p,disableOutsideScroll:f,...g}=s,v=Y9(_N,n),y=Gre(_N,n),b=cPe(n),w=$It(n),S=r2s(n),[C,E]=_.useState(null),P=_.useRef(null),M=el(t,P,v.onContentChange),I=_.useRef(0),D=_.useRef(""),F=_.useRef(0),q=_.useRef(null),G=_.useRef("right"),V=_.useRef(0),H=f?Mre:_.Fragment,K=f?{as:m2s,allowPinchZoom:!0}:void 0,Z=re=>{var ge,Ee;const ae=D.current+re,J=S().filter(Ne=>!Ne.disabled),te=document.activeElement,ce=(ge=J.find(Ne=>Ne.ref.current===te))==null?void 0:ge.textValue,ve=J.map(Ne=>Ne.textValue),me=k2s(ve,ae,ce),he=(Ee=J.find(Ne=>Ne.textValue===me))==null?void 0:Ee.ref.current;(function Ne(Pe){D.current=Pe,window.clearTimeout(I.current),Pe!==""&&(I.current=window.setTimeout(()=>Ne(""),1e3))})(ae),he&&setTimeout(()=>he.focus())};_.useEffect(()=>()=>window.clearTimeout(I.current),[]),OMe();const oe=_.useCallback(re=>{var J,te;return G.current===((J=q.current)==null?void 0:J.side)&&C2s(re,(te=q.current)==null?void 0:te.area)},[]);return e.jsx(d2s,{scope:n,searchRef:D,onItemEnter:_.useCallback(re=>{oe(re)&&re.preventDefault()},[oe]),onItemLeave:_.useCallback(re=>{var ae;oe(re)||((ae=P.current)==null||ae.focus(),E(null))},[oe]),onTriggerLeave:_.useCallback(re=>{oe(re)&&re.preventDefault()},[oe]),pointerGraceTimerRef:F,onPointerGraceIntentChange:_.useCallback(re=>{q.current=re},[]),children:e.jsx(H,{...K,children:e.jsx(Tre,{asChild:!0,trapped:a,onMountAutoFocus:wa(i,re=>{var ae;re.preventDefault(),(ae=P.current)==null||ae.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(pL,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,children:e.jsx(oPe,{asChild:!0,...w,dir:y.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:E,onEntryFocus:wa(c,re=>{y.isUsingKeyboardRef.current||re.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(Ore,{role:"menu","aria-orientation":"vertical","data-state":o8t(v.open),"data-radix-menu-content":"",dir:y.dir,...b,...g,ref:M,style:{outline:"none",...g.style},onKeyDown:wa(g.onKeyDown,re=>{const J=re.target.closest("[data-radix-menu-content]")===re.currentTarget,te=re.ctrlKey||re.altKey||re.metaKey,ce=re.key.length===1;J&&(re.key==="Tab"&&re.preventDefault(),!te&&ce&&Z(re.key));const ve=P.current;if(re.target!==ve||!t2s.includes(re.key))return;re.preventDefault();const he=S().filter(ge=>!ge.disabled).map(ge=>ge.ref.current);zIt.includes(re.key)&&he.reverse(),j2s(he)}),onBlur:wa(s.onBlur,re=>{re.currentTarget.contains(re.target)||(window.clearTimeout(I.current),D.current="")}),onPointerMove:wa(s.onPointerMove,cte(re=>{const ae=re.target,J=V.current!==re.clientX;if(re.currentTarget.contains(ae)&&J){const te=re.clientX>V.current?"right":"left";G.current=te,V.current=re.clientX}}))})})})})})})});HIt.displayName=_N;var p2s="MenuGroup",UQe=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(ci.div,{role:"group",...r,ref:t})});UQe.displayName=p2s;var f2s="MenuLabel",GIt=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(ci.div,{...r,ref:t})});GIt.displayName=f2s;var lAe="MenuItem",ypt="menu.itemSelect",dPe=_.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=_.useRef(null),l=Gre(lAe,s.__scopeMenu),o=BQe(lAe,s.__scopeMenu),c=el(t,i),d=_.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const m=new CustomEvent(ypt,{bubbles:!0,cancelable:!0});h.addEventListener(ypt,p=>r==null?void 0:r(p),{once:!0}),iQe(h,m),m.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(WIt,{...a,ref:c,disabled:n,onClick:wa(s.onClick,u),onPointerDown:h=>{var m;(m=s.onPointerDown)==null||m.call(s,h),d.current=!0},onPointerUp:wa(s.onPointerUp,h=>{var m;d.current||(m=h.currentTarget)==null||m.click()}),onKeyDown:wa(s.onKeyDown,h=>{const m=o.searchRef.current!=="";n||m&&h.key===" "||Wqe.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});dPe.displayName=lAe;var WIt=_.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=BQe(lAe,n),o=$It(n),c=_.useRef(null),d=el(t,c),[u,h]=_.useState(!1),[m,p]=_.useState("");return _.useEffect(()=>{const f=c.current;f&&p((f.textContent??"").trim())},[i.children]),e.jsx(lte.ItemSlot,{scope:n,disabled:r,textValue:a??m,children:e.jsx(lPe,{asChild:!0,...o,focusable:!r,children:e.jsx(ci.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:wa(s.onPointerMove,cte(f=>{r?l.onItemLeave(f):(l.onItemEnter(f),f.defaultPrevented||f.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:wa(s.onPointerLeave,cte(f=>l.onItemLeave(f))),onFocus:wa(s.onFocus,()=>h(!0)),onBlur:wa(s.onBlur,()=>h(!1))})})})}),x2s="MenuCheckboxItem",KIt=_.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(JIt,{scope:s.__scopeMenu,checked:n,children:e.jsx(dPe,{role:"menuitemcheckbox","aria-checked":cAe(n)?"mixed":n,...a,ref:t,"data-state":VQe(n),onSelect:wa(a.onSelect,()=>r==null?void 0:r(cAe(n)?!0:!n),{checkForDefaultPrevented:!1})})})});KIt.displayName=x2s;var YIt="MenuRadioGroup",[g2s,y2s]=K9(YIt,{value:void 0,onValueChange:()=>{}}),ZIt=_.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=Ax(r);return e.jsx(g2s,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(UQe,{...a,ref:t})})});ZIt.displayName=YIt;var XIt="MenuRadioItem",QIt=_.forwardRef((s,t)=>{const{value:n,...r}=s,a=y2s(XIt,s.__scopeMenu),i=n===a.value;return e.jsx(JIt,{scope:s.__scopeMenu,checked:i,children:e.jsx(dPe,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":VQe(i),onSelect:wa(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});QIt.displayName=XIt;var qQe="MenuItemIndicator",[JIt,v2s]=K9(qQe,{checked:!1}),e8t=_.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=v2s(qQe,n);return e.jsx(vg,{present:r||cAe(i.checked)||i.checked===!0,children:e.jsx(ci.span,{...a,ref:t,"data-state":VQe(i.checked)})})});e8t.displayName=qQe;var b2s="MenuSeparator",t8t=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(ci.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});t8t.displayName=b2s;var _2s="MenuArrow",s8t=_.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=cPe(n);return e.jsx(zre,{...a,...r,ref:t})});s8t.displayName=_2s;var w2s="MenuSub",[Z_r,n8t]=K9(w2s),vX="MenuSubTrigger",r8t=_.forwardRef((s,t)=>{const n=Y9(vX,s.__scopeMenu),r=Gre(vX,s.__scopeMenu),a=n8t(vX,s.__scopeMenu),i=BQe(vX,s.__scopeMenu),l=_.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=_.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return _.useEffect(()=>u,[u]),_.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(OQe,{asChild:!0,...d,children:e.jsx(WIt,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":o8t(n.open),...s,ref:jE(t,a.onTriggerChange),onClick:h=>{var m;(m=s.onClick)==null||m.call(s,h),!(s.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:wa(s.onPointerMove,cte(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:wa(s.onPointerLeave,cte(h=>{var p,f;u();const m=(p=n.content)==null?void 0:p.getBoundingClientRect();if(m){const g=(f=n.content)==null?void 0:f.dataset.side,v=g==="right",y=v?-5:5,b=m[v?"left":"right"],w=m[v?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+y,y:h.clientY},{x:b,y:m.top},{x:w,y:m.top},{x:w,y:m.bottom},{x:b,y:m.bottom}],side:g}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:wa(s.onKeyDown,h=>{var p;const m=i.searchRef.current!=="";s.disabled||m&&h.key===" "||s2s[r.dir].includes(h.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),h.preventDefault())})})})});r8t.displayName=vX;var a8t="MenuSubContent",i8t=_.forwardRef((s,t)=>{const n=qIt(_N,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=Y9(_N,s.__scopeMenu),l=Gre(_N,s.__scopeMenu),o=n8t(a8t,s.__scopeMenu),c=_.useRef(null),d=el(t,c);return e.jsx(lte.Provider,{scope:s.__scopeMenu,children:e.jsx(vg,{present:r||i.open,children:e.jsx(lte.Slot,{scope:s.__scopeMenu,children:e.jsx($Qe,{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:wa(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:wa(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:wa(s.onKeyDown,u=>{var p;const h=u.currentTarget.contains(u.target),m=n2s[l.dir].includes(u.key);h&&m&&(i.onOpenChange(!1),(p=o.trigger)==null||p.focus(),u.preventDefault())})})})})})});i8t.displayName=a8t;function o8t(s){return s?"open":"closed"}function cAe(s){return s==="indeterminate"}function VQe(s){return cAe(s)?"indeterminate":s?"checked":"unchecked"}function j2s(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function N2s(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function k2s(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=N2s(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 S2s(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=m>r&&n<(h-d)*(r-u)/(m-u)+d&&(a=!a)}return a}function C2s(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return S2s(n,t)}function cte(s){return t=>t.pointerType==="mouse"?s(t):void 0}var A2s=UIt,E2s=OQe,T2s=VIt,M2s=HIt,P2s=UQe,L2s=GIt,I2s=dPe,D2s=KIt,R2s=ZIt,F2s=QIt,O2s=e8t,z2s=t8t,B2s=s8t,$2s=r8t,U2s=i8t,uPe="DropdownMenu",[q2s,X_r]=uf(uPe,[BIt]),Db=BIt(),[V2s,l8t]=q2s(uPe),c8t=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=Db(t),d=_.useRef(null),[u,h]=Gg({prop:a,defaultProp:i??!1,onChange:l,caller:uPe});return e.jsx(V2s,{scope:t,triggerId:qg(),triggerRef:d,contentId:qg(),open:u,onOpenChange:h,onOpenToggle:_.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(A2s,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};c8t.displayName=uPe;var d8t="DropdownMenuTrigger",u8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=l8t(d8t,n),l=Db(n);return e.jsx(E2s,{asChild:!0,...l,children:e.jsx(ci.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:jE(t,i.triggerRef),onPointerDown:wa(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:wa(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});u8t.displayName=d8t;var H2s="DropdownMenuPortal",h8t=s=>{const{__scopeDropdownMenu:t,...n}=s,r=Db(t);return e.jsx(T2s,{...r,...n})};h8t.displayName=H2s;var m8t="DropdownMenuContent",p8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=l8t(m8t,n),i=Db(n),l=_.useRef(!1);return e.jsx(M2s,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:wa(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:wa(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)"}})});p8t.displayName=m8t;var G2s="DropdownMenuGroup",W2s=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(P2s,{...a,...r,ref:t})});W2s.displayName=G2s;var K2s="DropdownMenuLabel",f8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(L2s,{...a,...r,ref:t})});f8t.displayName=K2s;var Y2s="DropdownMenuItem",x8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(I2s,{...a,...r,ref:t})});x8t.displayName=Y2s;var Z2s="DropdownMenuCheckboxItem",g8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(D2s,{...a,...r,ref:t})});g8t.displayName=Z2s;var X2s="DropdownMenuRadioGroup",Q2s=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(R2s,{...a,...r,ref:t})});Q2s.displayName=X2s;var J2s="DropdownMenuRadioItem",y8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(F2s,{...a,...r,ref:t})});y8t.displayName=J2s;var eNs="DropdownMenuItemIndicator",v8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(O2s,{...a,...r,ref:t})});v8t.displayName=eNs;var tNs="DropdownMenuSeparator",b8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(z2s,{...a,...r,ref:t})});b8t.displayName=tNs;var sNs="DropdownMenuArrow",nNs=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(B2s,{...a,...r,ref:t})});nNs.displayName=sNs;var rNs="DropdownMenuSubTrigger",_8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx($2s,{...a,...r,ref:t})});_8t.displayName=rNs;var aNs="DropdownMenuSubContent",w8t=_.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Db(n);return e.jsx(U2s,{...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)"}})});w8t.displayName=aNs;var iNs=c8t,oNs=u8t,lNs=h8t,j8t=p8t,N8t=f8t,k8t=x8t,S8t=g8t,C8t=y8t,A8t=v8t,E8t=b8t,T8t=_8t,M8t=w8t;const ru=iNs,au=oNs,cNs=_.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(T8t,{ref:a,className:Ct("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(yi,{className:"ml-auto h-4 w-4"})]}));cNs.displayName=T8t.displayName;const dNs=_.forwardRef(({className:s,...t},n)=>e.jsx(M8t,{ref:n,className:Ct("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}));dNs.displayName=M8t.displayName;const qd=_.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(lNs,{children:e.jsx(j8t,{ref:r,sideOffset:t,className:Ct("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})}));qd.displayName=j8t.displayName;const ua=_.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(k8t,{ref:r,className:Ct("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}));ua.displayName=k8t.displayName;const uNs=_.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(S8t,{ref:a,className:Ct("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(A8t,{children:e.jsx(Wr,{className:"h-4 w-4"})})}),t]}));uNs.displayName=S8t.displayName;const hNs=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(C8t,{ref:r,className:Ct("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(A8t,{children:e.jsx(Gf,{className:"h-2 w-2 fill-current"})})}),t]}));hNs.displayName=C8t.displayName;const qP=_.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(N8t,{ref:r,className:Ct("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));qP.displayName=N8t.displayName;const Iy=_.forwardRef(({className:s,...t},n)=>e.jsx(E8t,{ref:n,className:Ct("-mx-1 my-1 h-px bg-muted",s),...t}));Iy.displayName=E8t.displayName;const mNs=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=qre();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(Oo,{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(On,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{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(Oo,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(ja,{className:"h-5 w-5",children:[e.jsx(xi,{src:t.avatar_url||void 0}),e.jsx(Na,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(cl,{className:"h-3 w-3"})]})}),e.jsxs(qd,{align:"start",className:"z-[2147483647]",children:[e.jsxs(ua,{onClick:i,className:"gap-2",children:[e.jsx(Oo,{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(Iy,{}),n.map(o=>e.jsxs(ua,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(xi,{src:o.avatar_url||void 0}),e.jsx(Na,{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"})]})})};function OS(){var c,d;const{user:s,isAdmin:t}=hs(),{data:n,isLoading:r}=rt({queryKey:["partnership-membership",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:u}=await U.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",s.id).eq("status","active").maybeSingle();if(!u)return null;const[{data:h},{data:m}]=await Promise.all([U.from("partnership_packages").select("*").eq("id",u.package_id).maybeSingle(),U.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",u.program_id).maybeSingle()]);return!h||!(m!=null&&m.enabled)?null:{membership:u,pkg:h,program:m}}}),a=_.useMemo(()=>{var u;return new Set(((u=n==null?void 0:n.pkg)==null?void 0:u.included_features)||[])},[n]),i=!!n,l=u=>t||!i?!0:a.has(u),o=u=>{var p,f;const h=((p=n==null?void 0:n.pkg)==null?void 0:p.feature_limits)||{},m=(f=h==null?void 0:h[u])==null?void 0:f.monthly_limit;return typeof m=="number"?m:null};return{isLoading:r,isMember:i,membership:(n==null?void 0:n.membership)??null,pkg:(n==null?void 0:n.pkg)??null,program:(n==null?void 0:n.program)??null,packageKey:((c=n==null?void 0:n.pkg)==null?void 0:c.key)??null,packageName:((d=n==null?void 0:n.pkg)==null?void 0:d.name)??null,features:a,hasFeature:l,limitFor:o,isRestricted:i&&!t}}const HQe={crm:"Contacts & CRM",mass_email:"Mass Email",website:"Agent Website",deals:"Deal Pipeline",listing_exchange:"Listing Exchange",smart_card:"Smart Card",guest_book:"Guest Book",landing_pages:"Landing Pages",learn:"Learn & Academy",community:"Community",quickvid:"QuickVid",reelflow:"ReelFlow",direct_mail:"Direct Mail",levelup_attract:"LevelUp Attract",listing_revival:"Listing Revival",fsbo_breakthrough:"By-Owner Breakthrough",weekly_reels:"Weekly Reels",coaching_access:"Coaching",marketing_studio:"Marketing Studio",video_library:"Video Library",presentations:"Presentations",card_studio:"Card Studio",newsletter:"Newsletters",scheduler:"Scheduler",client_portals:"Client Portals",social:"Social Swag"},Q_r=Object.keys(HQe),pNs={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},vpt={"mission-control":"crm",contacts:"crm","sphere-gaps":"crm","mass-emails":"mass_email","bulk-email":"mass_email",newsletters:"newsletter","my-card":"smart_card","guest-book":"guest_book","landing-pages":"landing_pages","card-studio":"card_studio","direct-mail":"direct_mail",quickvid:"quickvid","video-library":"video_library",reelflow:"reelflow",scheduler:"scheduler",community:"community",coaching:"coaching_access","my-coach":"coaching_access","client-portals":"client_portals",presentations:"presentations","social-swag":"social",attract:"levelup_attract","listing-revival":"listing_revival",fsbo:"fsbo_breakthrough","weekly-reels":"weekly_reels"},fNs={quickvid:"quickvid","smart-card":"smart_card","smart-presentations":"presentations","listing-presentation-studio":"presentations","landing-pages":"landing_pages","guest-book":"guest_book","card-studio":"card_studio","direct-mail":"direct_mail",reelflow:"reelflow","mass-emails":"mass_email","newsletter-pro":"newsletter","listing-studio":"listing_exchange","listing-revival":"listing_revival","fsbo-breakthrough":"fsbo_breakthrough",attract:"levelup_attract",scheduler:"scheduler","client-portals":"client_portals","social-swag":"social","weekly-reels":"weekly_reels"};function xNs(s){return s.id in vpt?vpt[s.id]:pNs[s.primaryCategory]??null}function gNs(s){return fNs[s]??null}const yNs=[["/mission-control/pipeline","deals"],["/mission-control/transactions","deals"],["/mission-control/tasks","deals"],["/mission-control/client-portals","client_portals"],["/mission-control/scheduler","scheduler"],["/mission-control/guest-book","guest_book"],["/mission-control/landing-pages","landing_pages"],["/mission-control/card-studio","card_studio"],["/mission-control/direct-mail","direct_mail"],["/mission-control/video-library","video_library"],["/mission-control/video","quickvid"],["/mission-control/my-card","smart_card"],["/mission-control/listing-presentations","presentations"],["/mission-control/sent-emails","mass_email"],["/mission-control/listings","listing_exchange"],["/mission-control/listing-studio","listing_exchange"],["/mission-control/cma","listing_exchange"],["/apps/listing-presentation-studio","presentations"],["/apps/listing-revival","listing_revival"],["/apps/fsbo-breakthrough","fsbo_breakthrough"],["/marketing-studio","marketing_studio"],["/social-swag","social"],["/weekly-reels","weekly_reels"],["/newsletters","newsletter"],["/email-campaigns","mass_email"],["/templates","marketing_studio"],["/reelflow","reelflow"],["/attract","levelup_attract"],["/community","community"],["/coaching","coaching_access"],["/my-coach","coaching_access"],["/events","learn"],["/academy","learn"],["/levelup-u","learn"],["/toolbox","learn"],["/programs","learn"]];function P8t(s){let t=null;for(const n of yNs){const[r]=n;(s===r||s.startsWith(r+"/")||s.startsWith(r+"?"))&&(!t||r.length>t[0].length)&&(t=n)}return t?t[1]:null}const be=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ct("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));be.displayName="Card";const _t=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ct("flex flex-col space-y-1.5 p-6",s),...t}));_t.displayName="CardHeader";const Nt=_.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Ct("text-2xl font-semibold leading-none tracking-tight",s),...t}));Nt.displayName="CardTitle";const En=_.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Ct("text-sm text-muted-foreground",s),...t}));En.displayName="CardDescription";const Le=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ct("p-6 pt-0",s),...t}));Le.displayName="CardContent";const dAe=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ct("flex items-center p-6 pt-0",s),...t}));dAe.displayName="CardFooter";const Ps=_.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Ct("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}));Ps.displayName="Textarea";const Is=UMe,rl=pQe,vNs=qMe,J_r=Ire,L8t=_.forwardRef(({className:s,...t},n)=>e.jsx(rW,{ref:n,className:Ct("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}));L8t.displayName=rW.displayName;const Ls=_.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(vNs,{children:[e.jsx(L8t,{className:n}),e.jsxs(aW,{ref:a,className:Ct("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(Ire,{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(er,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ls.displayName=aW.displayName;const Os=({className:s,...t})=>e.jsx("div",{className:Ct("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Os.displayName="DialogHeader";const hr=({className:s,...t})=>e.jsx("div",{className:Ct("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});hr.displayName="DialogFooter";const Rs=_.forwardRef(({className:s,...t},n)=>e.jsx(Pre,{ref:n,className:Ct("text-lg font-semibold leading-none tracking-tight",s),...t}));Rs.displayName=Pre.displayName;const _r=_.forwardRef(({className:s,...t},n)=>e.jsx(Lre,{ref:n,className:Ct("text-sm text-muted-foreground",s),...t}));_r.displayName=Lre.displayName;function bNs({featureKey:s,open:t,onOpenChange:n}){const{user:r}=hs(),a=$t(),[i,l]=_.useState(""),{data:o}=rt({queryKey:["partnership-upgrade-requests",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&t,queryFn:async()=>{const{data:h}=await U.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",r.id);return h||[]}}),c=!!(o!=null&&o.some(h=>h.feature_key===s&&h.status!=="declined")),d=mt({mutationFn:async()=>{const{error:h}=await U.from("lead_site_upgrade_requests").insert({user_id:r.id,feature_key:s,notes:i||null});if(h)throw h},onSuccess:()=>{a.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),ne.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>ne.error((h==null?void 0:h.message)||"Could not send your request")}),u=HQe[s]||s;return e.jsx(Is,{open:t,onOpenChange:n,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(_r,{children:[u," is included with the Signature package. Send a request and we'll get you set up."]})]}),c?e.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):e.jsx(Ps,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!c&&e.jsx(z,{onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Sending…":"Send request"})]})]})})}function _Ns({featureKey:s}){const[t,n]=_.useState(!1),r=HQe[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(be,{className:"max-w-lg w-full border-border/60",children:e.jsxs(Le,{className:"p-8 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Hl,{className:"h-6 w-6 text-primary"})}),e.jsxs("h2",{className:"text-2xl font-semibold",children:[r," is a Signature feature"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",r,". Request access and our team will upgrade your account."]}),e.jsxs(z,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(bNs,{featureKey:s,open:t,onOpenChange:n})]})}const I8t=s=>{const[t,n]=_.useState(null),[r,a]=_.useState(!0);return _.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await U.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=U.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);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 U.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},D8t=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await U.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=U.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},wNs=s=>{const[t,n]=_.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return _.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await U.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),m=new Date(d).getTime(),p=Math.ceil((m-h)/(1e3*60*60*24)),f=p<=0;n({isTrial:!0,isExpired:f,expiresAt:d,daysLeft:f?0:p,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},Wre=()=>{const{data:s,isLoading:t}=rt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await U.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")}},bpt="community_last_seen_post_at";function jNs(){const{user:s}=hs(),t=Pd(),[n,r]=_.useState(0),[a,i]=_.useState(null);_.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${bpt}_${s.id}`);i(o)},[s]),_.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const p=sessionStorage.getItem(o);if(p){const f=JSON.parse(p);if(f.ts&&Date.now()-f.ts{if(!s)return;const o=U.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(g=>g+1);const{data:h}=await U.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",p=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),f=p.length>50?p.substring(0,50)+"...":p;u||ne("New Community Post",{description:`${m}: ${f}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{U.removeChannel(o)}},[s,t.pathname]);const l=_.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${bpt}_${s.id}`,o),i(o),r(0)},[s]);return _.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function NNs(){const{isAdmin:s}=hs(),{data:t=0}=rt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await U.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}const NOe=s=>`levelup:activeTeam:${s}`,Kre=()=>{const s=ha();return rt({queryKey:["user-teams",s],queryFn:async()=>{const{data:t,error:n}=await U.from("team_members").select("id, team_id, role").eq("user_id",s);if(n)throw n;if(!(t!=null&&t.length))return[];const{data:r,error:a}=await U.from("teams").select("*").in("id",t.map(l=>l.team_id));if(a)throw a;const i=new Map((r||[]).map(l=>[l.id,l]));return t.filter(l=>i.has(l.team_id)).map(l=>({membershipId:l.id,teamId:l.team_id,role:l.role,team:i.get(l.team_id)})).sort((l,o)=>{var c,d;return l.role!==o.role?l.role==="team_leader"?-1:1:(((c=l.team)==null?void 0:c.name)||"").localeCompare(((d=o.team)==null?void 0:d.name)||"")})},enabled:!!s,staleTime:5*60*1e3})},K_=()=>{const s=ha(),t=Kre(),n=_.useMemo(()=>t.data||[],[t.data]),[r,a]=_.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(NOe(s)));_.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(NOe(s)))},[s]);const i=_.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(NOe(s),o)},[s]),l=_.useMemo(()=>n.length?n.find(o=>o.teamId===r)||n[0]:null,[n,r]);return{...t,data:l,teams:n,activeTeamId:(l==null?void 0:l.teamId)??null,setActiveTeamId:i}},sU="weekly_reels";function hPe(){const{user:s,loading:t,isAdmin:n}=hs(),{data:r,isLoading:a}=rt({queryKey:["feature-entitlement",sU,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",sU).maybeSingle();if(l)throw l;return i?{hasAccess:i.enabled&&(!i.expires_at||new Date(i.expires_at).getTime()>Date.now()),tier:i.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:n||!!(r!=null&&r.hasAccess),tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t||!n&&!!s&&a}}const Wg=UMe,Yre=pQe,kNs=qMe,R8t=_.forwardRef(({className:s,...t},n)=>e.jsx(rW,{className:Ct("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}));R8t.displayName=rW.displayName;const SNs=G9("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"}}),gg=_.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(kNs,{children:[e.jsx(R8t,{}),e.jsxs(aW,{ref:a,className:Ct(SNs({side:s}),t),...r,children:[n,e.jsxs(Ire,{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(er,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));gg.displayName=aW.displayName;const Dy=({className:s,...t})=>e.jsx("div",{className:Ct("flex flex-col space-y-2 text-center sm:text-left",s),...t});Dy.displayName="SheetHeader";const F8t=({className:s,...t})=>e.jsx("div",{className:Ct("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});F8t.displayName="SheetFooter";const Ry=_.forwardRef(({className:s,...t},n)=>e.jsx(Pre,{ref:n,className:Ct("text-lg font-semibold text-foreground",s),...t}));Ry.displayName=Pre.displayName;const Z9=_.forwardRef(({className:s,...t},n)=>e.jsx(Lre,{ref:n,className:Ct("text-sm text-muted-foreground",s),...t}));Z9.displayName=Lre.displayName;function dte(s,[t,n]){return Math.min(n,Math.max(t,s))}function CNs(s,t){return _.useReducer((n,r)=>t[n][r]??n,s)}var GQe="ScrollArea",[O8t,ewr]=uf(GQe),[ANs,qN]=O8t(GQe),z8t=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(null),[g,v]=_.useState(null),[y,b]=_.useState(0),[w,S]=_.useState(0),[C,E]=_.useState(!1),[P,M]=_.useState(!1),I=el(t,F=>c(F)),D=$E(a);return e.jsx(ANs,{scope:n,type:r,dir:D,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:m,scrollbarX:p,onScrollbarXChange:f,scrollbarXEnabled:C,onScrollbarXEnabledChange:E,scrollbarY:g,onScrollbarYChange:v,scrollbarYEnabled:P,onScrollbarYEnabledChange:M,onCornerWidthChange:b,onCornerHeightChange:S,children:e.jsx(ci.div,{dir:D,...l,ref:I,style:{position:"relative","--radix-scroll-area-corner-width":y+"px","--radix-scroll-area-corner-height":w+"px",...s.style}})})});z8t.displayName=GQe;var B8t="ScrollAreaViewport",$8t=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=qN(B8t,n),o=_.useRef(null),c=el(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(ci.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})})]})});$8t.displayName=B8t;var EC="ScrollAreaScrollbar",WQe=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=qN(EC,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return _.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(ENs,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(TNs,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(U8t,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(KQe,{...r,ref:t}):null});WQe.displayName=EC;var ENs=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=qN(EC,s.__scopeScrollArea),[i,l]=_.useState(!1);return _.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(vg,{present:n||i,children:e.jsx(U8t,{"data-state":i?"visible":"hidden",...r,ref:t})})}),TNs=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=qN(EC,s.__scopeScrollArea),i=s.orientation==="horizontal",l=pPe(()=>c("SCROLL_END"),100),[o,c]=CNs("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 _.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),_.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const m=()=>{const p=d[u];h!==p&&(c("SCROLL"),l()),h=p};return d.addEventListener("scroll",m),()=>d.removeEventListener("scroll",m)}},[a.viewport,i,c,l]),e.jsx(vg,{present:n||o!=="hidden",children:e.jsx(KQe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:wa(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:wa(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),U8t=_.forwardRef((s,t)=>{const n=qN(EC,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=_.useState(!1),o=s.orientation==="horizontal",c=pPe(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=qN(EC,s.__scopeScrollArea),i=_.useRef(null),l=_.useRef(0),[o,c]=_.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=W8t(o.viewport,o.content),u={...r,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:m=>i.current=m,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:m=>l.current=m};function h(m,p){return RNs(m,l.current,o,p)}return n==="horizontal"?e.jsx(MNs,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollLeft,p=_pt(m,o,a.dir);i.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollLeft=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollLeft=h(m,a.dir))}}):n==="vertical"?e.jsx(PNs,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollTop,p=_pt(m,o);i.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollTop=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollTop=h(m))}}):null}),MNs=_.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=qN(EC,s.__scopeScrollArea),[l,o]=_.useState(),c=_.useRef(null),d=el(t,c,i.onScrollbarXChange);return _.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(V8t,{"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":mPe(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,h)=>{if(i.viewport){const m=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(m),Y8t(m,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:hAe(l.paddingLeft),paddingEnd:hAe(l.paddingRight)}})}})}),PNs=_.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=qN(EC,s.__scopeScrollArea),[l,o]=_.useState(),c=_.useRef(null),d=el(t,c,i.onScrollbarYChange);return _.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(V8t,{"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":mPe(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,h)=>{if(i.viewport){const m=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(m),Y8t(m,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:hAe(l.paddingTop),paddingEnd:hAe(l.paddingBottom)}})}})}),[LNs,q8t]=O8t(EC),V8t=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:h,...m}=s,p=qN(EC,n),[f,g]=_.useState(null),v=el(t,I=>g(I)),y=_.useRef(null),b=_.useRef(""),w=p.viewport,S=r.content-r.viewport,C=Ax(u),E=Ax(c),P=pPe(h,10);function M(I){if(y.current){const D=I.clientX-y.current.left,F=I.clientY-y.current.top;d({x:D,y:F})}}return _.useEffect(()=>{const I=D=>{const F=D.target;(f==null?void 0:f.contains(F))&&C(D,S)};return document.addEventListener("wheel",I,{passive:!1}),()=>document.removeEventListener("wheel",I,{passive:!1})},[w,f,S,C]),_.useEffect(E,[r,E]),LH(f,P),LH(p.content,P),e.jsx(LNs,{scope:n,scrollbar:f,hasThumb:a,onThumbChange:Ax(i),onThumbPointerUp:Ax(l),onThumbPositionChange:E,onThumbPointerDown:Ax(o),children:e.jsx(ci.div,{...m,ref:v,style:{position:"absolute",...m.style},onPointerDown:wa(s.onPointerDown,I=>{I.button===0&&(I.target.setPointerCapture(I.pointerId),y.current=f.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),M(I))}),onPointerMove:wa(s.onPointerMove,M),onPointerUp:wa(s.onPointerUp,I=>{const D=I.target;D.hasPointerCapture(I.pointerId)&&D.releasePointerCapture(I.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),y.current=null})})})}),uAe="ScrollAreaThumb",H8t=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=q8t(uAe,s.__scopeScrollArea);return e.jsx(vg,{present:n||a.hasThumb,children:e.jsx(INs,{ref:t,...r})})}),INs=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=qN(uAe,n),l=q8t(uAe,n),{onThumbPositionChange:o}=l,c=el(t,h=>l.onThumbChange(h)),d=_.useRef(void 0),u=pPe(()=>{d.current&&(d.current(),d.current=void 0)},100);return _.useEffect(()=>{const h=i.viewport;if(h){const m=()=>{if(u(),!d.current){const p=FNs(h,o);d.current=p,o()}};return o(),h.addEventListener("scroll",m),()=>h.removeEventListener("scroll",m)}},[i.viewport,u,o]),e.jsx(ci.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:wa(s.onPointerDownCapture,h=>{const p=h.target.getBoundingClientRect(),f=h.clientX-p.left,g=h.clientY-p.top;l.onThumbPointerDown({x:f,y:g})}),onPointerUp:wa(s.onPointerUp,l.onThumbPointerUp)})});H8t.displayName=uAe;var YQe="ScrollAreaCorner",G8t=_.forwardRef((s,t)=>{const n=qN(YQe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(DNs,{...s,ref:t}):null});G8t.displayName=YQe;var DNs=_.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=qN(YQe,n),[i,l]=_.useState(0),[o,c]=_.useState(0),d=!!(i&&o);return LH(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),LH(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(ci.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 hAe(s){return s?parseInt(s,10):0}function W8t(s,t){const n=s/t;return isNaN(n)?0:n}function mPe(s){const t=W8t(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function RNs(s,t,n,r="ltr"){const a=mPe(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 K8t([c,d],h)(s)}function _pt(s,t,n="ltr"){const r=mPe(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=dte(s,c);return K8t([0,l],[0,o])(d)}function K8t(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 Y8t(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 pPe(s,t){const n=Ax(s),r=_.useRef(0);return _.useEffect(()=>()=>window.clearTimeout(r.current),[]),_.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function LH(s,t){const n=Ax(t);Rx(()=>{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 Z8t=z8t,ONs=$8t,zNs=G8t;const Ki=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Z8t,{ref:r,className:Ct("relative overflow-hidden",s),...n,children:[e.jsx(ONs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Zre,{}),e.jsx(zNs,{})]}));Ki.displayName=Z8t.displayName;const Zre=_.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(WQe,{ref:r,orientation:t,className:Ct("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(H8t,{className:"relative flex-1 rounded-full bg-border"})}));Zre.displayName=WQe.displayName;const BNs="/assets/levelup-logo-Eif24dqY.png",$Ns="/assets/levelup-logo-icon-C-7iromj.png",UNs="/assets/levelup-logo-mobile-B9skSjUG.png";var Xre=s=>s.type==="checkbox",vF=s=>s instanceof Date,ib=s=>s==null;const X8t=s=>typeof s=="object";var xg=s=>!ib(s)&&!Array.isArray(s)&&X8t(s)&&!vF(s),Q8t=s=>xg(s)&&s.target?Xre(s.target)?s.target.checked:s.target.value:s,qNs=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,J8t=(s,t)=>s.has(qNs(t)),VNs=s=>{const t=s.constructor&&s.constructor.prototype;return xg(t)&&t.hasOwnProperty("isPrototypeOf")},ZQe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function iy(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(!(ZQe&&(s instanceof Blob||r))&&(n||xg(s)))if(t=n?[]:{},!n&&!VNs(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=iy(s[a]));else return s;return t}var fPe=s=>/^\w*$/.test(s),eg=s=>s===void 0,XQe=s=>Array.isArray(s)?s.filter(Boolean):[],QQe=s=>XQe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),$i=(s,t,n)=>{if(!t||!xg(s))return n;const r=(fPe(t)?[t]:QQe(t)).reduce((a,i)=>ib(a)?a:a[i],s);return eg(r)||r===s?eg(s[t])?n:s[t]:r},Yw=s=>typeof s=="boolean",Oh=(s,t,n)=>{let r=-1;const a=fPe(t)?[t]:QQe(t),i=a.length,l=i-1;for(;++rFt.useContext(JQe),HNs=s=>{const{children:t,...n}=s;return Ft.createElement(JQe.Provider,{value:n},t)};var eDt=(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]!==aS.all&&(t._proxyFormState[l]=!r||aS.all),n&&(n[l]=!0),s[l]}});return a};const eJe=typeof window<"u"?Ft.useLayoutEffect:Ft.useEffect;function GNs(s){const t=xPe(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Ft.useState(n._formState),c=Ft.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return eJe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Ft.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Ft.useMemo(()=>eDt(l,n,c.current,!1),[l,n])}var D4=s=>typeof s=="string",tDt=(s,t,n,r,a)=>D4(s)?(r&&t.watch.add(s),$i(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),$i(n,i))):(r&&(t.watchAll=!0),n),Kqe=s=>ib(s)||!X8t(s);function MA(s,t,n=new WeakSet){if(Kqe(s)||Kqe(t))return s===t;if(vF(s)&&vF(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(vF(l)&&vF(o)||xg(l)&&xg(o)||Array.isArray(l)&&Array.isArray(o)?!MA(l,o,n):l!==o)return!1}}return!0}function WNs(s){const t=xPe(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Ft.useRef(a),d=Ft.useRef(o),u=Ft.useRef(void 0);d.current=o;const h=Ft.useMemo(()=>n._getWatch(r,c.current),[n,r]),[m,p]=Ft.useState(d.current?d.current(h):h);return eJe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:f=>{if(!i){const g=tDt(r,n._names,f.values||n._formValues,!1,c.current);if(d.current){const v=d.current(g);MA(v,u.current)||(p(v),u.current=v)}else p(g)}}}),[n,i,r,l]),Ft.useEffect(()=>n._removeUnmounted()),m}function KNs(s){const t=xPe(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=J8t(a._names.array,n),c=Ft.useMemo(()=>$i(a._formValues,n,$i(a._defaultValues,n,l)),[a,n,l]),d=WNs({control:a,name:n,defaultValue:c,exact:!0}),u=GNs({control:a,name:n,exact:!0}),h=Ft.useRef(s),m=Ft.useRef(a.register(n,{...s.rules,value:d,...Yw(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const p=Ft.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!$i(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!$i(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!$i(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!$i(u.validatingFields,n)},error:{enumerable:!0,get:()=>$i(u.errors,n)}}),[u,n]),f=Ft.useCallback(b=>m.current.onChange({target:{value:Q8t(b),name:n},type:mAe.CHANGE}),[n]),g=Ft.useCallback(()=>m.current.onBlur({target:{value:$i(a._formValues,n),name:n},type:mAe.BLUR}),[n,a._formValues]),v=Ft.useCallback(b=>{const w=$i(a._fields,n);w&&b&&(w._f.ref={focus:()=>b.focus&&b.focus(),select:()=>b.select&&b.select(),setCustomValidity:S=>b.setCustomValidity(S),reportValidity:()=>b.reportValidity()})},[a._fields,n]),y=Ft.useMemo(()=>({name:n,value:d,...Yw(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:f,onBlur:g,ref:v}),[n,r,u.disabled,f,g,v,d]);return Ft.useEffect(()=>{const b=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...Yw(h.current.disabled)?{disabled:h.current.disabled}:{}});const w=(S,C)=>{const E=$i(a._fields,S);E&&E._f&&(E._f.mount=C)};if(w(n,!0),b){const S=iy($i(a._options.defaultValues,n));Oh(a._defaultValues,n,S),eg($i(a._formValues,n))&&Oh(a._formValues,n,S)}return!o&&a.register(n),()=>{(o?b&&!a._state.action:b)?a.unregister(n):w(n,!1)}},[n,a,o,i]),Ft.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Ft.useMemo(()=>({field:y,formState:u,fieldState:p}),[y,u,p])}const YNs=s=>s.render(KNs(s));var sDt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},AJ=s=>Array.isArray(s)?s:[s],wpt=()=>{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=[]}}},x_=s=>xg(s)&&!Object.keys(s).length,tJe=s=>s.type==="file",iS=s=>typeof s=="function",pAe=s=>{if(!ZQe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},nDt=s=>s.type==="select-multiple",sJe=s=>s.type==="radio",ZNs=s=>sJe(s)||Xre(s),kOe=s=>pAe(s)&&s.isConnected;function XNs(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(iS(s[t]))return!0;return!1};function fAe(s,t={}){const n=Array.isArray(s);if(xg(s)||n)for(const r in s)Array.isArray(s[r])||xg(s[r])&&!rDt(s[r])?(t[r]=Array.isArray(s[r])?[]:{},fAe(s[r],t[r])):ib(s[r])||(t[r]=!0);return t}function aDt(s,t,n){const r=Array.isArray(s);if(xg(s)||r)for(const a in s)Array.isArray(s[a])||xg(s[a])&&!rDt(s[a])?eg(t)||Kqe(n[a])?n[a]=Array.isArray(s[a])?fAe(s[a],[]):{...fAe(s[a])}:aDt(s[a],ib(t)?{}:t[a],n[a]):n[a]=!MA(s[a],t[a]);return n}var $Y=(s,t)=>aDt(s,t,fAe(t));const jpt={value:!1,isValid:!1},Npt={value:!0,isValid:!0};var iDt=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&&!eg(s[0].attributes.value)?eg(s[0].value)||s[0].value===""?Npt:{value:s[0].value,isValid:!0}:Npt:jpt}return jpt},oDt=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>eg(s)?s:t?s===""?NaN:s&&+s:n&&D4(s)?new Date(s):r?r(s):s;const kpt={isValid:!1,value:null};var lDt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,kpt):kpt;function Spt(s){const t=s.ref;return tJe(t)?t.files:sJe(t)?lDt(s.refs).value:nDt(t)?[...t.selectedOptions].map(({value:n})=>n):Xre(t)?iDt(s.refs).value:oDt(eg(t.value)?s.ref.value:t.value,s)}var JNs=(s,t,n,r)=>{const a={};for(const i of s){const l=$i(t,i);l&&Oh(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},xAe=s=>s instanceof RegExp,UY=s=>eg(s)?s:xAe(s)?s.source:xg(s)?xAe(s.value)?s.value.source:s.value:s,Cpt=s=>({isOnSubmit:!s||s===aS.onSubmit,isOnBlur:s===aS.onBlur,isOnChange:s===aS.onChange,isOnAll:s===aS.all,isOnTouch:s===aS.onTouched});const Apt="AsyncFunction";var eks=s=>!!s&&!!s.validate&&!!(iS(s.validate)&&s.validate.constructor.name===Apt||xg(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===Apt)),tks=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),Ept=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const EJ=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=$i(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(EJ(o,t))break}else if(xg(o)&&EJ(o,t))break}}};function Tpt(s,t,n){const r=$i(s,n);if(r||fPe(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=$i(t,i),o=$i(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 sks=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return x_(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||aS.all))},nks=(s,t,n)=>!s||!t||s===t||AJ(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),rks=(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,aks=(s,t)=>!XQe($i(s,t)).length&&Eg(s,t),iks=(s,t,n)=>{const r=AJ($i(s,n));return Oh(r,"root",t[n]),Oh(s,n,r),s},T4e=s=>D4(s);function Mpt(s,t,n="validate"){if(T4e(s)||Array.isArray(s)&&s.every(T4e)||Yw(s)&&!s)return{type:n,message:T4e(s)?s:"",ref:t}}var SB=s=>xg(s)&&!xAe(s)?s:{value:s,message:""},Ppt=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:p,validate:f,name:g,valueAsNumber:v,mount:y}=s._f,b=$i(n,g);if(!y||t.has(g))return{};const w=o?o[0]:l,S=q=>{a&&w.reportValidity&&(w.setCustomValidity(Yw(q)?"":q||""),w.reportValidity())},C={},E=sJe(l),P=Xre(l),M=E||P,I=(v||tJe(l))&&eg(l.value)&&eg(b)||pAe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,D=sDt.bind(null,g,r,C),F=(q,G,V,H=y3.maxLength,K=y3.minLength)=>{const Z=q?G:V;C[g]={type:q?H:K,message:Z,ref:l,...D(q?H:K,Z)}};if(i?!Array.isArray(b)||!b.length:c&&(!M&&(I||ib(b))||Yw(b)&&!b||P&&!iDt(o).isValid||E&&!lDt(o).isValid)){const{value:q,message:G}=T4e(c)?{value:!!c,message:c}:SB(c);if(q&&(C[g]={type:y3.required,message:G,ref:w,...D(y3.required,G)},!r))return S(G),C}if(!I&&(!ib(h)||!ib(m))){let q,G;const V=SB(m),H=SB(h);if(!ib(b)&&!isNaN(b)){const K=l.valueAsNumber||b&&+b;ib(V.value)||(q=K>V.value),ib(H.value)||(G=Knew Date(new Date().toDateString()+" "+ae),oe=l.type=="time",re=l.type=="week";D4(V.value)&&b&&(q=oe?Z(b)>Z(V.value):re?b>V.value:K>new Date(V.value)),D4(H.value)&&b&&(G=oe?Z(b)+q.value,H=!ib(G.value)&&b.length<+G.value;if((V||H)&&(F(V,q.message,G.message),!r))return S(C[g].message),C}if(p&&!I&&D4(b)){const{value:q,message:G}=SB(p);if(xAe(q)&&!b.match(q)&&(C[g]={type:y3.pattern,message:G,ref:l,...D(y3.pattern,G)},!r))return S(G),C}if(f){if(iS(f)){const q=await f(b,n),G=Mpt(q,w);if(G&&(C[g]={...G,...D(y3.validate,G.message)},!r))return S(G.message),C}else if(xg(f)){let q={};for(const G in f){if(!x_(q)&&!r)break;const V=Mpt(await f[G](b,n),w,G);V&&(q={...V,...D(G,V.message)},S(V.message),r&&(C[g]=q))}if(!x_(q)&&(C[g]={ref:w,...q},!r))return C}}return S(!0),C};const oks={mode:aS.onSubmit,reValidateMode:aS.onChange,shouldFocusError:!0};function lks(s={}){let t={...oks,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:iS(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=xg(t.defaultValues)||xg(t.values)?iy(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:iy(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 m={array:wpt(),state:wpt()},p=t.criteriaMode===aS.all,f=Ze=>$e=>{clearTimeout(d),d=setTimeout(Ze,$e)},g=async Ze=>{if(!t.disabled&&(u.isValid||h.isValid||Ze)){const $e=t.resolver?x_((await P()).errors):await I(r,!0);$e!==n.isValid&&m.state.next({isValid:$e})}},v=(Ze,$e)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Ze||Array.from(o.mount)).forEach(Xe=>{Xe&&($e?Oh(n.validatingFields,Xe,$e):Eg(n.validatingFields,Xe))}),m.state.next({validatingFields:n.validatingFields,isValidating:!x_(n.validatingFields)}))},y=(Ze,$e=[],Xe,nt,Ge=!0,Je=!0)=>{if(nt&&Xe&&!t.disabled){if(l.action=!0,Je&&Array.isArray($i(r,Ze))){const ut=Xe($i(r,Ze),nt.argA,nt.argB);Ge&&Oh(r,Ze,ut)}if(Je&&Array.isArray($i(n.errors,Ze))){const ut=Xe($i(n.errors,Ze),nt.argA,nt.argB);Ge&&Oh(n.errors,Ze,ut),aks(n.errors,Ze)}if((u.touchedFields||h.touchedFields)&&Je&&Array.isArray($i(n.touchedFields,Ze))){const ut=Xe($i(n.touchedFields,Ze),nt.argA,nt.argB);Ge&&Oh(n.touchedFields,Ze,ut)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=$Y(a,i)),m.state.next({name:Ze,isDirty:F(Ze,$e),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Oh(i,Ze,$e)},b=(Ze,$e)=>{Oh(n.errors,Ze,$e),m.state.next({errors:n.errors})},w=Ze=>{n.errors=Ze,m.state.next({errors:n.errors,isValid:!1})},S=(Ze,$e,Xe,nt)=>{const Ge=$i(r,Ze);if(Ge){const Je=$i(i,Ze,eg(Xe)?$i(a,Ze):Xe);eg(Je)||nt&&nt.defaultChecked||$e?Oh(i,Ze,$e?Je:Spt(Ge._f)):V(Ze,Je),l.mount&&g()}},C=(Ze,$e,Xe,nt,Ge)=>{let Je=!1,ut=!1;const lt={name:Ze};if(!t.disabled){if(!Xe||nt){(u.isDirty||h.isDirty)&&(ut=n.isDirty,n.isDirty=lt.isDirty=F(),Je=ut!==lt.isDirty);const qt=MA($i(a,Ze),$e);ut=!!$i(n.dirtyFields,Ze),qt?Eg(n.dirtyFields,Ze):Oh(n.dirtyFields,Ze,!0),lt.dirtyFields=n.dirtyFields,Je=Je||(u.dirtyFields||h.dirtyFields)&&ut!==!qt}if(Xe){const qt=$i(n.touchedFields,Ze);qt||(Oh(n.touchedFields,Ze,Xe),lt.touchedFields=n.touchedFields,Je=Je||(u.touchedFields||h.touchedFields)&&qt!==Xe)}Je&&Ge&&m.state.next(lt)}return Je?lt:{}},E=(Ze,$e,Xe,nt)=>{const Ge=$i(n.errors,Ze),Je=(u.isValid||h.isValid)&&Yw($e)&&n.isValid!==$e;if(t.delayError&&Xe?(c=f(()=>b(Ze,Xe)),c(t.delayError)):(clearTimeout(d),c=null,Xe?Oh(n.errors,Ze,Xe):Eg(n.errors,Ze)),(Xe?!MA(Ge,Xe):Ge)||!x_(nt)||Je){const ut={...nt,...Je&&Yw($e)?{isValid:$e}:{},errors:n.errors,name:Ze};n={...n,...ut},m.state.next(ut)}},P=async Ze=>{v(Ze,!0);const $e=await t.resolver(i,t.context,JNs(Ze||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return v(Ze),$e},M=async Ze=>{const{errors:$e}=await P(Ze);if(Ze)for(const Xe of Ze){const nt=$i($e,Xe);nt?Oh(n.errors,Xe,nt):Eg(n.errors,Xe)}else n.errors=$e;return $e},I=async(Ze,$e,Xe={valid:!0})=>{for(const nt in Ze){const Ge=Ze[nt];if(Ge){const{_f:Je,...ut}=Ge;if(Je){const lt=o.array.has(Je.name),qt=Ge._f&&eks(Ge._f);qt&&u.validatingFields&&v([nt],!0);const zt=await Ppt(Ge,o.disabled,i,p,t.shouldUseNativeValidation&&!$e,lt);if(qt&&u.validatingFields&&v([nt]),zt[Je.name]&&(Xe.valid=!1,$e))break;!$e&&($i(zt,Je.name)?lt?iks(n.errors,zt,Je.name):Oh(n.errors,Je.name,zt[Je.name]):Eg(n.errors,Je.name))}!x_(ut)&&await I(ut,$e,Xe)}}return Xe.valid},D=()=>{for(const Ze of o.unMount){const $e=$i(r,Ze);$e&&($e._f.refs?$e._f.refs.every(Xe=>!kOe(Xe)):!kOe($e._f.ref))&&ge(Ze)}o.unMount=new Set},F=(Ze,$e)=>!t.disabled&&(Ze&&$e&&Oh(i,Ze,$e),!MA(ae(),a)),q=(Ze,$e,Xe)=>tDt(Ze,o,{...l.mount?i:eg($e)?a:D4(Ze)?{[Ze]:$e}:$e},Xe,$e),G=Ze=>XQe($i(l.mount?i:a,Ze,t.shouldUnregister?$i(a,Ze,[]):[])),V=(Ze,$e,Xe={})=>{const nt=$i(r,Ze);let Ge=$e;if(nt){const Je=nt._f;Je&&(!Je.disabled&&Oh(i,Ze,oDt($e,Je)),Ge=pAe(Je.ref)&&ib($e)?"":$e,nDt(Je.ref)?[...Je.ref.options].forEach(ut=>ut.selected=Ge.includes(ut.value)):Je.refs?Xre(Je.ref)?Je.refs.forEach(ut=>{(!ut.defaultChecked||!ut.disabled)&&(Array.isArray(Ge)?ut.checked=!!Ge.find(lt=>lt===ut.value):ut.checked=Ge===ut.value||!!Ge)}):Je.refs.forEach(ut=>ut.checked=ut.value===Ge):tJe(Je.ref)?Je.ref.value="":(Je.ref.value=Ge,Je.ref.type||m.state.next({name:Ze,values:iy(i)})))}(Xe.shouldDirty||Xe.shouldTouch)&&C(Ze,Ge,Xe.shouldTouch,Xe.shouldDirty,!0),Xe.shouldValidate&&re(Ze)},H=(Ze,$e,Xe)=>{for(const nt in $e){if(!$e.hasOwnProperty(nt))return;const Ge=$e[nt],Je=Ze+"."+nt,ut=$i(r,Je);(o.array.has(Ze)||xg(Ge)||ut&&!ut._f)&&!vF(Ge)?H(Je,Ge,Xe):V(Je,Ge,Xe)}},K=(Ze,$e,Xe={})=>{const nt=$i(r,Ze),Ge=o.array.has(Ze),Je=iy($e);Oh(i,Ze,Je),Ge?(m.array.next({name:Ze,values:iy(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&Xe.shouldDirty&&m.state.next({name:Ze,dirtyFields:$Y(a,i),isDirty:F(Ze,Je)})):nt&&!nt._f&&!ib(Je)?H(Ze,Je,Xe):V(Ze,Je,Xe),Ept(Ze,o)&&m.state.next({...n,name:Ze}),m.state.next({name:l.mount?Ze:void 0,values:iy(i)})},Z=async Ze=>{l.mount=!0;const $e=Ze.target;let Xe=$e.name,nt=!0;const Ge=$i(r,Xe),Je=qt=>{nt=Number.isNaN(qt)||vF(qt)&&isNaN(qt.getTime())||MA(qt,$i(i,Xe,qt))},ut=Cpt(t.mode),lt=Cpt(t.reValidateMode);if(Ge){let qt,zt;const Zt=$e.type?Spt(Ge._f):Q8t(Ze),ms=Ze.type===mAe.BLUR||Ze.type===mAe.FOCUS_OUT,Dt=!tks(Ge._f)&&!t.resolver&&!$i(n.errors,Xe)&&!Ge._f.deps||rks(ms,$i(n.touchedFields,Xe),n.isSubmitted,lt,ut),It=Ept(Xe,o,ms);Oh(i,Xe,Zt),ms?(Ge._f.onBlur&&Ge._f.onBlur(Ze),c&&c(0)):Ge._f.onChange&&Ge._f.onChange(Ze);const qs=C(Xe,Zt,ms),wt=!x_(qs)||It;if(!ms&&m.state.next({name:Xe,type:Ze.type,values:iy(i)}),Dt)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?ms&&g():ms||g()),wt&&m.state.next({name:Xe,...It?{}:qs});if(!ms&&It&&m.state.next({...n}),t.resolver){const{errors:Us}=await P([Xe]);if(Je(Zt),nt){const Es=Tpt(n.errors,r,Xe),kn=Tpt(Us,r,Es.name||Xe);qt=kn.error,Xe=kn.name,zt=x_(Us)}}else v([Xe],!0),qt=(await Ppt(Ge,o.disabled,i,p,t.shouldUseNativeValidation))[Xe],v([Xe]),Je(Zt),nt&&(qt?zt=!1:(u.isValid||h.isValid)&&(zt=await I(r,!0)));nt&&(Ge._f.deps&&re(Ge._f.deps),E(Xe,zt,qt,qs))}},oe=(Ze,$e)=>{if($i(n.errors,$e)&&Ze.focus)return Ze.focus(),1},re=async(Ze,$e={})=>{let Xe,nt;const Ge=AJ(Ze);if(t.resolver){const Je=await M(eg(Ze)?Ze:Ge);Xe=x_(Je),nt=Ze?!Ge.some(ut=>$i(Je,ut)):Xe}else Ze?(nt=(await Promise.all(Ge.map(async Je=>{const ut=$i(r,Je);return await I(ut&&ut._f?{[Je]:ut}:ut)}))).every(Boolean),!(!nt&&!n.isValid)&&g()):nt=Xe=await I(r);return m.state.next({...!D4(Ze)||(u.isValid||h.isValid)&&Xe!==n.isValid?{}:{name:Ze},...t.resolver||!Ze?{isValid:Xe}:{},errors:n.errors}),$e.shouldFocus&&!nt&&EJ(r,oe,Ze?Ge:o.mount),nt},ae=Ze=>{const $e={...l.mount?i:a};return eg(Ze)?$e:D4(Ze)?$i($e,Ze):Ze.map(Xe=>$i($e,Xe))},J=(Ze,$e)=>({invalid:!!$i(($e||n).errors,Ze),isDirty:!!$i(($e||n).dirtyFields,Ze),error:$i(($e||n).errors,Ze),isValidating:!!$i(n.validatingFields,Ze),isTouched:!!$i(($e||n).touchedFields,Ze)}),te=Ze=>{Ze&&AJ(Ze).forEach($e=>Eg(n.errors,$e)),m.state.next({errors:Ze?n.errors:{}})},ce=(Ze,$e,Xe)=>{const nt=($i(r,Ze,{_f:{}})._f||{}).ref,Ge=$i(n.errors,Ze)||{},{ref:Je,message:ut,type:lt,...qt}=Ge;Oh(n.errors,Ze,{...qt,...$e,ref:nt}),m.state.next({name:Ze,errors:n.errors,isValid:!1}),Xe&&Xe.shouldFocus&&nt&&nt.focus&&nt.focus()},ve=(Ze,$e)=>iS(Ze)?m.state.subscribe({next:Xe=>"values"in Xe&&Ze(q(void 0,$e),Xe)}):q(Ze,$e,!0),me=Ze=>m.state.subscribe({next:$e=>{nks(Ze.name,$e.name,Ze.exact)&&sks($e,Ze.formState||u,We,Ze.reRenderRoot)&&Ze.callback({values:{...i},...n,...$e,defaultValues:a})}}).unsubscribe,he=Ze=>(l.mount=!0,h={...h,...Ze.formState},me({...Ze,formState:h})),ge=(Ze,$e={})=>{for(const Xe of Ze?AJ(Ze):o.mount)o.mount.delete(Xe),o.array.delete(Xe),$e.keepValue||(Eg(r,Xe),Eg(i,Xe)),!$e.keepError&&Eg(n.errors,Xe),!$e.keepDirty&&Eg(n.dirtyFields,Xe),!$e.keepTouched&&Eg(n.touchedFields,Xe),!$e.keepIsValidating&&Eg(n.validatingFields,Xe),!t.shouldUnregister&&!$e.keepDefaultValue&&Eg(a,Xe);m.state.next({values:iy(i)}),m.state.next({...n,...$e.keepDirty?{isDirty:F()}:{}}),!$e.keepIsValid&&g()},Ee=({disabled:Ze,name:$e})=>{(Yw(Ze)&&l.mount||Ze||o.disabled.has($e))&&(Ze?o.disabled.add($e):o.disabled.delete($e))},Ne=(Ze,$e={})=>{let Xe=$i(r,Ze);const nt=Yw($e.disabled)||Yw(t.disabled);return Oh(r,Ze,{...Xe||{},_f:{...Xe&&Xe._f?Xe._f:{ref:{name:Ze}},name:Ze,mount:!0,...$e}}),o.mount.add(Ze),Xe?Ee({disabled:Yw($e.disabled)?$e.disabled:t.disabled,name:Ze}):S(Ze,!0,$e.value),{...nt?{disabled:$e.disabled||t.disabled}:{},...t.progressive?{required:!!$e.required,min:UY($e.min),max:UY($e.max),minLength:UY($e.minLength),maxLength:UY($e.maxLength),pattern:UY($e.pattern)}:{},name:Ze,onChange:Z,onBlur:Z,ref:Ge=>{if(Ge){Ne(Ze,$e),Xe=$i(r,Ze);const Je=eg(Ge.value)&&Ge.querySelectorAll&&Ge.querySelectorAll("input,select,textarea")[0]||Ge,ut=ZNs(Je),lt=Xe._f.refs||[];if(ut?lt.find(qt=>qt===Je):Je===Xe._f.ref)return;Oh(r,Ze,{_f:{...Xe._f,...ut?{refs:[...lt.filter(kOe),Je,...Array.isArray($i(a,Ze))?[{}]:[]],ref:{type:Je.type,name:Ze}}:{ref:Je}}}),S(Ze,!1,void 0,Je)}else Xe=$i(r,Ze,{}),Xe._f&&(Xe._f.mount=!1),(t.shouldUnregister||$e.shouldUnregister)&&!(J8t(o.array,Ze)&&l.action)&&o.unMount.add(Ze)}}},Pe=()=>t.shouldFocusError&&EJ(r,oe,o.mount),Oe=Ze=>{Yw(Ze)&&(m.state.next({disabled:Ze}),EJ(r,($e,Xe)=>{const nt=$i(r,Xe);nt&&($e.disabled=nt._f.disabled||Ze,Array.isArray(nt._f.refs)&&nt._f.refs.forEach(Ge=>{Ge.disabled=nt._f.disabled||Ze}))},0,!1))},ke=(Ze,$e)=>async Xe=>{let nt;Xe&&(Xe.preventDefault&&Xe.preventDefault(),Xe.persist&&Xe.persist());let Ge=iy(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:Je,values:ut}=await P();n.errors=Je,Ge=iy(ut)}else await I(r);if(o.disabled.size)for(const Je of o.disabled)Eg(Ge,Je);if(Eg(n.errors,"root"),x_(n.errors)){m.state.next({errors:{}});try{await Ze(Ge,Xe)}catch(Je){nt=Je}}else $e&&await $e({...n.errors},Xe),Pe(),setTimeout(Pe);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:x_(n.errors)&&!nt,submitCount:n.submitCount+1,errors:n.errors}),nt)throw nt},Ve=(Ze,$e={})=>{$i(r,Ze)&&(eg($e.defaultValue)?K(Ze,iy($i(a,Ze))):(K(Ze,$e.defaultValue),Oh(a,Ze,iy($e.defaultValue))),$e.keepTouched||Eg(n.touchedFields,Ze),$e.keepDirty||(Eg(n.dirtyFields,Ze),n.isDirty=$e.defaultValue?F(Ze,iy($i(a,Ze))):F()),$e.keepError||(Eg(n.errors,Ze),u.isValid&&g()),m.state.next({...n}))},_e=(Ze,$e={})=>{const Xe=Ze?iy(Ze):a,nt=iy(Xe),Ge=x_(Ze),Je=Ge?a:nt;if($e.keepDefaultValues||(a=Xe),!$e.keepValues){if($e.keepDirtyValues){const ut=new Set([...o.mount,...Object.keys($Y(a,i))]);for(const lt of Array.from(ut))$i(n.dirtyFields,lt)?Oh(Je,lt,$i(i,lt)):K(lt,$i(Je,lt))}else{if(ZQe&&eg(Ze))for(const ut of o.mount){const lt=$i(r,ut);if(lt&<._f){const qt=Array.isArray(lt._f.refs)?lt._f.refs[0]:lt._f.ref;if(pAe(qt)){const zt=qt.closest("form");if(zt){zt.reset();break}}}}if($e.keepFieldsRef)for(const ut of o.mount)K(ut,$i(Je,ut));else r={}}i=t.shouldUnregister?$e.keepDefaultValues?iy(a):{}:iy(Je),m.array.next({values:{...Je}}),m.state.next({values:{...Je}})}o={mount:$e.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!$e.keepIsValid||!!$e.keepDirtyValues,l.watch=!!t.shouldUnregister,m.state.next({submitCount:$e.keepSubmitCount?n.submitCount:0,isDirty:Ge?!1:$e.keepDirty?n.isDirty:!!($e.keepDefaultValues&&!MA(Ze,a)),isSubmitted:$e.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Ge?{}:$e.keepDirtyValues?$e.keepDefaultValues&&i?$Y(a,i):n.dirtyFields:$e.keepDefaultValues&&Ze?$Y(a,Ze):$e.keepDirty?n.dirtyFields:{},touchedFields:$e.keepTouched?n.touchedFields:{},errors:$e.keepErrors?n.errors:{},isSubmitSuccessful:$e.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Ae=(Ze,$e)=>_e(iS(Ze)?Ze(i):Ze,$e),Se=(Ze,$e={})=>{const Xe=$i(r,Ze),nt=Xe&&Xe._f;if(nt){const Ge=nt.refs?nt.refs[0]:nt.ref;Ge.focus&&(Ge.focus(),$e.shouldSelect&&iS(Ge.select)&&Ge.select())}},We=Ze=>{n={...n,...Ze}},Be={control:{register:Ne,unregister:ge,getFieldState:J,handleSubmit:ke,setError:ce,_subscribe:me,_runSchema:P,_focusError:Pe,_getWatch:q,_getDirty:F,_setValid:g,_setFieldArray:y,_setDisabledField:Ee,_setErrors:w,_getFieldArray:G,_reset:_e,_resetDefaultValues:()=>iS(t.defaultValues)&&t.defaultValues().then(Ze=>{Ae(Ze,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:D,_disableForm:Oe,_subjects:m,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Ze){l=Ze},get _defaultValues(){return a},get _names(){return o},set _names(Ze){o=Ze},get _formState(){return n},get _options(){return t},set _options(Ze){t={...t,...Ze}}},subscribe:he,trigger:re,register:Ne,handleSubmit:ke,watch:ve,setValue:K,getValues:ae,reset:Ae,resetField:Ve,clearErrors:te,unregister:ge,setError:ce,setFocus:Se,getFieldState:J};return{...Be,formControl:Be}}function gPe(s={}){const t=Ft.useRef(void 0),n=Ft.useRef(void 0),[r,a]=Ft.useState({isDirty:!1,isValidating:!1,isLoading:iS(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:iS(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!iS(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=lks(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,eJe(()=>{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]),Ft.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Ft.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Ft.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Ft.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Ft.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Ft.useEffect(()=>{s.values&&!MA(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]),Ft.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=eDt(r,i),t.current}const Lpt=(s,t,n)=>{if(s&&"reportValidity"in s){const r=$i(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},cDt=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?Lpt(r.ref,n,s):r.refs&&r.refs.forEach(a=>Lpt(a,n,s))}},cks=(s,t)=>{t.shouldUseNativeValidation&&cDt(s,t);const n={};for(const r in s){const a=$i(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(dks(t.names||Object.keys(s),r)){const l=Object.assign({},$i(n,r));Oh(l,"root",i),Oh(n,r,l)}else Oh(n,r,i)}return n},dks=(s,t)=>s.some(n=>n.startsWith(t+"."));var uks=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]=sDt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},yPe=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&&cDt({},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:cks(uks(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}},Ipt;function ga(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 Pq extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class dDt extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Ipt=globalThis).__zod_globalConfig??(Ipt.__zod_globalConfig={});const nJe=globalThis.__zod_globalConfig;function s9(s){return nJe}function uDt(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 Yqe(s,t){return typeof t=="bigint"?t.toString():t}function rJe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function aJe(s){return s==null}function iJe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function hks(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 gAe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const pks=rJe(()=>{var s;if(nJe.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 ute(s){if(gAe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(gAe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function mDt(s){return ute(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const fks=new Set(["string","number","symbol"]);function IH(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yL(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 ul(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 xks(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const gks={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 yks(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=gL(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 X9(this,"shape",l),l},checks:[]});return yL(s,i)}function vks(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=gL(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 X9(this,"shape",l),l},checks:[]});return yL(s,i)}function bks(s,t){if(!ute(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=gL(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return X9(this,"shape",i),i}});return yL(s,a)}function _ks(s,t){if(!ute(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=gL(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return X9(this,"shape",r),r}});return yL(s,n)}function wks(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=gL(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return X9(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return yL(s,n)}function jks(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=gL(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 X9(this,"shape",c),c},checks:[]});return yL(t,l)}function Nks(s,t,n){const r=gL(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 X9(this,"shape",i),i}});return yL(t,r)}function nU(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 vle(s){return typeof s=="string"?s:s==null?void 0:s.message}function n9(s,t,n){var c,d,u,h,m,p;const r=s.message?s.message:vle((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??vle((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??vle((m=n.customError)==null?void 0:m.call(n,s))??vle((p=n.localeError)==null?void 0:p.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function oJe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function hte(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const fDt=(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,Yqe,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},xDt=ga("$ZodError",fDt),gDt=ga("$ZodError",fDt,{Parent:Error});function Sks(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 Cks(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 Pq;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>n9(c,i,s9())));throw hDt(o,a==null?void 0:a.callee),o}return l.value},cJe=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=>n9(c,i,s9())));throw hDt(o,a==null?void 0:a.callee),o}return l.value},vPe=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 Pq;return i.issues.length?{success:!1,error:new(s??xDt)(i.issues.map(l=>n9(l,a,s9())))}:{success:!0,data:i.value}},Aks=vPe(gDt),bPe=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=>n9(l,a,s9())))}:{success:!0,data:i.value}},Eks=bPe(gDt),Tks=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return lJe(s)(t,n,a)},Mks=s=>(t,n,r)=>lJe(s)(t,n,r),Pks=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return cJe(s)(t,n,a)},Lks=s=>async(t,n,r)=>cJe(s)(t,n,r),Iks=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return vPe(s)(t,n,a)},Dks=s=>(t,n,r)=>vPe(s)(t,n,r),Rks=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return bPe(s)(t,n,a)},Fks=s=>async(t,n,r)=>bPe(s)(t,n,r),Oks=/^[cC][0-9a-z]{6,}$/,zks=/^[0-9a-z]+$/,Bks=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$ks=/^[0-9a-vA-V]{20}$/,Uks=/^[A-Za-z0-9]{27}$/,qks=/^[a-zA-Z0-9_-]{21}$/,Vks=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Hks=/^([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})$/,Fpt=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)$/,Gks=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Wks="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Kks(){return new RegExp(Wks,"u")}const Yks=/^(?:(?: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])$/,Zks=/^(([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}|:))$/,Xks=/^((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])$/,Qks=/^(([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])$/,Jks=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yDt=/^[A-Za-z0-9_-]*$/,eSs=/^https?$/,tSs=/^\+[1-9]\d{6,14}$/,vDt="(?:(?:\\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])))",sSs=new RegExp(`^${vDt}$`);function bDt(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 nSs(s){return new RegExp(`^${bDt(s)}$`)}function rSs(s){const t=bDt({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(`^${vDt}T(?:${r})$`)}const aSs=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}$`)},iSs=/^-?\d+$/,oSs=/^-?\d+(?:\.\d+)?$/,lSs=/^(?:true|false)$/i,cSs=/^[^A-Z]*$/,dSs=/^[^a-z]*$/,Y_=ga("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),_Dt={number:"number",bigint:"bigint",object:"date"},wDt=ga("$ZodCheckLessThan",(s,t)=>{Y_.init(s,t);const n=_Dt[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{Y_.init(s,t);const n=_Dt[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})}}),uSs=ga("$ZodCheckMultipleOf",(s,t)=>{Y_.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):hks(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})}}),hSs=ga("$ZodCheckNumberFormat",(s,t)=>{var l;Y_.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]=gks[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=iSs)}),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})}}),mSs=ga("$ZodCheckMaxLength",(s,t)=>{var n;Y_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!aJe(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=oJe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),pSs=ga("$ZodCheckMinLength",(s,t)=>{var n;Y_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!aJe(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=oJe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),fSs=ga("$ZodCheckLengthEquals",(s,t)=>{var n;Y_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!aJe(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=oJe(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})}}),_Pe=ga("$ZodCheckStringFormat",(s,t)=>{var n,r;Y_.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=()=>{})}),xSs=ga("$ZodCheckRegex",(s,t)=>{_Pe.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})}}),gSs=ga("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=cSs),_Pe.init(s,t)}),ySs=ga("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=dSs),_Pe.init(s,t)}),vSs=ga("$ZodCheckIncludes",(s,t)=>{Y_.init(s,t);const n=IH(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})}}),bSs=ga("$ZodCheckStartsWith",(s,t)=>{Y_.init(s,t);const n=new RegExp(`^${IH(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})}}),_Ss=ga("$ZodCheckEndsWith",(s,t)=>{Y_.init(s,t);const n=new RegExp(`.*${IH(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})}}),wSs=ga("$ZodCheckOverwrite",(s,t)=>{Y_.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class jSs{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 NSs={major:4,minor:4,patch:3},zx=ga("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=NSs;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=nU(o),h;for(const m of c){if(m._zod.def.when){if(kks(o)||!m._zod.def.when(o))continue}else if(u)continue;const p=o.issues.length,f=m._zod.check(o);if(f instanceof Promise&&(d==null?void 0:d.async)===!1)throw new Pq;if(h||f instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await f,o.issues.length!==p&&(u||(u=nU(o,p)))});else{if(o.issues.length===p)continue;u||(u=nU(o,p))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(nU(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new Pq;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 Pq;return d.then(u=>i(u,r,c))}return i(d,r,c)}}mm(s,"~standard",()=>({validate:i=>{var l;try{const o=Aks(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return Eks(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}))}),dJe=ga("$ZodString",(s,t)=>{var n;zx.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??aSs(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}}),hf=ga("$ZodStringFormat",(s,t)=>{_Pe.init(s,t),dJe.init(s,t)}),kSs=ga("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Hks),hf.init(s,t)}),SSs=ga("$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=Fpt(r))}else t.pattern??(t.pattern=Fpt());hf.init(s,t)}),CSs=ga("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=Gks),hf.init(s,t)}),ASs=ga("$ZodURL",(s,t)=>{hf.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)===eSs.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})}}}),ESs=ga("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=Kks()),hf.init(s,t)}),TSs=ga("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=qks),hf.init(s,t)}),MSs=ga("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Oks),hf.init(s,t)}),PSs=ga("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=zks),hf.init(s,t)}),LSs=ga("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Bks),hf.init(s,t)}),ISs=ga("$ZodXID",(s,t)=>{t.pattern??(t.pattern=$ks),hf.init(s,t)}),DSs=ga("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Uks),hf.init(s,t)}),RSs=ga("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=rSs(t)),hf.init(s,t)}),FSs=ga("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=sSs),hf.init(s,t)}),OSs=ga("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=nSs(t)),hf.init(s,t)}),zSs=ga("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Vks),hf.init(s,t)}),BSs=ga("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=Yks),hf.init(s,t),s._zod.bag.format="ipv4"}),$Ss=ga("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=Zks),hf.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})}}}),USs=ga("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=Xks),hf.init(s,t)}),qSs=ga("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=Qks),hf.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 NDt(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const VSs=ga("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=Jks),hf.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{NDt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function HSs(s){if(!yDt.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return NDt(n)}const GSs=ga("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=yDt),hf.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{HSs(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),WSs=ga("$ZodE164",(s,t)=>{t.pattern??(t.pattern=tSs),hf.init(s,t)});function KSs(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 YSs=ga("$ZodJWT",(s,t)=>{hf.init(s,t),s._zod.check=n=>{KSs(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),kDt=ga("$ZodNumber",(s,t)=>{zx.init(s,t),s._zod.pattern=s._zod.bag.pattern??oSs,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}}),ZSs=ga("$ZodNumberFormat",(s,t)=>{hSs.init(s,t),kDt.init(s,t)}),XSs=ga("$ZodBoolean",(s,t)=>{zx.init(s,t),s._zod.pattern=lSs,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}}),QSs=ga("$ZodUnknown",(s,t)=>{zx.init(s,t),s._zod.parse=n=>n}),JSs=ga("$ZodNever",(s,t)=>{zx.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function Opt(s,t,n){s.issues.length&&t.issues.push(...pDt(n,s.issues)),t.value[n]=s.value}const e5s=ga("$ZodArray",(s,t)=>{zx.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;lOpt(d,n,l))):Opt(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function yAe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...pDt(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 SDt(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=xks(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function CDt(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const m in t){if(m==="__proto__"||o.has(m))continue;if(d==="never"){l.push(m);continue}const p=c.run({value:t[m],issues:[]},r);p instanceof Promise?s.push(p.then(f=>yAe(f,n,m,t,u,h))):yAe(p,n,m,t,u,h)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>n):n}const t5s=ga("$ZodObject",(s,t)=>{zx.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=rJe(()=>SDt(t));mm(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=gAe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const m of l.keys){const p=h[m],f=p._zod.optin==="optional",g=p._zod.optout==="optional",v=p._zod.run({value:d[m],issues:[]},c);v instanceof Promise?u.push(v.then(y=>yAe(y,o,m,d,f,g))):yAe(v,o,m,d,f,g)}return i?CDt(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),s5s=ga("$ZodObjectJIT",(s,t)=>{t5s.init(s,t);const n=s._zod.parse,r=rJe(()=>SDt(t)),a=m=>{var w,S;const p=new jSs(["shape","payload","ctx"]),f=r.value,g=C=>{const E=Rpt(C);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};p.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const C of f.keys)v[C]=`key_${y++}`;p.write("const newResult = {};");for(const C of f.keys){const E=v[C],P=Rpt(C),M=m[C],I=((w=M==null?void 0:M._zod)==null?void 0:w.optin)==="optional",D=((S=M==null?void 0:M._zod)==null?void 0:S.optout)==="optional";p.write(`const ${E} = ${g(C)};`),I&&D?p.write(` if (${E}.issues.length) { if (${P} in input) { payload.issues = payload.issues.concat(${E}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } } if (${E}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${E}.value; } `):I?p.write(` if (${E}.issues.length) { payload.issues = payload.issues.concat(${E}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (${E}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${E}.value; } `):p.write(` const ${E}_present = ${P} in input; if (${E}.issues.length) { payload.issues = payload.issues.concat(${E}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (!${E}_present && !${E}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${P}] }); } if (${E}_present) { if (${E}.value === undefined) { newResult[${P}] = undefined; } else { newResult[${P}] = ${E}.value; } } `)}p.write("payload.value = newResult;"),p.write("return payload;");const b=p.compile();return(C,E)=>b(m,C,E)};let i;const l=gAe,o=!nJe.jitless,d=o&&pks.value,u=t.catchall;let h;s._zod.parse=(m,p)=>{h??(h=r.value);const f=m.value;return l(f)?o&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=a(t.shape)),m=i(m,p),u?CDt([],f,m,p,h,s):m):n(m,p):(m.issues.push({expected:"object",code:"invalid_type",input:f,inst:s}),m)}});function zpt(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=>!nU(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=>n9(l,r,s9())))}),t)}const n5s=ga("$ZodUnion",(s,t)=>{zx.init(s,t),mm(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),mm(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),mm(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),mm(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=>iJe(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=>zpt(o,r,s,a)):zpt(l,r,s,a)}}),r5s=ga("$ZodIntersection",(s,t)=>{zx.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])=>Bpt(n,c,d)):Bpt(n,i,l)}});function Zqe(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(ute(s)&&ute(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=Zqe(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}),nU(s))return s;const l=Zqe(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 a5s=ga("$ZodEnum",(s,t)=>{zx.init(s,t);const n=uDt(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>fks.has(typeof a)).map(a=>typeof a=="string"?IH(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}}),i5s=ga("$ZodLiteral",(s,t)=>{if(zx.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"?IH(r):r?IH(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}}),o5s=ga("$ZodTransform",(s,t)=>{zx.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new dDt(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 Pq;return n.value=a,n.fallback=!0,n}});function $pt(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const ADt=ga("$ZodOptional",(s,t)=>{zx.init(s,t),s._zod.optin="optional",s._zod.optout="optional",mm(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),mm(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${iJe(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=>$pt(l,a)):$pt(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),l5s=ga("$ZodExactOptional",(s,t)=>{ADt.init(s,t),mm(s._zod,"values",()=>t.innerType._zod.values),mm(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),c5s=ga("$ZodNullable",(s,t)=>{zx.init(s,t),mm(s._zod,"optin",()=>t.innerType._zod.optin),mm(s._zod,"optout",()=>t.innerType._zod.optout),mm(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${iJe(n.source)}|null)$`):void 0}),mm(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)}),d5s=ga("$ZodDefault",(s,t)=>{zx.init(s,t),s._zod.optin="optional",mm(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=>Upt(i,t)):Upt(a,t)}});function Upt(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const u5s=ga("$ZodPrefault",(s,t)=>{zx.init(s,t),s._zod.optin="optional",mm(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))}),h5s=ga("$ZodNonOptional",(s,t)=>{zx.init(s,t),mm(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=>qpt(i,s)):qpt(a,s)}});function qpt(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 m5s=ga("$ZodCatch",(s,t)=>{zx.init(s,t),s._zod.optin="optional",mm(s._zod,"optout",()=>t.innerType._zod.optout),mm(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=>n9(l,r,s9()))},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=>n9(i,r,s9()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),p5s=ga("$ZodPipe",(s,t)=>{zx.init(s,t),mm(s._zod,"values",()=>t.in._zod.values),mm(s._zod,"optin",()=>t.in._zod.optin),mm(s._zod,"optout",()=>t.out._zod.optout),mm(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=>ble(l,t.in,r)):ble(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>ble(i,t.out,r)):ble(a,t.out,r)}});function ble(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 f5s=ga("$ZodReadonly",(s,t)=>{zx.init(s,t),mm(s._zod,"propValues",()=>t.innerType._zod.propValues),mm(s._zod,"values",()=>t.innerType._zod.values),mm(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),mm(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(Vpt):Vpt(a)}});function Vpt(s){return s.value=Object.freeze(s.value),s}const x5s=ga("$ZodCustom",(s,t)=>{Y_.init(s,t),zx.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=>Hpt(i,n,r,s));Hpt(a,n,r,s)}});function Hpt(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(hte(a))}}var Gpt;class g5s{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 y5s(){return new g5s}(Gpt=globalThis).__zod_globalRegistry??(Gpt.__zod_globalRegistry=y5s());const bX=globalThis.__zod_globalRegistry;function v5s(s,t){return new s({type:"string",...ul(t)})}function b5s(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...ul(t)})}function Wpt(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...ul(t)})}function _5s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...ul(t)})}function w5s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ul(t)})}function j5s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ul(t)})}function N5s(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ul(t)})}function k5s(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...ul(t)})}function S5s(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...ul(t)})}function C5s(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...ul(t)})}function A5s(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...ul(t)})}function E5s(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...ul(t)})}function T5s(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...ul(t)})}function M5s(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...ul(t)})}function P5s(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...ul(t)})}function L5s(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...ul(t)})}function I5s(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...ul(t)})}function D5s(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ul(t)})}function R5s(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ul(t)})}function F5s(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...ul(t)})}function O5s(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...ul(t)})}function z5s(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...ul(t)})}function B5s(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...ul(t)})}function $5s(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ul(t)})}function U5s(s,t){return new s({type:"string",format:"date",check:"string_format",...ul(t)})}function q5s(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...ul(t)})}function V5s(s,t){return new s({type:"string",format:"duration",check:"string_format",...ul(t)})}function H5s(s,t){return new s({type:"number",checks:[],...ul(t)})}function G5s(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...ul(t)})}function W5s(s,t){return new s({type:"boolean",...ul(t)})}function K5s(s){return new s({type:"unknown"})}function Y5s(s,t){return new s({type:"never",...ul(t)})}function Kpt(s,t){return new wDt({check:"less_than",...ul(t),value:s,inclusive:!1})}function SOe(s,t){return new wDt({check:"less_than",...ul(t),value:s,inclusive:!0})}function Ypt(s,t){return new jDt({check:"greater_than",...ul(t),value:s,inclusive:!1})}function COe(s,t){return new jDt({check:"greater_than",...ul(t),value:s,inclusive:!0})}function Zpt(s,t){return new uSs({check:"multiple_of",...ul(t),value:s})}function EDt(s,t){return new mSs({check:"max_length",...ul(t),maximum:s})}function vAe(s,t){return new pSs({check:"min_length",...ul(t),minimum:s})}function TDt(s,t){return new fSs({check:"length_equals",...ul(t),length:s})}function Z5s(s,t){return new xSs({check:"string_format",format:"regex",...ul(t),pattern:s})}function X5s(s){return new gSs({check:"string_format",format:"lowercase",...ul(s)})}function Q5s(s){return new ySs({check:"string_format",format:"uppercase",...ul(s)})}function J5s(s,t){return new vSs({check:"string_format",format:"includes",...ul(t),includes:s})}function e4s(s,t){return new bSs({check:"string_format",format:"starts_with",...ul(t),prefix:s})}function t4s(s,t){return new _Ss({check:"string_format",format:"ends_with",...ul(t),suffix:s})}function pW(s){return new wSs({check:"overwrite",tx:s})}function s4s(s){return pW(t=>t.normalize(s))}function n4s(){return pW(s=>s.trim())}function r4s(){return pW(s=>s.toLowerCase())}function a4s(){return pW(s=>s.toUpperCase())}function i4s(){return pW(s=>mks(s))}function o4s(s,t,n){return new s({type:"array",element:t,...ul(n)})}function l4s(s,t,n){return new s({type:"custom",check:"custom",fn:t,...ul(n)})}function c4s(s,t){const n=d4s(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(hte(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(hte(i))}},s(r.value,r)),t);return n}function d4s(s,t){const n=new Y_({check:"custom",...ul(t)});return n._zod.check=s,n}function MDt(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)??bX,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 Ev(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l);const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const m={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,m);else{const f=l.schema,g=t.processors[a.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);g(s,t,f,m)}const p=s._zod.parent;p&&(l.ref||(l.ref=p),Ev(p,t,m),t.seen.get(p).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&Z1(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 PDt(s,t){var l,o,c,d;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of s.seen.entries()){const h=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(h){const m=r.get(h);if(m&&m!==u[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,u[0])}}const a=u=>{var g;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const v=(g=s.external.registry.get(u[0]))==null?void 0:g.id,y=s.external.uri??(w=>w);if(v)return{ref:y(v)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${y("__shared")}#/${h}/${b}`}}if(u[1]===n)return{ref:"#"};const p=`#/${h}/`,f=u[1].schema.id??`__schema${s.counter++}`;return{defId:f,ref:p+f}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:p}=a(u);h.def={...h.schema},p&&(h.defId=p);const f=h.schema;for(const g in f)delete f[g];f.$ref=m};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const p=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&p){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function LDt(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const p=m.def??m.schema,f={...p},g=m.ref;if(m.ref=null,g){r(g);const y=s.seen.get(g),b=y.schema;if(b.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(b)):Object.assign(p,b),Object.assign(p,f),h._zod.parent===g)for(const S in p)S==="$ref"||S==="allOf"||S in f||delete p[S];if(b.$ref&&y.def)for(const S in p)S==="$ref"||S==="allOf"||S in y.def&&JSON.stringify(p[S])===JSON.stringify(y.def[S])&&delete p[S]}const v=h._zod.parent;if(v&&v!==g){r(v);const y=s.seen.get(v);if(y!=null&&y.schema.$ref&&(p.$ref=y.schema.$ref,y.def))for(const b in p)b==="$ref"||b==="allOf"||b in y.def&&JSON.stringify(p[b])===JSON.stringify(y.def[b])&&delete p[b]}s.override({zodSchema:h,jsonSchema:p,path:m.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};for(const h of s.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,l[m.defId]=m.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:bAe(t,"input",s.processors),output:bAe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Z1(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 Z1(r.element,n);if(r.type==="set")return Z1(r.valueType,n);if(r.type==="lazy")return Z1(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 Z1(r.innerType,n);if(r.type==="intersection")return Z1(r.left,n)||Z1(r.right,n);if(r.type==="record"||r.type==="map")return Z1(r.keyType,n)||Z1(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Z1(r.in,n)||Z1(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Z1(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Z1(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Z1(a,n))return!0;return!!(r.rest&&Z1(r.rest,n))}return!1}const u4s=(s,t={})=>n=>{const r=MDt({...n,processors:t});return Ev(s,r),PDt(r,s),LDt(r,s)},bAe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=MDt({...a??{},target:i,io:t,processors:n});return Ev(s,l),PDt(l,s),LDt(l,s)},h4s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},m4s=(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=h4s[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}))])}},p4s=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=s._zod.bag;typeof o=="string"&&o.includes("int")?a.type="integer":a.type="number";const h=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),m=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";h?p?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),m?p?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},f4s=(s,t,n,r)=>{n.type="boolean"},x4s=(s,t,n,r)=>{n.not={}},g4s=(s,t,n,r)=>{},y4s=(s,t,n,r)=>{const a=s._zod.def,i=uDt(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},v4s=(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},b4s=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},_4s=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},w4s=(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=Ev(i.element,t,{...r,path:[...r.path,"items"]})},j4s=(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]=Ev(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=Ev(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},N4s=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Ev(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},k4s=(s,t,n,r)=>{const a=s._zod.def,i=Ev(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Ev(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},S4s=(s,t,n,r)=>{const a=s._zod.def,i=Ev(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"}]},C4s=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},A4s=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},E4s=(s,t,n,r)=>{const a=s._zod.def;Ev(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)))},T4s=(s,t,n,r)=>{const a=s._zod.def;Ev(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},M4s=(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;Ev(l,t,r);const o=t.seen.get(s);o.ref=l},P4s=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},IDt=(s,t,n,r)=>{const a=s._zod.def;Ev(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},L4s=ga("ZodISODateTime",(s,t)=>{RSs.init(s,t),tx.init(s,t)});function I4s(s){return $5s(L4s,s)}const D4s=ga("ZodISODate",(s,t)=>{FSs.init(s,t),tx.init(s,t)});function R4s(s){return U5s(D4s,s)}const F4s=ga("ZodISOTime",(s,t)=>{OSs.init(s,t),tx.init(s,t)});function O4s(s){return q5s(F4s,s)}const z4s=ga("ZodISODuration",(s,t)=>{zSs.init(s,t),tx.init(s,t)});function B4s(s){return V5s(z4s,s)}const DDt=(s,t)=>{xDt.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>Cks(s,n)},flatten:{value:n=>Sks(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,Yqe,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,Yqe,2)}},isEmpty:{get(){return s.issues.length===0}}})},$4s=ga("ZodError",DDt),VN=ga("ZodError",DDt,{Parent:Error}),U4s=lJe(VN),q4s=cJe(VN),V4s=vPe(VN),H4s=bPe(VN),G4s=Tks(VN),W4s=Mks(VN),K4s=Pks(VN),Y4s=Lks(VN),Z4s=Iks(VN),X4s=Dks(VN),Q4s=Rks(VN),J4s=Fks(VN),Xpt=new WeakMap;function Qre(s,t,n){const r=Object.getPrototypeOf(s);let a=Xpt.get(r);if(a||(a=new Set,Xpt.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 Bx=ga("ZodType",(s,t)=>(zx.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:bAe(s,"input"),output:bAe(s,"output")}}),s.toJSONSchema=u4s(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>U4s(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>V4s(s,n,r),s.parseAsync=async(n,r)=>q4s(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>H4s(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>G4s(s,n,r),s.decode=(n,r)=>W4s(s,n,r),s.encodeAsync=async(n,r)=>K4s(s,n,r),s.decodeAsync=async(n,r)=>Y4s(s,n,r),s.safeEncode=(n,r)=>Z4s(s,n,r),s.safeDecode=(n,r)=>X4s(s,n,r),s.safeEncodeAsync=async(n,r)=>Q4s(s,n,r),s.safeDecodeAsync=async(n,r)=>J4s(s,n,r),Qre(s,"ZodType",{check(...n){const r=this.def;return this.clone(gL(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 yL(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(KCs(n,r))},superRefine(n,r){return this.check(YCs(n,r))},overwrite(n){return this.check(pW(n))},optional(){return tft(this)},exactOptional(){return DCs(this)},nullable(){return sft(this)},nullish(){return tft(sft(this))},nonoptional(n){return $Cs(this,n)},array(){return kCs(this)},or(n){return ACs([this,n])},and(n){return TCs(this,n)},transform(n){return nft(this,LCs(n))},default(n){return OCs(this,n)},prefault(n){return BCs(this,n)},catch(n){return qCs(this,n)},pipe(n){return nft(this,n)},readonly(){return GCs(this)},describe(n){const r=this.clone();return bX.add(r,{description:n}),r},meta(...n){if(n.length===0)return bX.get(this);const r=this.clone();return bX.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=bX.get(s))==null?void 0:n.description},configurable:!0}),s)),RDt=ga("_ZodString",(s,t)=>{dJe.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>m4s(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,Qre(s,"_ZodString",{regex(...r){return this.check(Z5s(...r))},includes(...r){return this.check(J5s(...r))},startsWith(...r){return this.check(e4s(...r))},endsWith(...r){return this.check(t4s(...r))},min(...r){return this.check(vAe(...r))},max(...r){return this.check(EDt(...r))},length(...r){return this.check(TDt(...r))},nonempty(...r){return this.check(vAe(1,...r))},lowercase(r){return this.check(X5s(r))},uppercase(r){return this.check(Q5s(r))},trim(){return this.check(n4s())},normalize(...r){return this.check(s4s(...r))},toLowerCase(){return this.check(r4s())},toUpperCase(){return this.check(a4s())},slugify(){return this.check(i4s())}})}),eCs=ga("ZodString",(s,t)=>{dJe.init(s,t),RDt.init(s,t),s.email=n=>s.check(b5s(tCs,n)),s.url=n=>s.check(k5s(sCs,n)),s.jwt=n=>s.check(B5s(gCs,n)),s.emoji=n=>s.check(S5s(nCs,n)),s.guid=n=>s.check(Wpt(Qpt,n)),s.uuid=n=>s.check(_5s(_le,n)),s.uuidv4=n=>s.check(w5s(_le,n)),s.uuidv6=n=>s.check(j5s(_le,n)),s.uuidv7=n=>s.check(N5s(_le,n)),s.nanoid=n=>s.check(C5s(rCs,n)),s.guid=n=>s.check(Wpt(Qpt,n)),s.cuid=n=>s.check(A5s(aCs,n)),s.cuid2=n=>s.check(E5s(iCs,n)),s.ulid=n=>s.check(T5s(oCs,n)),s.base64=n=>s.check(F5s(pCs,n)),s.base64url=n=>s.check(O5s(fCs,n)),s.xid=n=>s.check(M5s(lCs,n)),s.ksuid=n=>s.check(P5s(cCs,n)),s.ipv4=n=>s.check(L5s(dCs,n)),s.ipv6=n=>s.check(I5s(uCs,n)),s.cidrv4=n=>s.check(D5s(hCs,n)),s.cidrv6=n=>s.check(R5s(mCs,n)),s.e164=n=>s.check(z5s(xCs,n)),s.datetime=n=>s.check(I4s(n)),s.date=n=>s.check(R4s(n)),s.time=n=>s.check(O4s(n)),s.duration=n=>s.check(B4s(n))});function Jo(s){return v5s(eCs,s)}const tx=ga("ZodStringFormat",(s,t)=>{hf.init(s,t),RDt.init(s,t)}),tCs=ga("ZodEmail",(s,t)=>{CSs.init(s,t),tx.init(s,t)}),Qpt=ga("ZodGUID",(s,t)=>{kSs.init(s,t),tx.init(s,t)}),_le=ga("ZodUUID",(s,t)=>{SSs.init(s,t),tx.init(s,t)}),sCs=ga("ZodURL",(s,t)=>{ASs.init(s,t),tx.init(s,t)}),nCs=ga("ZodEmoji",(s,t)=>{ESs.init(s,t),tx.init(s,t)}),rCs=ga("ZodNanoID",(s,t)=>{TSs.init(s,t),tx.init(s,t)}),aCs=ga("ZodCUID",(s,t)=>{MSs.init(s,t),tx.init(s,t)}),iCs=ga("ZodCUID2",(s,t)=>{PSs.init(s,t),tx.init(s,t)}),oCs=ga("ZodULID",(s,t)=>{LSs.init(s,t),tx.init(s,t)}),lCs=ga("ZodXID",(s,t)=>{ISs.init(s,t),tx.init(s,t)}),cCs=ga("ZodKSUID",(s,t)=>{DSs.init(s,t),tx.init(s,t)}),dCs=ga("ZodIPv4",(s,t)=>{BSs.init(s,t),tx.init(s,t)}),uCs=ga("ZodIPv6",(s,t)=>{$Ss.init(s,t),tx.init(s,t)}),hCs=ga("ZodCIDRv4",(s,t)=>{USs.init(s,t),tx.init(s,t)}),mCs=ga("ZodCIDRv6",(s,t)=>{qSs.init(s,t),tx.init(s,t)}),pCs=ga("ZodBase64",(s,t)=>{VSs.init(s,t),tx.init(s,t)}),fCs=ga("ZodBase64URL",(s,t)=>{GSs.init(s,t),tx.init(s,t)}),xCs=ga("ZodE164",(s,t)=>{WSs.init(s,t),tx.init(s,t)}),gCs=ga("ZodJWT",(s,t)=>{YSs.init(s,t),tx.init(s,t)}),FDt=ga("ZodNumber",(s,t)=>{kDt.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>p4s(s,r,a),Qre(s,"ZodNumber",{gt(r,a){return this.check(Ypt(r,a))},gte(r,a){return this.check(COe(r,a))},min(r,a){return this.check(COe(r,a))},lt(r,a){return this.check(Kpt(r,a))},lte(r,a){return this.check(SOe(r,a))},max(r,a){return this.check(SOe(r,a))},int(r){return this.check(Jpt(r))},safe(r){return this.check(Jpt(r))},positive(r){return this.check(Ypt(0,r))},nonnegative(r){return this.check(COe(0,r))},negative(r){return this.check(Kpt(0,r))},nonpositive(r){return this.check(SOe(0,r))},multipleOf(r,a){return this.check(Zpt(r,a))},step(r,a){return this.check(Zpt(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 TJ(s){return H5s(FDt,s)}const yCs=ga("ZodNumberFormat",(s,t)=>{ZSs.init(s,t),FDt.init(s,t)});function Jpt(s){return G5s(yCs,s)}const vCs=ga("ZodBoolean",(s,t)=>{XSs.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>f4s(s,n,r)});function bCs(s){return W5s(vCs,s)}const _Cs=ga("ZodUnknown",(s,t)=>{QSs.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>g4s()});function eft(){return K5s(_Cs)}const wCs=ga("ZodNever",(s,t)=>{JSs.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>x4s(s,n,r)});function jCs(s){return Y5s(wCs,s)}const NCs=ga("ZodArray",(s,t)=>{e5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>w4s(s,n,r,a),s.element=t.element,Qre(s,"ZodArray",{min(n,r){return this.check(vAe(n,r))},nonempty(n){return this.check(vAe(1,n))},max(n,r){return this.check(EDt(n,r))},length(n,r){return this.check(TDt(n,r))},unwrap(){return this.element}})});function kCs(s,t){return o4s(NCs,s,t)}const SCs=ga("ZodObject",(s,t)=>{s5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>j4s(s,n,r,a),mm(s,"shape",()=>t.shape),Qre(s,"ZodObject",{keyof(){return uJe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:eft()})},loose(){return this.clone({...this._zod.def,catchall:eft()})},strict(){return this.clone({...this._zod.def,catchall:jCs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return bks(this,n)},safeExtend(n){return _ks(this,n)},merge(n){return wks(this,n)},pick(n){return yks(this,n)},omit(n){return vks(this,n)},partial(...n){return jks(ODt,this,n[0])},required(...n){return Nks(zDt,this,n[0])}})});function Gj(s,t){const n={type:"object",shape:s??{},...ul(t)};return new SCs(n)}const CCs=ga("ZodUnion",(s,t)=>{n5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>N4s(s,n,r,a),s.options=t.options});function ACs(s,t){return new CCs({type:"union",options:s,...ul(t)})}const ECs=ga("ZodIntersection",(s,t)=>{r5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>k4s(s,n,r,a)});function TCs(s,t){return new ECs({type:"intersection",left:s,right:t})}const Xqe=ga("ZodEnum",(s,t)=>{a5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>y4s(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 Xqe({...t,checks:[],...ul(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 Xqe({...t,checks:[],...ul(a),entries:i})}});function uJe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new Xqe({type:"enum",entries:n,...ul(t)})}const MCs=ga("ZodLiteral",(s,t)=>{i5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>v4s(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 jx(s,t){return new MCs({type:"literal",values:Array.isArray(s)?s:[s],...ul(t)})}const PCs=ga("ZodTransform",(s,t)=>{o5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>_4s(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new dDt(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(hte(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(hte(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 LCs(s){return new PCs({type:"transform",transform:s})}const ODt=ga("ZodOptional",(s,t)=>{ADt.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>IDt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function tft(s){return new ODt({type:"optional",innerType:s})}const ICs=ga("ZodExactOptional",(s,t)=>{l5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>IDt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function DCs(s){return new ICs({type:"optional",innerType:s})}const RCs=ga("ZodNullable",(s,t)=>{c5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>S4s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function sft(s){return new RCs({type:"nullable",innerType:s})}const FCs=ga("ZodDefault",(s,t)=>{d5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>A4s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function OCs(s,t){return new FCs({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():mDt(t)}})}const zCs=ga("ZodPrefault",(s,t)=>{u5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>E4s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function BCs(s,t){return new zCs({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():mDt(t)}})}const zDt=ga("ZodNonOptional",(s,t)=>{h5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>C4s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function $Cs(s,t){return new zDt({type:"nonoptional",innerType:s,...ul(t)})}const UCs=ga("ZodCatch",(s,t)=>{m5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>T4s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function qCs(s,t){return new UCs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const VCs=ga("ZodPipe",(s,t)=>{p5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>M4s(s,n,r,a),s.in=t.in,s.out=t.out});function nft(s,t){return new VCs({type:"pipe",in:s,out:t})}const HCs=ga("ZodReadonly",(s,t)=>{f5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>P4s(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function GCs(s){return new HCs({type:"readonly",innerType:s})}const WCs=ga("ZodCustom",(s,t)=>{x5s.init(s,t),Bx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>b4s(s,n)});function KCs(s,t={}){return l4s(WCs,s,t)}function YCs(s,t){return c4s(s,t)}var ZCs="Label",BDt=_.forwardRef((s,t)=>e.jsx(ci.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())}}));BDt.displayName=ZCs;var $Dt=BDt;const XCs=G9("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ee=_.forwardRef(({className:s,...t},n)=>e.jsx($Dt,{ref:n,className:Ct(XCs(),s),...t}));ee.displayName=$Dt.displayName;const wPe=HNs,UDt=_.createContext({}),Mf=({...s})=>e.jsx(UDt.Provider,{value:{name:s.name},children:e.jsx(YNs,{...s})}),jPe=()=>{const s=_.useContext(UDt),t=_.useContext(qDt),{getFieldState:n,formState:r}=xPe(),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}},qDt=_.createContext({}),ef=_.forwardRef(({className:s,...t},n)=>{const r=_.useId();return e.jsx(qDt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Ct("space-y-2",s),...t})})});ef.displayName="FormItem";const tf=_.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=jPe();return e.jsx(ee,{ref:n,className:Ct(r&&"text-destructive",s),htmlFor:a,...t})});tf.displayName="FormLabel";const sf=_.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=jPe();return e.jsx(aQe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});sf.displayName="FormControl";const M4e=_.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=jPe();return e.jsx("p",{ref:n,id:r,className:Ct("text-sm text-muted-foreground",s),...t})});M4e.displayName="FormDescription";const hb=_.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=jPe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Ct("text-sm font-medium text-destructive",s),...n,children:l}):null});hb.displayName="FormMessage";const pe=_.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Ct("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}));pe.displayName="Input";function Jre(s){const t=_.useRef({value:s,previous:s});return _.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var QCs=[" ","Enter","ArrowUp","ArrowDown"],JCs=[" ","Enter"],r9="Select",[NPe,kPe,e3s]=tW(r9),[fW,twr]=uf(r9,[e3s,CC]),SPe=CC(),[t3s,vL]=fW(r9),[s3s,n3s]=fW(r9),VDt=s=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:p,form:f}=s,g=SPe(t),[v,y]=_.useState(null),[b,w]=_.useState(null),[S,C]=_.useState(!1),E=$E(d),[P,M]=Gg({prop:r,defaultProp:a??!1,onChange:i,caller:r9}),[I,D]=Gg({prop:l,defaultProp:o,onChange:c,caller:r9}),F=_.useRef(null),q=v?f||!!v.closest("form"):!0,[G,V]=_.useState(new Set),H=Array.from(G).map(K=>K.props.value).join(";");return e.jsx(Fre,{...g,children:e.jsxs(t3s,{required:p,scope:t,trigger:v,onTriggerChange:y,valueNode:b,onValueNodeChange:w,valueNodeHasChildren:S,onValueNodeHasChildrenChange:C,contentId:qg(),value:I,onValueChange:D,open:P,onOpenChange:M,dir:E,triggerPointerDownPosRef:F,disabled:m,children:[e.jsx(NPe.Provider,{scope:t,children:e.jsx(s3s,{scope:s.__scopeSelect,onNativeOptionAdd:_.useCallback(K=>{V(Z=>new Set(Z).add(K))},[]),onNativeOptionRemove:_.useCallback(K=>{V(Z=>{const oe=new Set(Z);return oe.delete(K),oe})},[]),children:n})}),q?e.jsxs(fRt,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:I,onChange:K=>D(K.target.value),disabled:m,form:f,children:[I===void 0?e.jsx("option",{value:""}):null,Array.from(G)]},H):null]})})};VDt.displayName=r9;var HDt="SelectTrigger",GDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=SPe(n),l=vL(HDt,n),o=l.disabled||r,c=el(t,l.onTriggerChange),d=kPe(n),u=_.useRef("touch"),[h,m,p]=gRt(g=>{const v=d().filter(w=>!w.disabled),y=v.find(w=>w.value===l.value),b=yRt(v,g,y);b!==void 0&&l.onValueChange(b.value)}),f=g=>{o||(l.onOpenChange(!0),p()),g&&(l.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return e.jsx(lW,{asChild:!0,...i,children:e.jsx(ci.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":xRt(l.value)?"":void 0,...a,ref:c,onClick:wa(a.onClick,g=>{g.currentTarget.focus(),u.current!=="mouse"&&f(g)}),onPointerDown:wa(a.onPointerDown,g=>{u.current=g.pointerType;const v=g.target;v.hasPointerCapture(g.pointerId)&&v.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(f(g),g.preventDefault())}),onKeyDown:wa(a.onKeyDown,g=>{const v=h.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&m(g.key),!(v&&g.key===" ")&&QCs.includes(g.key)&&(f(),g.preventDefault())})})})});GDt.displayName=HDt;var WDt="SelectValue",KDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=vL(WDt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=el(t,c.onValueNodeChange);return Rx(()=>{d(u)},[d,u]),e.jsx(ci.span,{...o,ref:h,style:{pointerEvents:"none"},children:xRt(c.value)?e.jsx(e.Fragment,{children:l}):i})});KDt.displayName=WDt;var r3s="SelectIcon",YDt=_.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(ci.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});YDt.displayName=r3s;var a3s="SelectPortal",ZDt=s=>e.jsx(sW,{asChild:!0,...s});ZDt.displayName=a3s;var a9="SelectContent",XDt=_.forwardRef((s,t)=>{const n=vL(a9,s.__scopeSelect),[r,a]=_.useState();if(Rx(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?pv.createPortal(e.jsx(QDt,{scope:s.__scopeSelect,children:e.jsx(NPe.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(JDt,{...s,ref:t})});XDt.displayName=a9;var Ak=10,[QDt,bL]=fW(a9),i3s="SelectContentImpl",o3s=OP("SelectContent.RemoveScroll"),JDt=_.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:m,collisionPadding:p,sticky:f,hideWhenDetached:g,avoidCollisions:v,...y}=s,b=vL(a9,n),[w,S]=_.useState(null),[C,E]=_.useState(null),P=el(t,ge=>S(ge)),[M,I]=_.useState(null),[D,F]=_.useState(null),q=kPe(n),[G,V]=_.useState(!1),H=_.useRef(!1);_.useEffect(()=>{if(w)return BMe(w)},[w]),OMe();const K=_.useCallback(ge=>{const[Ee,...Ne]=q().map(ke=>ke.ref.current),[Pe]=Ne.slice(-1),Oe=document.activeElement;for(const ke of ge)if(ke===Oe||(ke==null||ke.scrollIntoView({block:"nearest"}),ke===Ee&&C&&(C.scrollTop=0),ke===Pe&&C&&(C.scrollTop=C.scrollHeight),ke==null||ke.focus(),document.activeElement!==Oe))return},[q,C]),Z=_.useCallback(()=>K([M,w]),[K,M,w]);_.useEffect(()=>{G&&Z()},[G,Z]);const{onOpenChange:oe,triggerPointerDownPosRef:re}=b;_.useEffect(()=>{if(w){let ge={x:0,y:0};const Ee=Pe=>{var Oe,ke;ge={x:Math.abs(Math.round(Pe.pageX)-(((Oe=re.current)==null?void 0:Oe.x)??0)),y:Math.abs(Math.round(Pe.pageY)-(((ke=re.current)==null?void 0:ke.y)??0))}},Ne=Pe=>{ge.x<=10&&ge.y<=10?Pe.preventDefault():w.contains(Pe.target)||oe(!1),document.removeEventListener("pointermove",Ee),re.current=null};return re.current!==null&&(document.addEventListener("pointermove",Ee),document.addEventListener("pointerup",Ne,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ee),document.removeEventListener("pointerup",Ne,{capture:!0})}}},[w,oe,re]),_.useEffect(()=>{const ge=()=>oe(!1);return window.addEventListener("blur",ge),window.addEventListener("resize",ge),()=>{window.removeEventListener("blur",ge),window.removeEventListener("resize",ge)}},[oe]);const[ae,J]=gRt(ge=>{const Ee=q().filter(Oe=>!Oe.disabled),Ne=Ee.find(Oe=>Oe.ref.current===document.activeElement),Pe=yRt(Ee,ge,Ne);Pe&&setTimeout(()=>Pe.ref.current.focus())}),te=_.useCallback((ge,Ee,Ne)=>{const Pe=!H.current&&!Ne;(b.value!==void 0&&b.value===Ee||Pe)&&(I(ge),Pe&&(H.current=!0))},[b.value]),ce=_.useCallback(()=>w==null?void 0:w.focus(),[w]),ve=_.useCallback((ge,Ee,Ne)=>{const Pe=!H.current&&!Ne;(b.value!==void 0&&b.value===Ee||Pe)&&F(ge)},[b.value]),me=r==="popper"?Qqe:eRt,he=me===Qqe?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:f,hideWhenDetached:g,avoidCollisions:v}:{};return e.jsx(QDt,{scope:n,content:w,viewport:C,onViewportChange:E,itemRefCallback:te,selectedItem:M,onItemLeave:ce,itemTextRefCallback:ve,focusSelectedItem:Z,selectedItemText:D,position:r,isPositioned:G,searchRef:ae,children:e.jsx(Mre,{as:o3s,allowPinchZoom:!0,children:e.jsx(Tre,{asChild:!0,trapped:b.open,onMountAutoFocus:ge=>{ge.preventDefault()},onUnmountAutoFocus:wa(a,ge=>{var Ee;(Ee=b.trigger)==null||Ee.focus({preventScroll:!0}),ge.preventDefault()}),children:e.jsx(pL,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:ge=>ge.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:e.jsx(me,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:ge=>ge.preventDefault(),...y,...he,onPlaced:()=>V(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...y.style},onKeyDown:wa(y.onKeyDown,ge=>{const Ee=ge.ctrlKey||ge.altKey||ge.metaKey;if(ge.key==="Tab"&&ge.preventDefault(),!Ee&&ge.key.length===1&&J(ge.key),["ArrowUp","ArrowDown","Home","End"].includes(ge.key)){let Pe=q().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(ge.key)&&(Pe=Pe.slice().reverse()),["ArrowUp","ArrowDown"].includes(ge.key)){const Oe=ge.target,ke=Pe.indexOf(Oe);Pe=Pe.slice(ke+1)}setTimeout(()=>K(Pe)),ge.preventDefault()}})})})})})})});JDt.displayName=i3s;var l3s="SelectItemAlignedPosition",eRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=vL(a9,n),l=bL(a9,n),[o,c]=_.useState(null),[d,u]=_.useState(null),h=el(t,P=>u(P)),m=kPe(n),p=_.useRef(!1),f=_.useRef(!0),{viewport:g,selectedItem:v,selectedItemText:y,focusSelectedItem:b}=l,w=_.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&g&&v&&y){const P=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),I=i.valueNode.getBoundingClientRect(),D=y.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=D.left-M.left,ke=I.left-Oe,Ve=P.left-ke,_e=P.width+Ve,Ae=Math.max(_e,M.width),Se=window.innerWidth-Ak,We=dte(ke,[Ak,Math.max(Ak,Se-Ae)]);o.style.minWidth=_e+"px",o.style.left=We+"px"}else{const Oe=M.right-D.right,ke=window.innerWidth-I.right-Oe,Ve=window.innerWidth-P.right-ke,_e=P.width+Ve,Ae=Math.max(_e,M.width),Se=window.innerWidth-Ak,We=dte(ke,[Ak,Math.max(Ak,Se-Ae)]);o.style.minWidth=_e+"px",o.style.right=We+"px"}const F=m(),q=window.innerHeight-Ak*2,G=g.scrollHeight,V=window.getComputedStyle(d),H=parseInt(V.borderTopWidth,10),K=parseInt(V.paddingTop,10),Z=parseInt(V.borderBottomWidth,10),oe=parseInt(V.paddingBottom,10),re=H+K+G+oe+Z,ae=Math.min(v.offsetHeight*5,re),J=window.getComputedStyle(g),te=parseInt(J.paddingTop,10),ce=parseInt(J.paddingBottom,10),ve=P.top+P.height/2-Ak,me=q-ve,he=v.offsetHeight/2,ge=v.offsetTop+he,Ee=H+K+ge,Ne=re-Ee;if(Ee<=ve){const Oe=F.length>0&&v===F[F.length-1].ref.current;o.style.bottom="0px";const ke=d.clientHeight-g.offsetTop-g.offsetHeight,Ve=Math.max(me,he+(Oe?ce:0)+ke+Z),_e=Ee+Ve;o.style.height=_e+"px"}else{const Oe=F.length>0&&v===F[0].ref.current;o.style.top="0px";const Ve=Math.max(ve,H+g.offsetTop+(Oe?te:0)+he)+Ne;o.style.height=Ve+"px",g.scrollTop=Ee-ve+g.offsetTop}o.style.margin=`${Ak}px 0`,o.style.minHeight=ae+"px",o.style.maxHeight=q+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[m,i.trigger,i.valueNode,o,d,g,v,y,i.dir,r]);Rx(()=>w(),[w]);const[S,C]=_.useState();Rx(()=>{d&&C(window.getComputedStyle(d).zIndex)},[d]);const E=_.useCallback(P=>{P&&f.current===!0&&(w(),b==null||b(),f.current=!1)},[w,b]);return e.jsx(d3s,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:p,onScrollButtonChange:E,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:e.jsx(ci.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});eRt.displayName=l3s;var c3s="SelectPopperPosition",Qqe=_.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=Ak,...i}=s,l=SPe(n);return e.jsx(Ore,{...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)"}})});Qqe.displayName=c3s;var[d3s,hJe]=fW(a9,{}),Jqe="SelectViewport",tRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=bL(Jqe,n),l=hJe(Jqe,n),o=el(t,i.onViewportChange),c=_.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(NPe.Slot,{scope:n,children:e.jsx(ci.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:wa(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=l;if(m!=null&&m.current&&h){const p=Math.abs(c.current-u.scrollTop);if(p>0){const f=window.innerHeight-Ak*2,g=parseFloat(h.style.minHeight),v=parseFloat(h.style.height),y=Math.max(g,v);if(y0?S:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});tRt.displayName=Jqe;var sRt="SelectGroup",[u3s,h3s]=fW(sRt),nRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=qg();return e.jsx(u3s,{scope:n,id:a,children:e.jsx(ci.div,{role:"group","aria-labelledby":a,...r,ref:t})})});nRt.displayName=sRt;var rRt="SelectLabel",aRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=h3s(rRt,n);return e.jsx(ci.div,{id:a.id,...r,ref:t})});aRt.displayName=rRt;var _Ae="SelectItem",[m3s,iRt]=fW(_Ae),oRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=vL(_Ae,n),c=bL(_Ae,n),d=o.value===r,[u,h]=_.useState(i??""),[m,p]=_.useState(!1),f=el(t,b=>{var w;return(w=c.itemRefCallback)==null?void 0:w.call(c,b,r,a)}),g=qg(),v=_.useRef("touch"),y=()=>{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(m3s,{scope:n,value:r,disabled:a,textId:g,isSelected:d,onItemTextChange:_.useCallback(b=>{h(w=>w||((b==null?void 0:b.textContent)??"").trim())},[]),children:e.jsx(NPe.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(ci.div,{role:"option","aria-labelledby":g,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:f,onFocus:wa(l.onFocus,()=>p(!0)),onBlur:wa(l.onBlur,()=>p(!1)),onClick:wa(l.onClick,()=>{v.current!=="mouse"&&y()}),onPointerUp:wa(l.onPointerUp,()=>{v.current==="mouse"&&y()}),onPointerDown:wa(l.onPointerDown,b=>{v.current=b.pointerType}),onPointerMove:wa(l.onPointerMove,b=>{var w;v.current=b.pointerType,a?(w=c.onItemLeave)==null||w.call(c):v.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:wa(l.onPointerLeave,b=>{var w;b.currentTarget===document.activeElement&&((w=c.onItemLeave)==null||w.call(c))}),onKeyDown:wa(l.onKeyDown,b=>{var S;((S=c.searchRef)==null?void 0:S.current)!==""&&b.key===" "||(JCs.includes(b.key)&&y(),b.key===" "&&b.preventDefault())})})})})});oRt.displayName=_Ae;var _X="SelectItemText",lRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=vL(_X,n),o=bL(_X,n),c=iRt(_X,n),d=n3s(_X,n),[u,h]=_.useState(null),m=el(t,y=>h(y),c.onItemTextChange,y=>{var b;return(b=o.itemTextRefCallback)==null?void 0:b.call(o,y,c.value,c.disabled)}),p=u==null?void 0:u.textContent,f=_.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:v}=d;return Rx(()=>(g(f),()=>v(f)),[g,v,f]),e.jsxs(e.Fragment,{children:[e.jsx(ci.span,{id:c.textId,...i,ref:m}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?pv.createPortal(i.children,l.valueNode):null]})});lRt.displayName=_X;var cRt="SelectItemIndicator",dRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return iRt(cRt,n).isSelected?e.jsx(ci.span,{"aria-hidden":!0,...r,ref:t}):null});dRt.displayName=cRt;var eVe="SelectScrollUpButton",uRt=_.forwardRef((s,t)=>{const n=bL(eVe,s.__scopeSelect),r=hJe(eVe,s.__scopeSelect),[a,i]=_.useState(!1),l=el(t,r.onScrollButtonChange);return Rx(()=>{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(mRt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});uRt.displayName=eVe;var tVe="SelectScrollDownButton",hRt=_.forwardRef((s,t)=>{const n=bL(tVe,s.__scopeSelect),r=hJe(tVe,s.__scopeSelect),[a,i]=_.useState(!1),l=el(t,r.onScrollButtonChange);return Rx(()=>{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(mRt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});hRt.displayName=tVe;var mRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=bL("SelectScrollButton",n),l=_.useRef(null),o=kPe(n),c=_.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return _.useEffect(()=>()=>c(),[c]),Rx(()=>{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(ci.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:wa(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:wa(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:wa(a.onPointerLeave,()=>{c()})})}),p3s="SelectSeparator",pRt=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(ci.div,{"aria-hidden":!0,...r,ref:t})});pRt.displayName=p3s;var sVe="SelectArrow",f3s=_.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=SPe(n),i=vL(sVe,n),l=bL(sVe,n);return i.open&&l.position==="popper"?e.jsx(zre,{...a,...r,ref:t}):null});f3s.displayName=sVe;var x3s="SelectBubbleInput",fRt=_.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=_.useRef(null),i=el(r,a),l=Jre(t);return _.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(ci.select,{...n,style:{...gMt,...n.style},ref:i,defaultValue:t})});fRt.displayName=x3s;function xRt(s){return s===""||s===void 0}function gRt(s){const t=Ax(s),n=_.useRef(""),r=_.useRef(0),a=_.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=_.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return _.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function yRt(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=g3s(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 g3s(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var y3s=VDt,vRt=GDt,v3s=KDt,b3s=YDt,_3s=ZDt,bRt=XDt,w3s=tRt,j3s=nRt,_Rt=aRt,wRt=oRt,N3s=lRt,k3s=dRt,jRt=uRt,NRt=hRt,kRt=pRt;const ls=y3s,S3s=j3s,cs=v3s,rs=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(vRt,{ref:r,className:Ct("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(b3s,{asChild:!0,children:e.jsx(cl,{className:"h-4 w-4 opacity-50"})})]}));rs.displayName=vRt.displayName;const SRt=_.forwardRef(({className:s,...t},n)=>e.jsx(jRt,{ref:n,className:Ct("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(h1,{className:"h-4 w-4"})}));SRt.displayName=jRt.displayName;const CRt=_.forwardRef(({className:s,...t},n)=>e.jsx(NRt,{ref:n,className:Ct("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(cl,{className:"h-4 w-4"})}));CRt.displayName=NRt.displayName;const as=_.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(_3s,{children:e.jsxs(bRt,{ref:a,className:Ct("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(SRt,{}),e.jsx(w3s,{className:Ct("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(CRt,{})]})}));as.displayName=bRt.displayName;const ARt=_.forwardRef(({className:s,...t},n)=>e.jsx(_Rt,{ref:n,className:Ct("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));ARt.displayName=_Rt.displayName;const He=_.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(wRt,{ref:r,className:Ct("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(k3s,{children:e.jsx(Wr,{className:"h-4 w-4"})})}),e.jsx(N3s,{children:t})]}));He.displayName=wRt.displayName;const C3s=_.forwardRef(({className:s,...t},n)=>e.jsx(kRt,{ref:n,className:Ct("-mx-1 my-1 h-px bg-muted",s),...t}));C3s.displayName=kRt.displayName;const A3s=Gj({category:uJe(["general","technology","crm","marketing"]),subject:Jo().min(5,"Subject must be at least 5 characters").max(200),description:Jo().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),E3s={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function nVe({trigger:s}){const[t,n]=_.useState(!1),[r,a]=_.useState(!1),{user:i}=hs(),l=gPe({resolver:yPe(A3s),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ne.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await U.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await U.functions.invoke("support-ticket-notify",{body:{category:E3s[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ne.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ne.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(Is,{open:t,onOpenChange:n,children:[e.jsx(rl,{asChild:!0,children:s||e.jsxs(z,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(JQ,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Ls,{className:"sm:max-w-[500px]",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Need Help?"}),e.jsx(_r,{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(va,{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(wPe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Mf,{control:l.control,name:"category",render:({field:c})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Category"}),e.jsxs(ls,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(sf,{children:e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a category"})})}),e.jsxs(as,{children:[e.jsx(He,{value:"general",children:"General Support"}),e.jsx(He,{value:"technology",children:"Technology Support"}),e.jsx(He,{value:"crm",children:"CRM Support"}),e.jsx(He,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(hb,{})]})}),e.jsx(Mf,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Subject"}),e.jsx(sf,{children:e.jsx(pe,{placeholder:"Brief description of your issue",...c})}),e.jsx(hb,{})]})}),e.jsx(Mf,{control:l.control,name:"description",render:({field:c})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Description"}),e.jsx(sf,{children:e.jsx(Ps,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(hb,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}function fo(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 qh(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Uh(s,t){const n=fo(s);return isNaN(t)?qh(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function A0(s,t){const n=fo(s);if(isNaN(t))return qh(s,NaN);if(!t)return n;const r=n.getDate(),a=qh(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 ERt(s,t){const n=+fo(s);return qh(s,n+t)}const mJe=6048e5,T3s=864e5,CPe=6e4,APe=36e5,M3s=1e3,wle=43200,rft=1440;function aft(s,t){return ERt(s,t*APe)}let P3s={};function _L(){return P3s}function v1(s,t){var o,c,d,u;const n=_L(),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=fo(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function zf(s){const t=fo(s);return t.setHours(0,0,0,0),t}function VP(s){const t=fo(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 fv(s,t){const n=zf(s),r=zf(t),a=+n-VP(n),i=+r-VP(r);return Math.round((a-i)/T3s)}function L3s(s){const t=TRt(s),n=qh(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),SE(n)}function ift(s,t){return ERt(s,t*CPe)}function bF(s,t){const n=t*7;return Uh(s,n)}function I3s(s,t){return A0(s,t*12)}function D3s(s){let t;return s.forEach(function(n){const r=fo(n);(t===void 0||t{const r=fo(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function P4e(s,t){const n=fo(s),r=fo(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function EPe(s){return qh(s,Date.now())}function hm(s,t){const n=zf(s),r=zf(t);return+n==+r}function pJe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function rVe(s){if(!pJe(s)&&typeof s!="number")return!1;const t=fo(s);return!isNaN(Number(t))}function DH(s,t){const n=fo(s),r=fo(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function F3s(s,t,n){const r=v1(s,n),a=v1(t,n),i=+r-VP(r),l=+a-VP(a);return Math.round((i-l)/mJe)}function PN(s,t){const n=fo(s),r=fo(t),a=oft(n,r),i=Math.abs(fv(n,r));n.setDate(n.getDate()-a*i);const l=+(oft(n,r)===-a),o=a*(i-l);return o===0?0:o}function oft(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 O3s(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function z3s(s,t){return+fo(s)-+fo(t)}function B3s(s){const t=fo(s);return t.setHours(23,59,59,999),t}function b_(s){const t=fo(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function $3s(s){const t=fo(s);return+B3s(t)==+b_(t)}function U3s(s,t){const n=fo(s),r=fo(t),a=P4e(n,r),i=Math.abs(DH(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=P4e(n,r)===-a;$3s(fo(s))&&i===1&&P4e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function q3s(s,t,n){const r=z3s(s,t)/1e3;return O3s(n==null?void 0:n.roundingMethod)(r)}function V3s(s,t){const n=fo(s.start),r=fo(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(fo(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function H3s(s){const t=fo(s),n=t.getMonth(),r=n-n%3;return t.setMonth(r,1),t.setHours(0,0,0,0),t}function om(s){const t=fo(s);return t.setDate(1),t.setHours(0,0,0,0),t}function fJe(s){const t=fo(s),n=qh(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function TPe(s,t){var o,c,d,u;const n=_L(),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=fo(s),i=a.getDay(),l=(i{let r;const a=G3s[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 AOe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const K3s={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Y3s={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Z3s={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},X3s={date:AOe({formats:K3s,defaultWidth:"full"}),time:AOe({formats:Y3s,defaultWidth:"full"}),dateTime:AOe({formats:Z3s,defaultWidth:"full"})},Q3s={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},J3s=(s,t,n,r)=>Q3s[s];function qY(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 eAs={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},tAs={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},sAs={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"]},nAs={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"]},rAs={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"}},aAs={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"}},iAs=(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"},oAs={ordinalNumber:iAs,era:qY({values:eAs,defaultWidth:"wide"}),quarter:qY({values:tAs,defaultWidth:"wide",argumentCallback:s=>s-1}),month:qY({values:sAs,defaultWidth:"wide"}),day:qY({values:nAs,defaultWidth:"wide"}),dayPeriod:qY({values:rAs,defaultWidth:"wide",formattingValues:aAs,defaultFormattingWidth:"wide"})};function VY(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)?cAs(o,h=>h.test(l)):lAs(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 lAs(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function cAs(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 uAs=/^(\d+)(th|st|nd|rd)?/i,hAs=/\d+/i,mAs={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},pAs={any:[/^b/i,/^(a|c)/i]},fAs={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},xAs={any:[/1/i,/2/i,/3/i,/4/i]},gAs={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},yAs={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]},vAs={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},bAs={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]},_As={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},wAs={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}},jAs={ordinalNumber:dAs({matchPattern:uAs,parsePattern:hAs,valueCallback:s=>parseInt(s,10)}),era:VY({matchPatterns:mAs,defaultMatchWidth:"wide",parsePatterns:pAs,defaultParseWidth:"any"}),quarter:VY({matchPatterns:fAs,defaultMatchWidth:"wide",parsePatterns:xAs,defaultParseWidth:"any",valueCallback:s=>s+1}),month:VY({matchPatterns:gAs,defaultMatchWidth:"wide",parsePatterns:yAs,defaultParseWidth:"any"}),day:VY({matchPatterns:vAs,defaultMatchWidth:"wide",parsePatterns:bAs,defaultParseWidth:"any"}),dayPeriod:VY({matchPatterns:_As,defaultMatchWidth:"any",parsePatterns:wAs,defaultParseWidth:"any"})},MPe={code:"en-US",formatDistance:W3s,formatLong:X3s,formatRelative:J3s,localize:oAs,match:jAs,options:{weekStartsOn:0,firstWeekContainsDate:1}};function NAs(s){const t=fo(s);return fv(t,fJe(t))+1}function xJe(s){const t=fo(s),n=+SE(t)-+L3s(t);return Math.round(n/mJe)+1}function gJe(s,t){var u,h,m,p;const n=fo(s),r=n.getFullYear(),a=_L(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((p=(m=a.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=qh(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=v1(l,t),c=qh(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=v1(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function kAs(s,t){var o,c,d,u;const n=_L(),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=gJe(s,t),i=qh(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),v1(i,t)}function yJe(s,t){const n=fo(s),r=+v1(n,t)-+kAs(n,t);return Math.round(r/mJe)+1}function zh(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const ST={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return zh(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):zh(n+1,2)},d(s,t){return zh(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 zh(s.getHours()%12||12,t.length)},H(s,t){return zh(s.getHours(),t.length)},m(s,t){return zh(s.getMinutes(),t.length)},s(s,t){return zh(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return zh(a,t.length)}},CB={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},lft={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 ST.y(s,t)},Y:function(s,t,n,r){const a=gJe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return zh(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):zh(i,t.length)},R:function(s,t){const n=TRt(s);return zh(n,t.length)},u:function(s,t){const n=s.getFullYear();return zh(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 zh(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 zh(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 ST.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 zh(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=yJe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):zh(a,t.length)},I:function(s,t,n){const r=xJe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):zh(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):ST.d(s,t)},D:function(s,t,n){const r=NAs(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):zh(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 zh(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 zh(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 zh(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=CB.noon:r===0?a=CB.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=CB.evening:r>=12?a=CB.afternoon:r>=4?a=CB.morning:a=CB.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 ST.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):ST.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):zh(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):zh(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):ST.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):ST.s(s,t)},S:function(s,t){return ST.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return dft(r);case"XXXX":case"XX":return WR(r);case"XXXXX":case"XXX":default:return WR(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return dft(r);case"xxxx":case"xx":return WR(r);case"xxxxx":case"xxx":default:return WR(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+cft(r,":");case"OOOO":default:return"GMT"+WR(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+cft(r,":");case"zzzz":default:return"GMT"+WR(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return zh(r,t.length)},T:function(s,t,n){const r=s.getTime();return zh(r,t.length)}};function cft(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+zh(i,2)}function dft(s,t){return s%60===0?(s>0?"-":"+")+zh(Math.abs(s)/60,2):WR(s,t)}function WR(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=zh(Math.trunc(r/60),2),i=zh(r%60,2);return n+a+t+i}const uft=(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"})}},PRt=(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"})}},SAs=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return uft(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}}",uft(r,t)).replace("{{time}}",PRt(a,t))},aVe={p:PRt,P:SAs},CAs=/^D+$/,AAs=/^Y+$/,EAs=["D","DD","YY","YYYY"];function LRt(s){return CAs.test(s)}function IRt(s){return AAs.test(s)}function iVe(s,t,n){const r=TAs(s,t,n);if(console.warn(r),EAs.includes(s))throw new RangeError(r)}function TAs(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 MAs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,PAs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,LAs=/^'([^]*?)'?$/,IAs=/''/g,DAs=/[a-zA-Z]/;function Ys(s,t,n){var u,h,m,p,f,g,v,y;const r=_L(),a=(n==null?void 0:n.locale)??r.locale??MPe,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((p=(m=r.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((g=(f=n==null?void 0:n.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??r.weekStartsOn??((y=(v=r.locale)==null?void 0:v.options)==null?void 0:y.weekStartsOn)??0,o=fo(s);if(!rVe(o))throw new RangeError("Invalid time value");let c=t.match(PAs).map(b=>{const w=b[0];if(w==="p"||w==="P"){const S=aVe[w];return S(b,a.formatLong)}return b}).join("").match(MAs).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const w=b[0];if(w==="'")return{isToken:!1,value:RAs(b)};if(lft[w])return{isToken:!0,value:b};if(w.match(DAs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+w+"`");return{isToken:!1,value:b}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(b=>{if(!b.isToken)return b.value;const w=b.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&IRt(w)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&LRt(w))&&iVe(w,t,String(s));const S=lft[w[0]];return S(o,w,a.localize,d)}).join("")}function RAs(s){const t=s.match(LAs);return t?t[1].replace(IAs,"'"):s}function FAs(s,t,n){const r=_L(),a=(n==null?void 0:n.locale)??r.locale??MPe,i=2520,l=P4e(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=fo(t),d=fo(s)):(c=fo(s),d=fo(t));const u=q3s(d,c),h=(VP(d)-VP(c))/1e3,m=Math.round((u-h)/60);let p;if(m<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):m===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",m,o);if(m<45)return a.formatDistance("xMinutes",m,o);if(m<90)return a.formatDistance("aboutXHours",1,o);if(mr.getTime()}function wS(s,t){const n=fo(s),r=fo(t);return+n<+r}function VAs(s){return+fo(s)>Date.now()}function HAs(s,t){const n=t instanceof Date?qh(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 GAs=10;class DRt{constructor(){zr(this,"subPriority",0)}validate(t,n){return!0}}class WAs extends DRt{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 KAs extends DRt{constructor(){super(...arguments);zr(this,"priority",GAs);zr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:qh(n,HAs(n,Date))}}class dh{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new WAs(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class YAs extends dh{constructor(){super(...arguments);zr(this,"priority",140);zr(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 mg={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}/},C4={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 pg(s,t){return s&&{value:t(s.value),rest:s.rest}}function Of(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function A4(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*APe+i*CPe+l*M3s),rest:t.slice(n[0].length)}}function RRt(s){return Of(mg.anyDigitsSigned,s)}function Fx(s,t){switch(s){case 1:return Of(mg.singleDigit,t);case 2:return Of(mg.twoDigits,t);case 3:return Of(mg.threeDigits,t);case 4:return Of(mg.fourDigits,t);default:return Of(new RegExp("^\\d{1,"+s+"}"),t)}}function wAe(s,t){switch(s){case 1:return Of(mg.singleDigitSigned,t);case 2:return Of(mg.twoDigitsSigned,t);case 3:return Of(mg.threeDigitsSigned,t);case 4:return Of(mg.fourDigitsSigned,t);default:return Of(new RegExp("^-?\\d{1,"+s+"}"),t)}}function vJe(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 FRt(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 ORt(s){return s%400===0||s%4===0&&s%100!==0}class ZAs extends dh{constructor(){super(...arguments);zr(this,"priority",130);zr(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 pg(Fx(4,n),i);case"yo":return pg(a.ordinalNumber(n,{unit:"year"}),i);default:return pg(Fx(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=FRt(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 XAs extends dh{constructor(){super(...arguments);zr(this,"priority",130);zr(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 pg(Fx(4,n),i);case"Yo":return pg(a.ordinalNumber(n,{unit:"year"}),i);default:return pg(Fx(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=gJe(n,i);if(a.isTwoDigitYear){const c=FRt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),v1(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),v1(n,i)}}class QAs extends dh{constructor(){super(...arguments);zr(this,"priority",130);zr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return wAe(r==="R"?4:r.length,n)}set(n,r,a){const i=qh(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),SE(i)}}class JAs extends dh{constructor(){super(...arguments);zr(this,"priority",130);zr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return wAe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class eEs extends dh{constructor(){super(...arguments);zr(this,"priority",120);zr(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 Fx(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 tEs extends dh{constructor(){super(...arguments);zr(this,"priority",120);zr(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 Fx(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 sEs extends dh{constructor(){super(...arguments);zr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);zr(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return pg(Of(mg.month,n),i);case"MM":return pg(Fx(2,n),i);case"Mo":return pg(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 nEs extends dh{constructor(){super(...arguments);zr(this,"priority",110);zr(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 pg(Of(mg.month,n),i);case"LL":return pg(Fx(2,n),i);case"Lo":return pg(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 rEs(s,t,n){const r=fo(s),a=yJe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class aEs extends dh{constructor(){super(...arguments);zr(this,"priority",100);zr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Of(mg.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Fx(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return v1(rEs(n,a,i),i)}}function iEs(s,t){const n=fo(s),r=xJe(n)-t;return n.setDate(n.getDate()-r*7),n}class oEs extends dh{constructor(){super(...arguments);zr(this,"priority",100);zr(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 Of(mg.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Fx(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return SE(iEs(n,a))}}const lEs=[31,28,31,30,31,30,31,31,30,31,30,31],cEs=[31,29,31,30,31,30,31,31,30,31,30,31];class dEs extends dh{constructor(){super(...arguments);zr(this,"priority",90);zr(this,"subPriority",1);zr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Of(mg.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Fx(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=ORt(a),l=n.getMonth();return i?r>=1&&r<=cEs[l]:r>=1&&r<=lEs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class uEs extends dh{constructor(){super(...arguments);zr(this,"priority",90);zr(this,"subpriority",1);zr(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 Of(mg.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Fx(r.length,n)}}validate(n,r){const a=n.getFullYear();return ORt(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 bJe(s,t,n){var h,m,p,f;const r=_L(),a=(n==null?void 0:n.weekStartsOn)??((m=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((f=(p=r.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,i=fo(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 Uh(i,u)}class hEs extends dh{constructor(){super(...arguments);zr(this,"priority",90);zr(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=bJe(n,a,i),n.setHours(0,0,0,0),n}}class mEs extends dh{constructor(){super(...arguments);zr(this,"priority",90);zr(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 pg(Fx(r.length,n),l);case"eo":return pg(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=bJe(n,a,i),n.setHours(0,0,0,0),n}}class pEs extends dh{constructor(){super(...arguments);zr(this,"priority",90);zr(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 pg(Fx(r.length,n),l);case"co":return pg(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=bJe(n,a,i),n.setHours(0,0,0,0),n}}function fEs(s,t){const n=fo(s),r=BAs(n),a=t-r;return Uh(n,a)}class xEs extends dh{constructor(){super(...arguments);zr(this,"priority",90);zr(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 Fx(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return pg(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 pg(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return pg(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return pg(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=fEs(n,a),n.setHours(0,0,0,0),n}}class gEs extends dh{constructor(){super(...arguments);zr(this,"priority",80);zr(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(vJe(a),0,0,0),n}}class yEs extends dh{constructor(){super(...arguments);zr(this,"priority",80);zr(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(vJe(a),0,0,0),n}}class vEs extends dh{constructor(){super(...arguments);zr(this,"priority",80);zr(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(vJe(a),0,0,0),n}}class bEs extends dh{constructor(){super(...arguments);zr(this,"priority",70);zr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Of(mg.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Fx(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 _Es extends dh{constructor(){super(...arguments);zr(this,"priority",70);zr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Of(mg.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Fx(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class wEs extends dh{constructor(){super(...arguments);zr(this,"priority",70);zr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Of(mg.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Fx(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 jEs extends dh{constructor(){super(...arguments);zr(this,"priority",70);zr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Of(mg.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Fx(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 NEs extends dh{constructor(){super(...arguments);zr(this,"priority",60);zr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Of(mg.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Fx(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class kEs extends dh{constructor(){super(...arguments);zr(this,"priority",50);zr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Of(mg.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Fx(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class SEs extends dh{constructor(){super(...arguments);zr(this,"priority",30);zr(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return pg(Fx(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class CEs extends dh{constructor(){super(...arguments);zr(this,"priority",10);zr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return A4(C4.basicOptionalMinutes,n);case"XX":return A4(C4.basic,n);case"XXXX":return A4(C4.basicOptionalSeconds,n);case"XXXXX":return A4(C4.extendedOptionalSeconds,n);case"XXX":default:return A4(C4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:qh(n,n.getTime()-VP(n)-a)}}class AEs extends dh{constructor(){super(...arguments);zr(this,"priority",10);zr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return A4(C4.basicOptionalMinutes,n);case"xx":return A4(C4.basic,n);case"xxxx":return A4(C4.basicOptionalSeconds,n);case"xxxxx":return A4(C4.extendedOptionalSeconds,n);case"xxx":default:return A4(C4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:qh(n,n.getTime()-VP(n)-a)}}class EEs extends dh{constructor(){super(...arguments);zr(this,"priority",40);zr(this,"incompatibleTokens","*")}parse(n){return RRt(n)}set(n,r,a){return[qh(n,a*1e3),{timestampIsSet:!0}]}}class TEs extends dh{constructor(){super(...arguments);zr(this,"priority",20);zr(this,"incompatibleTokens","*")}parse(n){return RRt(n)}set(n,r,a){return[qh(n,a),{timestampIsSet:!0}]}}const MEs={G:new YAs,y:new ZAs,Y:new XAs,R:new QAs,u:new JAs,Q:new eEs,q:new tEs,M:new sEs,L:new nEs,w:new aEs,I:new oEs,d:new dEs,D:new uEs,E:new hEs,e:new mEs,c:new pEs,i:new xEs,a:new gEs,b:new yEs,B:new vEs,h:new bEs,H:new _Es,K:new wEs,k:new jEs,m:new NEs,s:new kEs,S:new SEs,X:new CEs,x:new AEs,t:new EEs,T:new TEs},PEs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,LEs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,IEs=/^'([^]*?)'?$/,DEs=/''/g,REs=/\S/,FEs=/[a-zA-Z]/;function _Je(s,t,n,r){var g,v,y,b;const a=zAs(),i=a.locale??MPe,l=a.firstWeekContainsDate??((v=(g=a.locale)==null?void 0:g.options)==null?void 0:v.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(y=a.locale)==null?void 0:y.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?fo(n):qh(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new KAs],u=t.match(LEs).map(w=>{const S=w[0];if(S in aVe){const C=aVe[S];return C(w,i.formatLong)}return w}).join("").match(PEs),h=[];for(let w of u){IRt(w)&&iVe(w,t,s),LRt(w)&&iVe(w,t,s);const S=w[0],C=MEs[S];if(C){const{incompatibleTokens:E}=C;if(Array.isArray(E)){const M=h.find(I=>E.includes(I.token)||I.token===S);if(M)throw new RangeError(`The format string mustn't contain \`${M.fullToken}\` and \`${w}\` at the same time`)}else if(C.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${w}\` and any other token at the same time`);h.push({token:S,fullToken:w});const P=C.run(s,w,i.match,c);if(!P)return qh(n,NaN);d.push(P.setter),s=P.rest}else{if(S.match(FEs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");if(w==="''"?w="'":S==="'"&&(w=OEs(w)),s.indexOf(w)===0)s=s.slice(w.length);else return qh(n,NaN)}}if(s.length>0&&REs.test(s))return qh(n,NaN);const m=d.map(w=>w.priority).sort((w,S)=>S-w).filter((w,S,C)=>C.indexOf(w)===S).map(w=>d.filter(S=>S.priority===w).sort((S,C)=>C.subPriority-S.subPriority)).map(w=>w[0]);let p=fo(n);if(isNaN(p.getTime()))return qh(n,NaN);const f={};for(const w of m){if(!w.validate(p,c))return qh(n,NaN);const S=w.set(p,f,c);Array.isArray(S)?(p=S[0],Object.assign(f,S[1])):p=S}return qh(n,p)}function OEs(s){return s.match(IEs)[1].replace(DEs,"'")}function sC(s){return+fo(s)i-l);return n>=r&&n<=a}function L4e(s,t){return Uh(s,-t)}function x0(s,t){const r=GEs(s);let a;if(r.date){const c=WEs(r.date,2);a=KEs(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=YEs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=ZEs(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 jle={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},qEs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,VEs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,HEs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function GEs(s){const t={},n=s.split(jle.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],jle.timeZoneDelimiter.test(t.date)&&(t.date=s.split(jle.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=jle.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function WEs(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 KEs(s,t){if(t===null)return new Date(NaN);const n=s.match(qEs);if(!n)return new Date(NaN);const r=!!n[4],a=HY(n[1]),i=HY(n[2])-1,l=HY(n[3]),o=HY(n[4]),c=HY(n[5])-1;if(r)return tTs(t,o,c)?XEs(t,o,c):new Date(NaN);{const d=new Date(0);return!JEs(t,i,l)||!eTs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function HY(s){return s?parseInt(s):1}function YEs(s){const t=s.match(VEs);if(!t)return NaN;const n=EOe(t[1]),r=EOe(t[2]),a=EOe(t[3]);return sTs(n,r,a)?n*APe+r*CPe+a*1e3:NaN}function EOe(s){return s&&parseFloat(s.replace(",","."))||0}function ZEs(s){if(s==="Z")return 0;const t=s.match(HEs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return nTs(r,a)?n*(r*APe+a*CPe):NaN}function XEs(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 QEs=[31,null,31,30,31,30,31,31,30,31,30,31];function zRt(s){return s%400===0||s%4===0&&s%100!==0}function JEs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(QEs[t]||(zRt(s)?29:28))}function eTs(s,t){return t>=1&&t<=(zRt(s)?366:365)}function tTs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function sTs(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function nTs(s,t){return t>=0&&t<=59}function TOe(s,t){const n=fo(s),r=n.getFullYear(),a=n.getDate(),i=qh(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=OAs(i);return n.setMonth(t,Math.min(a,l)),n}function BRt(s,t){const n=fo(s);return n.setHours(t),n}function $Rt(s,t){const n=fo(s);return n.setMinutes(t),n}function mft(s,t){const n=fo(s);return isNaN(+n)?qh(s,NaN):(n.setFullYear(t),n)}function _F(s,t){return A0(s,-t)}const rTs=()=>{const{user:s}=hs(),t=zn(),[n,r]=_.useState([]),[a,i]=_.useState(0),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null);_.useEffect(()=>{u.current=c},[c]),_.useEffect(()=>{if(!s)return;const g=`notification_last_read_${s.id}`,v=localStorage.getItem(g);v&&!u.current&&(u.current=v,d(v));const y=`nb_cache_${s.id}`,b=60*1e3,w=async()=>{try{const M=sessionStorage.getItem(y);if(M){const I=JSON.parse(M);if(I.ts&&Date.now()-I.ts{r(E);const P=u.current?new Date(u.current):null,M=E.filter(I=>P?new Date(I.created_at)>P:!0);i(M.length)};w();const C=U.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},E=>{const P=E.new;r(I=>{const D=[P,...I].slice(0,20);try{sessionStorage.setItem(y,JSON.stringify({ts:Date.now(),data:D}))}catch{}return D});const M=u.current?new Date(u.current):null;(!M||new Date(P.created_at)>M)&&i(I=>I+1),Notification.permission==="granted"&&new Notification(P.title,{body:P.body,icon:"/favicon.ico"})}).subscribe();return()=>{U.removeChannel(C)}},[s]);const h=g=>{const v=g.toLowerCase();return v.includes("community")||v.includes("post")?qi:v.includes("academy")||v.includes("video")?Xr:v.includes("template")?yc:v.includes("event")?ya:v.includes("newsletter")?vN:v.includes("brokerage")?Px:v.includes("swag")||v.includes("social")?Ko:v.includes("toolbox")||v.includes("tool")?eC:v.includes("brief")?un:qi},m=g=>{o(!1),g.url&&g.url!=="/"&&t(g.url)},p=()=>{if(!s)return;const g=new Date().toISOString(),v=`notification_last_read_${s.id}`;localStorage.setItem(v,g),d(g),i(0)},f=g=>{o(g),g&&a>0&&p()};return e.jsxs(ru,{open:l,onOpenChange:f,children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx($g,{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(qd,{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(z,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:p,children:"Mark all read"})]}),e.jsx(Ki,{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(g=>{const v=h(g.title);return e.jsxs(ua,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(g),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:g.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:g.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Md(new Date(g.created_at),{addSuffix:!0})})]})]},g.id)})})]})]})};function aTs(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function mf(){const{user:s}=hs(),{data:t,isLoading:n}=rt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await U.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, plan_tier, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id, mls_service_cities, mls_disclaimer_text, brokerage_legal_name").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return aTs(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isFreePlan:(t==null?void 0:t.plan_tier)==="free_luxury",hasIdx:!!(t!=null&&t.mls_provider_id)&&!(t!=null&&t.no_mls_mode),isLoading:n,siteUrl:t?t.custom_domain?`https://${t.custom_domain}`:`https://${t.subdomain_slug}.thelocalmove.com`:null}}function PPe(s=!0){const{user:t}=hs(),{data:n,isLoading:r}=rt({queryKey:["free-lead-site-offer",t==null?void 0:t.id],enabled:!!t&&s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a}=await U.from("profiles").select("brokerage_id").eq("id",t.id).maybeSingle();if(!(a!=null&&a.brokerage_id))return null;const{data:i}=await U.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",a.brokerage_id).eq("enabled",!0).maybeSingle();return i??null}});return{offer:n??null,hasOffer:!!n,isLoading:r}}const iTs="coaching_access";function URt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=hs(),{data:a,isLoading:i}=rt({queryKey:["coaching-access",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const[l,o]=await Promise.all([U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1),U.from("feature_entitlements").select("enabled, expires_at").eq("user_id",s.id).eq("feature_key",iTs).maybeSingle()]),c=(l.data||[]).length>0,d=o.data,u=!!(d!=null&&d.enabled)&&(!d.expires_at||new Date(d.expires_at).getTime()>Date.now());return{hasAssignment:c,entitled:u}}});return{hasAccess:!!(n||r||a!=null&&a.hasAssignment||a!=null&&a.entitled),hasAssignment:!!(a!=null&&a.hasAssignment),isLoading:t||i}}const eu=U,jAe=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function oVe(s){return s.total_items===0?"not_started":s.rejected_items>0?"changes_requested":s.approved_items>=s.total_items?"compliant":"in_review"}const qRt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function wJe(){return rt({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:s}=await U.auth.getUser();if(!s.user)return[];const{data:t,error:n}=await eu.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",s.user.id);if(n)throw n;return t||[]}})}function oTs(s){return rt({queryKey:["transaction-admins",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("brokerage_transaction_admins").select("id, user_id, created_at").eq("brokerage_id",s);if(n)throw n;const r=t||[];if(r.length===0)return[];const{data:a}=await eu.from("profiles").select("id, name, email").in("id",r.map(l=>l.user_id)),i=new Map((a||[]).map(l=>[l.id,{name:l.name??null,email:l.email??null}]));return r.map(l=>{var o,c;return{...l,name:((o=i.get(l.user_id))==null?void 0:o.name)??null,email:((c=i.get(l.user_id))==null?void 0:c.email)??null}})}})}function lTs(){const s=$t();return mt({mutationFn:async({brokerageId:t,userId:n})=>{const{error:r}=await eu.from("brokerage_transaction_admins").insert({brokerage_id:t,user_id:n});if(r)throw r},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function cTs(){const s=$t();return mt({mutationFn:async({id:t})=>{const{error:n}=await eu.from("brokerage_transaction_admins").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function dTs(s){return rt({queryKey:["compliance-settings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("brokerage_compliance_settings").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t}})}function uTs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await eu.from("brokerage_compliance_settings").upsert(t,{onConflict:"brokerage_id"});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["compliance-settings",n.brokerage_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function VRt(s){return rt({queryKey:["compliance-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("brokerage_checklist_templates").select("*").eq("brokerage_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function hTs(s){return rt({queryKey:["compliance-template-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("brokerage_checklist_template_items").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function mTs(){const s=$t();return mt({mutationFn:async t=>{if(t.id){const{error:a}=await eu.from("brokerage_checklist_templates").update(t).eq("id",t.id);if(a)throw a;return t.id}const{data:n,error:r}=await eu.from("brokerage_checklist_templates").insert(t).select("id").single();if(r)throw r;return n.id},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerage_id]})})}function pTs(){const s=$t();return mt({mutationFn:async({id:t})=>{const{error:n}=await eu.from("brokerage_checklist_templates").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerageId]})})}function fTs(){const s=$t();return mt({mutationFn:async t=>{if(t.id){const{error:r}=await eu.from("brokerage_checklist_template_items").update(t).eq("id",t.id);if(r)throw r;return}const{error:n}=await eu.from("brokerage_checklist_template_items").insert(t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.template_id]})})}function xTs(){const s=$t();return mt({mutationFn:async({id:t})=>{const{error:n}=await eu.from("brokerage_checklist_template_items").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.templateId]})})}function jJe(s){return rt({queryKey:["compliance-deals",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.rpc("get_brokerage_compliance_deals",{_brokerage_id:s});if(n)throw n;return t||[]}})}function HRt(s){return rt({queryKey:["deal-compliance-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("deal_compliance_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function gTs(s){return rt({queryKey:["deal-compliance-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("deal_compliance_events").select("*").eq("deal_id",s).order("created_at",{ascending:!1}).limit(200);if(n)throw n;return t||[]}})}async function LPe(s){var n;const{data:t}=await U.auth.getUser();await eu.from("deal_compliance_events").insert({deal_id:s.dealId,brokerage_id:s.brokerageId??null,item_id:s.itemId??null,actor_user_id:((n=t.user)==null?void 0:n.id)??null,event_type:s.eventType,detail:s.detail??null})}function yTs(){const s=$t();return mt({mutationFn:async({item:t,status:n,note:r})=>{var l;const{data:a}=await U.auth.getUser(),{error:i}=await eu.from("deal_compliance_items").update({status:n,review_note:r??null,reviewed_by:((l=a.user)==null?void 0:l.id)??null,reviewed_at:new Date().toISOString()}).eq("id",t.id);if(i)throw i;await LPe({dealId:t.deal_id,brokerageId:t.brokerage_id,itemId:t.id,eventType:n==="approved"?"item_approved":n==="rejected"?"item_rejected":"item_updated",detail:r?`${t.title}: ${r}`:t.title})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-items",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.item.deal_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function vTs(){const s=$t();return mt({mutationFn:async({dealId:t,brokerageId:n,templateId:r,deal:a})=>{const{data:i,error:l}=await eu.from("brokerage_checklist_template_items").select("*").eq("template_id",r).order("sort_order",{ascending:!0});if(l)throw l;const o=(u,h)=>{if(!u)return null;const[m,p,f]=u.split(/[-/T]/).map(Number);return new Date(Date.UTC(m,p-1,f+(h||0))).toISOString().slice(0,10)},c=(i||[]).map(u=>({deal_id:t,brokerage_id:n,template_item_id:u.id,title:u.title,description:u.description,phase:u.phase,requires_document:u.requires_document,required_for_closing:u.required_for_closing,due_date:u.due_anchor==="contract_date"?o(a==null?void 0:a.contract_date,u.due_offset_days):u.due_anchor==="target_close_date"?o(a==null?void 0:a.target_close_date,u.due_offset_days):null,sort_order:u.sort_order}));if(c.length===0)return;const{error:d}=await eu.from("deal_compliance_items").insert(c);if(d)throw d;await LPe({dealId:t,brokerageId:n,eventType:"checklist_applied",detail:`${c.length} items added`})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-items",n.dealId]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.dealId]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function bTs(s){return rt({queryKey:["deal-compliance-files",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("deal_files").select("id, deal_id, compliance_item_id, file_name, file_size, storage_path, version_no, is_current, created_at, owner_user_id").eq("deal_id",s).not("compliance_item_id","is",null).order("version_no",{ascending:!1});if(n)throw n;return t||[]}})}function _Ts(){const s=$t();return mt({mutationFn:async({item:t,file:n})=>{var h,m;const{data:r}=await U.auth.getUser(),a=(h=r.user)==null?void 0:h.id;if(!a)throw new Error("Not signed in");const{data:i}=await eu.from("deal_files").select("id, version_no").eq("compliance_item_id",t.id).order("version_no",{ascending:!1}).limit(1),l=(((m=i==null?void 0:i[0])==null?void 0:m.version_no)||0)+1,o=n.name.split(".").pop(),c=`${a}/${t.deal_id}/${crypto.randomUUID()}.${o}`,{error:d}=await U.storage.from("deal-files").upload(c,n);if(d)throw d;i!=null&&i.length&&await eu.from("deal_files").update({is_current:!1}).eq("compliance_item_id",t.id);const{error:u}=await eu.from("deal_files").insert({deal_id:t.deal_id,owner_user_id:a,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:c,compliance_item_id:t.id,version_no:l,is_current:!0});if(u)throw u;await eu.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",t.id),await LPe({dealId:t.deal_id,brokerageId:t.brokerage_id,itemId:t.id,eventType:"document_uploaded",detail:`${t.title} — ${n.name} (v${l})`})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-files",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-items",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-files",n.item.deal_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}async function pft(s){const{data:t,error:n}=await U.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;window.open(t.signedUrl,"_blank","noopener,noreferrer")}function wTs(s){return rt({queryKey:["deal-compliance-messages",s],enabled:!!s,refetchInterval:3e4,queryFn:async()=>{const{data:t,error:n}=await eu.from("deal_compliance_messages").select("*").eq("deal_id",s).order("created_at",{ascending:!0});if(n)throw n;const r=t||[],a=Array.from(new Set(r.map(o=>o.sender_user_id)));if(a.length===0)return r;const{data:i}=await eu.from("profiles").select("id, name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o.name??null]));return r.map(o=>({...o,sender_name:l.get(o.sender_user_id)??null}))}})}function jTs(){const s=$t();return mt({mutationFn:async({dealId:t,brokerageId:n,body:r,senderRole:a,itemId:i})=>{var u;const{data:l}=await U.auth.getUser(),o=(u=l.user)==null?void 0:u.id;if(!o)throw new Error("Not signed in");const{data:c,error:d}=await eu.from("deal_compliance_messages").insert({deal_id:t,brokerage_id:n,sender_user_id:o,sender_role:a,item_id:i??null,body:r.trim()}).select("id").single();if(d)throw d;try{await U.functions.invoke("compliance-message-notify",{body:{messageId:c.id}})}catch(h){console.error("compliance message notify failed",h)}return c.id},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["deal-compliance-messages",n.dealId]})})}function NTs(){const s=$t();return mt({mutationFn:async({dealId:t,senderRole:n})=>{const{error:r}=await eu.from("deal_compliance_messages").update({read_at:new Date().toISOString()}).eq("deal_id",t).neq("sender_role",n).is("read_at",null);if(r)throw r},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["deal-compliance-messages",n.dealId]})})}function kTs(s){return rt({queryKey:["brokerage-agent-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await eu.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function STs(s){return rt({queryKey:["agent-pipeline-stages",s],enabled:!!s,queryFn:async()=>{const t=async()=>{const{data:r,error:a}=await eu.from("deal_pipeline_stages").select("id, name, sort_order, default_probability").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(a)throw a;return r||[]};let n=await t();if(n.length===0){const{error:r}=await eu.rpc("initialize_deal_pipeline_stages",{p_user_id:s});r||(n=await t())}return n}})}function CTs(){const s=$t();return mt({mutationFn:async t=>{const n=t.price!=null&&t.commissionPercentage!=null?Math.round(t.price*(t.commissionPercentage/100)*100)/100:null,{data:r,error:a}=await eu.from("deal_pipeline").insert({owner_user_id:t.ownerUserId,deal_name:t.dealName.trim(),deal_type:t.dealType,stage_id:t.stageId,property_address:t.propertyAddress||null,city:t.city||null,state:t.state||null,zip_code:t.zipCode||null,contract_date:t.contractDate||null,target_close_date:t.targetCloseDate||null,actual_close_date:t.actualCloseDate||null,expected_price:t.price??null,sale_price:t.actualCloseDate?t.price??null:null,commission_percentage:t.commissionPercentage??null,expected_commission:n,notes:t.notes||null}).select("id").single();if(a)throw a;const i=r.id;try{await eu.rpc("ensure_deal_compliance",{_deal_id:i})}catch(l){console.error("ensure_deal_compliance failed",l)}return await LPe({dealId:i,brokerageId:t.brokerageId,eventType:"deal_added_by_staff",detail:"Deal added by brokerage staff for the agent's pipeline"}),i},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["compliance-deals",n.brokerageId]}),s.invalidateQueries({queryKey:["deal-pipeline"]})}})}const IPe=[{id:"home",label:"Home",icon:oP,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Fo,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:gj,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:oi,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:Nh,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:Wo,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:fm,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:v7,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Vw,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:On,route:"/team",description:"Your team hub — production, pond and resources",accent:"nav-team",visible:s=>s.isOnTeam&&!s.isAdmin&&!s.isBrokerageManager},{id:"brokerage",label:"Brokerage",icon:YU,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:lb,description:"Community, marketplace and help",accent:"nav-more"}],K1=s=>t=>t.hasPermission(s),ATs=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:K4,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:K1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:un,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"contacts",label:"All Contacts",route:"/mission-control/contacts",icon:On,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:pm,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:dq,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Fr,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:Oc,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:oi,description:"Enrich property data for your contacts",primaryCategory:"crm",section:"Contacts",visible:s=>s.isAdmin,searchKeywords:["property","zillow","enrichment","intelligence","home value"],displayOrder:75},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:gc,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:K1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:cf,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:on,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:rq,description:"Buying and selling signals from your database",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["signals","intent","hot leads"],displayOrder:110},{id:"popbys",label:"Popbys",route:"/mission-control/popbys",icon:Ko,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:K1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:gj,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:fN,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:cb,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:Zw,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:wl,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:K1("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:gc,description:"Every appointment, deadline and task in one view",primaryCategory:"crm",section:"Overview",visible:()=>!0,searchKeywords:["calendar","schedule","agenda","google calendar","my calendar"],displayOrder:24},{id:"scheduler",label:"LevelUp Scheduler",route:"/mission-control/scheduler",icon:gc,description:"Share your booking link and sync your calendar",primaryCategory:"crm",section:"Overview",toolId:"scheduler",visible:()=>!0,searchKeywords:["scheduler","booking","calendar","appointments"],displayOrder:25},{id:"listing-exchange",label:"Listing Exchange",route:"/mission-control/listings",icon:oi,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:K1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:C0,description:"Build a polished listing presentation PDF",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-presentation-studio",searchKeywords:["listing presentation","pdf","pitch"],displayOrder:20},{id:"listing-revival",label:"Listing Revival",route:"/apps/listing-revival",icon:vu,description:"Win expired and withdrawn listings",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-revival",searchKeywords:["expired","revival","withdrawn"],displayOrder:30},{id:"fsbo-breakthrough",label:"By-Owner Breakthrough",route:"/apps/fsbo-breakthrough",icon:sa,description:"Convert for-sale-by-owner sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"fsbo-breakthrough",searchKeywords:["fsbo","by owner"],displayOrder:40},{id:"cma",label:"CMA Reports",route:"/mission-control/cma",icon:pj,description:"Comparative market analysis for sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"cma",visible:s=>s.hasLeadSiteMLS,searchKeywords:["cma","market analysis","pricing"],displayOrder:50},{id:"guest-book",label:"Guest Book",route:"/mission-control/guest-book",icon:fN,description:"Digital open house sign-in",primaryCategory:"listings",section:"Open Houses",toolId:"guest-book",searchKeywords:["open house","sign in","guest book"],displayOrder:60},{id:"listing-studio",label:"Listing Studio",route:"/mission-control/listing-studio",icon:nc,description:"Marketing assets for a listing",primaryCategory:"listings",section:"Market the Listing",toolId:"listing-studio",searchKeywords:["listing marketing","flyer","just listed"],displayOrder:70},{id:"templates",label:"Templates",route:"/templates",icon:yc,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"staging-studio",label:"Staging Studio",route:"/apps/staging-studio",icon:hq,description:"Virtually stage, declutter and brighten listing photos",primaryCategory:"marketing",section:"Create",toolId:"staging-studio",visible:s=>s.isAdmin||s.stagingStudioEnabled,searchKeywords:["staging","virtual staging","twilight","declutter","sky replacement","photo"],displayOrder:11},{id:"reviews",label:"Reviews",route:"/apps/reviews",icon:Ia,description:"Collect, showcase and reply to client reviews",primaryCategory:"marketing",section:"Create",searchKeywords:["reviews","agent reviews","google reviews","testimonials","reputation","review link","review page","ratings","video review"],displayOrder:12},{id:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:nc,description:"Create branded marketing assets",primaryCategory:"marketing",section:"Create",searchKeywords:["marketing studio","design","brand kit"],displayOrder:20},{id:"social-studio",label:"Social Studio",route:"/social-studio",icon:p1,description:"Post to all your social accounts from one composer",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook","linkedin","google business","schedule","swag"],displayOrder:29},{id:"social-swag",label:"Social Swag",route:"/social-swag-2",icon:p1,description:"Daily social posts you can publish in a tap",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook"],displayOrder:30},{id:"weekly-reels",label:"Weekly Reels",route:"/weekly-reels",icon:Yh,description:"A fresh reel script every Monday",primaryCategory:"marketing",section:"Social & Content",toolId:"weekly-reels",visible:s=>s.hasWeeklyReels,searchKeywords:["reels","video script","instagram"],displayOrder:40},{id:"newsletter-pro",label:"Newsletter Pro",route:"/newsletters",icon:vN,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:on,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Mail Studio (beta)",route:"/mission-control/direct-mail",icon:Fr,description:"Postcards & letters via your thanks.io account",primaryCategory:"marketing",section:"Email & Mail",visible:s=>s.isAdmin,toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming","letter","thanks.io","mail studio"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:Ko,description:"Send digital celebration cards",primaryCategory:"marketing",section:"Email & Mail",toolId:"card-studio",searchKeywords:["cards","birthday","anniversary"],displayOrder:80},{id:"video-library",label:"Video Library",route:"/mission-control/video-library",icon:Xr,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:K1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:Xr,description:"Record a personalized video in seconds",primaryCategory:"marketing",section:"Video",toolId:"quickvid",searchKeywords:["record video","video email","screen record"],displayOrder:100},{id:"reelflow",label:"ReelFlow",route:"/admin/beta/homereel",icon:Yh,description:"AI-assisted short-form video creation",primaryCategory:"marketing",section:"Video",toolId:"reelflow",searchKeywords:["reelflow","ai video","reels"],displayOrder:110},{id:"landing-pages",label:"Landing Pages",route:"/mission-control/landing-pages",icon:Xf,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"buyer-match",label:"Buyer Match",route:"/mission-control/buyer-match",icon:jv,description:"Turn a buyer's wish list into seller conversations",primaryCategory:"marketing",section:"Lead Capture",searchKeywords:["buyer match","buyer needs","seller leads","wish list"],displayOrder:125},{id:"smart-card",label:"Smart Card",route:"/mission-control/my-card",icon:Oc,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"my-websites",label:"My Websites",route:"/websites",icon:op,description:"Every site you can edit: yours, your company and your team",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite||s.isBrokerageManager||s.isTeamLeader||s.isAdmin,searchKeywords:["websites","my sites","edit website","company site","team site"],displayOrder:1},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:Wo,description:"Claim the free site your brokerage offers",primaryCategory:"websites",section:"My Website",visible:s=>!s.hasLeadSite&&s.hasFreeSiteOffer,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:Wo,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:s=>!s.hasLeadSite&&!s.hasFreeSiteOffer,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:s=>s.siteUrl||"#",icon:xa,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:s=>s.hasLeadSite&&!!s.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit My Site",route:s=>`/my-website/${s.leadSiteId}/edit`,icon:Wa,description:"Site builder for pages, branding and content",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite&&!!s.leadSiteId,searchKeywords:["edit website","site builder","pages"],displayOrder:20},{id:"brokerage-website",label:"Edit Company Site",route:"/brokerage/website",icon:oi,description:"Your company site: agents, listings, recruiting and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isBrokerageManager||s.isAdmin,searchKeywords:["website","company site","brokerage site","agents","roster"],displayOrder:24},{id:"team-website",label:"Edit Team Site",route:"/team/website",icon:On,description:"Your team site: members, listings and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isTeamLeader||s.isAdmin,searchKeywords:["team website","team site","team page"],displayOrder:26},{id:"mls-listings",label:"MLS Listings",route:"/my-website/mls-listings",icon:sa,description:"Control which listings appear on your site",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mls","idx","listings on site"],displayOrder:30},{id:"market-reports",label:"Market Reports",route:"/my-website/market-report",icon:wl,description:"Monthly market reports for your areas",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite&&s.hasLeadSiteMLS,searchKeywords:["market report","stats"],displayOrder:40},{id:"website-activity",label:"Website Activity",route:"/mission-control/website-activity",icon:pm,description:"See who is browsing your site",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["website activity","visitors","analytics"],displayOrder:50},{id:"mobile-command",label:"Mobile Command",route:"/m",icon:p1,description:"The mobile-first agent console",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mobile","command"],displayOrder:60},{id:"website-apps",label:"Website Apps",route:"/website-apps",icon:un,description:"Lead magnets, video greeter and more",primaryCategory:"websites",section:"Website Add-Ons",toolId:"website-apps",searchKeywords:["widgets","lead magnet","video greeter"],displayOrder:70},{id:"levelup-u",label:"LevelUp U",route:"/levelup-u",icon:fm,description:"Structured courses and certifications",primaryCategory:"academy",section:"Learn",badge:"new",searchKeywords:["levelup u","courses","training"],displayOrder:10},{id:"academy",label:"Academy",route:"/academy",icon:ip,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:eC,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:v7,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:Xf,description:"Cohort programs like Reel Estate 90",primaryCategory:"academy",section:"Programs & Coaching",searchKeywords:["programs","reel estate 90","cohort"],displayOrder:50},{id:"coaching",label:"Coaching",route:"/coaching",icon:fm,description:"Your coaching hub and calendar",primaryCategory:"academy",section:"Programs & Coaching",visible:s=>s.isCoach,searchKeywords:["coaching","coach hub"],displayOrder:60},{id:"my-coach",label:"Coaching",route:"/my-coach",icon:Fo,description:"Sessions, goals and notes with your coach",primaryCategory:"academy",section:"Programs & Coaching",visible:s=>!s.isCoach&&(s.hasCoach||s.hasCoachingAccess),searchKeywords:["my coach","coaching","sessions","book session"],displayOrder:70},{id:"community",label:"Community",route:"/community",icon:qi,description:"Talk shop with other LevelUp members",primaryCategory:"more",section:"Community",badgeKey:"community",searchKeywords:["community","forum","posts"],displayOrder:10},{id:"wishlist",label:"Wishlist",route:"/wishlist",icon:yS,description:"Request and vote on new features",primaryCategory:"more",section:"Community",badgeKey:"wishlist",searchKeywords:["wishlist","feature request"],displayOrder:20},{id:"facebook-group",label:"Facebook Group",route:"https://www.facebook.com/share/g/1CC6thti2V/",icon:mr,description:"Our private Facebook community",primaryCategory:"more",section:"Community",external:!0,openInNewTab:!0,searchKeywords:["facebook group"],displayOrder:30},{id:"marketplace",label:"Marketplace",route:"/marketplace",icon:mq,description:"Print and promo products",primaryCategory:"more",section:"The Goods",badge:"new",visible:s=>s.isMarketplaceEnabled,searchKeywords:["marketplace","shop","print"],displayOrder:40},{id:"reward-store",label:"Reward Store",route:"/reward-store",icon:jl,description:"Spend the points you have earned",primaryCategory:"more",section:"The Goods",searchKeywords:["rewards","points","store"],displayOrder:50},{id:"refer-friends",label:"Refer & Earn",route:"/refer-friends",icon:Ko,description:"Invite agents and earn rewards",primaryCategory:"more",section:"The Goods",searchKeywords:["referral","refer a friend"],displayOrder:60},{id:"support",label:"Support",route:"/support",icon:ZU,description:"Get help from the LevelUp team",primaryCategory:"more",section:"Help & Services",searchKeywords:["support","help","ticket"],displayOrder:70},{id:"additional-services",label:"Additional Services",route:"/additional-services",icon:un,description:"Done-for-you services from LevelUp",primaryCategory:"more",section:"Help & Services",searchKeywords:["services","done for you"],displayOrder:80},{id:"integrations",label:"Integrations",route:"/mission-control/integrations",icon:_j,description:"Connect your CRM, calendar and socials",primaryCategory:"more",section:"Help & Services",searchKeywords:["integrations","connect","crm sync"],displayOrder:90},{id:"browser-extension",label:"Browser Extension",route:"/mission-control/browser-extension",icon:_j,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:un,description:"Relationship-first attraction coach",primaryCategory:"more",section:"Help & Services",badge:"beta",visible:s=>s.email==="jeremy@relevelup.com",searchKeywords:["attract","recruiting"],displayOrder:110},{id:"admin-dashboard",label:"Admin Dashboard",route:"/admin",icon:Hl,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"agent-activation",label:"Agent Activation",route:"/admin/agent-activation",icon:cf,description:"Wake up dormant agents with branded email sequences",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["activation","dormant","adoption","agents"],displayOrder:121},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon:oi,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:_4,description:"Ask for showing and open house coverage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["help board","coverage"],displayOrder:140},{id:"brokerage-content",label:"Brokerage Content",route:"/brokerage-content",icon:ip,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"team-hub",label:"Team Hub",route:"/team",icon:On,description:"Production, leaderboard, pond and resources for your team",primaryCategory:"team",section:"My Team",searchKeywords:["team","leaderboard","production","team hub","standing"],displayOrder:155},{id:"my-team",label:"My Team",route:"/my-team",icon:On,description:"Your team roster and lead pond",primaryCategory:"brokerage",section:"My Team",visible:s=>s.isOnTeam&&!s.isBrokerageManager&&!s.isAdmin,searchKeywords:["team","lead pond"],displayOrder:160},{id:"manage-brokerages",label:"Manage Brokerages",route:"/brokerage/dashboard",icon:Gc,description:"Brokerage manager dashboard",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["manage brokerage"],displayOrder:170},{id:"brokerage-teams",label:"Teams",route:"/brokerage/teams",icon:On,description:"Teams, rosters and lead ponds",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["teams","pond"],displayOrder:180},{id:"brokerage-recruiting",label:"Recruiting",route:"/brokerage/recruiting",icon:Nh,description:"Recruit and nurture agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["recruiting"],displayOrder:190},{id:"brokerage-onboarding",label:"Agent Onboarding",route:"/brokerage/onboarding",icon:Wf,description:"Onboarding checklists, documents and agent notes",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["onboarding","checklist","documents","new agent"],displayOrder:195},{id:"brokerage-operations",label:"Operations",route:"/brokerage/operations",icon:oP,description:"Daily action feed, office task board and brokerage calendar",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["operations","tasks","today","calendar","action items"],displayOrder:188},{id:"brokerage-commission-plans",label:"Financials",route:"/brokerage/commission-plans",icon:z_,description:"Commission plans, company dollar and fee statements",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["commission","split","cap","fees","agent plans"],displayOrder:195},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:Wf,description:"Review agent files, required documents and closing compliance",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["compliance","transactions","documents","closing","paperless"],displayOrder:196},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:jv,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-forms",label:"Brokerage Forms",route:"/brokerage/forms",icon:$r,description:"Official forms your agents can use",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["forms","pdf","documents"],displayOrder:205},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:Px,description:"Documents and links for your agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["resources"],displayOrder:210},{id:"my-partnership",label:"My Package",route:"/my-partnership",icon:un,description:"What is included in your partnership package",primaryCategory:"more",section:"Account",visible:s=>s.isPartnershipMember,searchKeywords:["partnership","package","upgrade","exp luxury"],displayOrder:5},{id:"coaching-onboarding",label:"Coaching Onboarding",route:"/coaching/onboarding",icon:Wf,description:"Tell your coach about your business before session one",primaryCategory:"academy",section:"Coaching",visible:s=>s.hasCoachingOnboarding,searchKeywords:["coaching","onboarding","intake"],displayOrder:45}];function GRt(s,t){return typeof s.route=="function"?s.route(t):s.route}function WRt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=hs(),{hasPermission:i}=qre(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o,isFeatureEnabled:c}=Wre(),{hasAccess:d}=hPe(),{data:u,teams:h}=K_(),{leadSite:m,hasLeadSite:p,siteUrl:f}=mf(),{hasOffer:g}=PPe(!p),v=OS(),{hasAccess:y}=URt(),{data:b}=wJe(),w=$t(),{data:S}=rt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:Z}=await U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(Z||[]).length>0}}),{data:C}=rt({queryKey:["user-tool-favorites",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const{data:Z}=await U.from("user_tool_favorites").select("tool_id").eq("user_id",s.id);return(Z||[]).map(oe=>oe.tool_id)}}),E=_.useMemo(()=>new Set(C||[]),[C]),P=mt({mutationFn:async Z=>{s!=null&&s.id&&(E.has(Z)?await U.from("user_tool_favorites").delete().eq("user_id",s.id).eq("tool_id",Z):await U.from("user_tool_favorites").insert({user_id:s.id,tool_id:Z}))},onSuccess:()=>{w.invalidateQueries({queryKey:["user-tool-favorites"]}),w.invalidateQueries({queryKey:["app-catalog"]})}}),M=_.useMemo(()=>{var Z,oe;return{isAdmin:!!t,isBrokerageManager:!!n,isTransactionAdmin:((b==null?void 0:b.length)||0)>0,isCoach:!!r,isOnTeam:!!u,isTeamLeader:(h||[]).some(re=>re.role==="team_leader"),hasCoach:!!S,brokerageId:a??null,hasPermission:i,isInnerCircleEnabled:!!l,stagingStudioEnabled:c("staging_studio_enabled"),isMarketplaceEnabled:!!o,hasWeeklyReels:!!d,hasLeadSite:!!p,hasLeadSiteMLS:!!(m!=null&&m.mls_provider_id),hasFreeSiteOffer:!!g,leadSiteId:(m==null?void 0:m.id)??null,siteUrl:f??null,email:(s==null?void 0:s.email)??null,isPartnershipMember:v.isMember,hasCoachingOnboarding:v.isMember&&!!((Z=v.pkg)!=null&&Z.includes_coaching),hasCoachingAccess:!!y||v.isMember&&!!((oe=v.pkg)!=null&&oe.includes_coaching)}},[t,n,b,r,u,h,S,a,i,l,o,c,d,p,m,g,f,s==null?void 0:s.email,v.isMember,v.pkg,y]),I=_.useMemo(()=>ATs.filter(Z=>Z.visible?Z.visible(M):!0).map(Z=>{if(!v.isRestricted)return Z;const oe=xNs(Z);return!oe||v.hasFeature(oe)?Z:{...Z,locked:!0,route:`/upgrade/${oe}`}}).sort((Z,oe)=>Z.displayOrder-oe.displayOrder),[M,v.isRestricted,v.features]),D=_.useMemo(()=>IPe.filter(Z=>Z.visible?Z.visible(M):!0),[M]),F=_.useMemo(()=>D.filter(Z=>!Z.route).map(Z=>{const oe=I.filter(J=>J.primaryCategory===Z.id),re=[],ae=new Map;for(const J of oe)ae.has(J.section)||(ae.set(J.section,[]),re.push(J.section)),ae.get(J.section).push(J);return{id:Z.id,label:Z.label,sections:re.map(J=>({title:J,items:ae.get(J)}))}}),[I,D]),q=_.useMemo(()=>new Map(F.map(Z=>[Z.id,Z])),[F]),G=Z=>Z.toolId||`nav:${Z.id}`,V=Z=>E.has(G(Z));return{ctx:M,categories:F,railCategories:D,categoryMap:q,destinations:I,favorites:E,isFavorite:V,favoritesFor:Z=>I.filter(oe=>oe.primaryCategory===Z&&V(oe)),favoriteKey:G,toggleFavorite:Z=>P.mutate(Z),searchDestinations:Z=>{const oe=Z.trim().toLowerCase();return oe?I.map(ae=>{const J=ae.label.toLowerCase(),te=(ae.description||"").toLowerCase(),ce=(ae.searchKeywords||[]).join(" ").toLowerCase();let ve=0;return J===oe?ve=100:J.startsWith(oe)?ve=80:J.includes(oe)?ve=60:ce.includes(oe)?ve=40:te.includes(oe)?ve=20:ae.section.toLowerCase().includes(oe)&&(ve=10),ve&&V(ae)&&(ve+=5),{d:ae,score:ve}}).filter(ae=>ae.score>0).sort((ae,J)=>J.score-ae.score).map(ae=>ae.d):[]},routeFor:Z=>GRt(Z,M)}}var fft=1,ETs=.9,TTs=.8,MTs=.17,MOe=.1,POe=.999,PTs=.9999,LTs=.99,ITs=/[\\\/_+.#"@\[\(\{&]/,DTs=/[\\\/_+.#"@\[\(\{&]/g,RTs=/[\s-]/,KRt=/[\s-]/g;function lVe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?fft:LTs;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,m,p,f;d>=0;)h=lVe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=fft:ITs.test(s.charAt(d-1))?(h*=TTs,p=s.slice(a,d-1).match(DTs),p&&a>0&&(h*=Math.pow(POe,p.length))):RTs.test(s.charAt(d-1))?(h*=ETs,f=s.slice(a,d-1).match(KRt),f&&a>0&&(h*=Math.pow(POe,f.length))):(h*=MTs,a>0&&(h*=Math.pow(POe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=PTs)),(hh&&(h=m*MOe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function xft(s){return s.toLowerCase().replace(KRt," ")}function FTs(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,lVe(s,t,xft(s),xft(t),0,0,{})}var GY='[cmdk-group=""]',LOe='[cmdk-group-items=""]',OTs='[cmdk-group-heading=""]',YRt='[cmdk-item=""]',gft=`${YRt}:not([aria-disabled="true"])`,cVe="cmdk-item-select",j$="data-value",zTs=(s,t,n)=>FTs(s,t,n),ZRt=_.createContext(void 0),tae=()=>_.useContext(ZRt),XRt=_.createContext(void 0),NJe=()=>_.useContext(XRt),QRt=_.createContext(void 0),JRt=_.forwardRef((s,t)=>{let n=N$(()=>{var te,ce;return{search:"",value:(ce=(te=s.value)!=null?te:s.defaultValue)!=null?ce:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=N$(()=>new Set),a=N$(()=>new Map),i=N$(()=>new Map),l=N$(()=>new Set),o=eFt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:f,disablePointerSelection:g=!1,vimBindings:v=!0,...y}=s,b=qg(),w=qg(),S=qg(),C=_.useRef(null),E=ZTs();i9(()=>{if(u!==void 0){let te=u.trim();n.current.value=te,P.emit()}},[u]),i9(()=>{E(6,G)},[]);let P=_.useMemo(()=>({subscribe:te=>(l.current.add(te),()=>l.current.delete(te)),snapshot:()=>n.current,setState:(te,ce,ve)=>{var me,he,ge,Ee;if(!Object.is(n.current[te],ce)){if(n.current[te]=ce,te==="search")q(),D(),E(1,F);else if(te==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ne=document.getElementById(S);Ne?Ne.focus():(me=document.getElementById(b))==null||me.focus()}if(E(7,()=>{var Ne;n.current.selectedItemId=(Ne=V())==null?void 0:Ne.id,P.emit()}),ve||E(5,G),((he=o.current)==null?void 0:he.value)!==void 0){let Ne=ce??"";(Ee=(ge=o.current).onValueChange)==null||Ee.call(ge,Ne);return}}P.emit()}},emit:()=>{l.current.forEach(te=>te())}}),[]),M=_.useMemo(()=>({value:(te,ce,ve)=>{var me;ce!==((me=i.current.get(te))==null?void 0:me.value)&&(i.current.set(te,{value:ce,keywords:ve}),n.current.filtered.items.set(te,I(ce,ve)),E(2,()=>{D(),P.emit()}))},item:(te,ce)=>(r.current.add(te),ce&&(a.current.has(ce)?a.current.get(ce).add(te):a.current.set(ce,new Set([te]))),E(3,()=>{q(),D(),n.current.value||F(),P.emit()}),()=>{i.current.delete(te),r.current.delete(te),n.current.filtered.items.delete(te);let ve=V();E(4,()=>{q(),(ve==null?void 0:ve.getAttribute("id"))===te&&F(),P.emit()})}),group:te=>(a.current.has(te)||a.current.set(te,new Set),()=>{i.current.delete(te),a.current.delete(te)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:S,labelId:w,listInnerRef:C}),[]);function I(te,ce){var ve,me;let he=(me=(ve=o.current)==null?void 0:ve.filter)!=null?me:zTs;return te?he(te,n.current.search,ce):0}function D(){if(!n.current.search||o.current.shouldFilter===!1)return;let te=n.current.filtered.items,ce=[];n.current.filtered.groups.forEach(me=>{let he=a.current.get(me),ge=0;he.forEach(Ee=>{let Ne=te.get(Ee);ge=Math.max(Ne,ge)}),ce.push([me,ge])});let ve=C.current;H().sort((me,he)=>{var ge,Ee;let Ne=me.getAttribute("id"),Pe=he.getAttribute("id");return((ge=te.get(Pe))!=null?ge:0)-((Ee=te.get(Ne))!=null?Ee:0)}).forEach(me=>{let he=me.closest(LOe);he?he.appendChild(me.parentElement===he?me:me.closest(`${LOe} > *`)):ve.appendChild(me.parentElement===ve?me:me.closest(`${LOe} > *`))}),ce.sort((me,he)=>he[1]-me[1]).forEach(me=>{var he;let ge=(he=C.current)==null?void 0:he.querySelector(`${GY}[${j$}="${encodeURIComponent(me[0])}"]`);ge==null||ge.parentElement.appendChild(ge)})}function F(){let te=H().find(ve=>ve.getAttribute("aria-disabled")!=="true"),ce=te==null?void 0:te.getAttribute(j$);P.setState("value",ce||void 0)}function q(){var te,ce,ve,me;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let he=0;for(let ge of r.current){let Ee=(ce=(te=i.current.get(ge))==null?void 0:te.value)!=null?ce:"",Ne=(me=(ve=i.current.get(ge))==null?void 0:ve.keywords)!=null?me:[],Pe=I(Ee,Ne);n.current.filtered.items.set(ge,Pe),Pe>0&&he++}for(let[ge,Ee]of a.current)for(let Ne of Ee)if(n.current.filtered.items.get(Ne)>0){n.current.filtered.groups.add(ge);break}n.current.filtered.count=he}function G(){var te,ce,ve;let me=V();me&&(((te=me.parentElement)==null?void 0:te.firstChild)===me&&((ve=(ce=me.closest(GY))==null?void 0:ce.querySelector(OTs))==null||ve.scrollIntoView({block:"nearest"})),me.scrollIntoView({block:"nearest"}))}function V(){var te;return(te=C.current)==null?void 0:te.querySelector(`${YRt}[aria-selected="true"]`)}function H(){var te;return Array.from(((te=C.current)==null?void 0:te.querySelectorAll(gft))||[])}function K(te){let ce=H()[te];ce&&P.setState("value",ce.getAttribute(j$))}function Z(te){var ce;let ve=V(),me=H(),he=me.findIndex(Ee=>Ee===ve),ge=me[he+te];(ce=o.current)!=null&&ce.loop&&(ge=he+te<0?me[me.length-1]:he+te===me.length?me[0]:me[he+te]),ge&&P.setState("value",ge.getAttribute(j$))}function oe(te){let ce=V(),ve=ce==null?void 0:ce.closest(GY),me;for(;ve&&!me;)ve=te>0?KTs(ve,GY):YTs(ve,GY),me=ve==null?void 0:ve.querySelector(gft);me?P.setState("value",me.getAttribute(j$)):Z(te)}let re=()=>K(H().length-1),ae=te=>{te.preventDefault(),te.metaKey?re():te.altKey?oe(1):Z(1)},J=te=>{te.preventDefault(),te.metaKey?K(0):te.altKey?oe(-1):Z(-1)};return _.createElement(ci.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:te=>{var ce;(ce=y.onKeyDown)==null||ce.call(y,te);let ve=te.nativeEvent.isComposing||te.keyCode===229;if(!(te.defaultPrevented||ve))switch(te.key){case"n":case"j":{v&&te.ctrlKey&&ae(te);break}case"ArrowDown":{ae(te);break}case"p":case"k":{v&&te.ctrlKey&&J(te);break}case"ArrowUp":{J(te);break}case"Home":{te.preventDefault(),K(0);break}case"End":{te.preventDefault(),re();break}case"Enter":{te.preventDefault();let me=V();if(me){let he=new Event(cVe);me.dispatchEvent(he)}}}}},_.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:QTs},c),DPe(s,te=>_.createElement(XRt.Provider,{value:P},_.createElement(ZRt.Provider,{value:M},te))))}),BTs=_.forwardRef((s,t)=>{var n,r;let a=qg(),i=_.useRef(null),l=_.useContext(QRt),o=tae(),c=eFt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;i9(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=tFt(a,i,[s.value,s.children,i],s.keywords),h=NJe(),m=HP(E=>E.value&&E.value===u.current),p=HP(E=>d||o.filter()===!1?!0:E.search?E.filtered.items.get(a)>0:!0);_.useEffect(()=>{let E=i.current;if(!(!E||s.disabled))return E.addEventListener(cVe,f),()=>E.removeEventListener(cVe,f)},[p,s.onSelect,s.disabled]);function f(){var E,P;g(),(P=(E=c.current).onSelect)==null||P.call(E,u.current)}function g(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:v,value:y,onSelect:b,forceMount:w,keywords:S,...C}=s;return _.createElement(ci.div,{ref:jE(i,t),...C,id:a,"cmdk-item":"",role:"option","aria-disabled":!!v,"aria-selected":!!m,"data-disabled":!!v,"data-selected":!!m,onPointerMove:v||o.getDisablePointerSelection()?void 0:g,onClick:v?void 0:f},s.children)}),$Ts=_.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=qg(),o=_.useRef(null),c=_.useRef(null),d=qg(),u=tae(),h=HP(p=>a||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);i9(()=>u.group(l),[]),tFt(l,o,[s.value,s.heading,c]);let m=_.useMemo(()=>({id:l,forceMount:a}),[a]);return _.createElement(ci.div,{ref:jE(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&_.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),DPe(s,p=>_.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},_.createElement(QRt.Provider,{value:m},p))))}),UTs=_.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=_.useRef(null),i=HP(l=>!l.search);return!n&&!i?null:_.createElement(ci.div,{ref:jE(a,t),...r,"cmdk-separator":"",role:"separator"})}),qTs=_.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=NJe(),l=HP(d=>d.search),o=HP(d=>d.selectedItemId),c=tae();return _.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),_.createElement(ci.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)}})}),VTs=_.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=_.useRef(null),l=_.useRef(null),o=HP(d=>d.selectedItemId),c=tae();return _.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let p=d.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),_.createElement(ci.div,{ref:jE(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},DPe(s,d=>_.createElement("div",{ref:jE(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),HTs=_.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return _.createElement(UMe,{open:n,onOpenChange:r},_.createElement(qMe,{container:l},_.createElement(rW,{"cmdk-overlay":"",className:a}),_.createElement(aW,{"aria-label":s.label,"cmdk-dialog":"",className:i},_.createElement(JRt,{ref:t,...o}))))}),GTs=_.forwardRef((s,t)=>HP(n=>n.filtered.count===0)?_.createElement(ci.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),WTs=_.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return _.createElement(ci.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},DPe(s,l=>_.createElement("div",{"aria-hidden":!0},l)))}),Z_=Object.assign(JRt,{List:VTs,Item:BTs,Input:qTs,Group:$Ts,Separator:UTs,Dialog:HTs,Empty:GTs,Loading:WTs});function KTs(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function YTs(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function eFt(s){let t=_.useRef(s);return i9(()=>{t.current=s}),t}var i9=typeof window>"u"?_.useEffect:_.useLayoutEffect;function N$(s){let t=_.useRef();return t.current===void 0&&(t.current=s()),t}function HP(s){let t=NJe(),n=()=>s(t.snapshot());return _.useSyncExternalStore(t.subscribe,n,n)}function tFt(s,t,n,r=[]){let a=_.useRef(),i=tae();return i9(()=>{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(j$,o),a.current=o}),a}var ZTs=()=>{let[s,t]=_.useState(),n=N$(()=>new Map);return i9(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function XTs(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function DPe({asChild:s,children:t},n){return s&&_.isValidElement(t)?_.cloneElement(XTs(t),{ref:t.ref},n(t.props.children)):n(t)}var QTs={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Ij=_.forwardRef(({className:s,...t},n)=>e.jsx(Z_,{ref:n,className:Ct("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Ij.displayName=Z_.displayName;const JTs=({children:s,...t})=>e.jsx(Is,{...t,children:e.jsx(Ls,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Ij,{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})})}),Dj=_.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Rr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Z_.Input,{ref:n,className:Ct("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})]}));Dj.displayName=Z_.Input.displayName;const Rj=_.forwardRef(({className:s,...t},n)=>e.jsx(Z_.List,{ref:n,className:Ct("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));Rj.displayName=Z_.List.displayName;const Fj=_.forwardRef((s,t)=>e.jsx(Z_.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Fj.displayName=Z_.Empty.displayName;const G_=_.forwardRef(({className:s,...t},n)=>e.jsx(Z_.Group,{ref:n,className:Ct("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}));G_.displayName=Z_.Group.displayName;const e6s=_.forwardRef(({className:s,...t},n)=>e.jsx(Z_.Separator,{ref:n,className:Ct("-mx-1 h-px bg-border",s),...t}));e6s.displayName=Z_.Separator.displayName;const c1=_.forwardRef(({className:s,...t},n)=>e.jsx(Z_.Item,{ref:n,className:Ct("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}));c1.displayName=Z_.Item.displayName;const t6s={event:{label:"Events",icon:gc,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:yc,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:fm,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:eC,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:un,color:"bg-fuchsia-500/10 text-fuchsia-600"}},yft=()=>{const[s,t]=_.useState(!1),[n,r]=_.useState(""),[a,i]=_.useState([]),[l,o]=_.useState(!1),c=zn(),{searchDestinations:d,isFavorite:u,routeFor:h}=WRt(),m=n.trim()?d(n).slice(0,6):[];_.useEffect(()=>{const v=y=>{y.key==="k"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),t(b=>!b))};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[]);const p=_.useCallback(async v=>{if(!v.trim()){i([]);return}o(!0);const y=`%${v}%`;try{const[b,w,S,C,E]=await Promise.all([U.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5),U.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${y},description.ilike.${y}`).limit(5),U.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5),U.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${y},description.ilike.${y}`).limit(5),U.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5)]),P=[];b.data&&b.data.forEach(M=>{P.push({id:M.id,title:M.title,description:M.description,type:"event",date:M.event_date,path:`/event/${M.id}`})}),w.data&&w.data.forEach(M=>{P.push({id:M.id,title:M.name,description:M.description,type:"template",date:M.publish_date,path:`/templates/${M.id}`})}),S.data&&S.data.forEach(M=>{P.push({id:M.id,title:M.title,description:M.description,type:"academy",date:M.publish_date,path:`/academy/${M.id}`})}),C.data&&C.data.forEach(M=>{P.push({id:M.id,title:M.name,description:M.description,type:"toolbox",date:M.publish_date,path:`/toolbox/${M.id}`})}),E.data&&E.data.forEach(M=>{P.push({id:M.id,title:M.title,description:M.description,type:"social-swag",date:M.publish_date,path:`/social-swag/${M.id}`})}),i(P)}catch(b){console.error("Search error:",b)}finally{o(!1)}},[]);_.useEffect(()=>{const v=setTimeout(()=>{p(n)},300);return()=>clearTimeout(v)},[n,p]);const f=v=>{t(!1),r(""),c(v)},g=a.reduce((v,y)=>(v[y.type]||(v[y.type]=[]),v[y.type].push(y),v),{});return e.jsxs(e.Fragment,{children:[e.jsxs(z,{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(Rr,{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(JTs,{open:s,onOpenChange:t,children:[e.jsx(Dj,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(Rj,{children:[m.length>0&&e.jsx(G_,{heading:"Go to",children:m.map(v=>{const y=v.icon;return e.jsxs(c1,{value:`nav-${v.id}-${v.label}`,onSelect:()=>{const b=h(v);v.external||v.openInNewTab?(t(!1),r(""),window.open(b,"_blank","noopener,noreferrer")):f(b)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:e.jsx(y,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[v.label,u(v)&&e.jsx(Ty,{className:"h-3 w-3 fill-current text-primary"})]}),v.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:v.description})]}),e.jsx(ze,{variant:"secondary",className:"text-xs shrink-0",children:v.section})]},`nav-${v.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(Fj,{children:['No results found for "',n,'"']}),!l&&!n&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(g).map(([v,y])=>{const b=t6s[v],w=b.icon;return e.jsx(G_,{heading:b.label,children:y.map(S=>e.jsxs(c1,{value:`${S.type}-${S.id}-${S.title}`,onSelect:()=>f(S.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${b.color}`,children:e.jsx(w,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:S.title}),S.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:S.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(ze,{variant:"secondary",className:"text-xs",children:b.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Md(new Date(S.date),{addSuffix:!0})})]})]},`${S.type}-${S.id}`))},v)})]})]})]})},s6s=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=_.useState(null),i=zn();if(_.useEffect(()=>{const d=()=>{const h=new Date().getTime(),p=new Date(s).getTime()-h;if(p<=0){a({days:0,hours:0,minutes:0});return}const f=Math.floor(p/(1e3*60*60*24)),g=Math.floor(p%(1e3*60*60*24)/(1e3*60*60)),v=Math.floor(p%(1e3*60*60)/(1e3*60));a({days:f,hours:g,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:Ct("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(nl,{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(z,{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:Ct("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(Zr,{className:Ct("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:Ct("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:Ct("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Ct("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Ct("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Ct("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs(z,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Ct("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"]})]})},n6s=()=>{const s=zn();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(be,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(_t,{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(nl,{className:"h-8 w-8 text-destructive"})}),e.jsx(Nt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(En,{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(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(be,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Le,{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(On,{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(z,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(be,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Le,{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(oi,{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(z,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(oi,{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(va,{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(on,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},r6s=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"icon",onClick:t,className:Ct("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(Nh,{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(Tx,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var RPe="Checkbox",[a6s,swr]=uf(RPe),[i6s,kJe]=a6s(RPe);function o6s(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,p]=Gg({prop:n,defaultProp:a??!1,onChange:c,caller:RPe}),[f,g]=_.useState(null),[v,y]=_.useState(null),b=_.useRef(!1),w=f?!!l||!!f.closest("form"):!0,S={checked:m,disabled:i,setChecked:p,control:f,setControl:g,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,required:d,defaultChecked:yP(a)?!1:a,isFormControl:w,bubbleInput:v,setBubbleInput:y};return e.jsx(i6s,{scope:t,...S,children:l6s(h)?h(S):r})}var sFt="CheckboxTrigger",nFt=_.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:m,isFormControl:p,bubbleInput:f}=kJe(sFt,s),g=el(a,u),v=_.useRef(c);return _.useEffect(()=>{const y=i==null?void 0:i.form;if(y){const b=()=>h(v.current);return y.addEventListener("reset",b),()=>y.removeEventListener("reset",b)}},[i,h]),e.jsx(ci.button,{type:"button",role:"checkbox","aria-checked":yP(c)?"mixed":c,"aria-required":d,"data-state":lFt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:g,onKeyDown:wa(t,y=>{y.key==="Enter"&&y.preventDefault()}),onClick:wa(n,y=>{h(b=>yP(b)?!0:!b),f&&p&&(m.current=y.isPropagationStopped(),m.current||y.stopPropagation())})})});nFt.displayName=sFt;var SJe=_.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(o6s,{__scopeCheckbox:n,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:r,form:u,value:c,internal_do_not_use_render:({isFormControl:m})=>e.jsxs(e.Fragment,{children:[e.jsx(nFt,{...h,ref:t,__scopeCheckbox:n}),m&&e.jsx(oFt,{__scopeCheckbox:n})]})})});SJe.displayName=RPe;var rFt="CheckboxIndicator",aFt=_.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=kJe(rFt,n);return e.jsx(vg,{present:r||yP(i.checked)||i.checked===!0,children:e.jsx(ci.span,{"data-state":lFt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});aFt.displayName=rFt;var iFt="CheckboxBubbleInput",oFt=_.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:m,setBubbleInput:p}=kJe(iFt,s),f=el(n,p),g=Jre(i),v=Rre(r);_.useEffect(()=>{const b=m;if(!b)return;const w=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(w,"checked").set,E=!a.current;if(g!==i&&C){const P=new Event("click",{bubbles:E});b.indeterminate=yP(i),C.call(b,yP(i)?!1:i),b.dispatchEvent(P)}},[m,g,i,a]);const y=_.useRef(yP(i)?!1:i);return e.jsx(ci.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??y.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:f,style:{...t.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});oFt.displayName=iFt;function l6s(s){return typeof s=="function"}function yP(s){return s==="indeterminate"}function lFt(s){return yP(s)?"indeterminate":s?"checked":"unchecked"}const za=_.forwardRef(({className:s,...t},n)=>e.jsx(SJe,{ref:n,className:Ct("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(aFt,{className:Ct("flex items-center justify-center text-current"),children:e.jsx(Wr,{className:"h-4 w-4"})})}));za.displayName=SJe.displayName;var CJe="Radio",[c6s,cFt]=uf(CJe),[d6s,u6s]=c6s(CJe),dFt=_.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,m]=_.useState(null),p=el(t,v=>m(v)),f=_.useRef(!1),g=h?d||!!h.closest("form"):!0;return e.jsxs(d6s,{scope:n,checked:a,disabled:l,children:[e.jsx(ci.button,{type:"button",role:"radio","aria-checked":a,"data-state":pFt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:p,onClick:wa(s.onClick,v=>{a||c==null||c(),g&&(f.current=v.isPropagationStopped(),f.current||v.stopPropagation())})}),g&&e.jsx(mFt,{control:h,bubbles:!f.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});dFt.displayName=CJe;var uFt="RadioIndicator",hFt=_.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=u6s(uFt,n);return e.jsx(vg,{present:r||i.checked,children:e.jsx(ci.span,{"data-state":pFt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});hFt.displayName=uFt;var h6s="RadioBubbleInput",mFt=_.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=_.useRef(null),o=el(l,i),c=Jre(n),d=Rre(t);return _.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[c,n,r]),e.jsx(ci.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}})});mFt.displayName=h6s;function pFt(s){return s?"checked":"unchecked"}var m6s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],FPe="RadioGroup",[p6s,nwr]=uf(FPe,[xL,cFt]),fFt=xL(),xFt=cFt(),[f6s,x6s]=p6s(FPe),gFt=_.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,...m}=s,p=fFt(n),f=$E(d),[g,v]=Gg({prop:i,defaultProp:a??null,onChange:h,caller:FPe});return e.jsx(f6s,{scope:n,name:r,required:l,disabled:o,value:g,onValueChange:v,children:e.jsx(oPe,{asChild:!0,...p,orientation:c,dir:f,loop:u,children:e.jsx(ci.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:f,...m,ref:t})})})});gFt.displayName=FPe;var yFt="RadioGroupItem",vFt=_.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=x6s(yFt,n),l=i.disabled||r,o=fFt(n),c=xFt(n),d=_.useRef(null),u=el(t,d),h=i.value===a.value,m=_.useRef(!1);return _.useEffect(()=>{const p=g=>{m6s.includes(g.key)&&(m.current=!0)},f=()=>m.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",f)}},[]),e.jsx(lPe,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(dFt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:wa(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:wa(a.onFocus,()=>{var p;m.current&&((p=d.current)==null||p.click())})})})});vFt.displayName=yFt;var g6s="RadioGroupIndicator",bFt=_.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=xFt(n);return e.jsx(hFt,{...a,...r,ref:t})});bFt.displayName=g6s;var _Ft=gFt,wFt=vFt,y6s=bFt;const C_=_.forwardRef(({className:s,...t},n)=>e.jsx(_Ft,{className:Ct("grid gap-2",s),...t,ref:n}));C_.displayName=_Ft.displayName;const am=_.forwardRef(({className:s,...t},n)=>e.jsx(wFt,{ref:n,className:Ct("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(y6s,{className:"flex items-center justify-center",children:e.jsx(Gf,{className:"h-2.5 w-2.5 fill-current text-current"})})}));am.displayName=wFt.displayName;const v6s=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=hs(),[i,l]=_.useState({}),[o,c]=_.useState({}),[d,u]=_.useState([]);_.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const v=s.polls.map(b=>b.id),{data:y}=await U.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",v);if(y){const b={};y.forEach(w=>{b[w.poll_id]||(b[w.poll_id]=[]),b[w.poll_id].push(w.option_id)}),c(b)}},m=(v,y)=>{l(b=>({...b,[v]:y}))},p=(v,y,b)=>{l(w=>{const S=w[v]||[];return b?{...w,[v]:[...S,y]}:{...w,[v]:S.filter(C=>C!==y)}})},f=async v=>{if(!a)return;const y=i[v];if(!y||Array.isArray(y)&&y.length===0){ne.error("Please select an option");return}u(b=>[...b,v]);try{await U.from("levelup_brief_poll_responses").delete().eq("poll_id",v).eq("user_id",a.id);const b=Array.isArray(y)?y:[y],w=b.map(C=>({poll_id:v,option_id:C,user_id:a.id})),{error:S}=await U.from("levelup_brief_poll_responses").insert(w);if(S)throw S;c(C=>({...C,[v]:b})),ne.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),ne.error("Failed to submit response")}finally{u(b=>b.filter(w=>w!==v))}},g=v=>(v.includes("mediadelivery.net")||v.includes("bunny"),v);return e.jsx(Is,{open:t,onOpenChange:v=>!v&&n(),children:e.jsxs(Ls,{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(er,{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(Nh,{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(Rs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Ki,{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:g(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(z,{variant:"outline",size:"sm",onClick:()=>window.open(v.url,"_blank"),className:"gap-2",children:[e.jsx(mr,{className:"h-4 w-4"}),v.title]},v.id))})]}),s.polls.map(v=>{var w,S;const y=((w=o[v.id])==null?void 0:w.length)>0,b=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}),y&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Mr,{className:"h-3 w-3"}),"Responded"]})]}),v.poll_type==="single"?e.jsx(C_,{value:i[v.id]||((S=o[v.id])==null?void 0:S[0])||"",onValueChange:C=>m(v.id,C),className:"space-y-2",children:v.options.map(C=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:C.id,id:C.id}),e.jsx(ee,{htmlFor:C.id,className:"cursor-pointer",children:C.option_text})]},C.id))}):e.jsx("div",{className:"space-y-2",children:v.options.map(C=>{const P=(i[v.id]||o[v.id]||[]).includes(C.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(za,{id:C.id,checked:P,onCheckedChange:M=>p(v.id,C.id,M)}),e.jsx(ee,{htmlFor:C.id,className:"cursor-pointer",children:C.option_text})]},C.id)})}),e.jsx(z,{size:"sm",onClick:()=>f(v.id),disabled:b,children:b?"Submitting...":y?"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(z,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},b6s=()=>{const{user:s}=hs(),[t,n]=_.useState(null),[r,a]=_.useState(!1),[i,l]=_.useState(!0),[o,c]=_.useState(!1),d=_.useCallback(async()=>{if(!s){l(!1);return}try{const{data:f,error:g}=await U.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(g||!f){l(!1);return}const{data:v}=await U.from("levelup_brief_views").select("*").eq("brief_id",f.id).eq("user_id",s.id).maybeSingle(),[y,b]=await Promise.all([U.from("levelup_brief_links").select("*").eq("brief_id",f.id).order("sort_order"),U.from("levelup_brief_polls").select("*").eq("brief_id",f.id).order("sort_order")]),w=[];if(b.data)for(const M of b.data){const{data:I}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");w.push({...M,options:I||[]})}const S={brief:f,links:y.data||[],polls:w};n(S);const C=!!v,E=(v==null?void 0:v.dismissed_at)!=null,P=localStorage.getItem(`brief-dismissed-${f.id}`)==="true";if(E||P)c(!1),a(!1);else if(!C)a(!0),c(!0);else if(f.show_frequency==="every_login")a(!0),c(!0);else if(f.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(f){console.error("Error fetching brief:",f)}finally{l(!1)}},[s]);_.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:f}=await U.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();f?await U.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",f.id):await U.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(f){console.error("Error marking brief as viewed:",f)}};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:f,error:g}=await U.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(g&&console.error("Error checking existing brief view:",g),f){const{error:v}=await U.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",f.id).eq("user_id",s.id);v&&console.error("Error updating brief dismiss:",v)}else{const{error:v}=await U.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(f){console.error("Error dismissing brief:",f),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function _6s(){const[s,t]=_.useState(!1),[n,r]=_.useState(!1),[a,i]=_.useState(null);_.useEffect(()=>{const c=localStorage.getItem("install-banner-dismissed"),d=localStorage.getItem("install-banner-shown");if(c||d)return;if(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches||window.matchMedia("(display-mode: minimal-ui)").matches||window.navigator.standalone===!0||document.referrer.startsWith("android-app://")){localStorage.setItem("install-banner-dismissed","true");return}if(!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const m=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(m),t(!0),localStorage.setItem("install-banner-shown","true");const p=f=>{f.preventDefault(),i(f)};return window.addEventListener("beforeinstallprompt",p),()=>{window.removeEventListener("beforeinstallprompt",p)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),localStorage.setItem("install-banner-shown","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(Ga,{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(mJ,{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(z,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx(z,{size:"sm",variant:"secondary",onClick:l,className:"text-xs",children:"Got it"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(er,{className:"h-4 w-4"})})]})]})}):null}const w6s=({children:s,onRefresh:t})=>{const[n,r]=_.useState(!1),[a,i]=_.useState(0),[l,o]=_.useState(!1),c=_.useRef(null),d=_.useRef(0),u=$t(),h=80,m=120,p=_.useCallback(b=>{const w=c.current;w&&w.scrollTop<=0&&(d.current=b.touches[0].clientY,r(!0))},[]),f=_.useCallback(b=>{if(!n||l)return;const w=c.current;if(!w||w.scrollTop>0){r(!1),i(0);return}const C=b.touches[0].clientY-d.current;if(C>0){const P=Math.min(C*.5,m);i(P),P>10&&b.preventDefault()}},[n,l]),g=_.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(b){console.error("Refresh failed:",b)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),v=Math.min(a/h,1),y=v*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:p,onTouchMove:f,onTouchEnd:g,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(${y}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Gi,{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})]})},jFt=()=>{const{user:s}=hs(),[t,n]=_.useState(!1),[r,a]=_.useState(!1),[i,l]=_.useState(0),[o,c]=_.useState(!0);_.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:p}=await U.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(p){a(!0),n(!1),c(!1);return}const{data:f}=await U.from("profiles").select("login_count").eq("id",s.id).single(),g=(f==null?void 0:f.login_count)||0;l(g);const v=sessionStorage.getItem("review-prompt-dismissed");n(g>=4&&!v)}catch(p){console.error("Error checking review eligibility:",p)}finally{c(!1)}})()},[s]);const d=_.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=_.useCallback(async(m,p)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:f}=await U.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:p});if(f)throw f;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(f){return console.error("Error submitting review:",f),{success:!1,error:f.message}}},[s]),h=_.useCallback(async()=>{if(s)try{await U.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(m){console.error("Error updating Google review status:",m)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},j6s="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",N6s=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=jFt(),[i,l]=_.useState(!1),[o,c]=_.useState("review"),[d,u]=_.useState(0),[h,m]=_.useState(0),[p,f]=_.useState(""),[g,v]=_.useState(!1),[y,b]=_.useState(!1);if(t||!s&&!y)return null;const w=async()=>{if(d===0){la({title:"Please select a rating",variant:"destructive"});return}v(!0);const E=await r(d,p);v(!1),E.success?(b(!0),la({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):la({title:"Error submitting review",description:E.error,variant:"destructive"})},S=async E=>{E&&(await navigator.clipboard.writeText(p||`${d} star rating for LevelUp!`),la({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(j6s,"_blank")),l(!1),n()},C=()=>{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(Ia,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(Is,{open:i,onOpenChange:C,children:e.jsx(Ls,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(_r,{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(E=>e.jsx("button",{type:"button",onClick:()=>u(E),onMouseEnter:()=>m(E),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Ia,{className:Ct("h-8 w-8 transition-colors",(h||d)>=E?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},E))}),e.jsx(Ps,{placeholder:"Tell us about your experience (optional)",value:p,onChange:E=>f(E.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:C,className:"flex-1",children:"Maybe Later"}),e.jsx(z,{onClick:w,disabled:g||d===0,className:"flex-1",children:g?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(_r,{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(z,{variant:"outline",onClick:()=>S(!1),className:"flex-1",children:"No Thanks"}),e.jsx(z,{onClick:()=>S(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function k6s(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 g="vapid_public_key";let v=localStorage.getItem(g);if(!v){const{data:w,error:S}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(S)throw S;if(v=(w==null?void 0:w.vapidPublicKey)??null,!v)throw new Error("Missing VAPID public key");localStorage.setItem(g,v)}u(v);const y=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(y),n(Notification.permission);const b=await y.pushManager.getSubscription();a(!!b)}catch(g){console.error("Error initializing push notifications:",g)}finally{l(!1)}})()},[h]);const m=_.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ne.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const f=await o.pushManager.getSubscription();if(f){try{await f.unsubscribe()}catch(S){console.warn("Failed to unsubscribe existing push subscription:",S)}const{error:w}=await U.from("push_subscriptions").delete().eq("user_id",s.id);w&&console.warn("Failed to cleanup push_subscriptions rows:",w)}if(Notification.permission!=="granted"){const w=await Notification.requestPermission();if(n(w),w!=="granted")return w==="denied"?ne.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ne.error("Notification permission was dismissed. Please try again."),!1}const g=k6s(d);let v;try{v=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:g})}catch(w){console.error("PushManager.subscribe() failed:",w);const S=(w==null?void 0:w.message)||String(w);return S.includes("permission")?ne.error("Push permission denied. Check your browser notification settings."):S.includes("key")||S.includes("VAPID")?ne.error("Push configuration error. Please contact support."):S.includes("AbortError")?ne.error("Push subscription was cancelled. Please try again."):ne.error(`Failed to subscribe: ${S}`),!1}const y=v.toJSON(),{error:b}=await U.from("push_subscriptions").upsert({user_id:s.id,endpoint:y.endpoint,p256dh_key:y.keys.p256dh,auth_key:y.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),ne.error("Failed to save notification preferences. Please try again."),b;return a(!0),ne.success("Push notifications enabled!"),!0}catch(f){if(console.error("Error subscribing to push notifications:",f),!(f instanceof Error&&f.message.includes("toast"))){const g=f instanceof Error?f.message:"Unknown error";ne.error("Failed to enable push notifications: "+g)}return!1}finally{l(!1)}},[h,o,s,d]),p=_.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const f=await o.pushManager.getSubscription();return f&&await f.unsubscribe(),await U.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ne.success("Push notifications disabled"),!0}catch(f){console.error("Error unsubscribing:",f);const g=f instanceof Error?f.message:"Unknown error";return ne.error("Failed to disable push notifications: "+g),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:p}}const IOe="push_notification_prompt_dismissed",S6s=["/dashboard","/admin"],C6s=()=>{const{user:s}=hs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=NFt(),i=Pd(),[l,o]=_.useState(!1),[c,d]=_.useState(!1),u=S6s.some(p=>i.pathname===p||i.pathname.startsWith(`${p}/`));_.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${IOe}_${s.id}`))return;const f=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(f)},[s,t,n,r,u]);const h=async()=>{d(!0);const p=await a();d(!1),p&&(s&&localStorage.setItem(`${IOe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${IOe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(Is,{open:l,onOpenChange:p=>!p&&m(),children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{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($g,{className:"h-6 w-6 text-primary"})}),e.jsx(Rs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(_r,{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(z,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(z,{variant:"ghost",onClick:m,className:"w-full",children:"Not Now"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},vft=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(p=>p(t,m))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},A6s=s=>s?vft(s):vft,E6s=s=>s;function T6s(s,t=E6s){const n=Ft.useSyncExternalStore(s.subscribe,Ft.useCallback(()=>t(s.getState()),[s,t]),Ft.useCallback(()=>t(s.getInitialState()),[s,t]));return Ft.useDebugValue(n),n}const bft=s=>{const t=A6s(s),n=r=>T6s(t,r);return Object.assign(n,t),n},M6s=s=>s?bft(s):bft;function P6s(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 dVe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return dVe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return dVe(r)(n)}}}},L6s=(s,t)=>(n,r,a)=>{let i={storage:P6s(()=>window.localStorage),partialize:v=>v,version:0,merge:(v,y)=>({...y,...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})},m=a.setState;a.setState=(v,y)=>(m(v,y),h());const p=s((...v)=>(n(...v),h()),r,a);a.getInitialState=()=>p;let f;const g=()=>{var v,y;if(!u)return;const b=++o;l=!1,c.forEach(S=>{var C;return S((C=r())!=null?C:p)});const w=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(v=r())!=null?v:p))||void 0;return dVe(u.getItem.bind(u))(i.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==i.version){if(i.migrate){const C=i.migrate(S.state,S.version);return C instanceof Promise?C.then(E=>[!0,E]):[!0,C]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var C;if(b!==o)return;const[E,P]=S;if(f=i.merge(P,(C=r())!=null?C:p),n(f,!0),E)return h()}).then(()=>{b===o&&(w==null||w(r(),void 0),f=r(),l=!0,d.forEach(S=>S(f)))}).catch(S=>{b===o&&(w==null||w(void 0,S))})};return a.persist={setOptions:v=>{i={...i,...v},v.storage&&(u=v.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>l,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(d.add(v),()=>{d.delete(v)})},i.skipHydration||g(),f||p},I6s=L6s,OPe=M6s()(I6s((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 D6s({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=IPe}){return e.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:i.map(l=>{const o=l.icon,c=s===l.id,d=t===l.id,u=(a==null?void 0:a[l.id])??0,h=`hsl(var(--${l.accent}))`,m=c||d;return e.jsxs("button",{type:"button",onClick:()=>n(l.id),onMouseEnter:()=>r==null?void 0:r(l.id),"aria-expanded":l.route?void 0:c,"aria-controls":l.route?void 0:"primary-nav-flyout","aria-current":d?"page":void 0,style:{color:m?h:void 0,backgroundColor:m?`hsl(var(--${l.accent}) / 0.12)`:void 0},className:Ct("group relative flex flex-col items-center gap-1 rounded-xl px-1 py-2.5 text-[11px] font-medium transition-colors","text-sidebar-foreground/70 hover:bg-sidebar-accent/10","focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[d&&e.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:h}}),e.jsxs("span",{className:"relative",children:[e.jsx(o,{className:"h-5 w-5 transition-colors",style:{color:h}}),u>0&&e.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[9px] font-bold text-primary-foreground",style:{backgroundColor:h},children:u>9?"9+":u})]}),e.jsx("span",{className:"leading-tight",children:l.label})]},l.id)})})}function R6s({category:s,top:t,left:n,onClose:r,onNavigate:a,isFavorite:i,favorites:l,onToggleFavorite:o,isCurrent:c,badgeCounts:d}){const u=_.useRef(null);_.useEffect(()=>{const m=f=>{f.key==="Escape"&&r()},p=f=>{var v;if(!u.current)return;const g=f.target;!u.current.contains(g)&&!((v=g==null?void 0:g.closest)!=null&&v.call(g,"[data-nav-rail]"))&&r()};return document.addEventListener("keydown",m),document.addEventListener("mousedown",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",p)}},[r]);const h=m=>{const p=m.icon,f=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:Ct("group flex items-start gap-3 rounded-lg p-2 transition-colors hover:bg-muted",c(m)&&"bg-muted"),children:[e.jsxs("button",{type:"button",onClick:()=>a(m),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[e.jsx("span",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(p,{className:"h-4 w-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:m.label}),m.badge==="new"&&e.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),m.badge==="beta"&&e.jsx("span",{className:"rounded border border-amber-500 bg-amber-500/10 px-1 py-px text-[9px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:"Beta"}),m.locked&&e.jsx(Hl,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),f>0&&e.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:f>9?"9+":f})]}),m.description&&e.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:m.description})]})]}),e.jsx("button",{type:"button","aria-label":i(m)?`Remove ${m.label} from favorites`:`Add ${m.label} to favorites`,onClick:g=>{g.stopPropagation(),o(m)},className:Ct("mt-1 rounded p-1 opacity-0 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-primary group-hover:opacity-100",i(m)&&"opacity-100 text-primary",!i(m)&&"text-muted-foreground/60 hover:text-primary"),children:e.jsx(Ty,{className:Ct("h-4 w-4",i(m)&&"fill-current")})})]},m.id)};return e.jsxs("div",{id:"primary-nav-flyout",ref:u,role:"dialog","aria-label":`${s.label} navigation`,style:{top:t,left:n,maxHeight:`calc(100vh - ${t+16}px)`},className:"fixed z-40 hidden w-[min(720px,calc(100vw-8rem))] animate-in fade-in-0 slide-in-from-left-2 duration-200 motion-reduce:animate-none overflow-hidden rounded-2xl border border-border bg-card shadow-2xl md:block",children:[e.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s.label})}),e.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[l.length>0&&e.jsxs("section",{className:"mb-4",children:[e.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(Ty,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),e.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:l.map(h)})]}),s.sections.map(m=>e.jsxs("section",{className:"mb-4 last:mb-0",children:[e.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:m.title}),e.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:m.items.map(h)})]},m.title)),s.sections.length===0&&e.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function F6s({categories:s,railCategories:t=IPe,currentCategory:n,onNavigate:r,onNavigateRoute:a,isCurrent:i,badgeCounts:l,isFavorite:o,onToggleFavorite:c}){const[d,u]=_.useState(n);return e.jsx("nav",{"aria-label":"Primary",className:"p-2",children:t.map(h=>{const m=h.icon;if(h.route)return e.jsxs("button",{type:"button",onClick:()=>a(h.route),className:Ct("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"bg-sidebar-accent"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label]},h.id);const p=s.find(g=>g.id===h.id),f=d===h.id;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":f,onClick:()=>u(f?null:h.id),className:Ct("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"text-primary"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label,e.jsx(cl,{className:Ct("ml-auto h-4 w-4 transition-transform",f&&"rotate-180")})]}),f&&p&&e.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:p.sections.map(g=>e.jsxs("div",{children:[e.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:g.title}),g.items.map(v=>{const y=v.icon,b=v.badgeKey?(l==null?void 0:l[v.badgeKey])??0:0,w=(o==null?void 0:o(v))??!1;return e.jsxs("div",{className:Ct("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",i(v)&&"bg-sidebar-accent"),children:[e.jsxs("button",{type:"button",onClick:()=>r(v),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[e.jsx(y,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:v.label}),b>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:b>9?"9+":b})]}),c&&e.jsx("button",{type:"button","aria-label":w?`Remove ${v.label} from favorites`:`Add ${v.label} to favorites`,onClick:()=>c(v),className:Ct("rounded p-2",w?"text-primary":"text-muted-foreground/60"),children:e.jsx(Ty,{className:Ct("h-4 w-4",w&&"fill-current")})})]},v.id)})]},g.title))})]},h.id)})})}function kFt(){const s=zn(),t=Pd(),n=WRt(),r=_.useCallback(o=>GRt(o,n.ctx),[n.ctx]),a=_.useMemo(()=>{if(t.pathname.startsWith("/apps"))return"apps";if(t.pathname==="/dashboard")return"home";let o=null;for(const c of n.destinations){if(c.external)continue;const d=r(c);d!=="/"&&t.pathname.startsWith(d)&&(!o||d.length>o.len)&&(o={id:c.primaryCategory,len:d.length})}return(o==null?void 0:o.id)??null},[t.pathname,n.destinations,r]),i=_.useCallback(o=>!o.external&&t.pathname===r(o),[t.pathname,r]),l=_.useCallback(o=>{const c=r(o);if(o.external||o.openInNewTab){window.open(c,"_blank","noopener,noreferrer");return}s(c)},[s,r]);return{nav:n,navigate:s,currentCategory:a,isCurrent:i,go:l}}function O6s({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=kFt(),[d,u]=_.useState(null),h=_.useRef(null),m=g=>{const v=IPe.find(y=>y.id===g);if(v!=null&&v.route){u(null),i(v.route);return}u(y=>y===g?null:g)},p=d?a.categoryMap.get(d):void 0,f={more:s+t};return e.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{h.current&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>u(null),250)},onMouseEnter:()=>{h.current&&window.clearTimeout(h.current)},children:[e.jsx(D6s,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:f}),p&&e.jsx(R6s,{category:p,top:n,left:r,onClose:()=>u(null),onNavigate:g=>{u(null),c(g)},isFavorite:a.isFavorite,favorites:a.favoritesFor(p.id),onToggleFavorite:g=>a.toggleFavorite(a.favoriteKey(g)),isCurrent:o,badgeCounts:{community:s,wishlist:t}})]})}function z6s({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=kFt();return e.jsx(F6s,{categories:r.categories,railCategories:r.railCategories,currentCategory:i,isCurrent:l,isFavorite:r.isFavorite,onToggleFavorite:c=>r.toggleFavorite(r.favoriteKey(c)),badgeCounts:{community:s,wishlist:t},onNavigate:c=>{o(c),n==null||n()},onNavigateRoute:c=>{a(c),n==null||n()}})}const B6s=({bannerHeight:s,communityUnreadCount:t,wishlistOpenCount:n,isTrial:r,isExpired:a})=>{const i=zn();return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:e.jsx("button",{type:"button",onClick:()=>i("/dashboard"),"aria-label":"LevelUp home",children:e.jsx("img",{src:$Ns,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(Ki,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(O6s,{communityUnreadCount:t,wishlistOpenCount:n,flyoutTop:s+64,flyoutLeft:80}),r&&!a&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>i("/subscription"),className:"flex w-full flex-col items-center gap-1 rounded-xl border border-amber-500/30 bg-amber-500/10 px-1 py-2 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[e.jsx(un,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},$6s=({isTrial:s,isExpired:t,expiresAt:n,communityUnreadCount:r,wishlistOpenCount:a,pathname:i,onSignOut:l,onNavigated:o})=>{const c=zn();return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:e.jsx("img",{src:BNs,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(Ki,{className:"flex-1",children:[s&&!t&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{c("/subscription"),o==null||o()},className:Ct("relative mb-1 w-full overflow-hidden rounded-md p-[1.5px]","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(un,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),n&&e.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((Date.parse(n)-Date.now())/864e5)),"d left"]})]})})}),e.jsx(z6s,{communityUnreadCount:r,wishlistOpenCount:a,onNavigated:o})]}),e.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:Ct("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",i==="/profile"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{c("/profile"),o==null||o()},children:[e.jsx(Oo,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:l,children:[e.jsx(o7,{className:"h-4 w-4"}),"Sign Out"]})]})]})},$s=({children:s,title:t})=>{var me;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=hs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=qre();hPe();const{isImpersonating:h}=iPe(),p=(c&&!!d?40:0)+(h?40:0),{avatarUrl:f}=I8t(n==null?void 0:n.id),{isTrial:g,isExpired:v,expiresAt:y}=wNs(n==null?void 0:n.id),{isInnerCircleEnabled:b,isMarketplaceEnabled:w}=Wre(),{currentBrief:S,shouldShowPopup:C,hasUnseenBrief:E,openBrief:P,closeBrief:M,dismissBrief:I}=b6s(),{unreadCount:D}=jNs(),{openCount:F}=NNs();K_();const G=OPe(he=>he.cartItems).reduce((he,ge)=>he+ge.quantity,0),{leadSite:V,hasLeadSite:H,siteUrl:K}=mf();PPe(!H);const Z=zn(),oe=Pd(),[re,ae]=_.useState(null);_.useEffect(()=>{n!=null&&n.id&&U.from("profiles").select("name").eq("id",n.id).single().then(({data:he})=>{he!=null&&he.name&&ae(he.name)})},[n==null?void 0:n.id]);const J=re||((me=n==null?void 0:n.user_metadata)==null?void 0:me.name)||(n==null?void 0:n.email)||"User",[te,ce]=_.useState(!1),ve=he=>he.split(" ").map(ge=>ge[0]).join("").toUpperCase().slice(0,2);return e.jsx(UN,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[g&&v&&oe.pathname!=="/subscription"&&e.jsx(n6s,{}),typeof document<"u"&&pv.createPortal(e.jsx("aside",{className:"hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto w-20",style:{top:`${p}px`,height:`calc(100vh - ${p}px)`},children:e.jsx(B6s,{bannerHeight:p,communityUnreadCount:D,wishlistOpenCount:F,isTrial:g,isExpired:v})}),document.body),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${p}px)`,marginTop:`${p}px`},children:[e.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[e.jsxs(Wg,{open:te,onOpenChange:ce,children:[e.jsx(Yre,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(ZA,{className:"h-5 w-5"})})}),e.jsx(gg,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx($6s,{isTrial:g,isExpired:v,expiresAt:y,communityUnreadCount:D,wishlistOpenCount:F,pathname:oe.pathname,onSignOut:r,onNavigated:()=>ce(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:UNs,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(yft,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[g&&!v&&y&&e.jsx(s6s,{expiresAt:y,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(yft,{})}),S&&e.jsx(r6s,{hasUnseenBrief:E,onClick:P}),w&&e.jsxs(z,{variant:"ghost",size:"icon",className:"relative",onClick:()=>Z("/marketplace/cart"),children:[e.jsx(bS,{className:"h-5 w-5"}),G>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:G>99?"99+":G})]}),e.jsx(z,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>Z("/mission-control/calendar"),children:e.jsx(gc,{className:"h-5 w-5"})}),e.jsx(rTs,{}),e.jsx(nVe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",J.split(" ")[0],"!"]}),e.jsxs(ru,{children:[e.jsx(au,{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(ja,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(xi,{src:f||void 0}),e.jsx(Na,{className:"bg-primary text-primary-foreground font-medium text-sm",children:ve(J)})]})})}),e.jsxs(qd,{align:"end",className:"w-48",children:[e.jsxs(ua,{onClick:()=>Z("/profile"),className:"cursor-pointer",children:[e.jsx(Oo,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(ua,{onClick:()=>Z("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(_j,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ua,{onClick:()=>Z("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(_j,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(Iy,{}),e.jsxs(ua,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(o7,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(w6s,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),S&&e.jsx(v6s,{brief:S,open:C,onClose:M,onDismiss:I}),e.jsx(_6s,{}),e.jsx(N6s,{}),e.jsx(C6s,{})]})]})})},dn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=hs(),c=Pd(),d=OS();if(a||(t||n)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!r){const u=c.pathname+c.search+c.hash;return u&&u!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",u),e.jsx(ed,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(ed,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(ed,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=P8t(c.pathname);if(u&&!d.hasFeature(u))return e.jsx($s,{title:"Upgrade required",children:e.jsx(_Ns,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};function DOe({children:s}){const{isAdmin:t,loading:n,rolesLoading:r}=hs(),{isFeatureEnabled:a,isLoading:i}=Wre();return n||r||i?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!t&&!a("staging_studio_enabled")?e.jsx(ed,{to:"/apps",replace:!0}):e.jsx($s,{title:"Staging Studio",children:e.jsx(_.Suspense,{fallback:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s})})}var AJe={};(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 ae=new OffscreenCanvas(1,1),J=ae.getContext("2d");J.fillRect(0,0,1,1);var te=ae.transferToImageBitmap();J.createPattern(te,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ae){var J=n.exports.Promise,te=J!==void 0?J:t.Promise;return typeof te=="function"?new te(ae):(ae(c,c),null)}var u=function(ae,J){return{transform:function(te){if(ae)return te;if(J.has(te))return J.get(te);var ce=new OffscreenCanvas(te.width,te.height),ve=ce.getContext("2d");return ve.drawImage(te,0,0),J.set(te,ce),ce},clear:function(){J.clear()}}}(o,new Map),h=function(){var ae=Math.floor(16.666666666666668),J,te,ce={},ve=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(J=function(me){var he=Math.random();return ce[he]=requestAnimationFrame(function ge(Ee){ve===Ee||ve+ae-1{const{data:t,error:n}=await U.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 q6s(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function V6s(){const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{error:r}=await U.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}const H6s={points_earned:jl,listing_created:sa,deal_closed:Nd,custom:Ia},wft={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"},jft=()=>{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 G6s(){const{user:s}=hs(),t=$t(),{data:n}=U6s(),r=q6s(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=_.useCallback(()=>{const p=Date.now()+3e3,f={startVelocity:30,spread:360,ticks:60,zIndex:9999},g=(y,b)=>Math.random()*(b-y)+y,v=setInterval(()=>{const y=p-Date.now();if(y<=0){clearInterval(v);return}const b=50*(y/3e3);_ft({...f,particleCount:b,origin:{x:g(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),_ft({...f,particleCount:b,origin:{x:g(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);_.useEffect(()=>{jft()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const m=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],p=>(p==null?void 0:p.filter(f=>f.id!==m))??[]),await r.mutateAsync(m)}};if(jft()||!a)return null;const u=H6s[a.celebration_type]||Ia,h=wft[a.celebration_type]||wft.custom;return e.jsx(Is,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Ls,{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(z,{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 ln({className:s,...t}){return e.jsx("div",{className:Ct("animate-pulse rounded-md bg-muted",s),...t})}var zPe="Tabs",[W6s,rwr]=uf(zPe,[xL]),SFt=xL(),[K6s,EJe]=W6s(zPe),CFt=_.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=$E(o),[h,m]=Gg({prop:r,onChange:a,defaultProp:i??"",caller:zPe});return e.jsx(K6s,{scope:n,baseId:qg(),value:h,onValueChange:m,orientation:l,dir:u,activationMode:c,children:e.jsx(ci.div,{dir:u,"data-orientation":l,...d,ref:t})})});CFt.displayName=zPe;var AFt="TabsList",EFt=_.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=EJe(AFt,n),l=SFt(n);return e.jsx(oPe,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(ci.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});EFt.displayName=AFt;var TFt="TabsTrigger",MFt=_.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=EJe(TFt,n),o=SFt(n),c=IFt(l.baseId,r),d=DFt(l.baseId,r),u=r===l.value;return e.jsx(lPe,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(ci.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:wa(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:wa(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:wa(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});MFt.displayName=TFt;var PFt="TabsContent",LFt=_.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=EJe(PFt,n),c=IFt(o.baseId,r),d=DFt(o.baseId,r),u=r===o.value,h=_.useRef(u);return _.useEffect(()=>{const m=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(m)},[]),e.jsx(vg,{present:a||u,children:({present:m})=>e.jsx(ci.div,{"data-state":u?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!m,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:h.current?"0s":void 0},children:m&&i})})});LFt.displayName=PFt;function IFt(s,t){return`${s}-trigger-${t}`}function DFt(s,t){return`${s}-content-${t}`}var Y6s=CFt,RFt=EFt,FFt=MFt,OFt=LFt;const Qr=Y6s,Jr=_.forwardRef(({className:s,...t},n)=>e.jsx(RFt,{ref:n,className:Ct("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Jr.displayName=RFt.displayName;const Wt=_.forwardRef(({className:s,...t},n)=>e.jsx(FFt,{ref:n,className:Ct("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}));Wt.displayName=FFt.displayName;const Kt=_.forwardRef(({className:s,...t},n)=>e.jsx(OFt,{ref:n,className:Ct("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));Kt.displayName=OFt.displayName;const mte="#0d0d0d",NAe="#1a1a1a",mv="#c9a84c",sae="#f0d78c",hC={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function BPe(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 U.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(hC.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function TJe(){try{return!!localStorage.getItem(hC.captured)}catch{return!1}}function Z6s(){try{const s=localStorage.getItem(hC.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function MJe({open:s,onClose:t,children:n}){return _.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?pv.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, ${NAe} 0%, ${mte} 100%)`,border:`1px solid ${mv}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${mv}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(er,{className:"h-4 w-4"})}),n]})}),document.body):null}function PJe(){const[s,t]=_.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=_.useState(!1),[a,i]=_.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function LJe({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(Oo,{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(on,{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(va,{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(Ha,{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 IJe({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, ${sae} 0%, ${mv} 100%)`,color:mte,boxShadow:`0 8px 24px ${mv}55`},children:s})}function Nft({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=PJe(),[d,u]=_.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await BPe({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(hC.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ne.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(MJe,{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($g,{className:"h-4 w-4",style:{color:mv}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:sae},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:`${mv}22`,border:`1px solid ${mv}55`},children:e.jsx(un,{className:"h-5 w-5",style:{color:mv}})}),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(LJe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(IJe,{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 X6s(){const[s,t]=_.useState(!0),[n,r]=_.useState(!1);_.useEffect(()=>{try{const i=!!localStorage.getItem(hC.stickyDismissed)||TJe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(hC.stickyDismissed,"1")}catch{}};return s?e.jsx(Nft,{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, ${NAe} 0%, ${mte} 100%)`,borderTop:`1px solid ${mv}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:`${mv}22`,border:`1px solid ${mv}55`},children:e.jsx($g,{className:"h-4 w-4",style:{color:mv}})}),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, ${sae} 0%, ${mv} 100%)`,color:mte},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(er,{className:"h-4 w-4"})})]})}),e.jsx(Nft,{open:n,onClose:()=>r(!1)})]})}function Q6s(){const[s,t]=_.useState(!1),n=_.useRef(!1);_.useEffect(()=>{try{if(sessionStorage.getItem(hC.exitShown)||TJe())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),p=f=>{if(n.current&&!(f.clientY>0)){t(!0);try{sessionStorage.setItem(hC.exitShown,"1")}catch{}window.removeEventListener("mouseleave",p),document.removeEventListener("mouseleave",p)}};return document.addEventListener("mouseleave",p),()=>{clearTimeout(m),document.removeEventListener("mouseleave",p)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=PJe(),[d,u]=_.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await BPe({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{ne.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(MJe,{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, ${mte} 0%, ${NAe} 60%, ${mv} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:sae},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:NAe,border:`1px solid ${mv}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(un,{className:"h-6 w-6",style:{color:mv}})}),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(LJe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(IJe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function J6s(){const[s,t]=_.useState([]);_.useEffect(()=>{try{const o=localStorage.getItem(hC.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(hC.savedListings,JSON.stringify(o))}catch{}},r=_.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 eMs({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=J6s(),l=r(s),[o,c]=_.useState(!1),d=()=>{if(l){i(s);return}if(TJe()){a(s),ne.success("Saved to your favorites"),BPe({lead_type:"saved_listing",email:Z6s()||"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(Fo,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(tMs,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function tMs({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=PJe(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await BPe({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(),ne.success("Saved to your favorites"),t()}catch{ne.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(MJe,{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(Fo,{className:"h-4 w-4",style:{color:mv}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:sae},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(LJe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(IJe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var zFt=["PageUp","PageDown"],BFt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$Ft={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},xW="Slider",[uVe,sMs,nMs]=tW(xW),[UFt,awr]=uf(xW,[nMs]),[rMs,$Pe]=UFt(xW),qFt=_.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:m=()=>{},inverted:p=!1,form:f,...g}=s,v=_.useRef(new Set),y=_.useRef(0),w=l==="horizontal"?aMs:iMs,[S=[],C]=Gg({prop:u,defaultProp:d,onChange:F=>{var G;(G=[...v.current][y.current])==null||G.focus(),h(F)}}),E=_.useRef(S);function P(F){const q=uMs(S,F);D(F,q)}function M(F){D(F,y.current)}function I(){const F=E.current[y.current];S[y.current]!==F&&m(S)}function D(F,q,{commit:G}={commit:!1}){const V=fMs(i),H=xMs(Math.round((F-r)/i)*i+r,V),K=dte(H,[r,a]);C((Z=[])=>{const oe=cMs(Z,K,q);if(pMs(oe,c*i)){y.current=oe.indexOf(K);const re=String(oe)!==String(Z);return re&&G&&m(oe),re?oe:Z}else return Z})}return e.jsx(rMs,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:y,thumbs:v.current,values:S,orientation:l,form:f,children:e.jsx(uVe.Provider,{scope:s.__scopeSlider,children:e.jsx(uVe.Slot,{scope:s.__scopeSlider,children:e.jsx(w,{"aria-disabled":o,"data-disabled":o?"":void 0,...g,ref:t,onPointerDown:wa(g.onPointerDown,()=>{o||(E.current=S)}),min:r,max:a,inverted:p,onSlideStart:o?void 0:P,onSlideMove:o?void 0:M,onSlideEnd:o?void 0:I,onHomeKeyDown:()=>!o&&D(r,0,{commit:!0}),onEndKeyDown:()=>!o&&D(a,S.length-1,{commit:!0}),onStepKeyDown:({event:F,direction:q})=>{if(!o){const H=zFt.includes(F.key)||F.shiftKey&&BFt.includes(F.key)?10:1,K=y.current,Z=S[K],oe=i*H*q;D(Z+oe,K,{commit:!0})}}})})})})});qFt.displayName=xW;var[VFt,HFt]=UFt(xW,{startEdge:"left",endEdge:"right",size:"width",direction:1}),aMs=_.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,m]=_.useState(null),p=el(t,w=>m(w)),f=_.useRef(void 0),g=$E(a),v=g==="ltr",y=v&&!i||!v&&i;function b(w){const S=f.current||h.getBoundingClientRect(),C=[0,S.width],P=DJe(C,y?[n,r]:[r,n]);return f.current=S,P(w-S.left)}return e.jsx(VFt,{scope:s.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:e.jsx(GFt,{dir:g,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const S=b(w.clientX);l==null||l(S)},onSlideMove:w=>{const S=b(w.clientX);o==null||o(S)},onSlideEnd:()=>{f.current=void 0,c==null||c()},onStepKeyDown:w=>{const C=$Ft[y?"from-left":"from-right"].includes(w.key);d==null||d({event:w,direction:C?-1:1})}})})}),iMs=_.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=_.useRef(null),h=el(t,u),m=_.useRef(void 0),p=!a;function f(g){const v=m.current||u.current.getBoundingClientRect(),y=[0,v.height],w=DJe(y,p?[r,n]:[n,r]);return m.current=v,w(g-v.top)}return e.jsx(VFt,{scope:s.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:e.jsx(GFt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const v=f(g.clientY);i==null||i(v)},onSlideMove:g=>{const v=f(g.clientY);l==null||l(v)},onSlideEnd:()=>{m.current=void 0,o==null||o()},onStepKeyDown:g=>{const y=$Ft[p?"from-bottom":"from-top"].includes(g.key);c==null||c({event:g,direction:y?-1:1})}})})}),GFt=_.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=$Pe(xW,n);return e.jsx(ci.span,{...d,ref:t,onKeyDown:wa(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):zFt.concat(BFt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:wa(s.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(m)?m.focus():r(h)}),onPointerMove:wa(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:wa(s.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),i(h))})})}),WFt="SliderTrack",KFt=_.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=$Pe(WFt,n);return e.jsx(ci.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});KFt.displayName=WFt;var hVe="SliderRange",YFt=_.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=$Pe(hVe,n),i=HFt(hVe,n),l=_.useRef(null),o=el(t,l),c=a.values.length,d=a.values.map(m=>QFt(m,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(ci.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});YFt.displayName=hVe;var mVe="SliderThumb",ZFt=_.forwardRef((s,t)=>{const n=sMs(s.__scopeSlider),[r,a]=_.useState(null),i=el(t,o=>a(o)),l=_.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(oMs,{...s,ref:i,index:l})}),oMs=_.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=$Pe(mVe,n),o=HFt(mVe,n),[c,d]=_.useState(null),u=el(t,b=>d(b)),h=c?l.form||!!c.closest("form"):!0,m=Rre(c),p=l.values[r],f=p===void 0?0:QFt(p,l.min,l.max),g=dMs(r,l.values.length),v=m==null?void 0:m[o.size],y=v?hMs(v,f,o.direction):0;return _.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(${f}% + ${y}px)`},children:[e.jsx(uVe.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(ci.span,{role:"slider","aria-label":s["aria-label"]||g,"aria-valuemin":l.min,"aria-valuenow":p,"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:p===void 0?{display:"none"}:s.style,onFocus:wa(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(XFt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:p},r)]})});ZFt.displayName=mVe;var lMs="RadioBubbleInput",XFt=_.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=_.useRef(null),i=el(a,r),l=Jre(t);return _.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(ci.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});XFt.displayName=lMs;function cMs(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function QFt(s,t,n){const i=100/(n-t)*(s-t);return dte(i,[0,100])}function dMs(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function uMs(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 hMs(s,t,n){const r=s/2,i=DJe([0,50],[0,r]);return(r-i(t)*n)*n}function mMs(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function pMs(s,t){if(t>0){const n=mMs(s);return Math.min(...n)>=t}return!0}function DJe(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 fMs(s){return(String(s).split(".")[1]||"").length}function xMs(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var JFt=qFt,gMs=KFt,yMs=YFt,vMs=ZFt;const Mx=_.forwardRef(({className:s,...t},n)=>e.jsxs(JFt,{ref:n,className:Ct("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(gMs,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(yMs,{className:"absolute h-full bg-primary"})}),e.jsx(vMs,{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"})]}));Mx.displayName=JFt.displayName;const bMs=s=>rt({queryKey:["public-listings",s],queryFn:async()=>{let t=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, 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).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch").or("listing_class.is.null,listing_class.neq.commercial").order("created_at",{ascending:!1});if(s!=null&&s.status?t=t.eq("status",s.status):t=t.neq("status","sold"),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}}),_Ms=()=>rt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const 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)}}}),wMs=s=>rt({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=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;const i=r;return Array.isArray(i==null?void 0:i.photos)&&(i.photos=[...i.photos].sort((l,o)=>(l.sort_order??0)-(o.sort_order??0)||(o.is_primary?1:0)-(l.is_primary?1:0))),i},enabled:!!s}),jMs=()=>mt({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let m=null,p=null;if(l){const{data:b}=await U.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();b&&(m=b.id,p=b.sharing_agent_id)}const f=crypto.randomUUID(),g={id:f},{error:v}=await U.from("listing_leads").insert({id:f,listing_id:s,agent_id:p||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:p,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null});if(v)throw v;const{error:y}=await U.functions.invoke("process-listing-lead",{body:{leadId:g.id}});return y&&console.error("Error processing lead:",y),g}}),NMs=()=>mt({mutationFn:async s=>{const{error:t}=await U.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}});function eOt({title:s,subtitle:t,areaLabel:n,sections:r,agent:a,tone:i="light"}){const l=i==="dark",o=l?"text-white/65":"text-muted-foreground",c=l?"border-white/10":"border-border";return e.jsxs("div",{className:l?"text-white":"text-foreground",id:"community-guide-print",children:[e.jsxs("header",{className:`border-b ${c} pb-6 mb-8`,children:[e.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${o} mb-3`,children:[e.jsx(ip,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),e.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:s}),t&&e.jsx("p",{className:`mt-3 text-base leading-relaxed ${o}`,children:t}),n&&e.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${o}`,children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),n]})]}),e.jsx("div",{className:"space-y-10",children:r.map((d,u)=>e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[e.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(u+1).padStart(2,"0")}),e.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:d.heading})]}),d.intro&&e.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${o} mb-4`,children:d.intro}),e.jsx("ul",{className:"space-y-3",children:(d.items??[]).map((h,m)=>e.jsxs("li",{className:`rounded-xl border ${c} ${l?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[e.jsx("p",{className:"font-medium text-sm sm:text-base",children:h.name}),h.note&&e.jsx("p",{className:`text-sm mt-1 leading-relaxed ${o}`,children:h.note})]},m))})]},u))}),(a==null?void 0:a.name)&&e.jsxs("footer",{className:`mt-10 pt-6 border-t ${c}`,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:a.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${o}`,children:"Prepared for you by"}),e.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:a.name}),a.brokerage&&e.jsx("p",{className:`text-sm ${o}`,children:a.brokerage}),e.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${o}`,children:[a.phone&&e.jsxs("a",{href:`tel:${a.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[e.jsx(va,{className:"h-3.5 w-3.5"}),a.phone]}),a.email&&e.jsxs("a",{href:`mailto:${a.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),a.email]})]})]})]}),e.jsxs("p",{className:`mt-4 text-sm ${o}`,children:["Thinking about a move in ",n||"the area","? Reach out any time — happy to share what never makes it online."]})]})]})}const Nle="border-white/15 bg-white/5 text-white placeholder:text-white/40";function kMs({listingId:s}){const[t,n]=_.useState(null),[r,a]=_.useState({firstName:"",lastName:"",email:"",phone:""}),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(!1);if(_.useEffect(()=>{let m=!1;return U.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:s}}).then(({data:p})=>{!m&&p&&n(p)}).catch(()=>{}),()=>{m=!0}},[s]),!(t!=null&&t.available))return null;const h=async m=>{if(m.preventDefault(),!r.firstName.trim()||!r.email.trim()){ne.error("Please add your name and email.");return}l(!0);try{const{data:p,error:f}=await U.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:s,...r}});if(f||p!=null&&p.error)throw new Error((p==null?void 0:p.error)||"Something went wrong.");c(p),u(!0),ne.success("Your guide is ready!")}catch(p){ne.error((p==null?void 0:p.message)||"We could not send your guide. Please try again.")}finally{l(!1)}};return e.jsxs(e.Fragment,{children:[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-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[e.jsx(ip,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),e.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:t.title}),t.subtitle&&e.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:t.subtitle}),(t.teaser??[]).length>0&&e.jsx("ul",{className:"mt-4 space-y-2",children:t.teaser.map((m,p)=>e.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[e.jsx(Wr,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),m]},p))}),o?e.jsxs(z,{className:"w-full mt-5",onClick:()=>u(!0),children:[e.jsx(ip,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):e.jsxs("form",{onSubmit:h,className:"mt-5 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),e.jsx(pe,{id:"cg-first",value:r.firstName,onChange:m=>a({...r,firstName:m.target.value}),className:Nle,required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),e.jsx(pe,{id:"cg-last",value:r.lastName,onChange:m=>a({...r,lastName:m.target.value}),className:Nle})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),e.jsx(pe,{id:"cg-email",type:"email",value:r.email,onChange:m=>a({...r,email:m.target.value}),className:Nle,required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),e.jsx(pe,{id:"cg-phone",type:"tel",value:r.phone,onChange:m=>a({...r,phone:m.target.value}),className:Nle})]}),e.jsxs(z,{type:"submit",className:"w-full",disabled:i,children:[i?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-2"}),i?"Preparing your guide…":"Get the free guide"]}),e.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[e.jsx(Hl,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),e.jsx(Is,{open:d,onOpenChange:u,children:e.jsx(Ls,{className:"max-w-2xl p-0 gap-0",children:e.jsx(Ki,{className:"max-h-[82vh]",children:e.jsxs("div",{className:"p-6 sm:p-8",children:[e.jsx("div",{id:"community-guide-print",children:o&&e.jsx(eOt,{title:o.title,subtitle:o.subtitle,areaLabel:o.area_label,sections:o.sections??[],agent:o.agent})}),e.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:e.jsxs(z,{variant:"outline",onClick:()=>SMs(o==null?void 0:o.title),children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function SMs(s){const t=document.getElementById("community-guide-print");if(!t)return window.print();const n=t.cloneNode(!0);n.removeAttribute("id"),n.setAttribute("data-print-root",""),document.body.appendChild(n),document.body.classList.add("printing-doc");const r=document.title;s&&(document.title=s);let a=!1;const i=()=>{a||(a=!0,n.remove(),document.body.classList.remove("printing-doc"),document.title=r,window.removeEventListener("afterprint",i))};window.addEventListener("afterprint",i);try{window.print()}finally{setTimeout(i,1e3)}}const GP={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},wL={office:"Office",retail:"Retail",industrial:"Industrial",flex:"Flex / R&D",multifamily:"Multifamily",land:"Land",medical:"Medical",hospitality:"Hospitality",self_storage:"Self Storage",mixed_use:"Mixed Use",special_purpose:"Special Purpose"},CMs=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],AMs={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},pVe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},kft={public:"Open download",email:"Email required",nda:"NDA required"},fVe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},ROe=[{key:"pitch",label:"Pitch",blurb:"Competing for the assignment"},{key:"won",label:"Won",blurb:"Assignment secured"},{key:"launched",label:"Launch",blurb:"Microsite & materials live"},{key:"marketing",label:"Market",blurb:"Campaign in market"},{key:"under_contract",label:"Under Contract",blurb:"Deal in escrow"},{key:"closed",label:"Closed",blurb:"Transaction complete"}],I4e=[{key:"photos",label:"Professional photography uploaded",detail:"At least 6 images for the microsite hero and gallery"},{key:"financials",label:"Financial snapshot completed",detail:"NOI, cap rate, occupancy or lease rate entered"},{key:"highlights",label:"Investment highlights written",detail:"3–6 reasons this opportunity matters"},{key:"om",label:"Offering Memorandum uploaded",detail:"Gated OM available for qualified prospects"},{key:"microsite",label:"Microsite published",detail:"Public commercial microsite is live"},{key:"email",label:"Broker & investor email sent",detail:"First distribution to your database"},{key:"social",label:"Social / LinkedIn announcement",detail:"Launch post published"},{key:"signage",label:"Signage & QR deployed",detail:"On-site QR code linking to the microsite"}],tOt=[{label:"Day 1 — Positioning & pricing",detail:"Finalize the pricing strategy, opportunity narrative and target buyer/tenant profile."},{label:"Day 2–4 — Institutional-grade materials",detail:"Photography, Offering Memorandum, investor teaser and branded flyer produced."},{label:"Day 5 — Property microsite goes live",detail:"Dedicated commercial microsite with gated OM, tour requests and full analytics."},{label:"Week 1 — Targeted broker & investor outreach",detail:"Direct email to qualified buyers, brokers and 1031 investors in the LevelUp database."},{label:"Week 2 — Digital & social distribution",detail:"LinkedIn campaign, syndication and QR-coded on-site signage."},{label:"Weekly — Owner activity reporting",detail:"Every week you receive views, OM requests, downloads, tours and prospect-level interest."}];function J2(s,t=0){return s==null||Number.isNaN(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:t}).format(Number(s))}function Sft(s){if(s==null)return null;const t=Number(s);return Number.isNaN(t)?null:t>=1e6?`$${(t/1e6).toFixed(t>=1e7?1:2).replace(/\.0+$/,"")}M`:t>=1e3?`$${Math.round(t/1e3)}K`:J2(t)}function OA(s){return s==null?null:`${new Intl.NumberFormat("en-US").format(Number(s))} SF`}function kAe(s,t=2){return s==null?null:`${Number(s).toFixed(t).replace(/\.?0+$/,"")}%`}function xVe(s){if(!(s!=null&&s.lease_rate))return null;const t=AMs[s.lease_rate_unit||"sf_year"]??"";return`${s.lease_rate_unit==="month"?J2(s.lease_rate):`$${Number(s.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${t}${s.lease_type?` ${s.lease_type}`:""}`}function RH(s,t){if(!s)return J2(t)??"Price on request";if(s.deal_type==="lease")return xVe(s)??"Rate on request";const n=s.asking_price??t;if(s.deal_type==="sale_or_lease"){const r=[J2(n),xVe(s)].filter(Boolean);return r.length?r.join(" · "):"Price on request"}return J2(n)??"Price on request"}function vP(s,t){return t!=null&&t.opportunity_title?t.opportunity_title:t!=null&&t.hide_address||t!=null&&t.is_confidential?`Confidential ${t!=null&&t.commercial_type?wL[t.commercial_type]:"Commercial"} Opportunity`:s.property_address||`${s.city??""}, ${s.state??""}`}function nae(s,t){const n=(t==null?void 0:t.submarket)||s.neighborhood,r=[s.city,s.state].filter(Boolean).join(", ");return n?`${n} · ${r}`:r}function EMs(s,t){var i;const n=(s==null?void 0:s.launch_checklist)??{},r=[],a={photos:t.photoCount>=6,financials:!!(s!=null&&s.noi||s!=null&&s.cap_rate||s!=null&&s.lease_rate||s!=null&&s.occupancy_pct),highlights:(((i=s==null?void 0:s.investment_highlights)==null?void 0:i.length)??0)>=3,om:t.hasOm,microsite:t.isPublic};for(const l of I4e)(a[l.key]||n[l.key])&&r.push(l.key);return{done:r,total:I4e.length,score:Math.round(r.length/I4e.length*100)}}const Cft={om_download:10,om_request:9,tour_request:15,inquiry:12,doc_download:8,om_view:5,gallery_view:2,page_view:1,contact_click:4,share_click:2,email_click:3,email_open:1,map_view:1};function Aft(s){return s>=30?{label:"Hot",tone:"bg-amber-500/15 text-amber-600 border-amber-500/30"}:s>=12?{label:"Warm",tone:"bg-orange-500/10 text-orange-600 border-orange-500/20"}:{label:"Tracking",tone:"bg-muted text-muted-foreground border-border"}}const TMs="https://commercial.relevelup.com",mC=U;function sOt(s){return rt({queryKey:["commercial-details",s],queryFn:async()=>{const{data:t,error:n}=await mC.from("commercial_listing_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function nOt(){const s=$t(),{user:t}=hs();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await mC.from("commercial_listing_details").upsert({listing_id:n,agent_id:t==null?void 0:t.id,...r},{onConflict:"listing_id"}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["commercial-details",r.listingId]}),s.invalidateQueries({queryKey:["listing",r.listingId]})}})}function MMs(s){return rt({queryKey:["commercial-pitch",s],queryFn:async()=>{const{data:t,error:n}=await mC.from("commercial_pitch_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function rOt(){const s=$t(),{user:t}=hs();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await mC.from("commercial_pitch_details").upsert({listing_id:n,agent_id:t==null?void 0:t.id,...r},{onConflict:"listing_id"}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["commercial-pitch",r.listingId]})})}function aOt(){const s=$t();return mt({mutationFn:async({listingId:t,stage:n,lostReason:r})=>{const a=n==="won",i=n==="lost",l={lifecycle_stage:n};a&&(l.status="coming_soon"),i&&(l.is_public=!1,l.allow_sharing=!1);const{error:o}=await mC.from("listings").update(l).eq("id",t);if(o)throw o;return(a||i)&&await mC.from("commercial_pitch_details").update({outcome:a?"won":"lost",won_at:a?new Date().toISOString():null,lost_at:i?new Date().toISOString():null,lost_reason:i?r??null:null}).eq("listing_id",t),n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing",n.listingId]}),s.invalidateQueries({queryKey:["commercial-pitch",n.listingId]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})}function PMs(){const s=$t();return mt({mutationFn:async({listingId:t,values:n})=>{const{error:r}=await mC.from("listings").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing",n.listingId]}),s.invalidateQueries({queryKey:["my-listings"]})}})}function RJe(s,t=90){return rt({queryKey:["commercial-engagement",s,t],queryFn:async()=>{const n=new Date(Date.now()-t*864e5).toISOString(),{data:r,error:a}=await mC.from("commercial_engagement_events").select("*").eq("listing_id",s).gte("created_at",n).order("created_at",{ascending:!1}).limit(1e3);if(a)throw a;return r??[]},enabled:!!s})}function FJe(s){return rt({queryKey:["commercial-leads",s],queryFn:async()=>{const{data:t,error:n}=await mC.from("listing_leads").select("*").eq("listing_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}const Eft="lu_commercial_session";function iOt(){try{let s=localStorage.getItem(Eft);return s||(s=crypto.randomUUID(),localStorage.setItem(Eft,s)),s}catch{return"anonymous"}}async function AB(s,t,n={}){try{await mC.from("commercial_engagement_events").insert({listing_id:s,event_type:t,session_id:iOt(),source:typeof document<"u"&&document.referrer||null,metadata:n})}catch{}}const LMs={om_request:{eyebrow:"Confidential materials",title:"Request the Offering Memorandum",blurb:"Complete the form below and the offering package will be released to you immediately.",cta:"Request access"},tour_request:{eyebrow:"Property tour",title:"Schedule a tour",blurb:"Tell us who you represent and preferred timing — the listing broker will confirm directly.",cta:"Request tour"},investor_inquiry:{eyebrow:"Investment inquiry",title:"Request information",blurb:"Send a note to the listing broker about this opportunity.",cta:"Send inquiry"}};function IMs({open:s,onOpenChange:t,listingId:n,kind:r,documentId:a,requiresNda:i,brokerName:l}){const o=LMs[r],[c,d]=_.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState(null),v=async()=>{if(!c.firstName.trim()||!c.email.trim()){ne.error("Name and email are required");return}if(i&&r==="om_request"&&!u){ne.error("Please acknowledge the confidentiality terms");return}p(!0);try{const{data:y,error:b}=await U.functions.invoke("commercial-lead",{body:{listingId:n,documentId:a??null,leadType:r,firstName:c.firstName,lastName:c.lastName,email:c.email,phone:c.phone||null,company:c.company||null,role:c.role,message:c.message||null,ndaAccepted:u,sessionId:iOt()}});if(b)throw b;if(y!=null&&y.error)throw new Error(y.error);g({signedUrl:(y==null?void 0:y.signedUrl)??null,fileName:(y==null?void 0:y.fileName)??null}),y!=null&&y.signedUrl&&window.open(y.signedUrl,"_blank")}catch(y){ne.error(y.message||"Something went wrong. Please try again.")}finally{p(!1)}};return e.jsx(Is,{open:s,onOpenChange:y=>{t(y),y||g(null)},children:e.jsxs(Ls,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[e.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:o.eyebrow}),e.jsx("h2",{className:"mt-2 font-serif text-2xl",children:f?"Access granted":o.title}),e.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:f?f.signedUrl?"Your download has opened in a new tab. The secure link expires in 30 minutes.":`Your request has been sent${l?` to ${l}`:""}. You'll hear back shortly.`:o.blurb})]}),f?e.jsxs("div",{className:"space-y-4 px-7 py-7",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[e.jsx(Mr,{className:"h-5 w-5 text-emerald-400"}),e.jsx("p",{className:"text-sm text-white/80",children:f.fileName??"Request received"})]}),f.signedUrl&&e.jsx(z,{className:"w-full",onClick:()=>window.open(f.signedUrl,"_blank"),children:"Download again"}),e.jsx(z,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>t(!1),children:"Close"})]}):e.jsxs("div",{className:"space-y-4 px-7 py-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(EI,{label:"First name *",children:e.jsx(pe,{value:c.firstName,onChange:y=>d({...c,firstName:y.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(EI,{label:"Last name",children:e.jsx(pe,{value:c.lastName,onChange:y=>d({...c,lastName:y.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(EI,{label:"Email *",children:e.jsx(pe,{type:"email",value:c.email,onChange:y=>d({...c,email:y.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(EI,{label:"Company",children:e.jsx(pe,{value:c.company,onChange:y=>d({...c,company:y.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(EI,{label:"Phone",children:e.jsx(pe,{value:c.phone,onChange:y=>d({...c,phone:y.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(EI,{label:"I am a *",children:e.jsxs(ls,{value:c.role,onValueChange:y=>d({...c,role:y}),children:[e.jsx(rs,{className:"border-white/15 bg-white/5 text-white",children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(fVe).map(([y,b])=>e.jsx(He,{value:y,children:b},y))})]})}),r!=="om_request"&&e.jsx(EI,{label:"Message",children:e.jsx(Ps,{rows:3,value:c.message,onChange:y=>d({...c,message:y.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:r==="tour_request"?"Preferred dates and times…":"Your question…"})}),i&&r==="om_request"&&e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[e.jsx(za,{checked:u,onCheckedChange:y=>h(!!y),className:"mt-0.5 border-white/30"}),e.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[e.jsx(Ch,{className:"mr-1 inline h-3.5 w-3.5"}),"I acknowledge these materials are confidential and agree not to distribute them without the listing broker's written consent."]})]}),e.jsxs(z,{className:"w-full",size:"lg",onClick:v,disabled:m,children:[m?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Hl,{className:"mr-2 h-4 w-4"}),o.cta]}),e.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function EI({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:s}),t]})}function OJe(s){if(!s)return[];const t=[],n=(r,a)=>{a&&t.push({label:r,value:a})};return n("Cap Rate",kAe(s.cap_rate)),n("NOI",Sft(s.noi)),n("Occupancy",s.occupancy_pct!=null?`${Math.round(Number(s.occupancy_pct))}%`:null),n("Building SF",OA(s.building_sf)),n("Available SF",OA(s.available_sf)),n("Lot Size",s.lot_acres!=null?`${Number(s.lot_acres)} AC`:null),n("Units",s.units!=null?String(s.units):null),n("Price / SF",s.price_per_sf!=null?J2(s.price_per_sf,2):null),n("Price / Unit",Sft(s.price_per_unit)),n("Lease Rate",s.deal_type!=="sale"?xVe(s):null),n("Year Built",null),n("Zoning",s.zoning??null),t}function oOt({details:s,className:t="",tone:n="light"}){const r=OJe(s).slice(0,8);if(!r.length)return null;const a=n==="dark";return e.jsx("div",{className:`grid gap-px overflow-hidden rounded-xl border ${a?"border-white/10 bg-white/10":"bg-border"} sm:grid-cols-2 lg:grid-cols-4 ${t}`,children:r.map(i=>e.jsxs("div",{className:`${a?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[e.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${a?"text-white/45":"text-muted-foreground"}`,children:i.label}),e.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${a?"text-white":""}`,children:i.value})]},i.label))})}function DMs(s){return rt({queryKey:["commercial-microsite",s],queryFn:async()=>{const{data:t,error:n}=await U.functions.invoke("commercial-public",{body:{slug:s}});if(n)throw n;if(t!=null&&t.error)throw new Error(t.error);return t},enabled:!!s})}function RMs({slug:s}){var F,q;const{data:t,isLoading:n,error:r}=DMs(s),[a,i]=_.useState(null),[l,o]=_.useState(null),c=t==null?void 0:t.listing,d=(t==null?void 0:t.details)??void 0,u=(t==null?void 0:t.documents)??[],h=(c==null?void 0:c.photos)??[],m=c==null?void 0:c.agent,p=!!(d!=null&&d.is_confidential||d!=null&&d.hide_address),f=_.useMemo(()=>OJe(d).slice(0,8),[d]);if(_.useEffect(()=>{c!=null&&c.id&&AB(c.id,"page_view",{slug:s})},[c==null?void 0:c.id,s]),_.useEffect(()=>{if(a===null)return;const G=V=>{V.key==="Escape"&&i(null),V.key==="ArrowRight"&&i(H=>H===null?H:(H+1)%h.length),V.key==="ArrowLeft"&&i(H=>H===null?H:(H-1+h.length)%h.length)};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[a,h.length]),n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!c)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This offering is no longer available."});const g=vP(c,d),v=nae(c,d),y=c.latitude&&c.longitude?`${c.latitude},${c.longitude}`:p?[d==null?void 0:d.submarket,c.city,c.state].filter(Boolean).join(", ")||null:[c.property_address,c.city,c.state].filter(Boolean).join(", ")||null,b=(F=h[0])==null?void 0:F.photo_url,w=(d==null?void 0:d.tenants)??[],S=(d==null?void 0:d.spaces)??[],C=(d==null?void 0:d.demographics)??{},E=(d==null?void 0:d.traffic_counts)??[],P=(d==null?void 0:d.investment_highlights)??[],M=(d==null?void 0:d.property_highlights)??[],I=["radius_1","radius_3","radius_5"].some(G=>(C==null?void 0:C[G])&&Object.values(C[G]).some(Boolean)),D=(G,V)=>{o({kind:G,documentId:V}),AB(c.id,G==="om_request"?"om_request":G,{})};return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(dl,{children:[e.jsx("title",{children:`${g} | ${v}`}),e.jsx("meta",{name:"description",content:(c.description??"").slice(0,155)||`${GP[(d==null?void 0:d.deal_type)??"sale"]} — ${v}`}),p&&e.jsx("meta",{name:"robots",content:"noindex,nofollow"}),e.jsx("meta",{property:"og:title",content:g}),e.jsx("meta",{property:"og:type",content:"website"})]}),e.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[e.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[e.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),e.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[b?e.jsx("img",{src:b,alt:g,className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[e.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:GP[(d==null?void 0:d.deal_type)??"sale"]}),(d==null?void 0:d.commercial_type)&&e.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:wL[d.commercial_type]}),p&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-300/30 bg-amber-300/10 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-200",children:[e.jsx(Hl,{className:"h-3 w-3"})," Confidential offering"]})]}),e.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:g}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[e.jsx(Ha,{className:"h-4 w-4"})," ",v]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(d==null?void 0:d.deal_type)==="lease"?"Lease rate":"Asking price"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:RH(d,c.price)})]}),(d==null?void 0:d.cap_rate)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:kAe(d.cap_rate)})]})]}),e.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[e.jsxs(z,{size:"lg",className:"rounded-full px-7",onClick:()=>{var G;return D("om_request",((G=u.find(V=>V.doc_kind==="om"))==null?void 0:G.id)??null)},children:["Request Offering Memorandum ",e.jsx(Da,{className:"ml-2 h-4 w-4"})]}),e.jsx(z,{size:"lg",variant:"outline",className:"rounded-full border-white/25 bg-white/5 px-7 text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Schedule a tour"})]})]})]}),f.length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:e.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(f.length,4)}, minmax(0, 1fr))`},children:f.map(G=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:G.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:G.value})]},G.label))})}),P.length>0&&e.jsx(CT,{eyebrow:"The opportunity",title:"Investment highlights",children:e.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:P.map((G,V)=>e.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(V+1).padStart(2,"0")}),e.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:G})]},V))})}),(c.description||M.length>0)&&e.jsx(CT,{eyebrow:"Property",title:"The asset",children:e.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[c.description&&e.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(c.description).split(/\n{2,}/).map((G,V)=>e.jsx("p",{children:G},V))}),M.length>0&&e.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:M.map((G,V)=>e.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[e.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",G]},V))})]})}),h.length>1&&e.jsx(CT,{eyebrow:"Gallery",title:"Property imagery",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:h.slice(1,10).map((G,V)=>e.jsx("button",{onClick:()=>{i(V+1),AB(c.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${V===0?"md:col-span-2 md:row-span-2":""}`,children:e.jsx("img",{src:G.photo_url,alt:`${g} — image ${V+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${V===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},G.id))})}),((d==null?void 0:d.noi)||(d==null?void 0:d.gross_income)||(d==null?void 0:d.operating_expenses)||(d==null?void 0:d.occupancy_pct)!=null)&&e.jsxs(CT,{eyebrow:"Financials",title:"Offering snapshot",children:[e.jsx("div",{className:"grid gap-px overflow-hidden rounded-2xl border border-white/10 bg-white/10 sm:grid-cols-2 lg:grid-cols-4",children:[{l:"Net operating income",v:J2(d==null?void 0:d.noi)},{l:"Gross income",v:J2(d==null?void 0:d.gross_income)},{l:"Operating expenses",v:J2(d==null?void 0:d.operating_expenses)},{l:"Occupancy",v:(d==null?void 0:d.occupancy_pct)!=null?`${Math.round(Number(d.occupancy_pct))}%`:null},{l:"Price per SF",v:(d==null?void 0:d.price_per_sf)!=null?J2(d.price_per_sf,2):null},{l:"Price per unit",v:J2(d==null?void 0:d.price_per_unit)},{l:"Tenancy",v:d!=null&&d.tenancy?`${d.tenancy[0].toUpperCase()}${d.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(d==null?void 0:d.broker_coop_pct)!=null?`${d.broker_coop_pct}%`:null}].filter(G=>G.v).map(G=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:G.l}),e.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:G.v})]},G.l))}),(d==null?void 0:d.call_for_offers_at)&&e.jsxs("p",{className:"mt-6 inline-flex items-center gap-2 rounded-full border border-amber-300/25 bg-amber-300/10 px-5 py-2 text-sm text-amber-100",children:["Call for offers · ",new Date(d.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(w.length>0||S.length>0)&&e.jsx(CT,{eyebrow:"Occupancy",title:S.length?"Space availability":"Tenant roster",children:e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-4",children:S.length?"Suite":"Tenant"}),e.jsx("th",{className:"px-6 py-4",children:"SF"}),e.jsx("th",{className:"px-6 py-4",children:S.length?"Rate":"Rent"}),e.jsx("th",{className:"px-6 py-4",children:S.length?"Availability":"Lease expiry"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:(S.length?S:w).map((G,V)=>e.jsxs("tr",{className:"text-white/80",children:[e.jsx("td",{className:"px-6 py-4 font-medium text-white",children:G.suite??G.name??"—"}),e.jsx("td",{className:"px-6 py-4 tabular-nums",children:G.sf?OA(Number(G.sf)):"—"}),e.jsx("td",{className:"px-6 py-4",children:G.rate??G.rent??"—"}),e.jsx("td",{className:"px-6 py-4",children:G.availability??G.lease_expiry??"—"})]},V))})]})})}),e.jsx(CT,{eyebrow:"Location",title:d!=null&&d.submarket?`${d.submarket} submarket`:v,children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[y?e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(y)}&z=${c.latitude&&c.longitude?15:12}&output=embed`,onLoad:()=>AB(c.id,"map_view",{})})}):e.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-center text-sm text-white/50",children:p?"Exact location released with the Offering Memorandum.":v}),e.jsxs("div",{className:"space-y-5",children:[(d==null?void 0:d.zoning)&&e.jsx(EB,{label:"Zoning",value:d.zoning}),(d==null?void 0:d.lot_acres)!=null&&e.jsx(EB,{label:"Site size",value:`${d.lot_acres} acres`}),(d==null?void 0:d.parking_spaces)!=null&&e.jsx(EB,{label:"Parking",value:`${d.parking_spaces} spaces`}),(d==null?void 0:d.opportunity_zone)&&e.jsx(EB,{label:"Opportunity Zone",value:"Qualified"}),E.filter(G=>G.road||G.count).map((G,V)=>e.jsx(EB,{label:`Traffic count — ${G.road??"Adjacent road"}`,value:`${G.count??"—"} VPD`},V)),!(d!=null&&d.zoning)&&(d==null?void 0:d.lot_acres)==null&&(d==null?void 0:d.parking_spaces)==null&&!(d!=null&&d.opportunity_zone)&&e.jsx(EB,{label:"Submarket",value:(d==null?void 0:d.submarket)||v})]})]})}),I&&e.jsx(CT,{eyebrow:"Market",title:"Demographics",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([G,V])=>{const H=C==null?void 0:C[G];return!H||!Object.values(H).some(Boolean)?null:e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:V}),e.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",H.population],["Households",H.households],["Avg. income",H.avg_income],["Daytime pop.",H.daytime_pop]].filter(([,K])=>K).map(([K,Z])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-white/50",children:K}),e.jsx("dd",{className:"font-medium tabular-nums",children:Z})]},K))})]},G)})})}),u.length>0&&e.jsx(CT,{eyebrow:"Deal room",title:"Offering documents",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:u.map(G=>{const V=G.gate_level==="public";return e.jsxs("div",{className:"flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] p-5 transition-colors hover:border-white/20",children:[e.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:V?e.jsx(Ga,{className:"h-5 w-5"}):G.gate_level==="nda"?e.jsx(Ch,{className:"h-5 w-5"}):e.jsx(Hl,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:G.title||pVe[G.doc_kind||"other"]}),e.jsx("p",{className:"text-xs text-white/45",children:V?"Available to download":G.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),e.jsx(z,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("om_request",G.id),children:V?"Download":"Request"})]},G.id)})})}),m&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:e.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-6",children:[m.avatar_url&&e.jsx("img",{src:m.avatar_url,alt:m.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:m.name}),e.jsx("p",{className:"text-sm text-white/55",children:((q=m.brokerage)==null?void 0:q.name)||m.brokerage_name})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[m.email&&e.jsxs(z,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{AB(c.id,"contact_click",{}),window.location.href=`mailto:${m.email}`},children:[e.jsx(on,{className:"mr-2 h-4 w-4"})," Email"]}),m.phone&&e.jsxs(z,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{AB(c.id,"contact_click",{}),window.location.href=`tel:${m.phone}`},children:[e.jsx(va,{className:"mr-2 h-4 w-4"})," Call"]}),e.jsx(z,{className:"rounded-full",onClick:()=>D("investor_inquiry"),children:"Request information"})]})]})})}),e.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:e.jsx("p",{children:"The information contained herein has been obtained from sources believed reliable but is not guaranteed. Prospective purchasers and tenants should conduct their own independent investigation."})}),e.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-6 py-3.5 md:px-10",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:g}),e.jsxs("p",{className:"truncate text-xs text-white/50",children:[RH(d,c.price)," · ",v]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Tour"}),e.jsx(z,{size:"sm",className:"rounded-full",onClick:()=>{var G;return D("om_request",((G=u.find(V=>V.doc_kind==="om"))==null?void 0:G.id)??null)},children:"Request OM"})]})]})}),e.jsx(Is,{open:a!==null,onOpenChange:G=>!G&&i(null),children:e.jsx(Ls,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:a!==null&&h[a]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h[a].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),e.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>i(null),children:e.jsx(er,{className:"h-5 w-5"})}),e.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>i(G=>(G-1+h.length)%h.length),children:e.jsx(Wc,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>i(G=>(G+1)%h.length),children:e.jsx(yi,{className:"h-6 w-6"})})]})})}),l&&e.jsx(IMs,{open:!0,onOpenChange:G=>!G&&o(null),listingId:c.id,kind:l.kind,documentId:l.documentId,requiresNda:!!(d!=null&&d.requires_nda)||(d==null?void 0:d.om_gate_mode)==="nda",brokerName:m==null?void 0:m.name})]})}function CT({eyebrow:s,title:t,children:n}){return e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:s}),e.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:t}),e.jsx("div",{className:"mt-12",children:n})]})})}function EB({label:s,value:t}){return e.jsxs("div",{className:"border-t border-white/10 pt-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:s}),e.jsx("p",{className:"mt-1 text-lg",children:t})]})}const Tft="/assets/levelup-logo-color-BeKd2k_g.png",FMs={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"},FOe={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"},Mft={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},OOe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),WY=s=>new Intl.NumberFormat("en-US").format(s);function zJe({slugOverride:s}={}){var It,qs,wt,Us,Es,kn;const t=Mi(),n=s||t.slugOrId,[r]=Gl(),{data:a,isLoading:i}=wMs(n||""),l=jMs(),o=NMs(),c=r.get("ref"),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState("in_person"),[I,D]=_.useState("info"),[F,q]=_.useState(!1),[G,V]=_.useState(!1),[H,K]=_.useState(null),[Z,oe]=_.useState(!1);_.useState(!1);const[re,ae]=_.useState(!1),[J,te]=_.useState(20),[ce,ve]=_.useState(6.5),[me,he]=_.useState(30),ge=_.useRef(null),[Ee,Ne]=_.useState(!1);_.useEffect(()=>{const Sn=()=>Ne(window.scrollY>300);return window.addEventListener("scroll",Sn,{passive:!0}),()=>window.removeEventListener("scroll",Sn)},[]),_.useEffect(()=>{c&&o.mutate(c)},[c]),_.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Pe=(a==null?void 0:a.photos)||[],Oe=Pe.find(Sn=>Sn.is_primary)||Pe[0],ke=_.useMemo(()=>{if(!(a!=null&&a.price))return 0;const Sn=a.price*(1-J/100),bn=ce/100/12,cr=me*12;return bn===0?Sn/cr:Sn*bn/(1-Math.pow(1+bn,-cr))},[a==null?void 0:a.price,J,ce,me]),Ve=async()=>{const Sn=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:Sn})}catch{}else await navigator.clipboard.writeText(Sn),ne.success("Link copied to clipboard")},_e=async Sn=>{if(Sn.preventDefault(),!d.trim()||!p.trim()||!a)return;const bn=I==="showing";if(bn&&!w){ne.error("Please pick a preferred date for your showing");return}q(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:p.trim(),phone:g.trim(),shareToken:c,leadType:bn?"showing_request":"info_request",preferredDate:bn?w:null,preferredTime:bn&&C||null,showingMode:bn?P:null,message:y.trim()||null}),V(!0),ne.success(bn?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(cr){console.error("Lead submission error:",cr),ne.error(`Failed to submit: ${cr.message||"Please try again"}`)}finally{q(!1)}},Ae=()=>{H!==null&&K(H===0?Pe.length-1:H-1)},Se=()=>{H!==null&&K(H===Pe.length-1?0:H+1)};if((a==null?void 0:a.listing_class)==="commercial")return e.jsx(RMs,{slug:n});if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(ln,{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(or,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Tft,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(sa,{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(z,{asChild:!0,children:e.jsx(or,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const We=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,qe=((qs=(It=a.agent)==null?void 0:It.brokerage)==null?void 0:qs.name)||((wt=a.agent)==null?void 0:wt.brokerage_name),Be=((Us=a.agent)==null?void 0:Us.name)||"",Ze=qe||Be||"",$e=FOe[a.status]==="Sold"?"Just Sold":FOe[a.status],Xe=$e?`${$e}: ${We}`:We,nt=[`${OOe(a.price)} · ${a.city}, ${a.state}`,Be?`Presented by ${Be}${qe?`, ${qe}`:""}.`:""].filter(Boolean).join(" · "),Ge=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,Je=a.description||"",ut=Je.length>420,lt=re||!ut?Je:Je.slice(0,420).trimEnd()+"…",qt=a.page_config||{},zt=Sn=>{var bn;return(((bn=qt.sections)==null?void 0:bn[Sn])??!0)!==!1},Zt=Array.isArray(qt.addons)?qt.addons:[],ms=qt.custom_note||"",Dt=qt.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:Ze?`${We} | ${Ze}`:We}),e.jsx("meta",{name:"description",content:`${OOe(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${Mft[a.property_type]} in ${a.city}, ${a.state}. ${Je.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:Xe}),e.jsx("meta",{property:"og:description",content:nt}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Oe&&e.jsx("meta",{property:"og:image",content:Oe.photo_url}),Ze&&e.jsx("meta",{property:"og:site_name",content:Ze}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Xe}),e.jsx("meta",{name:"twitter:description",content:nt}),Oe&&e.jsx("meta",{name:"twitter:image",content:Oe.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:Je,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Pe.map(Sn=>Sn.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 ${Ee?"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(or,{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(ka,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Ee&&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(([Sn,bn])=>e.jsx("a",{href:`#${Sn}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:bn},Sn))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(eMs,{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:Ve,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(sd,{className:"h-4 w-4 text-white"})}),e.jsx(z,{size:"sm",onClick:()=>oe(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref:ge,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Oe?e.jsx("img",{src:Oe.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:`${FMs[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:FOe[a.status]}),Pe.length>0&&e.jsxs("button",{onClick:()=>K(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(Lx,{className:"h-3.5 w-3.5"}),Pe.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:OOe(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:WY(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(Oo,{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}),qe&&e.jsx("p",{className:"text-xs text-white/60",children:qe})]}),e.jsx(z,{size:"sm",onClick:()=>oe(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),zt("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:mj,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:Ey,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:jb,label:"Interior",value:`${WY(a.square_footage)} sqft`},a.lot_size&&{icon:Q4,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:ya,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:pj,label:"Price / sqft",value:`$${WY(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((Sn,bn)=>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(Sn.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:Sn.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:Sn.value})]})]},bn))})}),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:[zt("story")&&Je&&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:lt})}),ut&&e.jsx("button",{onClick:()=>ae(!re),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:re?"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(oi,{className:"h-3 w-3 mr-1.5"}),Mft[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(z,{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(mr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(ms||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:['"',ms||a.agent_notes,'"']})]})]}),zt("gallery")&&Pe.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:()=>K(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Pe.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Pe.slice(0,7).map((Sn,bn)=>{const cr=["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"],Fs=bn===6&&Pe.length>7;return e.jsxs("button",{onClick:()=>K(bn),className:`${cr[bn]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:Sn.photo_url,alt:`Photo ${bn+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Fs&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(Lx,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Pe.length-7," more"]})]})]},Sn.id)})})]}),zt("video")&&((Es=a.video)==null?void 0:Es.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"})})]}),zt("map")&&Ge&&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:Ge,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(Ha,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),zt("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:["$",WY(Math.round(ke))]}),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(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[J,"%"]})]}),e.jsx(Mx,{value:[J],onValueChange:Sn=>te(Sn[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",WY(Math.round(a.price*J/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[ce.toFixed(2),"%"]})]}),e.jsx(Mx,{value:[ce],onValueChange:Sn=>ve(Sn[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(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[me," yr"]})]}),e.jsx(Mx,{value:[me],onValueChange:Sn=>he(Sn[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."})]})]}),Zt.map(Sn=>{const bn=Sn.type,cr=Sn.data||{};if(bn==="extra_video"&&cr.url){const Fs=String(cr.url).includes("youtu")?`https://www.youtube.com/embed/${String(cr.url).split(/[/=]/).pop()}`:cr.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:cr.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:cr.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Fs,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:cr.title||"Video"})})]},Sn.id)}return bn==="3d_tour"&&cr.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:cr.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:cr.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},Sn.id):bn==="floor_plan"&&cr.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:cr.title||"Layout"}),e.jsx("img",{src:cr.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},Sn.id):bn==="testimonial"&&cr.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:['"',cr.quote,'"']}),cr.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",cr.author]})]},Sn.id):bn==="custom_cta"&&cr.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:Dt?`${Dt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${Dt||"rgba(255,255,255,0.1)"}`},children:[cr.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:cr.title}),e.jsx(z,{asChild:!0,size:"lg",style:Dt?{background:Dt}:void 0,children:e.jsx("a",{href:cr.url||"#agent",children:cr.label})})]},Sn.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[e.jsx(kMs,{listingId:a.id}),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(Oo,{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}),qe&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:qe})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx(z,{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(va,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx(z,{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(on,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.co_agent_name&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(Oo,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:a.co_agent_brokerage})]})]}),(a.co_agent_phone||a.co_agent_email)&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.co_agent_phone&&e.jsx(z,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.co_agent_phone}`,children:[e.jsx(va,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx(z,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(on,{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(Pft,{submitted:G,activeTab:I,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:f,phone:g,setPhone:v,message:y,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:C,setPreferredTime:E,showingMode:P,setShowingMode:M,isSubmitting:F,onSubmit:_e})})]})]}),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:[((kn=a.agent)==null?void 0:kn.phone)&&e.jsx(z,{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(va,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(z,{onClick:()=>oe(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(Ud,{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:Tft,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(Is,{open:H!==null,onOpenChange:()=>K(null),children:e.jsxs(Ls,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Os,{className:"sr-only",children:e.jsx(Rs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>K(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(er,{className:"h-5 w-5"})}),H!==null&&Pe[H]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Pe[H].photo_url,alt:`Photo ${H+1}`,className:"w-full max-h-[85vh] object-contain"}),Pe.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Ae,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(Wc,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Se,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(yi,{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:[H+1," / ",Pe.length]})]})]})]})}),e.jsx(Is,{open:Z,onOpenChange:oe,children:e.jsxs(Ls,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Os,{className:"sr-only",children:e.jsx(Rs,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(Pft,{submitted:G,activeTab:I,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:f,phone:g,setPhone:v,message:y,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:C,setPreferredTime:E,showingMode:P,setShowingMode:M,isSubmitting:F,onSubmit:_e})})]})})]})]})}function Pft(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:p,preferredDate:f,setPreferredDate:g,preferredTime:v,setPreferredTime:y,showingMode:b,setShowingMode:w,isSubmitting:S,onSubmit:C}=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(Wr,{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(Qr,{value:n,onValueChange:E=>r(E),children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Wt,{value:"info",className:"gap-1.5",children:[e.jsx(qi,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Wt,{value:"showing",className:"gap-1.5",children:[e.jsx(Ud,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-3",children:[e.jsxs(Kt,{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(ee,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(pe,{id:"preferredDate",type:"date",value:f,onChange:E=>g(E.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(ls,{value:v,onValueChange:y,children:[e.jsx(rs,{id:"preferredTime",children:e.jsx(cs,{placeholder:"Any time"})}),e.jsxs(as,{children:[e.jsx(He,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(He,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(He,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(ls,{value:b,onValueChange:E=>w(E),children:[e.jsx(rs,{id:"showingMode",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(He,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(He,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"firstName",children:"First Name *"}),e.jsx(pe,{id:"firstName",value:a,onChange:E=>i(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lastName",children:"Last Name"}),e.jsx(pe,{id:"lastName",value:l,onChange:E=>o(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email *"}),e.jsx(pe,{id:"email",type:"email",value:c,onChange:E=>d(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(pe,{id:"phone",type:"tel",value:u,onChange:E=>h(E.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ps,{id:"message",value:m,onChange:E=>p(E.target.value),rows:2})]}),e.jsx(z,{type:"submit",disabled:S,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:S?"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 FH="/assets/levelup-logo-white-C2RAgAoG.png",OMs="/assets/listings-hero-noir-BHCJrhvU.jpg";var lOt={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Pp,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(k,x){var j=x[0],A=x[1],L=x[2],O=x[3],$=j*O-L*A;return $?(k[0]=O*($=1/$),k[1]=-A*$,k[2]=-L*$,k[3]=j*$,k):null}function h(){var k=new d(9);return d!=Float32Array&&(k[1]=0,k[2]=0,k[3]=0,k[5]=0,k[6]=0,k[7]=0),k[0]=1,k[4]=1,k[8]=1,k}function m(k,x){var j=x[0],A=x[1],L=x[2],O=x[3],$=x[4],Y=x[5],X=x[6],le=x[7],xe=x[8];return k[0]=$*xe-Y*le,k[1]=L*le-A*xe,k[2]=A*Y-L*$,k[3]=Y*X-O*xe,k[4]=j*xe-L*X,k[5]=L*O-j*Y,k[6]=O*le-$*X,k[7]=A*X-j*le,k[8]=j*$-A*O,k}function p(k,x,j){var A=x[0],L=x[1],O=x[2],$=x[3],Y=x[4],X=x[5],le=x[6],xe=x[7],je=x[8],Ce=j[0],Ie=j[1],Fe=j[2],Ke=j[3],et=j[4],at=j[5],vt=j[6],pt=j[7],At=j[8];return k[0]=Ce*A+Ie*$+Fe*le,k[1]=Ce*L+Ie*Y+Fe*xe,k[2]=Ce*O+Ie*X+Fe*je,k[3]=Ke*A+et*$+at*le,k[4]=Ke*L+et*Y+at*xe,k[5]=Ke*O+et*X+at*je,k[6]=vt*A+pt*$+At*le,k[7]=vt*L+pt*Y+At*xe,k[8]=vt*O+pt*X+At*je,k}function f(){var k=new d(16);return d!=Float32Array&&(k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[11]=0,k[12]=0,k[13]=0,k[14]=0),k[0]=1,k[5]=1,k[10]=1,k[15]=1,k}function g(k){var x=new d(16);return x[0]=k[0],x[1]=k[1],x[2]=k[2],x[3]=k[3],x[4]=k[4],x[5]=k[5],x[6]=k[6],x[7]=k[7],x[8]=k[8],x[9]=k[9],x[10]=k[10],x[11]=k[11],x[12]=k[12],x[13]=k[13],x[14]=k[14],x[15]=k[15],x}function v(k){return k[0]=1,k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[5]=1,k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[10]=1,k[11]=0,k[12]=0,k[13]=0,k[14]=0,k[15]=1,k}function y(k,x){var j=x[0],A=x[1],L=x[2],O=x[3],$=x[4],Y=x[5],X=x[6],le=x[7],xe=x[8],je=x[9],Ce=x[10],Ie=x[11],Fe=x[12],Ke=x[13],et=x[14],at=x[15],vt=j*Y-A*$,pt=j*X-L*$,At=j*le-O*$,Rt=A*X-L*Y,Bt=A*le-O*Y,Ns=L*le-O*X,us=xe*Ke-je*Fe,ws=xe*et-Ce*Fe,ys=xe*at-Ie*Fe,vs=je*et-Ce*Ke,vn=je*at-Ie*Ke,Nn=Ce*at-Ie*et,Rn=vt*Nn-pt*vn+At*vs+Rt*ys-Bt*ws+Ns*us;return Rn?(k[0]=(Y*Nn-X*vn+le*vs)*(Rn=1/Rn),k[1]=(L*vn-A*Nn-O*vs)*Rn,k[2]=(Ke*Ns-et*Bt+at*Rt)*Rn,k[3]=(Ce*Bt-je*Ns-Ie*Rt)*Rn,k[4]=(X*ys-$*Nn-le*ws)*Rn,k[5]=(j*Nn-L*ys+O*ws)*Rn,k[6]=(et*At-Fe*Ns-at*pt)*Rn,k[7]=(xe*Ns-Ce*At+Ie*pt)*Rn,k[8]=($*vn-Y*ys+le*us)*Rn,k[9]=(A*ys-j*vn-O*us)*Rn,k[10]=(Fe*Bt-Ke*At+at*vt)*Rn,k[11]=(je*At-xe*Bt-Ie*vt)*Rn,k[12]=(Y*ws-$*vs-X*us)*Rn,k[13]=(j*vs-A*ws+L*us)*Rn,k[14]=(Ke*pt-Fe*Rt-et*vt)*Rn,k[15]=(xe*Rt-je*pt+Ce*vt)*Rn,k):null}function b(k,x,j){var A=x[0],L=x[1],O=x[2],$=x[3],Y=x[4],X=x[5],le=x[6],xe=x[7],je=x[8],Ce=x[9],Ie=x[10],Fe=x[11],Ke=x[12],et=x[13],at=x[14],vt=x[15],pt=j[0],At=j[1],Rt=j[2],Bt=j[3];return k[0]=pt*A+At*Y+Rt*je+Bt*Ke,k[1]=pt*L+At*X+Rt*Ce+Bt*et,k[2]=pt*O+At*le+Rt*Ie+Bt*at,k[3]=pt*$+At*xe+Rt*Fe+Bt*vt,k[4]=(pt=j[4])*A+(At=j[5])*Y+(Rt=j[6])*je+(Bt=j[7])*Ke,k[5]=pt*L+At*X+Rt*Ce+Bt*et,k[6]=pt*O+At*le+Rt*Ie+Bt*at,k[7]=pt*$+At*xe+Rt*Fe+Bt*vt,k[8]=(pt=j[8])*A+(At=j[9])*Y+(Rt=j[10])*je+(Bt=j[11])*Ke,k[9]=pt*L+At*X+Rt*Ce+Bt*et,k[10]=pt*O+At*le+Rt*Ie+Bt*at,k[11]=pt*$+At*xe+Rt*Fe+Bt*vt,k[12]=(pt=j[12])*A+(At=j[13])*Y+(Rt=j[14])*je+(Bt=j[15])*Ke,k[13]=pt*L+At*X+Rt*Ce+Bt*et,k[14]=pt*O+At*le+Rt*Ie+Bt*at,k[15]=pt*$+At*xe+Rt*Fe+Bt*vt,k}function w(k,x,j){var A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke=j[0],et=j[1],at=j[2];return x===k?(k[12]=x[0]*Ke+x[4]*et+x[8]*at+x[12],k[13]=x[1]*Ke+x[5]*et+x[9]*at+x[13],k[14]=x[2]*Ke+x[6]*et+x[10]*at+x[14],k[15]=x[3]*Ke+x[7]*et+x[11]*at+x[15]):(L=x[1],O=x[2],$=x[3],Y=x[4],X=x[5],le=x[6],xe=x[7],je=x[8],Ce=x[9],Ie=x[10],Fe=x[11],k[0]=A=x[0],k[1]=L,k[2]=O,k[3]=$,k[4]=Y,k[5]=X,k[6]=le,k[7]=xe,k[8]=je,k[9]=Ce,k[10]=Ie,k[11]=Fe,k[12]=A*Ke+Y*et+je*at+x[12],k[13]=L*Ke+X*et+Ce*at+x[13],k[14]=O*Ke+le*et+Ie*at+x[14],k[15]=$*Ke+xe*et+Fe*at+x[15]),k}function S(k,x,j){var A=j[0],L=j[1],O=j[2];return k[0]=x[0]*A,k[1]=x[1]*A,k[2]=x[2]*A,k[3]=x[3]*A,k[4]=x[4]*L,k[5]=x[5]*L,k[6]=x[6]*L,k[7]=x[7]*L,k[8]=x[8]*O,k[9]=x[9]*O,k[10]=x[10]*O,k[11]=x[11]*O,k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15],k}function C(k,x,j){var A=Math.sin(j),L=Math.cos(j),O=x[4],$=x[5],Y=x[6],X=x[7],le=x[8],xe=x[9],je=x[10],Ce=x[11];return x!==k&&(k[0]=x[0],k[1]=x[1],k[2]=x[2],k[3]=x[3],k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15]),k[4]=O*L+le*A,k[5]=$*L+xe*A,k[6]=Y*L+je*A,k[7]=X*L+Ce*A,k[8]=le*L-O*A,k[9]=xe*L-$*A,k[10]=je*L-Y*A,k[11]=Ce*L-X*A,k}function E(k,x,j){var A=Math.sin(j),L=Math.cos(j),O=x[0],$=x[1],Y=x[2],X=x[3],le=x[8],xe=x[9],je=x[10],Ce=x[11];return x!==k&&(k[4]=x[4],k[5]=x[5],k[6]=x[6],k[7]=x[7],k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15]),k[0]=O*L-le*A,k[1]=$*L-xe*A,k[2]=Y*L-je*A,k[3]=X*L-Ce*A,k[8]=O*A+le*L,k[9]=$*A+xe*L,k[10]=Y*A+je*L,k[11]=X*A+Ce*L,k}function P(k,x,j){var A=Math.sin(j),L=Math.cos(j),O=x[0],$=x[1],Y=x[2],X=x[3],le=x[4],xe=x[5],je=x[6],Ce=x[7];return x!==k&&(k[8]=x[8],k[9]=x[9],k[10]=x[10],k[11]=x[11],k[12]=x[12],k[13]=x[13],k[14]=x[14],k[15]=x[15]),k[0]=O*L+le*A,k[1]=$*L+xe*A,k[2]=Y*L+je*A,k[3]=X*L+Ce*A,k[4]=le*L-O*A,k[5]=xe*L-$*A,k[6]=je*L-Y*A,k[7]=Ce*L-X*A,k}function M(k,x){return k[0]=x[0],k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[5]=x[1],k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[10]=x[2],k[11]=0,k[12]=0,k[13]=0,k[14]=0,k[15]=1,k}function I(k,x,j){var A,L,O,$=j[0],Y=j[1],X=j[2],le=Math.sqrt($*$+Y*Y+X*X);return le0&&(O=1/Math.sqrt(O)),k[0]=x[0]*O,k[1]=x[1]*O,k[2]=x[2]*O,k}function Pe(k,x){return k[0]*x[0]+k[1]*x[1]+k[2]*x[2]}function Oe(k,x,j){var A=x[0],L=x[1],O=x[2],$=j[0],Y=j[1],X=j[2];return k[0]=L*X-O*Y,k[1]=O*$-A*X,k[2]=A*Y-L*$,k}function ke(k,x,j,A){var L=x[0],O=x[1],$=x[2];return k[0]=L+A*(j[0]-L),k[1]=O+A*(j[1]-O),k[2]=$+A*(j[2]-$),k}function Ve(k,x,j){var A=x[0],L=x[1],O=x[2],$=j[3]*A+j[7]*L+j[11]*O+j[15];return k[0]=(j[0]*A+j[4]*L+j[8]*O+j[12])/($=$||1),k[1]=(j[1]*A+j[5]*L+j[9]*O+j[13])/$,k[2]=(j[2]*A+j[6]*L+j[10]*O+j[14])/$,k}function _e(k,x,j){var A=x[0],L=x[1],O=x[2];return k[0]=A*j[0]+L*j[3]+O*j[6],k[1]=A*j[1]+L*j[4]+O*j[7],k[2]=A*j[2]+L*j[5]+O*j[8],k}function Ae(k,x,j){var A=j[0],L=j[1],O=j[2],$=j[3],Y=x[0],X=x[1],le=x[2],xe=L*le-O*X,je=O*Y-A*le,Ce=A*X-L*Y;return k[0]=Y+$*(xe+=xe)+L*(Ce+=Ce)-O*(je+=je),k[1]=X+$*je+O*xe-A*Ce,k[2]=le+$*Ce+A*je-L*xe,k}function Se(k){return k[0]=0,k[1]=0,k[2]=0,k}function We(k,x){return k[0]===x[0]&&k[1]===x[1]&&k[2]===x[2]}var qe=re,Be=ae,Ze=H;function $e(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0,k[3]=0),k}function Xe(k,x,j){return k[0]=x[0]*j,k[1]=x[1]*j,k[2]=x[2]*j,k[3]=x[3]*j,k}function nt(k,x){var j=x[0],A=x[1],L=x[2],O=x[3],$=j*j+A*A+L*L+O*O;return $>0&&($=1/Math.sqrt($)),k[0]=j*$,k[1]=A*$,k[2]=L*$,k[3]=O*$,k}function Ge(k,x){return k[0]*x[0]+k[1]*x[1]+k[2]*x[2]+k[3]*x[3]}function Je(k,x,j){var A=x[0],L=x[1],O=x[2],$=x[3];return k[0]=j[0]*A+j[4]*L+j[8]*O+j[12]*$,k[1]=j[1]*A+j[5]*L+j[9]*O+j[13]*$,k[2]=j[2]*A+j[6]*L+j[10]*O+j[14]*$,k[3]=j[3]*A+j[7]*L+j[11]*O+j[15]*$,k}function ut(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0),k[3]=1,k}function lt(k){return k[0]=0,k[1]=0,k[2]=0,k[3]=1,k}function qt(k,x,j){j*=.5;var A=x[0],L=x[1],O=x[2],$=x[3],Y=Math.sin(j),X=Math.cos(j);return k[0]=A*X+$*Y,k[1]=L*X+O*Y,k[2]=O*X-L*Y,k[3]=$*X-A*Y,k}function zt(k,x,j){j*=.5;var A=x[0],L=x[1],O=x[2],$=x[3],Y=Math.sin(j),X=Math.cos(j);return k[0]=A*X-O*Y,k[1]=L*X+$*Y,k[2]=O*X+A*Y,k[3]=$*X-L*Y,k}G(),$e();var Zt,ms,Dt,It=nt,qs=(Zt=G(),ms=K(1,0,0),Dt=K(0,1,0),function(k,x,j){var A=Pe(x,j);return A<-.999999?(Oe(Zt,ms,x),Ze(Zt)<1e-6&&Oe(Zt,Dt,x),Ne(Zt,Zt),function(L,O,$){$*=.5;var Y=Math.sin($);L[0]=Y*O[0],L[1]=Y*O[1],L[2]=Y*O[2],L[3]=Math.cos($)}(k,Zt,Math.PI),k):A>.999999?(k[0]=0,k[1]=0,k[2]=0,k[3]=1,k):(Oe(Zt,x,j),k[0]=Zt[0],k[1]=Zt[1],k[2]=Zt[2],k[3]=1+A,It(k,k))});function wt(){var k=new d(2);return d!=Float32Array&&(k[0]=0,k[1]=0),k}function Us(k,x){var j=new d(2);return j[0]=k,j[1]=x,j}function Es(k,x,j){return k[0]=x,k[1]=j,k}function kn(k,x,j){return k[0]=x[0]+j[0],k[1]=x[1]+j[1],k}function Sn(k,x,j){return k[0]=x[0]-j[0],k[1]=x[1]-j[1],k}function bn(k,x,j){return k[0]=x[0]*j,k[1]=x[1]*j,k}function cr(k){var x=k[0],j=k[1];return Math.sqrt(x*x+j*j)}function Fs(k,x){var j=x[0],A=x[1],L=j*j+A*A;return L>0&&(L=1/Math.sqrt(L)),k[0]=x[0]*L,k[1]=x[1]*L,k}function cn(k,x){return k[0]*x[0]+k[1]*x[1]}ut(),ut(),h();var lr,Tn,Yn=Sn;function fs(k){return k&&k.__esModule&&Object.prototype.hasOwnProperty.call(k,"default")?k.default:k}wt();var wn=function(){if(Tn)return lr;function k(x,j,A,L){this.cx=3*x,this.bx=3*(A-x)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*j,this.by=3*(L-j)-this.cy,this.ay=1-this.cy-this.by,this.p1x=x,this.p1y=j,this.p2x=A,this.p2y=L}return Tn=1,lr=k,k.prototype={sampleCurveX:function(x){return((this.ax*x+this.bx)*x+this.cx)*x},sampleCurveY:function(x){return((this.ay*x+this.by)*x+this.cy)*x},sampleCurveDerivativeX:function(x){return(3*this.ax*x+2*this.bx)*x+this.cx},solveCurveX:function(x,j){if(j===void 0&&(j=1e-6),x<0)return 0;if(x>1)return 1;for(var A=x,L=0;L<8;L++){var O=this.sampleCurveX(A)-x;if(Math.abs(O)O?Y=A:X=A,A=.5*(X-Y)+Y;return A},solve:function(x,j){return this.sampleCurveY(this.solveCurveX(x,j))}},lr}(),As=fs(wn);function Ss(k,x){this.x=k,this.y=x}function pr(k,x){if(Array.isArray(k)){if(!Array.isArray(x)||k.length!==x.length)return!1;for(let j=0;j=1)return 1;const x=k*k,j=x*k;return 4*(k<.5?j:3*(k-x)+j-.75)}function Yt(k,x,j,A){const L=new As(k,x,j,A);return function(O){return L.solve(O)}}const it=Yt(.25,.1,.25,1);function gt(k,x,j){return Math.min(j,Math.max(x,k))}function ft(k,x,j){return(j=gt((j-k)/(x-k),0,1))*j*(3-2*j)}function Lt(k,x,j){const A=j-x,L=((k-x)%A+A)%A+x;return L===x?j:L}function Mt(k,x,j){if(!k.length)return j(null,[]);let A=k.length;const L=new Array(k.length);let O=null;k.forEach(($,Y)=>{x($,(X,le)=>{X&&(O=X),L[Y]=le,--A===0&&j(O,L)})})}let Qt=1;function ks(){return Qt++}function gs(k){return k<=1?1:Math.pow(2,Math.ceil(Math.log2(k)))}function Vt(k,x){k.forEach(j=>{x[j]&&(x[j]=x[j].bind(x))})}function Vs(k,x,j){const A={};for(const L in k)A[L]=x.call(this,k[L],L,k);return A}function Zs(k,x,j){const A={};for(const L in k)x.call(this,k[L],L,k)&&(A[L]=k[L]);return A}function Zn(k){return Array.isArray(k)?k.map(Zn):typeof k=="object"&&k?Vs(k,Zn):k}function Or(k,x){for(let j=0;j=0)return!0;return!1}const oa={};function aa(k){oa[k]||(typeof console<"u"&&console.warn(k),oa[k]=!0)}function Kr(k,x,j){return(j.y-k.y)*(x.x-k.x)>(x.y-k.y)*(j.x-k.x)}function Tr(k){let x=0;for(let j,A,L=0,O=k.length,$=O-1;L@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(j,A,L,O)=>{const $=L||O;return x[A]=!$||$.toLowerCase(),""}),x["max-age"]){const j=parseInt(x["max-age"],10);isNaN(j)?delete x["max-age"]:x["max-age"]=j}return x}let Ro,ji=null;function Oa(k,x){return[k[4*x],k[4*x+1],k[4*x+2],k[4*x+3]]}function Ao(k,x,j,A){for(;x>1;k[L]>1;k[L]<=A?x=L+1:j=L}return x}function Ua(k){return k>0?1/(1.001-k):1+k}function Eo(k){return k>0?1-1/(1.001-k):-k}function Ji(k,x,j){return(k-x.min)*(j.max-j.min)/(x.max-x.min)+j.min}const qa={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(!qa.API_URL)return null;try{const k=new URL(qa.API_URL);return k.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":k.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 ar(){return new URL(qa.DRACO_URL,qa.API_URL).href}function ui(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Ro===void 0){if(typeof WebAssembly!="object")return!1;const k=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]);Ro=WebAssembly.validate(k)}return Ro}()?qa.MESHOPT_SIMD_URL:qa.MESHOPT_URL,qa.API_URL).href}function zo(){return new URL(qa.BUILDING_GEN_URL,qa.API_URL).href}function gl(k){return qa.API_URL_REGEX.test(k)}function tl(k){return qa.API_SPRITE_REGEX.test(k)}let Ll,Ku,uh,ym,Ld,Bm;function Sl(){return Ll==null&&(Ll=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Ll}const wu={now:()=>ym!==void 0?ym:performance.now(),setNow(k){ym=k},restoreNow(){ym=void 0},frame(k){const x=requestAnimationFrame(k);return{cancel:()=>cancelAnimationFrame(x)}},getImageData(k,x=0){const{width:j,height:A}=k;Ld||(Ld=document.createElement("canvas"));const L=Ld.getContext("2d",{willReadFrequently:!0});if(!L)throw new Error("failed to create canvas 2d context");return(j>Ld.width||A>Ld.height)&&(Ld.width=j,Ld.height=A),L.clearRect(-x,-x,j+2*x,A+2*x),L.drawImage(k,0,0,j,A),L.getImageData(-x,-x,j+2*x,A+2*x)},resolveURL:k=>(Ku||(Ku=document.createElement("a")),Ku.href=k,Ku.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(uh==null&&(uh=window.matchMedia("(prefers-reduced-motion: reduce)")),uh.matches)},hasCanvasFingerprintNoise(){if(Bm!==void 0)return Bm;if(!Sl())return Bm=!1,!1;const k=new OffscreenCanvas(85,1),x=k.getContext("2d",{willReadFrequently:!0});let j=0;for(let L=0;L0?`?${O}`:""}`}const to="mapbox-tiles";let Ta=500,so=50;const ho=["language","worldview","jobid"];let pi;function $m(){try{return caches}catch{}}function al(){const k=$m();k&&pi==null&&(pi=k.open(to))}let vo=1/0;const $x={supported:!1,testSupport:function(k){!E1&&yl&&(zc?hp(k):il=k)}};let il,yl,E1=!1,zc=!1;const Dp=typeof self<"u"?self:{};function hp(k){const x=k.createTexture();k.bindTexture(k.TEXTURE_2D,x);try{if(k.texImage2D(k.TEXTURE_2D,0,k.RGBA,k.RGBA,k.UNSIGNED_BYTE,yl),k.isContextLost())return;$x.supported=!0}catch{}k.deleteTexture(x),E1=!0}Dp.document&&(yl=Dp.document.createElement("img"),yl.onload=function(){il&&hp(il),il=null,zc=!0},yl.onerror=function(){E1=!0,il=null},yl.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const _g={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(_g);class Dv extends Error{constructor(x,j,A){j===401&&gl(A)&&(x+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(x),this.status=j,this.url=A}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function nx(k){return typeof k=="object"&&k!==null&&"status"in k&&k.status===404}const Pi=Ba()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,vm=function(k,x){return/^file:/.test(j=k.url)||/^file:/.test(Pi())&&!/^\w+:/.test(j)?function(A,L){const O=new XMLHttpRequest;O.open(A.method||"GET",A.url,!0),A.type==="arrayBuffer"&&(O.responseType="arraybuffer");for(const $ in A.headers)O.setRequestHeader($,A.headers[$]);return A.type==="json"&&(O.responseType="text",O.setRequestHeader("Accept","application/json")),O.withCredentials=A.credentials==="include",O.onerror=()=>{L(new Error(O.statusText))},O.onload=()=>{if((O.status>=200&&O.status<300||O.status===0)&&O.response!==null){let $=O.response;if(A.type==="json")try{$=JSON.parse(O.response)}catch(X){return L(X)}const Y=new Headers;O.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(X=>{const le=X.split(": "),xe=le.shift(),je=le.join(": ");Y.append(xe,je)}),L(null,$,Y)}else L(new Dv(O.statusText,O.status,A.url))},O.send(A.body),{cancel:()=>O.abort()}}(k,x):function(A,L){const O=new AbortController,$=new Request(A.url,{method:A.method||"GET",body:A.body,credentials:A.credentials,headers:A.headers,referrer:Pi(),referrerPolicy:A.referrerPolicy,signal:O.signal});let Y=!1,X=!1;const le=(xe=$.url).indexOf("sku=")>0&&gl(xe);var xe;A.type==="json"&&$.headers.set("Accept","application/json");const je=(Ie,Fe,Ke)=>{if(X)return;if(Ie&&Ie.message!=="SecurityError"&&aa(Ie.toString()),Fe&&Ke)return Ce(Fe);const et=Date.now();fetch($).then(at=>{if(at.ok){const vt=le?at.clone():null;return Ce(at,vt,et)}return L(new Dv(at.statusText,at.status,A.url))}).catch(at=>{at.name!=="AbortError"&&L(new Error(`${at.message} ${A.url}`))})},Ce=(Ie,Fe,Ke)=>{(A.type==="arrayBuffer"?Ie.arrayBuffer():A.type==="json"?Ie.json():Ie.text()).then(et=>{X||(Fe&&Ke&&function(at,vt,pt){if(al(),pi==null)return;const At=Ja(vt.headers.get("cache-control")||"");if(At["no-store"])return;const Rt={status:vt.status,statusText:vt.statusText,headers:new Headers};vt.headers.forEach((ys,vs)=>Rt.headers.set(vs,ys)),At["max-age"]&&Rt.headers.set("Expires",new Date(pt+1e3*At["max-age"]).toUTCString());const Bt=Rt.headers.get("expires");if(!Bt||new Date(Bt).getTime()-pt<42e4)return;let Ns=Ma(at.url,{persistentParams:ho});if(vt.status===206){const ys=at.headers.get("Range");if(!ys)return;Rt.status=200,Ns=js(Ns,{range:ys})}const us=new Response((ws=vt.status)!==200&&ws!==404&&[101,103,204,205,304].includes(ws)?null:vt.body,Rt);var ws;al(),pi!=null&&pi.then(ys=>ys.put(Ns,us)).catch(ys=>aa(ys.message))}($,Fe,Ke),Y=!0,L(null,et,Ie.headers))}).catch(et=>{X||L(new Error(et.message))})};return le?function(Ie,Fe){if(al(),pi==null)return Fe(null);pi.then(Ke=>{let et=Ma(Ie.url,{persistentParams:ho});const at=Ie.headers.get("Range");at&&(et=js(et,{range:at})),Ke.match(et).then(vt=>{const pt=function(At){if(!At)return!1;const Rt=new Date(At.headers.get("expires")||0),Bt=Ja(At.headers.get("cache-control")||"");return Number(Rt)>Date.now()&&!Bt["no-cache"]}(vt);Ke.delete(et).catch(Fe),pt&&Ke.put(et,vt.clone()).catch(Fe),Fe(null,vt,pt)}).catch(Fe)}).catch(Fe)}($,je):je(null,null),{cancel:()=>{X=!0,Y||O.abort()}}}(k,x);var j},Yg=function(k,x){return vm(Object.assign(k,{type:"arrayBuffer"}),x)};function hh(k){const x=document.createElement("a");return x.href=k,x.protocol===location.protocol&&x.host===location.host}let mh,pd;mh=[],pd=0;const fd=function(k,x){if($x.supported&&(k.headers||(k.headers={}),k.headers.accept="image/webp,*/*"),pd>=qa.MAX_PARALLEL_IMAGE_REQUESTS){const O={requestParameters:k,callback:x,cancelled:!1,cancel(){this.cancelled=!0}};return mh.push(O),O}pd++;let j=!1;const A=()=>{if(!j)for(j=!0,pd--;mh.length&&pd{A(),O?x(O):$&&function(X,le){const xe=new Blob([new Uint8Array(X)],{type:"image/png"});createImageBitmap(xe).then(je=>{le(null,je)}).catch(je=>{le(new Error(`Could not load image because of ${je.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}($,(X,le)=>x(X,le,Y))});return{cancel:()=>{L.cancel(),A()}}};var Ux,Ah,Eh,Jh={exports:{}},Uu={exports:{}},rx={exports:{}},R0=function(){if(Eh)return Jh.exports;Eh=1;var k=(Ux||(Ux=1,Uu.exports=function(j,A){var L,O,$,Y,X,le,xe,je;for(O=j.length-(L=3&j.length),$=A,X=3432918353,le=461845907,je=0;je>>16)*X&65535)<<16)&4294967295)<<15|xe>>>17))*le+(((xe>>>16)*le&65535)<<16)&4294967295)<<13|$>>>19))+((5*($>>>16)&65535)<<16)&4294967295))+(((Y>>>16)+58964&65535)<<16);switch(xe=0,L){case 3:xe^=(255&j.charCodeAt(je+2))<<16;case 2:xe^=(255&j.charCodeAt(je+1))<<8;case 1:$^=xe=(65535&(xe=(xe=(65535&(xe^=255&j.charCodeAt(je)))*X+(((xe>>>16)*X&65535)<<16)&4294967295)<<15|xe>>>17))*le+(((xe>>>16)*le&65535)<<16)&4294967295}return $^=j.length,$=2246822507*(65535&($^=$>>>16))+((2246822507*($>>>16)&65535)<<16)&4294967295,$=3266489909*(65535&($^=$>>>13))+((3266489909*($>>>16)&65535)<<16)&4294967295,($^=$>>>16)>>>0}),Uu.exports),x=(Ah||(Ah=1,rx.exports=function(j,A){for(var L,O=j.length,$=A^O,Y=0;O>=4;)L=1540483477*(65535&(L=255&j.charCodeAt(Y)|(255&j.charCodeAt(++Y))<<8|(255&j.charCodeAt(++Y))<<16|(255&j.charCodeAt(++Y))<<24))+((1540483477*(L>>>16)&65535)<<16),$=1540483477*(65535&$)+((1540483477*($>>>16)&65535)<<16)^(L=1540483477*(65535&(L^=L>>>24))+((1540483477*(L>>>16)&65535)<<16)),O-=4,++Y;switch(O){case 3:$^=(255&j.charCodeAt(Y+2))<<16;case 2:$^=(255&j.charCodeAt(Y+1))<<8;case 1:$=1540483477*(65535&($^=255&j.charCodeAt(Y)))+((1540483477*($>>>16)&65535)<<16)}return $=1540483477*(65535&($^=$>>>13))+((1540483477*($>>>16)&65535)<<16),($^=$>>>15)>>>0}),rx.exports);return Jh.exports=k,Jh.exports.murmur3=k,Jh.exports.murmur2=x,Jh.exports}(),mc=fs(R0);class Sd{constructor(x,...j){Object.assign(this,j[0]||{}),this.type=x}}class pf extends Sd{constructor(x,j={}){super("error",Object.assign({error:x},j))}}function lu(k,x,j){j[k]&&j[k].indexOf(x)!==-1||(j[k]=j[k]||[],j[k].push(x))}function mp(k,x,j){if(j&&j[k]){const A=j[k].indexOf(x);A!==-1&&j[k].splice(A,1)}}class Um{on(x,j){return this._listeners=this._listeners||{},lu(x,j,this._listeners),this}off(x,j){return mp(x,j,this._listeners),mp(x,j,this._oneTimeListeners),this}once(x,j){return j?(this._oneTimeListeners=this._oneTimeListeners||{},lu(x,j,this._oneTimeListeners),this):new Promise(A=>{this.once(x,A)})}fire(x,j){const A=typeof x=="string"?new Sd(x,j):x,L=A.type;if(this.listens(L)){A.target=this;const O=this._listeners&&this._listeners[L]?this._listeners[L].slice():[];for(const X of O)X.call(this,A);const $=this._oneTimeListeners&&this._oneTimeListeners[L]?this._oneTimeListeners[L].slice():[];for(const X of $)mp(L,X,this._oneTimeListeners),X.call(this,A);const Y=this._eventedParent;if(Y){const X=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(A,X),Y.fire(A)}}else A instanceof pf&&console.error(A.error);return this}listens(x){return!!(this._listeners&&this._listeners[x]&&this._listeners[x].length>0||this._oneTimeListeners&&this._oneTimeListeners[x]&&this._oneTimeListeners[x].length>0||this._eventedParent&&this._eventedParent.listens(x))}setEventedParent(x,j){return this._eventedParent=x,this._eventedParentData=j,this}}class qm{constructor(x){typeof x=="string"?this.name=x:(this.name=x.name,this.iconsetId=x.iconsetId)}static from(x){return new qm(x)}static toString(x){return x.iconsetId?`${x.name}${x.iconsetId}`:x.name}static parse(x){const[j,A]=x.split("");return new qm({name:j,iconsetId:A})}static isEqual(x,j){return x.name===j.name&&x.iconsetId===j.iconsetId}toString(){return qm.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var ot,ts={},Ks=function(){if(ot)return ts;ot=1;var k={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 x(O){return(O=Math.round(O))<0?0:O>255?255:O}function j(O){return x(O[O.length-1]==="%"?parseFloat(O)/100*255:parseInt(O))}function A(O){return($=O[O.length-1]==="%"?parseFloat(O)/100:parseFloat(O))<0?0:$>1?1:$;var $}function L(O,$,Y){return Y<0?Y+=1:Y>1&&(Y-=1),6*Y<1?O+($-O)*Y*6:2*Y<1?$:3*Y<2?O+($-O)*(2/3-Y)*6:O}try{ts.parseCSSColor=function(O){var $,Y=O.replace(/ /g,"").toLowerCase();if(Y in k)return k[Y].slice();if(Y[0]==="#")return Y.length===4?($=parseInt(Y.substr(1),16))>=0&&$<=4095?[(3840&$)>>4|(3840&$)>>8,240&$|(240&$)>>4,15&$|(15&$)<<4,1]:null:Y.length===7&&($=parseInt(Y.substr(1),16))>=0&&$<=16777215?[(16711680&$)>>16,(65280&$)>>8,255&$,1]:null;var X=Y.indexOf("("),le=Y.indexOf(")");if(X!==-1&&le+1===Y.length){var xe=Y.substr(0,X),je=Y.substr(X+1,le-(X+1)).split(","),Ce=1;switch(xe){case"rgba":if(je.length!==4)return null;Ce=A(je.pop());case"rgb":return je.length!==3?null:[j(je[0]),j(je[1]),j(je[2]),Ce];case"hsla":if(je.length!==4)return null;Ce=A(je.pop());case"hsl":if(je.length!==3)return null;var Ie=(parseFloat(je[0])%360+360)%360/360,Fe=A(je[1]),Ke=A(je[2]),et=Ke<=.5?Ke*(Fe+1):Ke+Fe-Ke*Fe,at=2*Ke-et;return[x(255*L(at,et,Ie+1/3)),x(255*L(at,et,Ie)),x(255*L(at,et,Ie-1/3)),Ce];default:return null}}return null}}catch{}return ts}();class Js{constructor(x,j,A,L=1){this.r=x,this.g=j,this.b=A,this.a=L}static parse(x){if(!x)return;if(x instanceof Js)return x;if(typeof x!="string")return;const j=Ks.parseCSSColor(x);return j?new Js(j[0]/255,j[1]/255,j[2]/255,j[3]):void 0}toString(){const[x,j,A,L]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*x)},${Math.round(255*j)},${Math.round(255*A)},${L})`}toNonPremultipliedRenderColor(x){const{r:j,g:A,b:L,a:O}=this;return new Ur(x,j,A,L,O)}toPremultipliedRenderColor(x){const{r:j,g:A,b:L,a:O}=this;return new ea(x,j*O,A*O,L*O,O)}clone(){return new Js(this.r,this.g,this.b,this.a)}}class Mn{constructor(x,j,A,L,O,$=!1){if(this.premultiplied=!1,this.premultiplied=$,x){const Y=x.image.height,X=Y*Y;this.premultiplied?(j=O===0?0:j/O*(Y-1),A=O===0?0:A/O*(Y-1),L=O===0?0:L/O*(Y-1)):(j*=Y-1,A*=Y-1,L*=Y-1),j=Math.max(0,Math.min(Y-1,j)),A=Math.max(0,Math.min(Y-1,A)),L=Math.max(0,Math.min(Y-1,L));const le=Math.floor(j),xe=Math.floor(A),je=Math.floor(L),Ce=Math.ceil(j),Ie=Math.ceil(A),Fe=Math.ceil(L),Ke=j-le,et=A-xe,at=L-je,vt=x.image.data,pt=4*(le+xe*X+je*Y),At=4*(le+xe*X+Fe*Y),Rt=4*(le+Ie*X+je*Y),Bt=4*(le+Ie*X+Fe*Y),Ns=4*(Ce+xe*X+je*Y),us=4*(Ce+xe*X+Fe*Y),ws=4*(Ce+Ie*X+je*Y),ys=4*(Ce+Ie*X+Fe*Y);this.r=Pr(Pr(Pr(vt[pt],vt[At],at),Pr(vt[Rt],vt[Bt],at),et),Pr(Pr(vt[Ns],vt[us],at),Pr(vt[ws],vt[ys],at),et),Ke)/255*(this.premultiplied?O:1),this.g=Pr(Pr(Pr(vt[pt+1],vt[At+1],at),Pr(vt[Rt+1],vt[Bt+1],at),et),Pr(Pr(vt[Ns+1],vt[us+1],at),Pr(vt[ws+1],vt[ys+1],at),et),Ke)/255*(this.premultiplied?O:1),this.b=Pr(Pr(Pr(vt[pt+2],vt[At+2],at),Pr(vt[Rt+2],vt[Bt+2],at),et),Pr(Pr(vt[Ns+2],vt[us+2],at),Pr(vt[ws+2],vt[ys+2],at),et),Ke)/255*(this.premultiplied?O:1),this.a=O}else this.r=j,this.g=A,this.b=L,this.a=O}toArray(){const{r:x,g:j,b:A,a:L}=this;return[255*x,255*j,255*A,L]}toHslaArray(){let{r:x,g:j,b:A,a:L}=this;if(this.premultiplied){if(L===0)return[0,0,0,0];const Fe=1/L;x*=Fe,j*=Fe,A*=Fe}const O=Math.min(Math.max(x,0),1),$=Math.min(Math.max(j,0),1),Y=Math.min(Math.max(A,0),1),X=Math.min(O,$,Y),le=Math.max(O,$,Y),xe=le-X,je=.5*(X+le);if(xe===0)return[0,0,100*je,L];const Ce=je>.5?xe/(2-le-X):xe/(le+X);let Ie;switch(le){case O:Ie=60*(($-Y)/xe+($Pr(A,x[L],j))}Js.black=new Js(0,0,0,1),Js.white=new Js(1,1,1,1),Js.transparent=new Js(0,0,0,0),Js.red=new Js(1,0,0,1),Js.blue=new Js(0,0,1,1);var Lo=Object.freeze({__proto__:null,array:Ni,color:function(k,x,j){return new Js(Pr(k.r,x.r,j),Pr(k.g,x.g,j),Pr(k.b,x.b,j),Pr(k.a,x.a,j))},number:Pr});class wo extends Error{constructor(x,j){super(j),this.message=j,this.key=x}}class Wl{constructor(x,j=[]){this.parent=x,this.bindings={};for(const[A,L]of j)this.bindings[A]=L}concat(x){return new Wl(this,x)}get(x){if(this.bindings[x])return this.bindings[x];if(this.parent)return this.parent.get(x);throw new Error(`${x} not found in scope.`)}has(x){return!!this.bindings[x]||!!this.parent&&this.parent.has(x)}}const xd={kind:"null"},Vr={kind:"number"},gi={kind:"string"},Ai={kind:"boolean"},rc={kind:"color"},Yc={kind:"object"},mo={kind:"value"},em={kind:"collator"},Gt={kind:"formatted"},An={kind:"resolvedImage"};function qn(k,x){return{kind:"array",itemType:k,N:x}}function qr(k){if(k.kind==="array"){const x=qr(k.itemType);return typeof k.N=="number"?`array<${x}, ${k.N}>`:k.itemType.kind==="value"?"array":`array<${x}>`}return k.kind}const Pa=[xd,Vr,gi,Ai,rc,Gt,Yc,qn(mo),An];function vi(k,x){if(x.kind==="error")return null;if(k.kind==="array"){if(x.kind==="array"&&(x.N===0&&x.itemType.kind==="value"||!vi(k.itemType,x.itemType))&&(typeof k.N!="number"||k.N===x.N))return null}else{if(k.kind===x.kind)return null;if(k.kind==="value"){for(const j of Pa)if(!vi(j,x))return null}}return`Expected ${qr(k)} but found ${qr(x)} instead.`}function Li(k,x){return x.some(j=>j.kind===k.kind)}function wi(k,x){return x.some(j=>j==="null"?k===null:j==="array"?Array.isArray(k):j==="object"?k&&!Array.isArray(k)&&typeof k=="object":j===typeof k)}function rd(k,x){return k.kind==="array"&&x.kind==="array"?k.N===x.N&&rd(k.itemType,x.itemType):k.kind===x.kind}class Au{constructor(x,j,A){this.sensitivity=x?j?"variant":"case":j?"accent":"base",this.locale=A,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(x,j){return this.collator.compare(x,j)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class pp{constructor(x,j,A,L,O){this.text=x.normalize?x.normalize():x,this.image=j,this.scale=A,this.fontStack=L,this.textColor=O}}class gd{constructor(x){this.sections=x}static fromString(x){return new gd([new pp(x,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(x=>x.text.length!==0||!!x.image&&x.image.hasPrimary())}static factory(x){return x instanceof gd?x:gd.fromString(x)}toString(){return this.sections.length===0?"":this.sections.map(x=>x.text).join("")}serialize(){const x=["format"];for(const j of this.sections){if(j.image){const L=j.image.getPrimary().id.toString();x.push(["image",L]);continue}x.push(j.text);const A={};j.fontStack&&(A["text-font"]=["literal",j.fontStack.split(",")]),j.scale&&(A["font-scale"]=j.scale),j.textColor&&(A["text-color"]=["rgba"].concat(j.textColor.toNonPremultipliedRenderColor(null).toArray())),x.push(A)}return x}}class Hd{constructor(x,j={}){this.id=qm.from(x),this.params=j.params,this.sx=j.sx||1,this.sy=j.sy||1}toString(){return JSON.stringify(this)}static parse(x){let j,A,L,O;try{({id:j,params:A,sx:L,sy:O}=JSON.parse(x)||{})}catch{return null}return j?new Hd(j,{params:A,sx:L,sy:O}):null}scaleSelf(x,j=x){return this.sx*=x,this.sy*=j,this}}class Th{constructor(x,j,A,L,O=!1){this.primaryId=qm.from(x),this.primaryOptions=j,A&&(this.secondaryId=qm.from(A)),this.secondaryOptions=L,this.available=O}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Hd(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Hd(this.secondaryId,this.secondaryOptions):null}static from(x){return typeof x=="string"?Th.build({name:x}):x}static build(x,j,A,L){return!x||typeof x=="object"&&!("name"in x)?null:new Th(x,A,j,L)}}function Rp(k,x,j,A){return typeof k=="number"&&k>=0&&k<=255&&typeof x=="number"&&x>=0&&x<=255&&typeof j=="number"&&j>=0&&j<=255?A===void 0||typeof A=="number"&&A>=0&&A<=1?null:`Invalid rgba value [${[k,x,j,A].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof A=="number"?[k,x,j,A]:[k,x,j]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function qx(k){if(k===null||typeof k=="string"||typeof k=="boolean"||typeof k=="number"||k instanceof Js||k instanceof Au||k instanceof gd||k instanceof Th)return!0;if(Array.isArray(k)){for(const x of k)if(!qx(x))return!1;return!0}if(typeof k=="object"){for(const x in k)if(!qx(k[x]))return!1;return!0}return!1}function ac(k){if(k===null)return xd;if(typeof k=="string")return gi;if(typeof k=="boolean")return Ai;if(typeof k=="number")return Vr;if(k instanceof Js)return rc;if(k instanceof Au)return em;if(k instanceof gd)return Gt;if(k instanceof Th)return An;if(Array.isArray(k)){const x=k.length;let j;for(const A of k){const L=ac(A);if(j){if(j===L)continue;j=mo;break}j=L}return qn(j||mo,x)}return Yc}function $a(k){const x=typeof k;return k===null?"":x==="string"||x==="number"||x==="boolean"?String(k):k instanceof gd||k instanceof Th||k instanceof Js?k.toString():JSON.stringify(k)}class Yr{constructor(x,j){this.type=x,this.value=j}static parse(x,j){if(x.length!==2)return j.error(`'literal' expression requires exactly one argument, but found ${x.length-1} instead.`);if(!qx(x[1]))return j.error("invalid value");const A=x[1];let L=ac(A);const O=j.expectedType;return L.kind!=="array"||L.N!==0||!O||O.kind!=="array"||typeof O.N=="number"&&O.N!==0||(L=O),new Yr(L,A)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Js?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof gd?this.value.serialize():this.value}}class Tc{constructor(x){this.name="ExpressionEvaluationError",this.message=x}toJSON(){return this.message}}const Va={string:gi,number:Vr,boolean:Ai,object:Yc};class Fp{constructor(x,j){this.type=x,this.args=j}static parse(x,j){if(x.length<2)return j.error("Expected at least one argument.");let A,L=1;const O=x[0];if(O==="array"){let Y,X;if(x.length>2){const le=x[1];if(typeof le!="string"||!(le in Va)||le==="object")return j.error('The item type argument of "array" must be one of string, number, boolean',1);Y=Va[le],L++}else Y=mo;if(x.length>3){if(x[2]!==null&&(typeof x[2]!="number"||x[2]<0||x[2]!==Math.floor(x[2])))return j.error('The length argument to "array" must be a positive integer literal',2);X=x[2],L++}A=qn(Y,X)}else A=Va[O];const $=[];for(;Lx.outputDefined())}serialize(){const x=this.type,j=[x.kind];if(x.kind==="array"){const A=x.itemType;if(A.kind==="string"||A.kind==="number"||A.kind==="boolean"){j.push(A.kind);const L=x.N;(typeof L=="number"||this.args.length>1)&&j.push(L)}}return j.concat(this.args.map(A=>A.serialize()))}}class cu{constructor(x){this.type=Gt,this.sections=x}static parse(x,j){if(x.length<2)return j.error("Expected at least one argument.");const A=x[1];if(!Array.isArray(A)&&typeof A=="object")return j.error("First argument must be an image or text section.");const L=[];let O=!1;for(let $=1;$<=x.length-1;++$){const Y=x[$];if(O&&typeof Y=="object"&&!Array.isArray(Y)){O=!1;let X=null;if(Y["font-scale"]&&(X=j.parseObjectValue(Y["font-scale"],$,"font-scale",Vr),!X))return null;let le=null;if(Y["text-font"]&&(le=j.parseObjectValue(Y["text-font"],$,"text-font",qn(gi)),!le))return null;let xe=null;if(Y["text-color"]&&(xe=j.parseObjectValue(Y["text-color"],$,"text-color",rc),!xe))return null;const je=L[L.length-1];je.scale=X,je.font=le,je.textColor=xe}else{const X=j.parse(x[$],$,mo);if(!X)return null;const le=X.type.kind;if(le!=="string"&&le!=="value"&&le!=="null"&&le!=="resolvedImage")return j.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");O=!0,L.push({content:X,scale:null,font:null,textColor:null})}}return new cu(L)}evaluate(x){return new gd(this.sections.map(j=>{const A=j.content.evaluate(x);return rd(ac(A),An)?new pp("",A,null,null,null):new pp($a(A),null,j.scale?j.scale.evaluate(x):null,j.font?j.font.evaluate(x).join(","):null,j.textColor?j.textColor.evaluate(x):null)}))}eachChild(x){for(const j of this.sections)x(j.content),j.scale&&x(j.scale),j.font&&x(j.font),j.textColor&&x(j.textColor)}outputDefined(){return!1}serialize(){const x=["format"];for(const j of this.sections){x.push(j.content.serialize());const A={};j.scale&&(A["font-scale"]=j.scale.serialize()),j.font&&(A["text-font"]=j.font.serialize()),j.textColor&&(A["text-color"]=j.textColor.serialize()),x.push(A)}return x}}class ba{constructor(x,j,A,L){this._imageWarnHistory={},this.type=An,this.namePrimary=x,this.nameSecondary=j,A&&(this.paramsPrimary=A.params,this.iconsetIdPrimary=A.iconset?A.iconset.id:void 0),L&&(this.paramsSecondary=L.params,this.iconsetIdSecondary=L.iconset?L.iconset.id:void 0)}static parse(x,j){if(x.length<2)return j.error("Expected two or more arguments.");let A=1;const L=[];function O(){if(Aqm.isEqual($,O)),L.available){const $=L.getSecondary()?L.getSecondary().id:null;$&&(L.available=x.availableImages.some(Y=>qm.isEqual(Y,$)))}}return L}eachChild(x){if(x(this.namePrimary),this.paramsPrimary)for(const j in this.paramsPrimary)this.paramsPrimary[j]&&x(this.paramsPrimary[j]);if(this.nameSecondary&&(x(this.nameSecondary),this.paramsSecondary))for(const j in this.paramsSecondary)this.paramsSecondary[j]&&x(this.paramsSecondary[j])}outputDefined(){return!1}serializeOptions(x,j){const A={};if(j&&(A.iconset={id:j}),x){A.params={};for(const L in x)x[L]&&(A.params[L]=x[L].serialize())}return Object.keys(A).length>0?A:void 0}serialize(){const x=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const j=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);j&&x.push(j)}if(this.nameSecondary&&(x.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const j=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);j&&x.push(j)}return x}}function Zg(k){return wg(k)?"string":F0(k)?"number":Vx(k)?"boolean":Array.isArray(k)?"array":k===null?"null":qy(k)?"object":typeof k}function qy(k){return k!=null&&!Array.isArray(k)&&typeof k!="function"&&!(k instanceof String||k instanceof Number||k instanceof Boolean)&&typeof k=="object"}function wg(k){return typeof k=="string"||k instanceof String}function F0(k){return typeof k=="number"||k instanceof Number}function Vx(k){return typeof k=="boolean"||k instanceof Boolean}const Id={"to-boolean":Ai,"to-color":rc,"to-number":Vr,"to-string":gi};class ff{constructor(x,j){this.type=x,this.args=j}static parse(x,j){if(x.length<2)return j.error("Expected at least one argument.");const A=x[0],L=[];let O=xd;if(A==="to-array"){if(!Array.isArray(x[1]))return null;const $=x[1].length;if(j.expectedType){if(j.expectedType.kind!=="array")return j.error(`Expected ${j.expectedType.kind} but found array.`);O=qn(j.expectedType.itemType,$)}else{if(!($>0&&qx(x[1][0])))return null;O=qn(ac(x[1][0]),$)}for(let Y=0;Y<$;Y++){const X=x[1][Y];let le;if(Array.isArray(X))le=j.parse(X,void 0,O.itemType);else{const xe=Zg(X);if(xe!==O.itemType.kind)return j.error(`Expected ${O.itemType.kind} but found ${xe}.`);le=j.registry.literal.parse(["literal",X===void 0?null:X],j)}if(!le)return null;L.push(le)}}else{if((A==="to-boolean"||A==="to-string")&&x.length!==2)return j.error("Expected one argument.");O=Id[A];for(let $=1;$4?`Invalid rbga value ${JSON.stringify(j)}: expected an array containing either three or four numeric values.`:Rp(j[0],j[1],j[2],j[3]),!A))return new Js(j[0]/255,j[1]/255,j[2]/255,j[3])}throw new Tc(A||`Could not parse color from value '${typeof j=="string"?j:String(JSON.stringify(j))}'`)}if(this.type.kind==="number"){let j=null;for(const A of this.args){if(j=A.evaluate(x),j===null)return 0;const L=Number(j);if(!isNaN(L))return L}throw new Tc(`Could not convert ${JSON.stringify(j)} to number.`)}return this.type.kind==="formatted"?gd.fromString($a(this.args[0].evaluate(x))):this.type.kind==="resolvedImage"?Th.build($a(this.args[0].evaluate(x))):this.type.kind==="array"?this.args.map(j=>j.evaluate(x)):$a(this.args[0].evaluate(x))}eachChild(x){this.args.forEach(x)}outputDefined(){return this.args.every(x=>x.outputDefined())}serialize(){if(this.type.kind==="formatted")return new cu([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new ba(this.args[0]).serialize();const x=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(j=>{x.push(j.serialize())}),x}}const bm=["Unknown","Point","LineString","Polygon"];class ph{constructor(x,j,A){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=x,this.options=j,this.iconImageUseTheme=A}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?bm[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(x){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const x=this.featureDistanceData.center,j=this.featureDistanceData.scale,{x:A,y:L}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(A*j-x[0])+this.featureDistanceData.bearing[1]*(L*j-x[1])}return 0}parseColor(x){let j=this._parseColorCache[x];return j||(j=this._parseColorCache[x]=Js.parse(x)),j}getConfig(x){return this.options?this.options.get(x):null}}class Gd{constructor(x,j,A,L,O){this.name=x,this.type=j,this._evaluate=A,this.args=L,this._overloadIndex=O}evaluate(x){if(!this._evaluate){const j=Gd.definitions[this.name];this._evaluate=Array.isArray(j)?j[2]:j.overloads[this._overloadIndex][1]}return this._evaluate(x,this.args)}eachChild(x){this.args.forEach(x)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(x=>x.serialize()))}static parse(x,j){const A=x[0],L=Gd.definitions[A];if(!L)return j.error(`Unknown expression "${A}". If you wanted a literal array, use ["literal", [...]].`,0);const O=Array.isArray(L)?L[0]:L.type,$=Array.isArray(L)?[[L[1],L[2]]]:L.overloads,Y=[];let X=null,le=-1;for(const[xe,je]of $){if(Array.isArray(xe)&&xe.length!==x.length-1)continue;Y.push(xe),le++,X=new rk(j.registry,j.path,null,j.scope,void 0,j._scope,j.options,j.iconImageUseTheme);const Ce=[];let Ie=!1;for(let Fe=1;FeCe)).map(xf).join(" | "),je=[];for(let Ce=1;Cej;){if(A-j>600){const X=A-j+1,le=x-j+1,xe=Math.log(X),je=.5*Math.exp(2*xe/3),Ce=.5*Math.sqrt(xe*je*(X-je)/X)*(le-X/2<0?-1:1);M1(k,x,Math.max(j,Math.floor(x-le*je/X+Ce)),Math.min(A,Math.floor(x+(X-le)*je/X+Ce)),L)}const O=k[x];let $=j,Y=A;for(yd(k,j,x),L(k[A],O)>0&&yd(k,j,A);$0;)Y--}L(k[j],O)===0?yd(k,j,Y):(Y++,yd(k,Y,A)),Y<=x&&(j=Y+1),x<=Y&&(A=Y-1)}}function yd(k,x,j){const A=k[x];k[x]=k[j],k[j]=A}function Xg(k,x){return kx?1:0}function O0(k){let x=0;for(let j,A,L=0,O=k.length,$=O-1;L=x[2]||k[1]<=x[1]||k[3]>=x[3])}function Fb(k,x,j){const A=k[0]-x[0],L=k[1]-x[1],O=k[0]-j[0],$=k[1]-j[1];return A*$-O*L===0&&A*O<=0&&L*$<=0}function fh(k,x,j){return x[1]>k[1]!=j[1]>k[1]&&k[0]<(j[0]-x[0])*(k[1]-x[1])/(j[1]-x[1])+x[0]}function Mc(k,x,j=!1){let A=!1;for(let L=0,O=x.length;L0&&Y<0||$<0&&Y>0}function fl(k,x,j,A){return(L=[A[0]-j[0],A[1]-j[1]])[0]*(O=[x[0]-k[0],x[1]-k[1]])[1]-L[1]*O[0]!==0&&!(!Cl(k,x,j,A)||!Cl(j,A,k,x));var L,O}function qu(k){const x=new Ss(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),j=new Ss(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const A of k[0])x.x>A.x&&(x.x=A.x),x.y>A.y&&(x.y=A.y),j.xj[2]){const L=.5*A;let O=k[0]-j[0]>L?-A:j[0]-k[0]>L?A:0;O===0&&(O=k[0]-j[2]>L?-A:j[2]-k[0]>L?A:0),k[0]+=O}_m(x,k)}function B0(k,x,j,A){const L=Math.pow(2,A.z)*Wd,O=[A.x*Wd,A.y*Wd],$=[];if(!k)return $;for(const Y of k)for(const X of Y){const le=[X.x+O[0],X.y+O[1]];xh(le,x,j,L),$.push(le)}return $}function Xj(k,x,j,A){const L=Math.pow(2,A.z)*Wd,O=[A.x*Wd,A.y*Wd],$=[];if(!k)return $;for(const X of k){const le=[];for(const xe of X){const je=[xe.x+O[0],xe.y+O[1]];_m(x,je),le.push(je)}$.push(le)}if(x[2]-x[0]<=L/2){(Y=x)[0]=Y[1]=1/0,Y[2]=Y[3]=-1/0;for(const X of $)for(const le of X)xh(le,x,j,L)}var Y;return $}class $0{constructor(x,j){this.type=Ai,this.geojson=x,this.geometries=j}static parse(x,j){if(x.length!==2)return j.error(`'within' expression requires exactly one argument, but found ${x.length-1} instead.`);if(qx(x[1])){const A=x[1];if(A.type==="FeatureCollection")for(let L=0;Lj)return iw(O,$,(j-(A-Y))/Y)}return x[x.length-1]}pointToSegmentDistance(x,j,A){let[L,O]=j,$=gf(A[0]-L)*this.kx,Y=(A[1]-O)*this.ky;if($!==0||Y!==0){const X=(gf(x[0]-L)*this.kx*$+(x[1]-O)*this.ky*Y)/($*$+Y*Y);X>1?(L=A[0],O=A[1]):X>0&&(L+=$/this.kx*X,O+=Y/this.ky*X)}return $=gf(x[0]-L)*this.kx,Y=(x[1]-O)*this.ky,Math.sqrt($*$+Y*Y)}pointOnLine(x,j){let A=1/0,L=x[0][0],O=x[0][1],$=0,Y=0;for(let X=0;X1?(le=x[X+1][0],xe=x[X+1][1]):Ie>0&&(le+=je/this.kx*Ie,xe+=Ce/this.ky*Ie)),je=gf(j[0]-le)*this.kx,Ce=(j[1]-xe)*this.ky;const Fe=je*je+Ce*Ce;FeO.index||L.index===O.index&&L.t>O.t){const le=L;L=O,O=le}const $=[L.point],Y=L.index+1,X=O.index;!tk(A[Y],$[0])&&Y<=X&&$.push(A[Y]);for(let le=Y+1;le<=X;le++)$.push(A[le]);return tk(A[X],O.point)||$.push(O.point),$}lineSliceAlong(x,j,A){let L=0;const O=[];for(let $=0;$x&&O.length===0&&O.push(iw(Y,X,(x-(L-le))/le)),L>=j)return O.push(iw(Y,X,(j-(L-le))/le)),O;L>x&&O.push(X)}return O}bufferPoint(x,j){const A=j/this.ky,L=j/this.kx;return[x[0]-L,x[1]-A,x[0]+L,x[1]+A]}bufferBBox(x,j){const A=j/this.ky,L=j/this.kx;return[x[0]-L,x[1]-A,x[2]+L,x[3]+A]}insideBBox(x,j){return gf(x[0]-j[0])>=0&&gf(x[0]-j[2])<=0&&x[1]>=j[1]&&x[1]<=j[3]}}function tk(k,x){return k[0]===x[0]&&k[1]===x[1]}function iw(k,x,j){const A=gf(x[0]-k[0]);return[k[0]+A*j,k[1]+(x[1]-k[1])*j]}function gf(k){for(;k<-180;)k+=360;for(;k>180;)k-=360;return k}class jm{constructor(x=[],j=(A,L)=>AL?1:0){if(this.data=x,this.length=this.data.length,this.compare=j,this.length>0)for(let A=(this.length>>1)-1;A>=0;A--)this._down(A)}push(x){this.data.push(x),this._up(this.length++)}pop(){if(this.length===0)return;const x=this.data[0],j=this.data.pop();return--this.length>0&&(this.data[0]=j,this._down(0)),x}peek(){return this.data[0]}_up(x){const{data:j,compare:A}=this,L=j[x];for(;x>0;){const O=x-1>>1,$=j[O];if(A(L,$)>=0)break;j[x]=$,x=O}j[x]=L}_down(x){const{data:j,compare:A}=this,L=this.length>>1,O=j[x];for(;x=0)break;j[x]=j[$],x=$}j[x]=O}}var fr=8192;function Bb(k,x){return x.dist-k.dist}function $b(k){const x=[1/0,1/0,-1/0,-1/0];if(x.length!==k.length)return!1;for(let j=0;j=k[0]&&k[1]k[1])return[null,null];const j=P1(k);if(x){if(j===2)return[k,null];const A=Math.floor(j/2);return[[k[0],k[0]+A],[k[0]+A,k[1]]]}{if(j===1)return[k,null];const A=Math.floor(j/2)-1;return[[k[0],k[0]+A],[k[0]+A+1,k[1]]]}}function U0(k,x){const j=[1/0,1/0,-1/0,-1/0];if(!ax(x,k.length))return j;for(let A=x[0];A<=x[1];++A)_m(j,k[A]);return j}function ow(k){const x=[1/0,1/0,-1/0,-1/0];for(let j=0;jx[2]&&(A=k[0]-x[2]),k[1]>x[3]&&(L=k[1]-x[3]),k[3]=A)return A;if(Hx(L,O)){if(lw(k,x))return 0}else if(lw(x,k))return 0;let $=A;for(const Y of k)for(let X=0,le=Y.length,xe=le-1;X=O)continue;const xe=le.range1;if(P1(xe)<=Y){if(!ax(xe,k.length))return NaN;if(x){const je=vd(k,xe,j,A);if((O=Math.min(O,je))===0)return O}else for(let je=xe[0];je<=xe[1];++je){const Ce=tT(k[je],j,A);if((O=Math.min(O,Ce))===0)return O}}else{const je=Rv(xe,x);if(je[0]!==null){const Ce=L1(U0(k,je[0]),X,A);Ce=$)continue;const je=xe.range1,Ce=xe.range2;if(P1(je)<=X&&P1(Ce)<=le){if(!ax(je,k.length)||!ax(Ce,j.length))return NaN;if(x&&A?$=Math.min($,XL(k,je,j,Ce,L)):x||A?x&&!A?$=Math.min($,XS(j,Ce,k,je,L)):!x&&A&&($=Math.min($,XS(k,je,j,Ce,L))):$=Math.min($,KC(k,je,j,Ce,L)),$===0)return $}else{const Ie=Rv(je,x),Fe=Rv(Ce,A);Ub(Y,$,L,k,j,Ie[0],Fe[0]),Ub(Y,$,L,k,j,Ie[0],Fe[1]),Ub(Y,$,L,k,j,Ie[1],Fe[0]),Ub(Y,$,L,k,j,Ie[1],Fe[1])}}return $}function Jj(k,x,j,A,L=1/0){let O=L;const $=U0(k,[0,k.length-1]);for(const Y of j)if(!(O!==1/0&&L1($,U0(Y,[0,Y.length-1]),A)>=O)&&(O=Math.min(O,Hy(k,x,Y,!0,A,O)),O===0))return O;return O}function cw(k,x,j,A,L=1/0){let O=L;const $=U0(k,[0,k.length-1]);for(const Y of j){if(O!==1/0&&L1($,ow(Y),A)>=O)continue;const X=QL(k,x,Y,A,O);if(isNaN(X))return X;if((O=Math.min(O,X))===0)return O}return O}function QS(k){return k==="Point"||k==="MultiPoint"||k==="LineString"||k==="MultiLineString"||k==="Polygon"||k==="MultiPolygon"}class qb{constructor(x,j){this.type=Vr,this.geojson=x,this.geometries=j}static parse(x,j){if(x.length!==2)return j.error(`'distance' expression requires either one argument, but found ' ${x.length-1} instead.`);if(qx(x[1])){const A=x[1];if(A.type==="FeatureCollection"){for(let L=0;L{x&&!Vb(j)&&(x=!1)}),x}function Gx(k){if(k instanceof Gd&&k.name==="feature-state")return!1;let x=!0;return k.eachChild(j=>{x&&!Gx(j)&&(x=!1)}),x}function Yu(k,x){if(k instanceof Gd&&x.indexOf(k.name)>=0)return!1;let j=!0;return k.eachChild(A=>{j&&!Yu(A,x)&&(j=!1)}),j}function Gy(k,x,j){return[k,x,j].filter(Boolean).join("")}function nk(k,x){switch(k){case"string":return $a(x);case"number":return+x;case"boolean":return!!x;case"color":return Js.parse(x);case"formatted":return gd.fromString($a(x));case"resolvedImage":return Th.build($a(x))}return x}function ZC(k,x,j,A){return A!==void 0&&(k=A*Math.round(k/A)),x!==void 0&&kj&&(k=j),k}class jg{constructor(x,j,A,L=!1){this.type=x,this.key=j,this.scope=A,this.featureConstant=L}static parse(x,j){let A=j.expectedType;if(A==null&&(A=mo),x.length<2||x.length>3)return j.error("Invalid number of arguments for 'config' expression.");const L=j.parse(x[1],1);if(!(L instanceof Yr))return j.error("Key name of 'config' expression must be a string literal.");let O,$=!0;const Y=$a(L.value);if(x.length>=3){const X=j.parse(x[2],2);if(!(X instanceof Yr))return j.error("Scope of 'config' expression must be a string literal.");O=$a(X.value)}if(j.options){const X=Gy(Y,O,j._scope),le=j.options.get(X);le&&($=Vb(le.value||le.default))}return new jg(A,Y,O,$)}evaluate(x){const j=Gy(this.key,this.scope,x.scope),A=x.getConfig(j);if(!A)return null;const{type:L,value:O,values:$,minValue:Y,maxValue:X,stepValue:le}=A,xe=A.default.evaluate(x);let je=xe;if(O){const Ce=x.scope;x.scope=(Ce||"").split("").slice(1).join(""),je=O.evaluate(x),x.scope=Ce}return L&&(je=nk(L,je)),je===void 0||Y===void 0&&X===void 0&&le===void 0||(typeof je=="number"?je=ZC(je,Y,X,le):Array.isArray(je)&&(je=je.map(Ce=>typeof Ce=="number"?ZC(Ce,Y,X,le):Ce))),O!==void 0&&je!==void 0&&$&&!$.includes(je)&&(je=xe,L&&(je=nk(L,je))),(L&&L!==this.type||je!==void 0&&!rd(ac(je),this.type))&&(je=nk(this.type.kind,je)),je}eachChild(){}outputDefined(){return!1}serialize(){const x=["config",this.key];return this.scope&&x.concat(this.scope),x}}class ix{constructor(x,j){this.type=j.type,this.name=x,this.boundExpression=j}static parse(x,j){if(x.length!==2||typeof x[1]!="string")return j.error("'var' expression requires exactly one string literal argument.");const A=x[1];return j.scope.has(A)?new ix(A,j.scope.get(A)):j.error(`Unknown variable "${A}". Make sure "${A}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(x){return this.boundExpression.evaluate(x)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class rk{constructor(x,j=[],A,L=new Wl,O=[],$,Y,X){this.registry=x,this.path=j,this.key=j.map(le=>typeof le=="string"?`['${le}']`:`[${le}]`).join(""),this.scope=L,this.errors=O,this.expectedType=A,this._scope=$,this.options=Y,this.iconImageUseTheme=X}parse(x,j,A,L,O={}){return j||A?this.concat(j,null,A,L)._parse(x,O):this._parse(x,O)}parseObjectValue(x,j,A,L,O,$={}){return this.concat(j,A,L,O)._parse(x,$)}_parse(x,j){function A(L,O,$){return $==="assert"?new Fp(O,[L]):$==="coerce"?new ff(O,[L]):L}if(x!==null&&typeof x!="string"&&typeof x!="boolean"&&typeof x!="number"||(x=["literal",x]),Array.isArray(x)){if(x.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const L=typeof x[0]=="string"?this.registry[x[0]]:void 0;if(L){let O=L.parse(x,this);if(!O)return null;if(this.expectedType){const $=this.expectedType,Y=O.type;if($.kind!=="string"&&$.kind!=="number"&&$.kind!=="boolean"&&$.kind!=="object"&&$.kind!=="array"||Y.kind!=="value")if($.kind!=="color"&&$.kind!=="formatted"&&$.kind!=="resolvedImage"||Y.kind!=="value"&&Y.kind!=="string"){if(this.checkSubtype($,Y))return null}else O=A(O,$,j.typeAnnotation||"coerce");else O=A(O,$,j.typeAnnotation||"assert")}if(!(O instanceof Yr)&&O.type.kind!=="resolvedImage"&&JS(O)){const $=new ph(this._scope,this.options,this.iconImageUseTheme);try{O=new Yr(O.type,O.evaluate($))}catch(Y){return this.error(Y.message),null}}return O}return ff.parse(["to-array",x],this)}return this.error(x===void 0?"'undefined' value invalid. Use null instead.":typeof x=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof x} instead.`)}concat(x,j,A,L){let O=typeof x=="number"?this.path.concat(x):this.path;O=typeof j=="string"?O.concat(j):O;const $=L?this.scope.concat(L):this.scope;return new rk(this.registry,O,A||null,$,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(x,...j){const A=`${this.key}${j.map(L=>`[${L}]`).join("")}`;this.errors.push(new wo(A,x))}checkSubtype(x,j){const A=vi(x,j);return A&&this.error(A),A}}function JS(k){if(k instanceof ix)return JS(k.boundExpression);if(k instanceof Gd&&k.name==="error"||k instanceof T1||k instanceof $0||k instanceof qb||k instanceof jg)return!1;const x=k instanceof ff||k instanceof Fp;let j=!0;return k.eachChild(A=>{j=x?j&&JS(A):j&&A instanceof Yr}),!!j&&Vb(k)&&Yu(k,["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 e2(k,x){const j=k.length-1;let A,L,O=0,$=j,Y=0;for(;O<=$;)if(Y=Math.floor((O+$)/2),A=k[Y],L=k[Y+1],A<=x){if(Y===j||xx))throw new Tc("Input is not a number.");$=Y-1}return 0}class t2{constructor(x,j,A){this.type=x,this.input=j,this.labels=[],this.outputs=[];for(const[L,O]of A)this.labels.push(L),this.outputs.push(O)}static parse(x,j){if(x.length-1<4)return j.error(`Expected at least 4 arguments, but found only ${x.length-1}.`);if((x.length-1)%2!=0)return j.error("Expected an even number of arguments.");const A=j.parse(x[1],1,Vr);if(!A)return null;const L=[];let O=null;j.expectedType&&j.expectedType.kind!=="value"&&(O=j.expectedType);for(let $=1;$=Y)return j.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',le);const je=j.parse(X,xe,O);if(!je)return null;O=O||je.type,L.push([Y,je])}return new t2(O,A,L)}evaluate(x){const j=this.labels,A=this.outputs;if(j.length===1)return A[0].evaluate(x);const L=this.input.evaluate(x);if(L<=j[0])return A[0].evaluate(x);const O=j.length;return L>=j[O-1]?A[O-1].evaluate(x):A[e2(j,L)].evaluate(x)}eachChild(x){x(this.input);for(const j of this.outputs)x(j)}outputDefined(){return this.outputs.every(x=>x.outputDefined())}serialize(){const x=["step",this.input.serialize()];for(let j=0;j0&&x.push(this.labels[j]),x.push(this.outputs[j].serialize());return x}}const ox=.95047,yf=1.08883,XC=4/29,Fv=6/29,s2=3*Fv*Fv,n2=Fv*Fv*Fv,e5=Math.PI/180,t5=180/Math.PI;function s5(k){return k>n2?Math.pow(k,1/3):k/s2+XC}function r2(k){return k>Fv?k*k*k:s2*(k-XC)}function a2(k){return 255*(k<=.0031308?12.92*k:1.055*Math.pow(k,1/2.4)-.055)}function dw(k){return(k/=255)<=.04045?k/12.92:Math.pow((k+.055)/1.055,2.4)}function ak(k){const x=dw(k.r),j=dw(k.g),A=dw(k.b),L=s5((.4124564*x+.3575761*j+.1804375*A)/ox),O=s5((.2126729*x+.7151522*j+.072175*A)/1);return{l:116*O-16,a:500*(L-O),b:200*(O-s5((.0193339*x+.119192*j+.9503041*A)/yf)),alpha:k.a}}function n5(k){let x=(k.l+16)/116,j=isNaN(k.a)?x:x+k.a/500,A=isNaN(k.b)?x:x-k.b/200;return x=1*r2(x),j=ox*r2(j),A=yf*r2(A),new Js(a2(3.2404542*j-1.5371385*x-.4985314*A),a2(-.969266*j+1.8760108*x+.041556*A),a2(.0556434*j-.2040259*x+1.0572252*A),k.alpha)}function sT(k,x,j){const A=x-k;return k+j*(A>180||A<-180?A-360*Math.round(A/360):A)}const uw={forward:ak,reverse:n5,interpolate:function(k,x,j){return{l:Pr(k.l,x.l,j),a:Pr(k.a,x.a,j),b:Pr(k.b,x.b,j),alpha:Pr(k.alpha,x.alpha,j)}}},Ov={forward:function(k){const{l:x,a:j,b:A}=ak(k),L=Math.atan2(A,j)*t5;return{h:L<0?L+360:L,c:Math.sqrt(j*j+A*A),l:x,alpha:k.a}},reverse:function(k){const x=k.h*e5,j=k.c;return n5({l:k.l,a:Math.cos(x)*j,b:Math.sin(x)*j,alpha:k.alpha})},interpolate:function(k,x,j){return{h:sT(k.h,x.h,j),c:Pr(k.c,x.c,j),l:Pr(k.l,x.l,j),alpha:Pr(k.alpha,x.alpha,j)}}};var i2=Object.freeze({__proto__:null,hcl:Ov,lab:uw});class fp{constructor(x,j,A,L,O){this.type=x,this.operator=j,this.interpolation=A,this.input=L,this.labels=[],this.outputs=[];for(const[$,Y]of O)this.labels.push($),this.outputs.push(Y)}static interpolationFactor(x,j,A,L){let O=0;if(x.name==="exponential")O=o2(j,x.base,A,L);else if(x.name==="linear")O=o2(j,1,A,L);else if(x.name==="cubic-bezier"){const $=x.controlPoints;O=new As($[0],$[1],$[2],$[3]).solve(o2(j,1,A,L))}return O}static parse(x,j){let[A,L,O,...$]=x;if(!Array.isArray(L)||L.length===0)return j.error("Expected an interpolation type expression.",1);if(L[0]==="linear")L={name:"linear"};else if(L[0]==="exponential"){const le=L[1];if(typeof le!="number")return j.error("Exponential interpolation requires a numeric base.",1,1);L={name:"exponential",base:le}}else{if(L[0]!=="cubic-bezier")return j.error(`Unknown interpolation type ${String(L[0])}`,1,0);{const le=L.slice(1);if(le.length!==4||le.some(xe=>typeof xe!="number"||xe<0||xe>1))return j.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);L={name:"cubic-bezier",controlPoints:le}}}if(x.length-1<4)return j.error(`Expected at least 4 arguments, but found only ${x.length-1}.`);if(x.length-1>3&&(x.length-1)%2!=0)return j.error("Expected an even number of arguments.");if(O=j.parse(O,2,Vr),!O)return null;const Y=[];let X=null;A==="interpolate-hcl"||A==="interpolate-lab"?X=rc:j.expectedType&&j.expectedType.kind!=="value"&&(X=j.expectedType);for(let le=0;le<$.length;le+=2){const xe=$[le],je=$[le+1],Ce=le+3,Ie=le+4;if(typeof xe!="number")return j.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',Ce);if(Y.length&&Y[Y.length-1][0]>=xe)return j.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',Ce);const Fe=j.parse(je,Ie,X);if(!Fe)return null;X=X||Fe.type,Y.push([xe,Fe])}return X.kind==="number"||X.kind==="color"||X.kind==="array"&&X.itemType.kind==="number"&&typeof X.N=="number"?new fp(X,A,L,O,Y):j.error(`Type ${qr(X)} is not interpolatable.`)}evaluate(x){const j=this.labels,A=this.outputs;if(j.length===1)return A[0].evaluate(x);const L=this.input.evaluate(x);if(L<=j[0])return A[0].evaluate(x);const O=j.length;if(L>=j[O-1])return A[O-1].evaluate(x);const $=e2(j,L),Y=fp.interpolationFactor(this.interpolation,L,j[$],j[$+1]),X=A[$].evaluate(x),le=A[$+1].evaluate(x);return this.operator==="interpolate"?Lo[this.type.kind.toLowerCase()](X,le,Y):this.operator==="interpolate-hcl"?Ov.reverse(Ov.interpolate(Ov.forward(X),Ov.forward(le),Y)):uw.reverse(uw.interpolate(uw.forward(X),uw.forward(le),Y))}eachChild(x){x(this.input);for(const j of this.outputs)x(j)}outputDefined(){return this.outputs.every(x=>x.outputDefined())}serialize(){let x;x=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const j=[this.operator,x,this.input.serialize()];for(let A=0;Avi(L,Y.type));return new hw($?mo:A,O)}evaluate(x){let j,A=null,L=0;for(const O of this.args){if(L++,A=O.evaluate(x),A&&A instanceof Th&&!A.available&&(j||(j=A),A=null,L===this.args.length))return j;if(A!==null)break}return A}eachChild(x){this.args.forEach(x)}outputDefined(){return this.args.every(x=>x.outputDefined())}serialize(){const x=["coalesce"];return this.eachChild(j=>{x.push(j.serialize())}),x}}class Me{constructor(x,j){this.type=j.type,this.bindings=[].concat(x),this.result=j}evaluate(x){return this.result.evaluate(x)}eachChild(x){for(const j of this.bindings)x(j[1]);x(this.result)}static parse(x,j){if(x.length<4)return j.error(`Expected at least 3 arguments, but found ${x.length-1} instead.`);const A=[];for(let O=1;O=A.length)throw new Tc("Array index out of bounds: index exceeds array size");if(j!==Math.floor(j))throw new Tc("Array index must be an integer. Use at-interpolated for fractional indices");return A[j]}eachChild(x){x(this.index),x(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class xt{constructor(x,j,A){this.type=x,this.index=j,this.input=A}static parse(x,j){if(x.length!==3)return j.error(`Expected 2 arguments, but found ${x.length-1} instead.`);const A=j.parse(x[1],1,Vr),L=j.parse(x[2],2,qn(j.expectedType||mo));return A&&L?new xt(L.type.itemType,A,L):null}evaluate(x){const j=this.index.evaluate(x),A=this.input.evaluate(x);if(j<0)throw new Tc(`Array index out of bounds: ${j} < 0.`);if(j>A.length-1)throw new Tc(`Array index out of bounds: ${j} > ${A.length-1}.`);if(j===Math.floor(j))return A[j];const L=Math.floor(j),O=Math.ceil(j),$=A[L],Y=A[O];if(typeof $!="number"||typeof Y!="number")throw new Tc(`Cannot interpolate between non-number values at index ${j}.`);const X=j-L;return $*(1-X)+Y*X}eachChild(x){x(this.index),x(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class jt{constructor(x,j){this.type=Ai,this.needle=x,this.haystack=j}static parse(x,j){if(x.length!==3)return j.error(`Expected 2 arguments, but found ${x.length-1} instead.`),null;const A=j.parse(x[1],1,mo),L=j.parse(x[2],2,mo);return A&&L?Li(A.type,[Ai,gi,Vr,xd,mo])?new jt(A,L):(j.error(`Expected first argument to be of type boolean, string, number or null, but found ${qr(A.type)} instead`),null):null}evaluate(x){const j=this.needle.evaluate(x),A=this.haystack.evaluate(x);if(A==null)return!1;if(!wi(j,["boolean","string","number","null"]))throw new Tc(`Expected first argument to be of type boolean, string, number or null, but found ${qr(ac(j))} instead.`);if(!wi(A,["string","array"]))throw new Tc(`Expected second argument to be of type array or string, but found ${qr(ac(A))} instead.`);return A.indexOf(j)>=0}eachChild(x){x(this.needle),x(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class ns{constructor(x,j,A){this.type=Vr,this.needle=x,this.haystack=j,this.fromIndex=A}static parse(x,j){if(x.length<=2||x.length>=5)return j.error(`Expected 3 or 4 arguments, but found ${x.length-1} instead.`),null;const A=j.parse(x[1],1,mo),L=j.parse(x[2],2,mo);if(!A||!L)return null;if(!Li(A.type,[Ai,gi,Vr,xd,mo]))return j.error(`Expected first argument to be of type boolean, string, number or null, but found ${qr(A.type)} instead`),null;if(x.length===4){const O=j.parse(x[3],3,Vr);return O?new ns(A,L,O):null}return new ns(A,L)}evaluate(x){const j=this.needle.evaluate(x),A=this.haystack.evaluate(x);if(!wi(j,["boolean","string","number","null"]))throw new Tc(`Expected first argument to be of type boolean, string, number or null, but found ${qr(ac(j))} instead.`);if(!wi(A,["string","array"]))throw new Tc(`Expected second argument to be of type array or string, but found ${qr(ac(A))} instead.`);if(this.fromIndex){const L=this.fromIndex.evaluate(x);return A.indexOf(j,L)}return A.indexOf(j)}eachChild(x){x(this.needle),x(this.haystack),this.fromIndex&&x(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const x=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),x]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class xs{constructor(x,j,A,L,O,$){this.inputType=x,this.type=j,this.input=A,this.cases=L,this.outputs=O,this.otherwise=$}static parse(x,j){if(x.length<5)return j.error(`Expected at least 4 arguments, but found only ${x.length-1}.`);if(x.length%2!=1)return j.error("Expected an even number of arguments.");let A,L;j.expectedType&&j.expectedType.kind!=="value"&&(L=j.expectedType);const O={},$=[];for(let le=2;leNumber.MAX_SAFE_INTEGER)return Ce.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Fe=="number"&&Math.floor(Fe)!==Fe)return Ce.error("Numeric branch labels must be integer values.");if(A){if(Ce.checkSubtype(A,ac(Fe)))return null}else A=ac(Fe);if(O[String(Fe)]!==void 0)return Ce.error("Branch labels must be unique.");O[String(Fe)]=$.length}const Ie=j.parse(je,le,L);if(!Ie)return null;L=L||Ie.type,$.push(Ie)}const Y=j.parse(x[1],1,mo);if(!Y)return null;const X=j.parse(x[x.length-1],x.length-1,L);return X?Y.type.kind!=="value"&&j.concat(1).checkSubtype(A,Y.type)?null:new xs(A,L,Y,O,$,X):null}evaluate(x){const j=this.input.evaluate(x);return(rd(ac(j),this.inputType)&&this.outputs[this.cases[j]]||this.otherwise).evaluate(x)}eachChild(x){x(this.input),this.outputs.forEach(x),x(this.otherwise)}outputDefined(){return this.outputs.every(x=>x.outputDefined())&&this.otherwise.outputDefined()}serialize(){const x=["match",this.input.serialize()],j=Object.keys(this.cases).sort(),A=[],L={};for(const $ of j){const Y=L[this.cases[$]];Y===void 0?(L[this.cases[$]]=A.length,A.push([this.cases[$],[$]])):A[Y][1].push($)}const O=$=>this.inputType.kind==="number"?Number($):$;for(const[$,Y]of A)x.push(Y.length===1?O(Y[0]):Y.map(O)),x.push(this.outputs[$].serialize());return x.push(this.otherwise.serialize()),x}}class bs{constructor(x,j,A){this.type=x,this.branches=j,this.otherwise=A}static parse(x,j){if(x.length<4)return j.error(`Expected at least 3 arguments, but found only ${x.length-1}.`),null;if(x.length%2!=0)return j.error("Expected an odd number of arguments."),null;let A;j.expectedType&&j.expectedType.kind!=="value"&&(A=j.expectedType);const L=[];for(let $=1;$j.outputDefined())&&this.otherwise.outputDefined()}serialize(){const x=["case"];return this.eachChild(j=>{x.push(j.serialize())}),x}}class Ms{constructor(x,j,A,L){this.type=x,this.input=j,this.beginIndex=A,this.endIndex=L}static parse(x,j){if(x.length<=2||x.length>=5)return j.error(`Expected 3 or 4 arguments, but found ${x.length-1} instead.`),null;const A=j.parse(x[1],1,mo),L=j.parse(x[2],2,Vr);if(!A||!L)return null;if(!Li(A.type,[qn(mo),gi,mo]))return j.error(`Expected first argument to be of type array or string, but found ${qr(A.type)} instead`),null;if(x.length===4){const O=j.parse(x[3],3,Vr);return O?new Ms(A.type,A,L,O):null}return new Ms(A.type,A,L)}evaluate(x){const j=this.input.evaluate(x),A=this.beginIndex.evaluate(x);if(!wi(j,["string","array"]))throw new Tc(`Expected first argument to be of type array or string, but found ${qr(ac(j))} instead.`);if(this.endIndex){const L=this.endIndex.evaluate(x);return j.slice(A,L)}return j.slice(A)}eachChild(x){x(this.input),x(this.beginIndex),this.endIndex&&x(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const x=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),x]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class zs{constructor(x,j){this.type=qn(gi),this.str=x,this.delimiter=j}static parse(x,j){if(x.length!==3)return j.error(`Expected 2 arguments, but found ${x.length-1} instead.`);const A=j.parse(x[1],1,gi),L=j.parse(x[2],2,gi);return A&&L?new zs(A,L):void 0}evaluate(x){const j=this.str.evaluate(x),A=this.delimiter.evaluate(x);return j.split(A)}eachChild(x){x(this.str),x(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function en(k,x){return k==="=="||k==="!="?x.kind==="boolean"||x.kind==="string"||x.kind==="number"||x.kind==="null"||x.kind==="value":x.kind==="string"||x.kind==="number"||x.kind==="value"}function Dn(k,x,j,A){return A.compare(x,j)===0}function Jn(k,x,j){const A=k!=="=="&&k!=="!=";return class cOt{constructor(O,$,Y){this.type=Ai,this.lhs=O,this.rhs=$,this.collator=Y,this.hasUntypedArgument=O.type.kind==="value"||$.type.kind==="value"}static parse(O,$){if(O.length!==3&&O.length!==4)return $.error("Expected two or three arguments.");const Y=O[0];let X=$.parse(O[1],1,mo);if(!X)return null;if(!en(Y,X.type))return $.concat(1).error(`"${Y}" comparisons are not supported for type '${qr(X.type)}'.`);let le=$.parse(O[2],2,mo);if(!le)return null;if(!en(Y,le.type))return $.concat(2).error(`"${Y}" comparisons are not supported for type '${qr(le.type)}'.`);if(X.type.kind!==le.type.kind&&X.type.kind!=="value"&&le.type.kind!=="value")return $.error(`Cannot compare types '${qr(X.type)}' and '${qr(le.type)}'.`);A&&(X.type.kind==="value"&&le.type.kind!=="value"?X=new Fp(le.type,[X]):X.type.kind!=="value"&&le.type.kind==="value"&&(le=new Fp(X.type,[le])));let xe=null;if(O.length===4){if(X.type.kind!=="string"&&le.type.kind!=="string"&&X.type.kind!=="value"&&le.type.kind!=="value")return $.error("Cannot use collator to compare non-string types.");if(xe=$.parse(O[3],3,em),!xe)return null}return new cOt(X,le,xe)}evaluate(O){const $=this.lhs.evaluate(O),Y=this.rhs.evaluate(O);if(A&&this.hasUntypedArgument){const X=ac($),le=ac(Y);if(X.kind!==le.kind||X.kind!=="string"&&X.kind!=="number")throw new Tc(`Expected arguments for "${k}" to be (string, string) or (number, number), but found (${X.kind}, ${le.kind}) instead.`)}if(this.collator&&!A&&this.hasUntypedArgument){const X=ac($),le=ac(Y);if(X.kind!=="string"||le.kind!=="string")return x(O,$,Y)}return this.collator?j(O,$,Y,this.collator.evaluate(O)):x(O,$,Y)}eachChild(O){O(this.lhs),O(this.rhs),this.collator&&O(this.collator)}outputDefined(){return!0}serialize(){const O=[k];return this.eachChild($=>{O.push($.serialize())}),O}}}const tn=Jn("==",function(k,x,j){return x===j},Dn),Hn=Jn("!=",function(k,x,j){return x!==j},function(k,x,j,A){return!Dn(0,x,j,A)}),ir=Jn("<",function(k,x,j){return x",function(k,x,j){return x>j},function(k,x,j,A){return A.compare(x,j)>0}),Nr=Jn("<=",function(k,x,j){return x<=j},function(k,x,j,A){return A.compare(x,j)<=0}),Gn=Jn(">=",function(k,x,j){return x>=j},function(k,x,j,A){return A.compare(x,j)>=0});class Gr{constructor(x,j,A,L,O,$){this.type=gi,this.number=x,this.locale=j,this.currency=A,this.unit=L,this.minFractionDigits=O,this.maxFractionDigits=$}static parse(x,j){if(x.length!==3)return j.error("Expected two arguments.");const A=j.parse(x[1],1,Vr);if(!A)return null;const L=x[2];if(typeof L!="object"||Array.isArray(L))return j.error("NumberFormat options argument must be an object.");let O=null;if(L.locale&&(O=j.parseObjectValue(L.locale,2,"locale",gi),!O))return null;let $=null;if(L.currency&&($=j.parseObjectValue(L.currency,2,"currency",gi),!$))return null;let Y=null;if(L.unit&&(Y=j.parseObjectValue(L.unit,2,"unit",gi),!Y))return null;let X=null;if(L["min-fraction-digits"]&&(X=j.parseObjectValue(L["min-fraction-digits"],2,"min-fraction-digits",Vr),!X))return null;let le=null;return L["max-fraction-digits"]&&(le=j.parseObjectValue(L["max-fraction-digits"],2,"max-fraction-digits",Vr),!le)?null:new Gr(A,O,$,Y,X,le)}evaluate(x){return new Intl.NumberFormat(this.locale?this.locale.evaluate(x):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(x):void 0,unit:this.unit?this.unit.evaluate(x):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(x):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(x):void 0}).format(this.number.evaluate(x))}eachChild(x){x(this.number),this.locale&&x(this.locale),this.currency&&x(this.currency),this.unit&&x(this.unit),this.minFractionDigits&&x(this.minFractionDigits),this.maxFractionDigits&&x(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const x={};return this.locale&&(x.locale=this.locale.serialize()),this.currency&&(x.currency=this.currency.serialize()),this.unit&&(x.unit=this.unit.serialize()),this.minFractionDigits&&(x["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(x["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),x]}}class Ca{constructor(x){this.type=Vr,this.input=x}static parse(x,j){if(x.length!==2)return j.error(`Expected 1 argument, but found ${x.length-1} instead.`),null;const A=j.parse(x[1],1);return A?A.type.kind!=="array"&&A.type.kind!=="string"&&A.type.kind!=="value"?(j.error(`Expected argument of type string or array, but found ${qr(A.type)} instead.`),null):new Ca(A):null}evaluate(x){const j=this.input.evaluate(x);if(typeof j=="string"||Array.isArray(j))return j.length;throw new Tc(`Expected value to be of type string or array, but found ${qr(ac(j))} instead.`)}eachChild(x){x(this.input)}outputDefined(){return!1}serialize(){const x=["length"];return this.eachChild(j=>{x.push(j.serialize())}),x}}function _a(k){return function(){k=1831565813+(k|=0)|0;let x=Math.imul(k^k>>>15,1|k);return x=x+Math.imul(x^x>>>7,61|x)^x,((x^x>>>14)>>>0)/4294967296}}const ro={"==":tn,"!=":Hn,">":Dr,"<":ir,">=":Gn,"<=":Nr,array:Fp,at:Ue,"at-interpolated":xt,boolean:Fp,case:bs,coalesce:hw,collator:T1,format:cu,image:ba,in:jt,"index-of":ns,interpolate:fp,"interpolate-hcl":fp,"interpolate-lab":fp,length:Ca,let:Me,literal:Yr,match:xs,number:Fp,"number-format":Gr,object:Fp,slice:Ms,step:t2,string:Fp,"to-boolean":ff,"to-color":ff,"to-number":ff,"to-string":ff,var:ix,within:$0,distance:qb,config:jg,split:zs};function Oi(k,[x,j,A,L]){x=x.evaluate(k),j=j.evaluate(k),A=A.evaluate(k);const O=L?L.evaluate(k):1,$=Rp(x,j,A,O);if($)throw new Tc($);return new Js(x/255,j/255,A/255,O)}function Al(k,[x,j,A,L]){x=x.evaluate(k),j=j.evaluate(k),A=A.evaluate(k);const O=L?L.evaluate(k):1,$=function(le,xe,je,Ce){return typeof le=="number"&&le>=0&&le<=360?typeof xe=="number"&&xe>=0&&xe<=100&&typeof je=="number"&&je>=0&&je<=100?Ce===void 0||typeof Ce=="number"&&Ce>=0&&Ce<=1?null:`Invalid hsla value [${[le,xe,je,Ce].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof Ce=="number"?[le,xe,je,Ce]:[le,xe,je]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof Ce=="number"?[le,xe,je,Ce]:[le,xe,je]).join(", ")}]: 'h' must be between 0 and 360.`}(x,j,A,O);if($)throw new Tc($);const Y=`hsla(${x}, ${j}%, ${A}%, ${O})`,X=Js.parse(Y);if(!X)throw new Tc(`Failed to parse HSLA color: ${Y}`);return X}function Yi(k,x){return k in x}function bc(k,x){const j=x[k];return j===void 0?null:j}function Eu(k){return{type:k}}function El(k){if(k instanceof jg)return new Set([k.key]);let x=new Set;return k.eachChild(j=>{x=new Set([...x,...El(j)])}),x}function eo(k){if(k instanceof Gd&&k.name==="is-active-floor")return!0;let x=!1;return k.eachChild(j=>{!x&&eo(j)&&(x=!0)}),x}function fi(k){return{result:"success",value:k}}function Il(k){return{result:"error",value:k}}function To(k,x){return!!k&&!!k.parameters&&k.parameters.indexOf(x)>-1}function vl(k){return k["property-type"]==="data-driven"}function ju(k){return To(k.expression,"measure-light")}function Vm(k){return To(k.expression,"zoom")}function Nu(k){return!!k.expression&&k.expression.interpolated}function Zu(k){return typeof k=="object"&&k!==null&&!Array.isArray(k)}function Vu(k){return k}function lx(k,x){const j=x.type==="color",A=k.stops&&typeof k.stops[0][0]=="object",L=A||!(A||k.property!==void 0),O=k.type||(Nu(x)?"exponential":"interval");if(j&&((k=Object.assign({},k)).stops&&(k.stops=k.stops.map(le=>[le[0],Js.parse(le[1])])),k.default=Js.parse(k.default?k.default:x.default)),k.colorSpace&&k.colorSpace!=="rgb"&&!i2[k.colorSpace])throw new Error(`Unknown color space: ${k.colorSpace}`);let $,Y,X;if(O==="exponential")$=gh;else if(O==="interval")$=Kd;else if(O==="categorical"){$=ad,Y=Object.create(null);for(const le of k.stops)Y[le[0]]=le[1];X=typeof k.stops[0][0]}else{if(O!=="identity")throw new Error(`Unknown function type "${O}"`);$=bd}if(A){const le={},xe=[];for(let Ie=0;IeIe[0]),evaluate:({zoom:Ie},Fe)=>gh({stops:je,base:k.base},x,Ie).evaluate(Ie,Fe)}}if(L){const le=O==="exponential"?{name:"exponential",base:k.base!==void 0?k.base:1}:null;return{kind:"camera",interpolationType:le,interpolationFactor:fp.interpolationFactor.bind(void 0,le),zoomStops:k.stops.map(xe=>xe[0]),evaluate:({zoom:xe})=>$(k,x,xe,Y,X)}}return{kind:"source",evaluate(le,xe){const je=xe&&xe.properties?xe.properties[k.property]:void 0;return je===void 0?du(k.default,x.default):$(k,x,je,Y,X)}}}function du(k,x,j){return k!==void 0?k:x!==void 0?x:j!==void 0?j:void 0}function ad(k,x,j,A,L){return du(typeof j===L?A[j]:void 0,k.default,x.default)}function Kd(k,x,j){if(!F0(j))return du(k.default,x.default);const A=k.stops.length;if(A===1||j<=k.stops[0][0])return k.stops[0][1];if(j>=k.stops[A-1][0])return k.stops[A-1][1];const L=e2(k.stops.map(O=>O[0]),j);return k.stops[L][1]}function gh(k,x,j){const A=k.base!==void 0?k.base:1;if(!F0(j))return du(k.default,x.default);const L=k.stops.length;if(L===1||j<=k.stops[0][0])return k.stops[0][1];if(j>=k.stops[L-1][0])return k.stops[L-1][1];const O=e2(k.stops.map(xe=>xe[0]),j),$=function(xe,je,Ce,Ie){const Fe=Ie-Ce,Ke=xe-Ce;return Fe===0?0:je===1?Ke/Fe:(Math.pow(je,Ke)-1)/(Math.pow(je,Fe)-1)}(j,A,k.stops[O][0],k.stops[O+1][0]),Y=k.stops[O][1],X=k.stops[O+1][1];let le=Lo[x.type]||Vu;if(k.colorSpace&&k.colorSpace!=="rgb"){const xe=i2[k.colorSpace];le=(je,Ce)=>xe.reverse(xe.interpolate(xe.forward(je),xe.forward(Ce),$))}return typeof Y.evaluate=="function"?{evaluate(...xe){const je=Y.evaluate.apply(void 0,xe),Ce=X.evaluate.apply(void 0,xe);if(je!==void 0&&Ce!==void 0)return le(je,Ce,$)}}:le(Y,X,$)}function bd(k,x,j){return x.type==="color"?j=Js.parse(j):x.type==="formatted"?j=gd.fromString(j.toString()):x.type==="resolvedImage"?j=Th.build(j.toString()):Zg(j)===x.type||x.type==="enum"&&x.values[j]||(j=void 0),du(j,k.default,x.default)}Gd.register(ro,{error:[{kind:"error"},[gi],(k,[x])=>{throw new Tc(x.evaluate(k))}],typeof:[gi,[mo],(k,[x])=>qr(ac(x.evaluate(k)))],"to-rgba":[qn(Vr,4),[rc],(k,[x])=>x.evaluate(k).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[qn(Vr,4),[rc],(k,[x])=>x.evaluate(k).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[rc,[Vr,Vr,Vr],Oi],rgba:[rc,[Vr,Vr,Vr,Vr],Oi],hsl:[rc,[Vr,Vr,Vr],Al],hsla:[rc,[Vr,Vr,Vr,Vr],Al],has:{type:Ai,overloads:[[[gi],(k,[x])=>Yi(x.evaluate(k),k.properties())],[[gi,Yc],(k,[x,j])=>Yi(x.evaluate(k),j.evaluate(k))]]},get:{type:mo,overloads:[[[gi],(k,[x])=>bc(x.evaluate(k),k.properties())],[[gi,Yc],(k,[x,j])=>bc(x.evaluate(k),j.evaluate(k))]]},"feature-state":[mo,[gi],(k,[x])=>bc(x.evaluate(k),k.featureState||{})],properties:[Yc,[],k=>k.properties()],"geometry-type":[gi,[],k=>k.geometryType()],worldview:[gi,[],k=>k.globals.worldview||""],"is-active-floor":[Ai,Eu(gi),(k,x)=>{if(!(k.globals&&k.globals.activeFloors&&k.globals.activeFloors.size>0))return!1;if(x.length===0)return!0;const j=k.globals.activeFloors;return x.some(A=>{const L=A.evaluate(k);return j.has(L)})}],id:[mo,[],k=>k.id()],zoom:[Vr,[],k=>k.globals.zoom],pitch:[Vr,[],k=>k.globals.pitch||0],"distance-from-center":[Vr,[],k=>k.distanceFromCenter()],"measure-light":[Vr,[gi],(k,[x])=>k.measureLight(x.evaluate(k))],"heatmap-density":[Vr,[],k=>k.globals.heatmapDensity||0],"line-progress":[Vr,[],k=>k.globals.lineProgress||0],"raster-value":[Vr,[],k=>k.globals.rasterValue||0],"raster-particle-speed":[Vr,[],k=>k.globals.rasterParticleSpeed||0],"sky-radial-progress":[Vr,[],k=>k.globals.skyRadialProgress||0],accumulated:[mo,[],k=>k.globals.accumulated===void 0?null:k.globals.accumulated],"+":[Vr,Eu(Vr),(k,x)=>{let j=0;for(const A of x)j+=A.evaluate(k);return j}],"*":[Vr,Eu(Vr),(k,x)=>{let j=1;for(const A of x)j*=A.evaluate(k);return j}],"-":{type:Vr,overloads:[[[Vr,Vr],(k,[x,j])=>x.evaluate(k)-j.evaluate(k)],[[Vr],(k,[x])=>-x.evaluate(k)]]},"/":[Vr,[Vr,Vr],(k,[x,j])=>x.evaluate(k)/j.evaluate(k)],"%":[Vr,[Vr,Vr],(k,[x,j])=>x.evaluate(k)%j.evaluate(k)],ln2:[Vr,[],()=>Math.LN2],pi:[Vr,[],()=>Math.PI],e:[Vr,[],()=>Math.E],"^":[Vr,[Vr,Vr],(k,[x,j])=>Math.pow(x.evaluate(k),j.evaluate(k))],sqrt:[Vr,[Vr],(k,[x])=>Math.sqrt(x.evaluate(k))],log10:[Vr,[Vr],(k,[x])=>Math.log(x.evaluate(k))/Math.LN10],ln:[Vr,[Vr],(k,[x])=>Math.log(x.evaluate(k))],log2:[Vr,[Vr],(k,[x])=>Math.log2(x.evaluate(k))],sin:[Vr,[Vr],(k,[x])=>Math.sin(x.evaluate(k))],cos:[Vr,[Vr],(k,[x])=>Math.cos(x.evaluate(k))],tan:[Vr,[Vr],(k,[x])=>Math.tan(x.evaluate(k))],asin:[Vr,[Vr],(k,[x])=>Math.asin(x.evaluate(k))],acos:[Vr,[Vr],(k,[x])=>Math.acos(x.evaluate(k))],atan:[Vr,[Vr],(k,[x])=>Math.atan(x.evaluate(k))],min:[Vr,Eu(Vr),(k,x)=>Math.min(...x.map(j=>j.evaluate(k)))],max:[Vr,Eu(Vr),(k,x)=>Math.max(...x.map(j=>j.evaluate(k)))],abs:[Vr,[Vr],(k,[x])=>Math.abs(x.evaluate(k))],round:[Vr,[Vr],(k,[x])=>{const j=x.evaluate(k);return j<0?-Math.round(-j):Math.round(j)}],floor:[Vr,[Vr],(k,[x])=>Math.floor(x.evaluate(k))],ceil:[Vr,[Vr],(k,[x])=>Math.ceil(x.evaluate(k))],"filter-==":[Ai,[gi,mo],(k,[x,j])=>k.properties()[x.value]===j.value],"filter-id-==":[Ai,[mo],(k,[x])=>k.id()===x.value],"filter-type-==":[Ai,[gi],(k,[x])=>k.geometryType()===x.value],"filter-<":[Ai,[gi,mo],(k,[x,j])=>{const A=k.properties()[x.value],L=j.value;return typeof A==typeof L&&A{const j=k.id(),A=x.value;return typeof j==typeof A&&j":[Ai,[gi,mo],(k,[x,j])=>{const A=k.properties()[x.value],L=j.value;return typeof A==typeof L&&A>L}],"filter-id->":[Ai,[mo],(k,[x])=>{const j=k.id(),A=x.value;return typeof j==typeof A&&j>A}],"filter-<=":[Ai,[gi,mo],(k,[x,j])=>{const A=k.properties()[x.value],L=j.value;return typeof A==typeof L&&A<=L}],"filter-id-<=":[Ai,[mo],(k,[x])=>{const j=k.id(),A=x.value;return typeof j==typeof A&&j<=A}],"filter->=":[Ai,[gi,mo],(k,[x,j])=>{const A=k.properties()[x.value],L=j.value;return typeof A==typeof L&&A>=L}],"filter-id->=":[Ai,[mo],(k,[x])=>{const j=k.id(),A=x.value;return typeof j==typeof A&&j>=A}],"filter-has":[Ai,[mo],(k,[x])=>x.value in k.properties()],"filter-has-id":[Ai,[],k=>k.id()!==null&&k.id()!==void 0],"filter-type-in":[Ai,[qn(gi)],(k,[x])=>x.value.indexOf(k.geometryType())>=0],"filter-id-in":[Ai,[qn(mo)],(k,[x])=>x.value.indexOf(k.id())>=0],"filter-in-small":[Ai,[gi,qn(mo)],(k,[x,j])=>j.value.indexOf(k.properties()[x.value])>=0],"filter-in-large":[Ai,[gi,qn(mo)],(k,[x,j])=>function(A,L,O,$){for(;O<=$;){const Y=O+$>>1;if(L[Y]===A)return!0;L[Y]>A?$=Y-1:O=Y+1}return!1}(k.properties()[x.value],j.value,0,j.value.length-1)],all:{type:Ai,overloads:[[[Ai,Ai],(k,[x,j])=>x.evaluate(k)&&j.evaluate(k)],[Eu(Ai),(k,x)=>{for(const j of x)if(!j.evaluate(k))return!1;return!0}]]},any:{type:Ai,overloads:[[[Ai,Ai],(k,[x,j])=>x.evaluate(k)||j.evaluate(k)],[Eu(Ai),(k,x)=>{for(const j of x)if(j.evaluate(k))return!0;return!1}]]},"!":[Ai,[Ai],(k,[x])=>!x.evaluate(k)],"is-supported-script":[Ai,[gi],(k,[x])=>{const j=k.globals&&k.globals.isSupportedScript;return!j||j(x.evaluate(k))}],upcase:[gi,[gi],(k,[x])=>x.evaluate(k).toUpperCase()],downcase:[gi,[gi],(k,[x])=>x.evaluate(k).toLowerCase()],concat:[gi,Eu(mo),(k,x)=>x.map(j=>$a(j.evaluate(k))).join("")],"resolved-locale":[gi,[em],(k,[x])=>x.evaluate(k).resolvedLocale()],random:[Vr,[Vr,Vr,mo],(k,x)=>{const[j,A,L]=x.map($=>$.evaluate(k));if(j>A||j===A)return j;let O;if(typeof L=="string")O=function($){let Y=0;if($.length===0)return Y;for(let X=0;X<$.length;X++)Y=(Y<<5)-Y+$.charCodeAt(X),Y&=Y;return Y}(L);else{if(typeof L!="number")throw new Tc(`Invalid seed input: ${L}`);O=L}return j+_a(O)()*(A-j)}]});class Mh{constructor(x,j,A,L,O){this.expression=x,this._warningHistory={},this._scope=A,this._options=L,this._iconImageUseTheme=O,this._evaluator=new ph(A,L,O),this._defaultValue=j?function($){return $.type==="color"&&(Zu($.default)||Array.isArray($.default))?new Js(0,0,0,0):$.type==="color"?Js.parse($.default)||null:$.default===void 0?null:$.default}(j):null,this._enumValues=j&&j.type==="enum"?j.values:null,this.configDependencies=El(x),this.isIndoorDependent=eo(x)}evaluateWithoutErrorHandling(x,j,A,L,O,$,Y,X){return this._evaluator.globals=x,this._evaluator.feature=j,this._evaluator.featureState=A,this._evaluator.canonical=L||null,this._evaluator.availableImages=O||null,this._evaluator.formattedSection=$,this._evaluator.featureTileCoord=Y||null,this._evaluator.featureDistanceData=X||null,this.expression.evaluate(this._evaluator)}evaluate(x,j,A,L,O,$,Y,X,le){this._evaluator||(this._evaluator=new ph(this._scope,this._options,this._iconImageUseTheme)),this._evaluator.globals=x,this._evaluator.feature=j||null,this._evaluator.featureState=A||null,this._evaluator.canonical=L||null,this._evaluator.availableImages=O||null,this._evaluator.formattedSection=$||null,this._evaluator.featureTileCoord=Y||null,this._evaluator.featureDistanceData=X||null,this._evaluator.iconImageUseTheme=le||null;try{const xe=this.expression.evaluate(this._evaluator);if(xe==null||typeof xe=="number"&&xe!=xe)return this._defaultValue;if(this._enumValues&&!(xe in this._enumValues))throw new Tc(`Expected value to be one of ${Object.keys(this._enumValues).map(je=>JSON.stringify(je)).join(", ")}, but found ${JSON.stringify(xe)} instead.`);return xe}catch(xe){const je=xe;return this._warningHistory[je.message]||(this._warningHistory[je.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${je.message}`)),this._defaultValue}}}function Op(k){return Array.isArray(k)&&k.length>0&&typeof k[0]=="string"&&k[0]in ro}function Dd(k,x,j,A,L){const O=new rk(ro,[],x?function(Y){const X={color:rc,string:gi,number:Vr,enum:gi,boolean:Ai,formatted:Gt,resolvedImage:An};return Y.type==="array"?qn(X[Y.value]||mo,Y.length):X[Y.type]}(x):void 0,void 0,void 0,j,A,L),$=O.parse(k,void 0,void 0,void 0,x&&x.type==="string"?{typeAnnotation:"coerce"}:void 0);return $?fi(new Mh($,x,j,A,L)):Il(O.errors)}class tm{constructor(x,j,A,L){this.kind=x,this._styleExpression=j,this.isLightConstant=A,this.isLineProgressConstant=L,this.isStateDependent=x!=="constant"&&!Gx(j.expression),this.configDependencies=El(j.expression),this.isIndoorDependent=eo(j.expression)}evaluateWithoutErrorHandling(x,j,A,L,O,$){return this._styleExpression.evaluateWithoutErrorHandling(x,j,A,L,O,$)}evaluate(x,j,A,L,O,$,Y){return this._styleExpression.evaluate(x,j,A,L,O,$,void 0,void 0,Y)}}class Pc{constructor(x,j,A,L,O,$){this.kind=x,this.zoomStops=A,this._styleExpression=j,this.isStateDependent=x!=="camera"&&!Gx(j.expression),this.isIndoorDependent=eo(j.expression),this.isLightConstant=O,this.isLineProgressConstant=$,this.configDependencies=El(j.expression),this.interpolationType=L}evaluateWithoutErrorHandling(x,j,A,L,O,$){return this._styleExpression.evaluateWithoutErrorHandling(x,j,A,L,O,$)}evaluate(x,j,A,L,O,$){return this._styleExpression.evaluate(x,j,A,L,O,$)}interpolationFactor(x,j,A){return this.interpolationType?fp.interpolationFactor(this.interpolationType,x,j,A):0}}function Ph(k,x,j,A,L){if((k=Dd(k,x,j,A,L)).result==="error")return k;const O=k.value.expression,$=Vb(O);if(!$&&!vl(x))return Il([new wo("","data expressions not supported")]);const Y=Yu(O,["zoom","pitch","distance-from-center"]);if(!Y&&!Vm(x))return Il([new wo("","zoom expressions not supported")]);const X=Yu(O,["measure-light"]);if(!X&&!ju(x))return Il([new wo("","measure-light expression not supported")]);const le=Yu(O,["line-progress"]);if(!le&&!function(Ce){return To(Ce.expression,"line-progress")}(x))return Il([new wo("","line-progress expression not supported")]);const xe=x.expression&&x.expression.relaxZoomRestriction,je=Tu(O);return je||Y||xe?je instanceof wo?Il([je]):je instanceof fp&&!Nu(x)?Il([new wo("",'"interpolate" expressions cannot be used with this property')]):fi(je?new Pc($&&le?"camera":"composite",k.value,je.labels,je instanceof fp?je.interpolation:void 0,X,le):new tm($&&le?"constant":"source",k.value,X,le)):Il([new wo("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class zp{constructor(x,j){this._parameters=x,this._specification=j,Object.assign(this,lx(this._parameters,this._specification))}static deserialize(x){return new zp(x._parameters,x._specification)}static serialize(x){return{_parameters:x._parameters,_specification:x._specification}}}function Tu(k){let x=null;if(k instanceof Me)x=Tu(k.result);else if(k instanceof hw){for(const j of k.args)if(x=Tu(j),x)break}else(k instanceof t2||k instanceof fp)&&k.input instanceof Gd&&k.input.name==="zoom"&&(x=k);return x instanceof wo||k.eachChild(j=>{const A=Tu(j);A instanceof wo?x=A:x&&A&&x!==A&&(x=new wo("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),x}var cx,dx,Bp=function(){if(dx)return cx;dx=1,cx=x;var k=3;function x(j,A,L){var O=this.cells=[];if(j instanceof ArrayBuffer){this.arrayBuffer=j;var $=new Int32Array(this.arrayBuffer);j=$[0],this.d=(A=$[1])+2*(L=$[2]);for(var Y=0;Y=Ce[Ke+0]&&O>=Ce[Ke+1])?(X[Fe]=!0,Y.push(je[Fe])):X[Fe]=!1}}},x.prototype._forEachCell=function(j,A,L,O,$,Y,X,le){for(var xe=this._convertToCellCoord(j),je=this._convertToCellCoord(A),Ce=this._convertToCellCoord(L),Ie=this._convertToCellCoord(O),Fe=xe;Fe<=Ce;Fe++)for(var Ke=je;Ke<=Ie;Ke++){var et=this.d*Ke+Fe;if((!le||le(this._convertFromCellCoord(Fe),this._convertFromCellCoord(Ke),this._convertFromCellCoord(Fe+1),this._convertFromCellCoord(Ke+1)))&&$.call(this,j,A,L,O,et,Y,X,le))return}},x.prototype._convertFromCellCoord=function(j){return(j-this.padding)/this.scale},x.prototype._convertToCellCoord=function(j){return Math.max(0,Math.min(this.d-1,Math.floor(j*this.scale)+this.padding))},x.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var j=this.cells,A=k+this.cells.length+1+1,L=0,O=0;O=0||(L[O]=Cd(k[O],x)));k instanceof Error&&(L.message=k.message)}if(L.$name)throw new Error("$name property is reserved for worker serialization logic.");return A!=="Object"&&(L.$name=A),L}throw new Error("can't serialize object of type "+typeof k)}function Zc(k){if(k==null||typeof k=="boolean"||typeof k=="number"||typeof k=="string"||k instanceof Boolean||k instanceof Number||k instanceof String||k instanceof Date||k instanceof RegExp||$o(k)||k instanceof ImageBitmap||ArrayBuffer.isView(k)||k instanceof ImageData)return k;if(Array.isArray(k))return k.map(Zc);if(typeof k=="object"){const x=k.$name||"Object";if(x==="Map"){const L=k.entries||[],O=new Map;for(let $=0;$k>=1536&&k<=1791,xp=k=>k>=1872&&k<=1919,q0=k=>k>=2208&&k<=2303,Xu=k=>k>=11904&&k<=12031,vf=k=>k>=12032&&k<=12255,I1=k=>k>=12272&&k<=12287,Hb=k=>k>=12288&&k<=12351,D1=k=>k>=12352&&k<=12447,$p=k=>k>=12448&&k<=12543,ux=k=>k>=12544&&k<=12591,l2=k=>k>=12704&&k<=12735,Wy=k=>k>=12736&&k<=12783,V0=k=>k>=12784&&k<=12799,zv=k=>k>=12800&&k<=13055,c2=k=>k>=13056&&k<=13311,d2=k=>k>=13312&&k<=19903,Ng=k=>k>=19968&&k<=40959,Bv=k=>k>=40960&&k<=42127,kg=k=>k>=42128&&k<=42191,mw=k=>k>=44032&&k<=55215,Gb=k=>k>=63744&&k<=64255,Wb=k=>k>=64336&&k<=65023,u2=k=>k>=65040&&k<=65055,Kb=k=>k>=65072&&k<=65103,yh=k=>k>=65104&&k<=65135,H0=k=>k>=65136&&k<=65279,Wx=k=>k>=65280&&k<=65519;function hx(k){for(const x of k)if(r5(x.charCodeAt(0)))return!0;return!1}function QC(k){for(const x of k)if(!Yb(x.charCodeAt(0)))return!1;return!0}function Yb(k){return!(od(k)||xp(k)||q0(k)||Wb(k)||H0(k))}function JC(k){return!(k<11904||!(l2(k)||ux(k)||Kb(k)||Gb(k)||c2(k)||Xu(k)||Wy(k)||Hb(k)||d2(k)||Ng(k)||zv(k)||Wx(k)||D1(k)||I1(k)||vf(k)||V0(k)||$p(k)||u2(k)||kg(k)||Bv(k)))}function r5(k){return!(k!==746&&k!==747&&(k<4352||!(l2(k)||ux(k)||Kb(k)&&!(k>=65097&&k<=65103)||Gb(k)||c2(k)||Xu(k)||Wy(k)||!(!Hb(k)||k>=12296&&k<=12305||k>=12308&&k<=12319||k===12336)||d2(k)||Ng(k)||zv(k)||(x=>x>=12592&&x<=12687)(k)||(x=>x>=43360&&x<=43391)(k)||(x=>x>=55216&&x<=55295)(k)||(x=>x>=4352&&x<=4607)(k)||mw(k)||D1(k)||I1(k)||(x=>x>=12688&&x<=12703)(k)||vf(k)||V0(k)||$p(k)&&k!==12540||!(!Wx(k)||k===65288||k===65289||k===65293||k>=65306&&k<=65310||k===65339||k===65341||k===65343||k>=65371&&k<=65503||k===65507||k>=65512&&k<=65519)||!(!yh(k)||k>=65112&&k<=65118||k>=65123&&k<=65126)||(x=>x>=5120&&x<=5759)(k)||(x=>x>=6320&&x<=6399)(k)||u2(k)||(x=>x>=19904&&x<=19967)(k)||Bv(k)||kg(k))))}function R1(k){return k===12312||k===12313||k===12316||k===12540||k===12448}function F1(k){return!(r5(k)||function(x){return!!((j=>j>=128&&j<=255)(x)&&(x===167||x===169||x===174||x===177||x===188||x===189||x===190||x===215||x===247)||(j=>j>=8192&&j<=8303)(x)&&(x===8214||x===8224||x===8225||x===8240||x===8241||x===8251||x===8252||x===8258||x===8263||x===8264||x===8265||x===8273)||(j=>j>=8448&&j<=8527)(x)||(j=>j>=8528&&j<=8591)(x)||(j=>j>=8960&&j<=9215)(x)&&(x>=8960&&x<=8967||x>=8972&&x<=8991||x>=8996&&x<=9e3||x===9003||x>=9085&&x<=9114||x>=9150&&x<=9165||x===9167||x>=9169&&x<=9179||x>=9186&&x<=9215)||(j=>j>=9216&&j<=9279)(x)&&x!==9251||(j=>j>=9280&&j<=9311)(x)||(j=>j>=9312&&j<=9471)(x)||(j=>j>=9632&&j<=9727)(x)||(j=>j>=9728&&j<=9983)(x)&&!(x>=9754&&x<=9759)||(j=>j>=11008&&j<=11263)(x)&&(x>=11026&&x<=11055||x>=11088&&x<=11097||x>=11192&&x<=11243)||Hb(x)||$p(x)||(j=>j>=57344&&j<=63743)(x)||Kb(x)||yh(x)||Wx(x)||x===8734||x===8756||x===8757||x>=9984&&x<=10087||x>=10102&&x<=10131||x===65532||x===65533)}(k))}function e3(k){return od(k)||xp(k)||q0(k)||Wb(k)||H0(k)}function O1(k){return k>=1424&&k<=2303||Wb(k)||H0(k)}function Ky(k,x){return!(!x&&O1(k)||k>=2304&&k<=3583||k>=3840&&k<=4255||(j=>j>=6016&&j<=6143)(k))}function ik(k){for(const x of k)if(O1(x.charCodeAt(0)))return!0;return!1}const Lh={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let gp=null,Mu=Lh.unavailable,mx=null;const a5=function(k){k&&typeof k=="string"&&k.indexOf("NetworkError")>-1&&(Mu=Lh.error),gp&&gp(k)};function ok(){i5.fire(new Sd("pluginStateChange",{pluginStatus:Mu,pluginURL:mx}))}const i5=new Um,G0=function(){return Mu},o5=function(){if(Mu!==Lh.deferred||!mx)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Mu=Lh.loading,ok(),mx&&Yg({url:mx},k=>{k?a5(k):(Mu=Lh.loaded,ok())})},ey={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Mu===Lh.loaded||ey.applyArabicShaping!=null,isLoading:()=>Mu===Lh.loading,setState(k){Mu=k.pluginStatus,mx=k.pluginURL},isParsing:()=>Mu===Lh.parsing,isParsed:()=>Mu===Lh.parsed,getPluginURL:()=>mx},JL=function(){ey.isLoading()||ey.isLoaded()||G0()!=="deferred"||o5()};class Vi{constructor(x,j){this.zoom=x,j?(this.now=j.now,this.fadeDuration=j.fadeDuration,this.transition=j.transition,this.pitch=j.pitch,this.brightness=j.brightness,this.worldview=j.worldview,this.activeFloors=j.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(x){return function(j,A){for(const L of j)if(!Ky(L.charCodeAt(0),A))return!1;return!0}(x,ey.isLoaded())}}class l5{constructor(x,j,A,L,O){this.property=x,this.value=j,this.expression=function($,Y,X,le,xe){if(Zu($))return new zp($,Y);if(Op($)||Array.isArray($)&&$.length>0){const je=Ph($,Y,X,le,xe);if(je.result==="error")throw new Error(je.value.map(Ce=>`${Ce.key}: ${Ce.message}`).join(", "));return je.value}{let je=$;return typeof $=="string"&&Y.type==="color"&&(je=Js.parse($)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>je}}}(j===void 0?x.specification.default:j,x.specification,A,L,O)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(x,j,A,L){return this.property.possiblyEvaluate(this,x,j,A,L)}}class t3{constructor(x,j,A,L){this.property=x,this.value=new l5(x,void 0,j,A,L)}transitioned(x,j){return new c5(this.property,this.value,j,Object.assign({},x.transition,this.transition),x.now)}untransitioned(){return new c5(this.property,this.value,null,{},0)}}class nT{constructor(x,j,A,L){this._properties=x,this._values=Object.create(x.defaultTransitionablePropertyValues),this._scope=j,this._options=A,this._iconImageUseTheme=L,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(x){return Zn(this._values[x].value.value)}setValue(x,j){this._values.hasOwnProperty(x)||(this._values[x]=new t3(this._values[x].property,this._scope,this._options,this._iconImageUseTheme)),this._values[x].value=new l5(this._values[x].property,j===null?void 0:Zn(j),this._scope,this._options,this._iconImageUseTheme),this._values[x].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[x].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[x].value.isIndoorDependent())}setTransitionOrValue(x,j){j&&(this._options=j);const A=this._properties.properties;if(x)for(const L in x){const O=x[L];if(L.endsWith("-transition")){const $=L.slice(0,-11);A[$]&&this.setTransition($,O)}else A.hasOwnProperty(L)&&this.setValue(L,O)}}getTransition(x){return Zn(this._values[x].transition)}setTransition(x,j){this._values.hasOwnProperty(x)||(this._values[x]=new t3(this._values[x].property)),this._values[x].transition=Zn(j)||void 0}serialize(){const x={};for(const j of Object.keys(this._values)){const A=this.getValue(j);A!==void 0&&(x[j]=A);const L=this.getTransition(j);L!==void 0&&(x[`${j}-transition`]=L)}return x}transitioned(x,j){const A=new rT(this._properties);for(const L of Object.keys(this._values))A._values[L]=this._values[L].transitioned(x,j._values[L]);return A}untransitioned(){const x=new rT(this._properties);for(const j of Object.keys(this._values))x._values[j]=this._values[j].untransitioned();return x}isIndoorDependent(){return this._isIndoorDependent}}class c5{constructor(x,j,A,L,O){const $=L.delay||0,Y=L.duration||0;O=O||0,this.property=x,this.value=j,this.begin=O+$,this.end=this.begin+Y,x.specification.transition&&(L.delay||L.duration)&&(this.prior=A)}possiblyEvaluate(x,j,A){const L=x.now||0,O=this.value.possiblyEvaluate(x,j,A),$=this.prior;if($){if(L>this.end)return this.prior=null,O;if(this.value.isDataDriven())return this.prior=null,O;if(L":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 s3(k){return k instanceof Number||k instanceof String||k instanceof Boolean?k.valueOf():k}function d5(k){if(Array.isArray(k))return k.map(d5);if(k instanceof Object&&!(k instanceof Number||k instanceof String||k instanceof Boolean)){const x={};for(const j in k)x[j]=d5(k[j]);return x}return s3(k)}function n3(k){if(k===!0||k===!1)return!0;if(!Array.isArray(k)||k.length===0)return!1;switch(k[0]){case"has":return k.length>=2&&k[1]!=="$id"&&k[1]!=="$type";case"in":return k.length>=3&&(typeof k[1]!="string"||Array.isArray(k[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return k.length!==3||Array.isArray(k[1])||Array.isArray(k[2]);case"any":case"all":for(const x of k.slice(1))if(!n3(x)&&typeof x!="boolean")return!1;return!0;default:return!0}}function iT(k,x="",j=null,A="fill"){if(k==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};n3(k)||(k=lT(k));const L=k;let O=!0;try{O=function(xe){if(!ck(xe))return xe;let je=d5(xe);return tI(je),je=eI(je),je}(L)}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(L,null,2)} `)}let $=null,Y=null;if(A!=="background"&&A!=="sky"&&A!=="slot"){Y=Ws[`filter_${A}`];const xe=Dd(O,Y,x,j);if(xe.result==="error")throw new Error(xe.value.map(je=>`${je.key}: ${je.message}`).join(", "));$=(je,Ce,Ie)=>xe.value.evaluate(je,Ce,{},Ie)}let X=null,le=null;if(O!==L){const xe=Dd(L,Y,x,j);if(xe.result==="error")throw new Error(xe.value.map(je=>`${je.key}: ${je.message}`).join(", "));X=(je,Ce,Ie,Fe,Ke)=>xe.value.evaluate(je,Ce,{},Ie,void 0,void 0,Fe,Ke),le=!Vb(xe.value.expression)}return{filter:$,dynamicFilter:X||void 0,needGeometry:Dz(O),needFeature:!!le}}function eI(k){if(!Array.isArray(k))return k;const x=function(j){if(sI.has(j[0])){for(let A=1;AeI(j))}function tI(k){let x=!1;const j=[];if(k[0]==="case"){for(let A=1;A",">=","<","<=","to-boolean"]);function oT(k,x){return kx?1:0}function Dz(k){if(!Array.isArray(k))return!1;if(k[0]==="within"||k[0]==="distance")return!0;for(let x=1;x"||x==="<="||x===">="?ie(k[1],k[2],x):x==="any"?(j=k.slice(1),["any"].concat(j.map(lT))):x==="all"?["all"].concat(k.slice(1).map(lT)):x==="none"?["all"].concat(k.slice(1).map(lT).map(st)):x==="in"?de(k[1],k.slice(2)):x==="!in"?st(de(k[1],k.slice(2))):x==="has"?Re(k[1]):x!=="!has"||st(Re(k[1]));var j}function ie(k,x,j){switch(k){case"$type":return[`filter-type-${j}`,x];case"$id":return[`filter-id-${j}`,x];default:return[`filter-${j}`,k,x]}}function de(k,x){if(x.length===0)return!1;switch(k){case"$type":return["filter-type-in",["literal",x]];case"$id":return["filter-id-in",["literal",x]];default:return x.length>200&&!x.some(j=>typeof j!=typeof x[0])?["filter-in-large",k,["literal",x.sort(oT)]]:["filter-in-small",k,["literal",x]]}}function Re(k){switch(k){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",k]}}function st(k){return["!",k]}const dt="";function Pt(k,x){return x?`${k}${dt}${x}`:k}function Hs(k){const x=k.indexOf(dt);return x>=0?k.slice(x+1):""}let Qn;const Br=()=>Qn||(Qn=new ld({"icon-size":new dr(Ws.layout_symbol["icon-size"]),"icon-image":new dr(Ws.layout_symbol["icon-image"]),"icon-rotate":new dr(Ws.layout_symbol["icon-rotate"]),"icon-offset":new dr(Ws.layout_symbol["icon-offset"]),"text-size":new dr(Ws.layout_symbol["text-size"]),"text-rotate":new dr(Ws.layout_symbol["text-rotate"]),"text-offset":new dr(Ws.layout_symbol["text-offset"])}));let Ka;const no=()=>Ka||(Ka=new ld({"icon-opacity":new dr(Ws.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new dr(Ws.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new dr(Ws.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new dr(Ws.paint_symbol["text-emissive-strength"]),"icon-color":new dr(Ws.paint_symbol["icon-color"]),"icon-halo-color":new dr(Ws.paint_symbol["icon-halo-color"]),"icon-halo-width":new dr(Ws.paint_symbol["icon-halo-width"]),"icon-halo-blur":new dr(Ws.paint_symbol["icon-halo-blur"]),"icon-translate":new dr(Ws.paint_symbol["icon-translate"]),"text-opacity":new dr(Ws.paint_symbol["text-opacity"]),"text-occlusion-opacity":new dr(Ws.paint_symbol["text-occlusion-opacity"]),"text-color":new dr(Ws.paint_symbol["text-color"],{runtimeType:rc,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new dr(Ws.paint_symbol["text-halo-color"]),"text-halo-width":new dr(Ws.paint_symbol["text-halo-width"]),"text-halo-blur":new dr(Ws.paint_symbol["text-halo-blur"]),"text-translate":new dr(Ws.paint_symbol["text-translate"]),"symbol-z-offset":new dr(Ws.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}));class ic{constructor(x,j,A,L,O,$){this._conditionSpec=x,this._propertiesSpec=A;const Y=Dd(x,Ws.appearance.condition);if(Y.result==="success"&&(this.condition=Y.value),this.name=j,A){this.layoutProperties=new Up(Br()),this.unevaluatedLayout=new aT(Br(),L,O,$),this.paintProperties=new Up(no()),this.unevaluatedPaint=new aT(no(),L,O,"");for(const X in A)X in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(X,A[X]):X in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(X,A[X])}}isActive(x){return!(this.condition||!x.isHidden||this.name!=="hidden")||this.condition.evaluate(x.globals,x.feature,x.featureState,x.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(x){return this.layoutProperties.get(x)}getPaintProperty(x){return this.paintProperties.get(x)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(x){return this.unevaluatedLayout._values[x]}getUnevaluatedPaintProperty(x){return this.unevaluatedPaint._values[x]}recalculate(x,j,A){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(x,void 0,j,A)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(x,void 0,j,""))}serialize(){const x={};x.condition=this.condition.expression.serialize(),this.name&&(x.name=this.name);const j=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},A=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},L=Object.assign({},j,A);return Object.keys(L).length>0&&(x.properties=L),x}hasIconLayoutProperties(){const x=this.hasLayoutProperty("icon-image"),j=this.hasLayoutProperty("icon-size"),A=this.hasLayoutProperty("icon-offset"),L=this.hasLayoutProperty("icon-rotate");return x||j||A||L}hasTextLayoutProperties(){const x=this.hasLayoutProperty("text-size"),j=this.hasLayoutProperty("text-offset"),A=this.hasLayoutProperty("text-rotate");return x||j||A}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(x=>!x.endsWith("-use-theme")).some(x=>(x.startsWith("icon-")||x==="symbol-z-offset")&&this.hasPaintProperty(x))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(x=>!x.endsWith("-use-theme")).some(x=>(x.startsWith("text-")||x==="symbol-z-offset")&&this.hasPaintProperty(x))}hasLayoutProperty(x){return this.unevaluatedLayout&&this.unevaluatedLayout._values[x].value!==void 0}hasPaintProperty(x){return this.unevaluatedPaint&&this.unevaluatedPaint._values[x].value!==void 0}}const Ri="-transition",Ih=new Set(["fill","line","background","hillshade","raster"]);class oc extends Um{constructor(x,j,A,L,O,$){if(super(),this.id=x.id,this.fqid=Pt(this.id,A),this.type=x.type,this.scope=A,this.lut=L,this.options=O,this.iconImageUseTheme=$,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},x.type!=="custom"){if(this.metadata=x.metadata,this.minzoom=x.minzoom,this.maxzoom=x.maxzoom,x.type&&x.type!=="background"&&x.type!=="sky"&&x.type!=="slot"){this.source=x.source,this.sourceLayer=x["source-layer"],this.filter=x.filter;const Y=Dd(this.filter,Ws[`filter_${x.type}`]);Y.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...Y.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||Y.value.isIndoorDependent)}if(x.slot&&(this.slot=x.slot),x.appearances&&this.setAppearances(x.appearances),j.layout&&(this._unevaluatedLayout=new aT(j.layout,this.scope,O,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),j.paint){this._transitionablePaint=new nT(j.paint,this.scope,O);for(const Y in x.paint)this.setPaintProperty(Y,x.paint[Y]);for(const Y in x.layout)this.setLayoutProperty(Y,x.layout[Y]);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 Up(j.paint)}}}onAdd(x){}onRemove(x){}isDraped(x){return!this.is3D(!0)&&Ih.has(this.type)}getLayoutProperty(x){return x==="visibility"?this.visibility:this._unevaluatedLayout.getValue(x)}setLayoutProperty(x,j){if(this.type==="custom"&&x==="visibility")return void(this.visibility=j);const A=this._unevaluatedLayout;A._properties.properties[x]&&(A.setValue(x,j),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...A.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||A.isIndoorDependent(),x==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(x){this.appearances=[],x.forEach(j=>{this.appearances.push(new ic(j.condition,j.name,j.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(x){return x.endsWith(Ri)?this._transitionablePaint.getTransition(x.slice(0,-11)):this._transitionablePaint.getValue(x)}isPaintProperty(x){return!!this._transitionablePaint._properties.properties[x]}setPaintProperty(x,j){const A=this._transitionablePaint,L=A._properties.properties;if(x.endsWith(Ri)){const je=x.slice(0,-11);return L[je]&&A.setTransition(je,j||void 0),!1}if(!L[x])return!1;const O=A._values[x],$=O.value.isDataDriven(),Y=O.value;A.setValue(x,j),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...A.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||A.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(x);const X=A._values[x].value,le=X.isDataDriven(),xe=x.endsWith("pattern")||x==="line-dasharray";return le||$||xe||this._handleOverridablePaintPropertyUpdate(x,Y,X)}_handleSpecialPaintPropertyUpdate(x){}getProgramIds(){return null}getDefaultProgramParams(x,j,A){return null}_handleOverridablePaintPropertyUpdate(x,j,A){return!1}isHidden(x){return!!(this.minzoom&&x=this.maxzoom)||this.visibility==="none"}updateTransitions(x){this._transitioningPaint=this._transitionablePaint.transitioned(x,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(x,j){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(x,void 0,j,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(x,void 0,j)}serialize(){const x={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&&(x.appearances=this.appearances.map(j=>j.serialize())),Zs(x,(j,A)=>!(j===void 0||A==="layout"&&!Object.keys(j).length||A==="paint"&&!Object.keys(j).length))}is3D(x){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 x in this.paint._values){const j=this.paint.get(x);if(j instanceof lk&&vl(j.property.specification)&&(j.value.kind==="source"||j.value.kind==="composite")&&j.value.isStateDependent)return!0}for(const x of this.appearances)if(!Gx(x.condition.expression))return!0;return!1}compileFilter(x){this._filterCompiled||(this._featureFilter=iT(this.filter,this.scope,x),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(x){this._stats&&(x.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(x,j,A){return{}}queryRadius(x){}queryIntersectsFeature(x,j,A,L,O,$,Y,X,le,xe){}}const Kx={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class K0{constructor(x,j){this._structArray=x,this._pos1=j*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Ir=new ArrayBuffer(0);class Ln{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(x,j){return x._trim(),j&&x.arrayBuffer&&j.add(x.arrayBuffer),{length:x.length,arrayBuffer:x.arrayBuffer}}static deserialize(x){const j=Object.create(this.prototype);return j.arrayBuffer=x.arrayBuffer,j.length=x.length,x.arrayBuffer?j.capacity=x.arrayBuffer.byteLength/j.bytesPerElement:(j.capacity=0,j.arrayBuffer=Ir),j._refreshViews(),j}_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(x){this.reserve(x),this.length=x}reserve(x){if(x>this.capacity){this._reallocCount++,this.capacity=Math.max(x,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const j=this.uint8;this._refreshViews(),j&&this.uint8.set(j)}}reserveForAdditional(x){this.reserve(this.length+x)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...x){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...x){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 Wn(k,x=1){let j=0,A=0;return{members:k.map(L=>{const O=Kx[L.type].BYTES_PER_ELEMENT,$=j=Hi(j,Math.max(x,O)),Y=L.components||1;return A=Math.max(A,O),j+=O*Y,{name:L.name,type:L.type,components:Y,offset:$}}),size:Hi(j,Math.max(A,x)),alignment:x}}function Hi(k,x){return Math.ceil(k/x)*x}class ao extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j){const A=this.length;return this.resize(A+1),this.emplace(A,x,j)}emplace(x,j,A){const L=2*x;return this.int16[L+0]=j,this.int16[L+1]=A,x}}ao.prototype.bytesPerElement=4,kr(ao,"StructArrayLayout2i4");class xl extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,j,A)}emplace(x,j,A,L){const O=3*x;return this.int16[O+0]=j,this.int16[O+1]=A,this.int16[O+2]=L,x}}xl.prototype.bytesPerElement=6,kr(xl,"StructArrayLayout3i6");class bo extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j,A,L){const O=this.length;return this.resize(O+1),this.emplace(O,x,j,A,L)}emplace(x,j,A,L,O){const $=4*x;return this.int16[$+0]=j,this.int16[$+1]=A,this.uint16[$+2]=L,this.uint16[$+3]=O,x}}bo.prototype.bytesPerElement=8,kr(bo,"StructArrayLayout2i2ui8");class Jl extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x){const j=this.length;return this.resize(j+1),this.emplace(j,x)}emplace(x,j){return this.float32[1*x+0]=j,x}}Jl.prototype.bytesPerElement=4,kr(Jl,"StructArrayLayout1f4");class qp extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,j,A)}emplace(x,j,A,L){const O=4*x,$=2*x;return this.int16[O+0]=j,this.int16[O+1]=A,this.float32[$+1]=L,x}}qp.prototype.bytesPerElement=8,kr(qp,"StructArrayLayout2i1f8");class Ad extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,j,A)}emplace(x,j,A,L){const O=4*x;return this.int16[O+0]=j,this.int16[O+1]=A,this.int16[O+2]=L,x}}Ad.prototype.bytesPerElement=8,kr(Ad,"StructArrayLayout3i8");class Zb extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A,L){const O=this.length;return this.resize(O+1),this.emplace(O,x,j,A,L)}emplace(x,j,A,L,O){const $=4*x;return this.int16[$+0]=j,this.int16[$+1]=A,this.int16[$+2]=L,this.int16[$+3]=O,x}}Zb.prototype.bytesPerElement=8,kr(Zb,"StructArrayLayout4i8");class nI extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O){const $=this.length;return this.resize($+1),this.emplace($,x,j,A,L,O)}emplace(x,j,A,L,O,$){const Y=5*x;return this.int16[Y+0]=j,this.int16[Y+1]=A,this.int16[Y+2]=L,this.int16[Y+3]=O,this.int16[Y+4]=$,x}}nI.prototype.bytesPerElement=10,kr(nI,"StructArrayLayout5i10");class rI extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y){const X=this.length;return this.resize(X+1),this.emplace(X,x,j,A,L,O,$,Y)}emplace(x,j,A,L,O,$,Y,X){const le=6*x,xe=12*x,je=3*x;return this.int16[le+0]=j,this.int16[le+1]=A,this.uint8[xe+4]=L,this.uint8[xe+5]=O,this.uint8[xe+6]=$,this.uint8[xe+7]=Y,this.float32[je+2]=X,x}}rI.prototype.bytesPerElement=12,kr(rI,"StructArrayLayout2i4ub1f12");class Xb extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,j,A)}emplace(x,j,A,L){const O=3*x;return this.float32[O+0]=j,this.float32[O+1]=A,this.float32[O+2]=L,x}}Xb.prototype.bytesPerElement=12,kr(Xb,"StructArrayLayout3f12");class h2 extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O){const $=this.length;return this.resize($+1),this.emplace($,x,j,A,L,O)}emplace(x,j,A,L,O,$){const Y=6*x,X=3*x;return this.uint16[Y+0]=j,this.uint16[Y+1]=A,this.uint16[Y+2]=L,this.uint16[Y+3]=O,this.float32[X+2]=$,x}}h2.prototype.bytesPerElement=12,kr(h2,"StructArrayLayout4ui1f12");class cT extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j,A,L){const O=this.length;return this.resize(O+1),this.emplace(O,x,j,A,L)}emplace(x,j,A,L,O){const $=4*x;return this.uint16[$+0]=j,this.uint16[$+1]=A,this.uint16[$+2]=L,this.uint16[$+3]=O,x}}cT.prototype.bytesPerElement=8,kr(cT,"StructArrayLayout4ui8");class Rz extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$){const Y=this.length;return this.resize(Y+1),this.emplace(Y,x,j,A,L,O,$)}emplace(x,j,A,L,O,$,Y){const X=6*x;return this.int16[X+0]=j,this.int16[X+1]=A,this.int16[X+2]=L,this.int16[X+3]=O,this.int16[X+4]=$,this.int16[X+5]=Y,x}}Rz.prototype.bytesPerElement=12,kr(Rz,"StructArrayLayout6i12");class CK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le,xe,je,Ce){const Ie=this.length;return this.resize(Ie+1),this.emplace(Ie,x,j,A,L,O,$,Y,X,le,xe,je,Ce)}emplace(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie){const Fe=12*x;return this.int16[Fe+0]=j,this.int16[Fe+1]=A,this.int16[Fe+2]=L,this.int16[Fe+3]=O,this.uint16[Fe+4]=$,this.uint16[Fe+5]=Y,this.uint16[Fe+6]=X,this.uint16[Fe+7]=le,this.int16[Fe+8]=xe,this.int16[Fe+9]=je,this.int16[Fe+10]=Ce,this.int16[Fe+11]=Ie,x}}CK.prototype.bytesPerElement=24,kr(CK,"StructArrayLayout4i4ui4i24");class AK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$){const Y=this.length;return this.resize(Y+1),this.emplace(Y,x,j,A,L,O,$)}emplace(x,j,A,L,O,$,Y){const X=10*x,le=5*x;return this.int16[X+0]=j,this.int16[X+1]=A,this.int16[X+2]=L,this.float32[le+2]=O,this.float32[le+3]=$,this.float32[le+4]=Y,x}}AK.prototype.bytesPerElement=20,kr(AK,"StructArrayLayout3i3f20");class dk extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L){const O=this.length;return this.resize(O+1),this.emplace(O,x,j,A,L)}emplace(x,j,A,L,O){const $=4*x;return this.float32[$+0]=j,this.float32[$+1]=A,this.float32[$+2]=L,this.float32[$+3]=O,x}}dk.prototype.bytesPerElement=16,kr(dk,"StructArrayLayout4f16");class aI extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(x){const j=this.length;return this.resize(j+1),this.emplace(j,x)}emplace(x,j){return this.uint32[1*x+0]=j,x}}aI.prototype.bytesPerElement=4,kr(aI,"StructArrayLayout1ul4");class Qb extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j){const A=this.length;return this.resize(A+1),this.emplace(A,x,j)}emplace(x,j,A){const L=2*x;return this.uint16[L+0]=j,this.uint16[L+1]=A,x}}Qb.prototype.bytesPerElement=4,kr(Qb,"StructArrayLayout2ui4");class Fz extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie){const Fe=this.length;return this.resize(Fe+1),this.emplace(Fe,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie)}emplace(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe){const Ke=20*x,et=10*x;return this.int16[Ke+0]=j,this.int16[Ke+1]=A,this.int16[Ke+2]=L,this.int16[Ke+3]=O,this.int16[Ke+4]=$,this.float32[et+3]=Y,this.float32[et+4]=X,this.float32[et+5]=le,this.float32[et+6]=xe,this.int16[Ke+14]=je,this.uint32[et+8]=Ce,this.uint16[Ke+18]=Ie,this.uint16[Ke+19]=Fe,x}}Fz.prototype.bytesPerElement=40,kr(Fz,"StructArrayLayout5i4f1i1ul2ui40");class iI extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y){const X=this.length;return this.resize(X+1),this.emplace(X,x,j,A,L,O,$,Y)}emplace(x,j,A,L,O,$,Y,X){const le=8*x;return this.int16[le+0]=j,this.int16[le+1]=A,this.int16[le+2]=L,this.int16[le+4]=O,this.int16[le+5]=$,this.int16[le+6]=Y,this.int16[le+7]=X,x}}iI.prototype.bytesPerElement=16,kr(iI,"StructArrayLayout3i2i2i16");class EK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O){const $=this.length;return this.resize($+1),this.emplace($,x,j,A,L,O)}emplace(x,j,A,L,O,$){const Y=4*x,X=8*x;return this.float32[Y+0]=j,this.float32[Y+1]=A,this.float32[Y+2]=L,this.int16[X+6]=O,this.int16[X+7]=$,x}}EK.prototype.bytesPerElement=16,kr(EK,"StructArrayLayout2f1f2i16");class oI extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$){const Y=this.length;return this.resize(Y+1),this.emplace(Y,x,j,A,L,O,$)}emplace(x,j,A,L,O,$,Y){const X=20*x,le=5*x;return this.uint8[X+0]=j,this.uint8[X+1]=A,this.float32[le+1]=L,this.float32[le+2]=O,this.float32[le+3]=$,this.float32[le+4]=Y,x}}oI.prototype.bytesPerElement=20,kr(oI,"StructArrayLayout2ub4f20");class Qu extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j,A){const L=this.length;return this.resize(L+1),this.emplace(L,x,j,A)}emplace(x,j,A,L){const O=3*x;return this.uint16[O+0]=j,this.uint16[O+1]=A,this.uint16[O+2]=L,x}}Qu.prototype.bytesPerElement=6,kr(Qu,"StructArrayLayout3ui6");class Oz extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt)}emplace(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt,Bt){const Ns=30*x,us=15*x,ws=60*x;return this.int16[Ns+0]=j,this.int16[Ns+1]=A,this.int16[Ns+2]=L,this.float32[us+2]=O,this.float32[us+3]=$,this.uint16[Ns+8]=Y,this.uint16[Ns+9]=X,this.uint32[us+5]=le,this.uint32[us+6]=xe,this.uint32[us+7]=je,this.uint16[Ns+16]=Ce,this.uint16[Ns+17]=Ie,this.uint16[Ns+18]=Fe,this.float32[us+10]=Ke,this.float32[us+11]=et,this.uint8[ws+48]=at,this.uint8[ws+49]=vt,this.uint8[ws+50]=pt,this.uint32[us+13]=At,this.int16[Ns+28]=Rt,this.uint8[ws+58]=Bt,x}}Oz.prototype.bytesPerElement=60,kr(Oz,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class TK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt,Bt,Ns,us,ws,ys,vs,vn,Nn,Rn,$n,Fn,sr){const gn=this.length;return this.resize(gn+1),this.emplace(gn,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt,Bt,Ns,us,ws,ys,vs,vn,Nn,Rn,$n,Fn,sr)}emplace(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt,Bt,Ns,us,ws,ys,vs,vn,Nn,Rn,$n,Fn,sr,gn){const Bn=20*x,Vn=40*x,nr=80*x;return this.float32[Bn+0]=j,this.float32[Bn+1]=A,this.int16[Vn+4]=L,this.int16[Vn+5]=O,this.int16[Vn+6]=$,this.int16[Vn+7]=Y,this.int16[Vn+8]=X,this.int16[Vn+9]=le,this.int16[Vn+10]=xe,this.int16[Vn+11]=je,this.int16[Vn+12]=Ce,this.uint16[Vn+13]=Ie,this.uint16[Vn+14]=Fe,this.uint16[Vn+15]=Ke,this.uint16[Vn+16]=et,this.uint16[Vn+17]=at,this.uint16[Vn+18]=vt,this.uint16[Vn+19]=pt,this.uint16[Vn+20]=At,this.uint16[Vn+21]=Rt,this.uint16[Vn+22]=Bt,this.uint16[Vn+23]=Ns,this.uint16[Vn+24]=us,this.uint16[Vn+25]=ws,this.uint16[Vn+26]=ys,this.uint16[Vn+27]=vs,this.uint32[Bn+14]=vn,this.float32[Bn+15]=Nn,this.float32[Bn+16]=Rn,this.float32[Bn+17]=$n,this.float32[Bn+18]=Fn,this.uint8[nr+76]=sr,this.uint16[Vn+39]=gn,x}}TK.prototype.bytesPerElement=80,kr(TK,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class zz extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$){const Y=this.length;return this.resize(Y+1),this.emplace(Y,x,j,A,L,O,$)}emplace(x,j,A,L,O,$,Y){const X=6*x;return this.float32[X+0]=j,this.float32[X+1]=A,this.float32[X+2]=L,this.float32[X+3]=O,this.float32[X+4]=$,this.float32[X+5]=Y,x}}zz.prototype.bytesPerElement=24,kr(zz,"StructArrayLayout6f24");class r3 extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O){const $=this.length;return this.resize($+1),this.emplace($,x,j,A,L,O)}emplace(x,j,A,L,O,$){const Y=5*x;return this.float32[Y+0]=j,this.float32[Y+1]=A,this.float32[Y+2]=L,this.float32[Y+3]=O,this.float32[Y+4]=$,x}}r3.prototype.bytesPerElement=20,kr(r3,"StructArrayLayout5f20");class lI extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y){const X=this.length;return this.resize(X+1),this.emplace(X,x,j,A,L,O,$,Y)}emplace(x,j,A,L,O,$,Y,X){const le=7*x;return this.float32[le+0]=j,this.float32[le+1]=A,this.float32[le+2]=L,this.float32[le+3]=O,this.float32[le+4]=$,this.float32[le+5]=Y,this.float32[le+6]=X,x}}lI.prototype.bytesPerElement=28,kr(lI,"StructArrayLayout7f28");class MK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le,xe,je){const Ce=this.length;return this.resize(Ce+1),this.emplace(Ce,x,j,A,L,O,$,Y,X,le,xe,je)}emplace(x,j,A,L,O,$,Y,X,le,xe,je,Ce){const Ie=11*x;return this.float32[Ie+0]=j,this.float32[Ie+1]=A,this.float32[Ie+2]=L,this.float32[Ie+3]=O,this.float32[Ie+4]=$,this.float32[Ie+5]=Y,this.float32[Ie+6]=X,this.float32[Ie+7]=le,this.float32[Ie+8]=xe,this.float32[Ie+9]=je,this.float32[Ie+10]=Ce,x}}MK.prototype.bytesPerElement=44,kr(MK,"StructArrayLayout11f44");class PK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le){const xe=this.length;return this.resize(xe+1),this.emplace(xe,x,j,A,L,O,$,Y,X,le)}emplace(x,j,A,L,O,$,Y,X,le,xe){const je=9*x;return this.float32[je+0]=j,this.float32[je+1]=A,this.float32[je+2]=L,this.float32[je+3]=O,this.float32[je+4]=$,this.float32[je+5]=Y,this.float32[je+6]=X,this.float32[je+7]=le,this.float32[je+8]=xe,x}}PK.prototype.bytesPerElement=36,kr(PK,"StructArrayLayout9f36");class a3 extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j){const A=this.length;return this.resize(A+1),this.emplace(A,x,j)}emplace(x,j,A){const L=2*x;return this.float32[L+0]=j,this.float32[L+1]=A,x}}a3.prototype.bytesPerElement=8,kr(a3,"StructArrayLayout2f8");class LK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x,j,A,L){const O=this.length;return this.resize(O+1),this.emplace(O,x,j,A,L)}emplace(x,j,A,L,O){const $=6*x;return this.uint32[3*x+0]=j,this.uint16[$+2]=A,this.uint16[$+3]=L,this.uint16[$+4]=O,x}}LK.prototype.bytesPerElement=12,kr(LK,"StructArrayLayout1ul3ui12");class i3 extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(x){const j=this.length;return this.resize(j+1),this.emplace(j,x)}emplace(x,j){return this.uint16[1*x+0]=j,x}}i3.prototype.bytesPerElement=2,kr(i3,"StructArrayLayout1ui2");class IK extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et){const at=this.length;return this.resize(at+1),this.emplace(at,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et)}emplace(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at){const vt=16*x;return this.float32[vt+0]=j,this.float32[vt+1]=A,this.float32[vt+2]=L,this.float32[vt+3]=O,this.float32[vt+4]=$,this.float32[vt+5]=Y,this.float32[vt+6]=X,this.float32[vt+7]=le,this.float32[vt+8]=xe,this.float32[vt+9]=je,this.float32[vt+10]=Ce,this.float32[vt+11]=Ie,this.float32[vt+12]=Fe,this.float32[vt+13]=Ke,this.float32[vt+14]=et,this.float32[vt+15]=at,x}}IK.prototype.bytesPerElement=64,kr(IK,"StructArrayLayout16f64");class Bz extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(x,j,A,L,O,$,Y){const X=this.length;return this.resize(X+1),this.emplace(X,x,j,A,L,O,$,Y)}emplace(x,j,A,L,O,$,Y,X){const le=10*x,xe=5*x;return this.uint16[le+0]=j,this.uint16[le+1]=A,this.uint16[le+2]=L,this.uint16[le+3]=O,this.float32[xe+2]=$,this.float32[xe+3]=Y,this.float32[xe+4]=X,x}}Bz.prototype.bytesPerElement=20,kr(Bz,"StructArrayLayout4ui3f20");class $z extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(x){const j=this.length;return this.resize(j+1),this.emplace(j,x)}emplace(x,j){return this.int16[1*x+0]=j,x}}$z.prototype.bytesPerElement=2,kr($z,"StructArrayLayout1i2");class Uz extends Ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(x){const j=this.length;return this.resize(j+1),this.emplace(j,x)}emplace(x,j){return this.uint8[1*x+0]=j,x}}Uz.prototype.bytesPerElement=1,kr(Uz,"StructArrayLayout1ub1");class jie extends K0{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]}}jie.prototype.size=40;class DK extends Fz{get(x){return new jie(this,x)}}kr(DK,"CollisionBoxArray");class Nie extends K0{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(x){this._structArray.uint8[this._pos1+49]=x}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(x){this._structArray.uint8[this._pos1+50]=x}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(x){this._structArray.uint32[this._pos4+13]=x}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(x){this._structArray.uint8[this._pos1+58]=x}}Nie.prototype.size=60;class kie extends Oz{get(x){return new Nie(this,x)}}kr(kie,"PlacedSymbolArray");class cI extends K0{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(x){this._structArray.uint32[this._pos4+14]=x}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(x){this._structArray.float32[this._pos4+18]=x}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}cI.prototype.size=80;class Sie extends TK{get(x){return new cI(this,x)}}kr(Sie,"SymbolInstanceArray");class Cie extends Jl{getoffsetX(x){return this.float32[1*x+0]}}kr(Cie,"GlyphOffsetArray");class dI extends ao{getx(x){return this.int16[2*x+0]}gety(x){return this.int16[2*x+1]}}kr(dI,"SymbolLineVertexArray");class Aie extends K0{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]}}Aie.prototype.size=12;class RK extends LK{get(x){return new Aie(this,x)}}kr(RK,"FeatureIndexArray");class Eie extends Qb{geta_centroid_pos0(x){return this.uint16[2*x+0]}geta_centroid_pos1(x){return this.uint16[2*x+1]}}kr(Eie,"FillExtrusionCentroidArray");class FK extends K0{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]}}FK.prototype.size=6;class OK extends xl{get(x){return new FK(this,x)}}kr(OK,"FillExtrusionWallArray");const Tie=Wn([{name:"a_pos",components:2,type:"Int16"}],4),zDe=Wn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),BDe=Wn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Bc{constructor(x=[]){this.segments=x}_prepareSegment(x,j,A,L,O){let $=this.segments[this.segments.length-1];return x>Bc.MAX_VERTEX_ARRAY_LENGTH&&aa(`Max vertices per segment is ${Bc.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${x}`),(!$||$.vertexLength+x>Bc.MAX_VERTEX_ARRAY_LENGTH||$.sortKey!==L||O!==void 0&&$&&$.batchIndex!==void 0&&$.batchIndex!==O)&&($={vertexOffset:j,primitiveOffset:A,vertexLength:0,primitiveLength:0},L!==void 0&&($.sortKey=L),O!==void 0&&($.batchIndex=O),this.segments.push($)),$}prepareSegment(x,j,A,L,O){return this._prepareSegment(x,j.length,A.length,L,O)}get(){return this.segments}destroy(){for(const x of this.segments)for(const j in x.vaos)x.vaos[j].destroy()}static simpleSegment(x,j,A,L){return new Bc([{vertexOffset:x,primitiveOffset:j,vertexLength:A,primitiveLength:L,vaos:{},sortKey:0}])}}function qz(k,x){return 256*(k=gt(Math.floor(k),0,255))+gt(Math.floor(x),0,255)}Bc.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,kr(Bc,"SegmentVector");const $De=Wn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),UDe=Wn([{name:"a_pattern_b",components:4,type:"Uint16"}]),qDe=Wn([{name:"a_dash",components:4,type:"Uint16"}]);class uI{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(x,j,A,L){this.ids.push(zK(x)),this.positions.push(j,A,L)}eachPosition(x,j){const A=zK(x);let L=0,O=this.ids.length-1;for(;L>1;this.ids[$]>=A?O=$:L=$+1}for(;this.ids[L]===A;)j(this.positions[3*L],this.positions[3*L+1],this.positions[3*L+2]),L++}static serialize(x,j){const A=new Float64Array(x.ids),L=new Uint32Array(x.positions);return hI(A,L,0,A.length-1),j&&(j.add(A.buffer),j.add(L.buffer)),{ids:A,positions:L}}static deserialize(x){const j=new uI;let A;j.ids=x.ids,j.positions=x.positions;for(const L of j.ids)L!==A&&j.uniqueIds.push(L),A=L;return j.indexed=!0,j}}function zK(k){const x=+k;return Number.isSafeInteger(x)?x:mc(String(k))}function hI(k,x,j,A){for(;j>1];let O=j-1,$=A+1;for(;;){do O++;while(k[O]L);if(O>=$)break;z1(k,O,$),z1(x,3*O,3*$),z1(x,3*O+1,3*$+1),z1(x,3*O+2,3*$+2)}$-j`u_${O}`),this.type=A,this.context=L}setUniform(x,j,A,L,O){const $=L.constantOr(this.value);j.set(x,O,$ instanceof Js?$.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):$)}getBinding(x,j){return this.type==="color"?new HDe(x):new Hm(x)}}class we{constructor(x,j){this.uniformNames=j.map(A=>`u_${A}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(x,j){this.pixelRatio=x.pixelRatio||1,this.pattern=x.tl.concat(x.br),this.patternTransition=j?j.tl.concat(j.br):this.pattern}setUniform(x,j,A,L,O){let $=null;O!=="u_pattern"&&O!=="u_dash"||($=this.pattern),O==="u_pattern_b"&&($=this.patternTransition),O==="u_pixel_ratio"&&($=this.pixelRatio),$&&j.set(x,O,$)}getBinding(x,j){return j==="u_pattern"||j==="u_pattern_b"||j==="u_dash"?new VDe(x):new Hm(x)}}class Te{constructor(x,j,A,L){this.expression=x,this.type=A,this.maxValue=0,this.paintVertexAttributes=j.map(O=>({name:`a_${O}`,type:"Float32",components:A==="color"?2:1,offset:0})),this.paintVertexArray=new L}populatePaintArray(x,j,A,L,O,$,Y,X){const le=this.paintVertexArray.length,xe=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Vi(0,{brightness:$,worldview:X}),j,{},O,L,Y):this.expression.kind==="constant"&&this.expression.value,je=se(this.lutExpression,j,{},L,O,$,Y,X);this.paintVertexArray.resize(x),this._setPaintValue(le,x,xe,je?null:this.context.lut)}updatePaintArray(x,j,A,L,O,$,Y,X){const le=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:Y,worldview:X},A,L,void 0,O):this.expression.kind==="constant"&&this.expression.value,xe=se(this.lutExpression,A,L,O,void 0,Y,void 0,X);this._setPaintValue(x,j,le,xe?null:this.context.lut)}_setPaintValue(x,j,A,L){if(this.type==="color"){const O=Q(A.toPremultipliedRenderColor(L));for(let $=x;$`u_${Y}_t`),this.type=A,this.useIntegerZoom=L,this.context=O,this.maxValue=0,this.paintVertexAttributes=j.map(Y=>({name:`a_${Y}`,type:"Float32",components:A==="color"?4:2,offset:0})),this.paintVertexArray=new $}populatePaintArray(x,j,A,L,O,$,Y,X){const le=this.expression.evaluate(new Vi(this.context.zoom,{brightness:$,worldview:X}),j,{},O,L,Y),xe=this.expression.evaluate(new Vi(this.context.zoom+1,{brightness:$,worldview:X}),j,{},O,L,Y),je=se(this.lutExpression,j,{},L,O,$,Y,X),Ce=this.paintVertexArray.length;this.paintVertexArray.resize(x),this._setPaintValue(Ce,x,le,xe,je?null:this.context.lut)}updatePaintArray(x,j,A,L,O,$,Y,X){const le=this.expression.evaluate({zoom:this.context.zoom,brightness:Y,worldview:X},A,L,void 0,O),xe=this.expression.evaluate({zoom:this.context.zoom+1,brightness:Y,worldview:X},A,L,void 0,O),je=se(this.lutExpression,A,L,O,void 0,Y,void 0,X);this._setPaintValue(x,j,le,xe,je?null:this.context.lut)}_setPaintValue(x,j,A,L,O){if(this.type==="color"){const $=Q(A.toPremultipliedRenderColor(O)),Y=Q(L.toPremultipliedRenderColor(O));for(let X=x;X!0){this.binders={},this._buffers=[],this.context=j;const L=[],O=x;for(const $ in x.paint._values){const Y=O.paint.get($);if($.endsWith("-use-theme")||!A($)||!(Y instanceof lk&&vl(Y.property.specification)))continue;const X=ct($,x.type),le=Y.value,xe=Y.property.specification.type,je=!!Y.property.useIntegerZoom,Ce=$==="line-dasharray"||$.endsWith("pattern"),Ie=O.paint.get(`${$}-use-theme`),Fe=$==="line-dasharray"&&O.layout.get("line-cap").value.kind!=="constant"||Ie&&Ie.value.kind!=="constant";if(le.kind!=="constant"||Fe)if(le.kind==="source"||Fe||Ce){const Ke=Ut($,xe,"source");this.binders[$]=Ce?new Qe(le,X,xe,Ke,x.id):new Te(le,X,xe,Ke),L.push(`/a_${$}`)}else{const Ke=Ut($,xe,"composite");this.binders[$]=new De(le,X,xe,je,j,Ke),L.push(`/z_${$}`)}else this.binders[$]=Ce?new we(le.value,X):new ue(le.value,X,xe,j),L.push(`/u_${$}`);Ie&&(this.binders[$].lutExpression=Ie.value)}this.cacheKey=L.sort().join("")}getMaxValue(x){const j=this.binders[x];return j instanceof Te||j instanceof De?j.maxValue:0}populatePaintArrays(x,j,A,L,O,$,Y,X){for(const le in this.binders){const xe=this.binders[le];xe.context=this.context,(xe instanceof Te||xe instanceof De||xe instanceof Qe)&&xe.populatePaintArray(x,j,A,L,O,$,Y,X)}}setConstantPatternPositions(x,j){for(const A in this.binders){const L=this.binders[A];L instanceof we&&L.setConstantPatternPositions(x,j)}}getPatternTransitionVertexBuffer(x){const j=this.binders[x];return j instanceof Qe?j.paintTransitionVertexBuffer:null}updatePaintArrays(x,j,A,L,O,$,Y,X,le,xe){let je=!1;const Ce=Object.keys(x),Ie=Ce.length!==0&&!X,Fe=Ie?Ce:j.uniqueIds;this.context.lut=O.lut;for(const Ke in this.binders){const et=this.binders[Ke];if(et.context=this.context,(et instanceof Te||et instanceof De||et instanceof Qe)&&et.expression&&et.expression.kind&&et.expression.kind!=="constant"&&(et.expression.isStateDependent===!0||et.expression.isLightConstant===!1)){const at=O.paint.get(Ke);et.expression=at.value;for(const vt of Fe){const pt=x[vt.toString()];j.eachPosition(vt,(At,Rt,Bt)=>{const Ns=L.feature(At);et.updatePaintArray(Rt,Bt,Ns,pt,$,Y,le,xe)})}if(!Ie)for(const vt of A.uniqueIds){const pt=x[vt.toString()];A.eachPosition(vt,(At,Rt,Bt)=>{const Ns=L.feature(At);et.updatePaintArray(Rt,Bt,Ns,pt,$,Y,le,xe)})}je=!0}}return je}defines(){const x=[];for(const j in this.binders){const A=this.binders[j];(A instanceof ue||A instanceof we)&&x.push(...A.uniformNames.map(L=>`#define HAS_UNIFORM_${L}`))}return x}getPaintVertexBuffers(){return this._buffers}getUniforms(x){const j=[];for(const A in this.binders){const L=this.binders[A];if(L instanceof ue||L instanceof we||L instanceof De)for(const O of L.uniformNames)j.push({name:O,property:A,binding:L.getBinding(x,O)})}return j}setUniforms(x,j,A,L,O){for(const{name:$,property:Y,binding:X}of A)this.binders[Y].setUniform(x,X,O,L.get(Y),$)}updatePaintBuffers(){this._buffers=[];for(const x in this.binders){const j=this.binders[x];(j instanceof Te||j instanceof De||j instanceof Qe)&&j.paintVertexBuffer&&this._buffers.push(j.paintVertexBuffer),j instanceof Qe&&j.paintTransitionVertexBuffer&&this._buffers.push(j.paintTransitionVertexBuffer)}}upload(x){for(const j in this.binders){const A=this.binders[j];(A instanceof Te||A instanceof De||A instanceof Qe)&&A.upload(x)}this.updatePaintBuffers()}destroy(){for(const x in this.binders){const j=this.binders[x];(j instanceof Te||j instanceof De||j instanceof Qe)&&j.destroy()}}}class tt{constructor(x,j,A=()=>!0){this.programConfigurations={};for(const L of x)this.programConfigurations[L.id]=new Ye(L,j,A);this.needsUpload=!1,this._featureMap=new uI,this._featureMapWithoutIds=new uI,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(x,j,A,L,O,$,Y,X,le){for(const xe in this.programConfigurations)this.programConfigurations[xe].populatePaintArrays(x,j,L,O,$,Y,X,le);j.id!==void 0?this._featureMap.add(j.id,A,this._bufferOffset,x):(this._featureMapWithoutIds.add(this._idlessCounter,A,this._bufferOffset,x),this._idlessCounter+=1),this._bufferOffset=x,this.needsUpload=!0}updatePaintArrays(x,j,A,L,O,$,Y,X){for(const le of A)this.needsUpload=this.programConfigurations[le.id].updatePaintArrays(x,this._featureMap,this._featureMapWithoutIds,j,le,L,O,$,Y||0,X)||this.needsUpload}get(x){return this.programConfigurations[x]}upload(x){if(this.needsUpload){for(const j in this.programConfigurations)this.programConfigurations[j].upload(x);this.needsUpload=!1}}destroy(){for(const x in this.programConfigurations)this.programConfigurations[x].destroy()}}const ht={"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 ct(k,x){return ht[k]||[k.replace(`${x}-`,"").replace(/-/g,"_")]}const St={"line-pattern":{source:h2,composite:h2},"fill-pattern":{source:h2,composite:h2},"fill-extrusion-pattern":{source:h2,composite:h2},"line-dasharray":{source:cT,composite:cT}},kt={color:{source:a3,composite:dk},number:{source:Jl,composite:a3}};function Ut(k,x,j){const A=St[k];return A&&A[j]||kt[x][j]}kr(ue,"ConstantBinder"),kr(we,"PatternConstantBinder"),kr(Te,"SourceExpressionBinder"),kr(Qe,"PatternCompositeBinder"),kr(De,"CompositeExpressionBinder"),kr(Ye,"ProgramConfiguration",{omit:["_buffers"]}),kr(tt,"ProgramConfigurationSet");const Xt=fr/Math.PI/2,Et=64,Ts=[Et,32,16],ds=-Xt,Cs=Xt;function es(k,x,j,A=Xt){return j=Gs(j),[k*Math.sin(j)*A,-x*A,k*Math.cos(j)*A]}function is(k,x,j){return es(Math.cos(Gs(k)),Math.sin(Gs(k)),x,j)}const _s=63710088e-1,Xs=2*Math.PI*_s;class Ds{constructor(x,j){if(isNaN(x)||isNaN(j))throw new Error(`Invalid LngLat object: (${x}, ${j})`);if(this.lng=+x,this.lat=+j,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Ds(Lt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(x){const j=Math.PI/180,A=this.lat*j,L=x.lat*j,O=Math.sin(A)*Math.sin(L)+Math.cos(A)*Math.cos(L)*Math.cos((x.lng-this.lng)*j);return _s*Math.acos(Math.min(O,1))}toBounds(x=0){const j=360*x/40075017,A=j/Math.cos(Math.PI/180*this.lat);return new _n({lng:this.lng-A,lat:this.lat-j},{lng:this.lng+A,lat:this.lat+j})}toEcef(x){return is(this.lat,this.lng,Xt+x*Xt/_s)}static convert(x){if(x instanceof Ds)return x;if(Array.isArray(x)&&(x.length===2||x.length===3))return new Ds(Number(x[0]),Number(x[1]));if(!Array.isArray(x)&&typeof x=="object"&&x!==null)return new Ds(Number("lng"in x?x.lng:x.lon),Number(x.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 _n{constructor(x,j){x&&(j?this.setSouthWest(x).setNorthEast(j):Array.isArray(x)&&x.length===4?this.setSouthWest([x[0],x[1]]).setNorthEast([x[2],x[3]]):this.setSouthWest(x[0]).setNorthEast(x[1]))}setNorthEast(x){return this._ne=x instanceof Ds?new Ds(x.lng,x.lat):Ds.convert(x),this}setSouthWest(x){return this._sw=x instanceof Ds?new Ds(x.lng,x.lat):Ds.convert(x),this}extend(x){const j=this._sw,A=this._ne;let L,O;if(x instanceof Ds)L=x,O=x;else{if(!(x instanceof _n))return Array.isArray(x)?x.length===4||x.every(Array.isArray)?this.extend(_n.convert(x)):this.extend(Ds.convert(x)):typeof x=="object"&&x!==null&&x.hasOwnProperty("lat")&&(x.hasOwnProperty("lon")||x.hasOwnProperty("lng"))?this.extend(Ds.convert(x)):this;if(L=x._sw,O=x._ne,!L||!O)return this}return j||A?(j.lng=Math.min(L.lng,j.lng),j.lat=Math.min(L.lat,j.lat),A.lng=Math.max(O.lng,A.lng),A.lat=Math.max(O.lat,A.lat)):(this._sw=new Ds(L.lng,L.lat),this._ne=new Ds(O.lng,O.lat)),this}getCenter(){return new Ds((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 Ds(this.getWest(),this.getNorth())}getSouthEast(){return new Ds(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(x){const{lng:j,lat:A}=Ds.convert(x);let L=this._sw.lng<=j&&j<=this._ne.lng;return this._sw.lng>this._ne.lng&&(L=this._sw.lng>=j&&j>=this._ne.lng),this._sw.lat<=A&&A<=this._ne.lat&&L}static convert(x){if(x)return x instanceof _n?x:new _n(x)}}function pn(k){return Xs*Math.cos(k*Math.PI/180)}function Un(k){return(180+k)/360}function Xn(k){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+k*Math.PI/360)))/360}function nn(k,x){return k/pn(x)}function Bs(k){return 360*k-180}function yn(k){return 360/Math.PI*Math.atan(Math.exp((180-360*k)*Math.PI/180))-90}function jn(k,x){return k*pn(yn(x))}const In=85.051129;function Sr(k){return Math.cos(Gs(gt(k,-85.051129,In)))}function xr(k,x){const j=gt(x,0,25.5),A=Math.pow(2,j);return Sr(k)*Xs/(512*A)}function gr(k){return 1/Math.cos(k*Math.PI/180)}function Kn(k,x=0){const j=Math.exp(Math.PI*(1-(k.y+x/fr)/(1<=X?(Ea(k,x,j,le,xe,O,je,Y,X),Ea(k,le,xe,A,L,je,$,Y,X)):k.push($)}function na(k,x,j){let A=k[0],L=A.x,O=A.y;x(A);const $=[A];for(let Y=1;Yk.x+1||Ak.y+1)&&aa("Geometry exceeds allowed extent, reduce your vector tile buffer size"),k}function ti(k,x,j){const A=k.loadGeometry(),L=k.extent,O=fr/L;if(x&&j&&j.projection.isReprojectedInTileSpace){const $=1<{const Ie=Bs((x.x+Ce.x/L)/$),Fe=yn((x.y+Ce.y/L)/$),Ke=xe.project(Ie,Fe);Ce.x=(Ke.x*Y-X)*L,Ce.y=(Ke.y*Y-le)*L};for(let Ce=0;Ce=L||Fe.y<0||Fe.y>=L||(je(Fe),Ie.push(Fe));A[Ce]=Ie}}for(const $ of A)for(const Y of $)io(Y,O);return A}function oo(k,x){return{type:k.type,id:k.id,properties:k.properties,geometry:x?ti(k):[]}}class Si{constructor(x,j,A,L,O){this.properties={},this.extent=A,this.type=0,this.id=void 0,this._pbf=x,this._geometry=-1,this._keys=L,this._values=O,x.readFields(ol,this,j)}loadGeometry(){const x=this._pbf;x.pos=this._geometry;const j=x.readVarint()+x.pos,A=[];let L,O=1,$=0,Y=0,X=0;for(;x.pos>3}if($--,O===1||O===2)Y+=x.readSVarint(),X+=x.readSVarint(),O===1&&(L&&A.push(L),L=[]),L&&L.push(new Ss(Y,X));else{if(O!==7)throw new Error(`unknown command ${O}`);L&&L.push(L[0].clone())}}return L&&A.push(L),A}bbox(){const x=this._pbf;x.pos=this._geometry;const j=x.readVarint()+x.pos;let A=1,L=0,O=0,$=0,Y=1/0,X=-1/0,le=1/0,xe=-1/0;for(;x.pos>3}if(L--,A===1||A===2)O+=x.readSVarint(),$+=x.readSVarint(),OX&&(X=O),$xe&&(xe=$);else if(A!==7)throw new Error(`unknown command ${A}`)}return[Y,le,X,xe]}toGeoJSON(x,j,A){const L=this.extent*Math.pow(2,A),O=this.extent*x,$=this.extent*j,Y=this.loadGeometry();function X(Ce){return[360*(Ce.x+O)/L-180,360/Math.PI*Math.atan(Math.exp((1-2*(Ce.y+$)/L)*Math.PI))-90]}function le(Ce){return Ce.map(X)}let xe;if(this.type===1){const Ce=[];for(const Fe of Y)Ce.push(Fe[0]);const Ie=le(Ce);xe=Ce.length===1?{type:"Point",coordinates:Ie[0]}:{type:"MultiPoint",coordinates:Ie}}else if(this.type===2){const Ce=Y.map(le);xe=Ce.length===1?{type:"LineString",coordinates:Ce[0]}:{type:"MultiLineString",coordinates:Ce}}else{if(this.type!==3)throw new Error("unknown feature type");{const Ce=function(Fe){const Ke=Fe.length;if(Ke<=1)return[Fe];const et=[];let at,vt;for(let pt=0;pt=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[x];const j=this._pbf.readVarint()+this._pbf.pos;return new Si(this._pbf,j,this.extent,this._keys,this._values)}}function $c(k,x,j){k===15?x.version=j.readVarint():k===1?x.name=j.readString():k===5?x.extent=j.readVarint():k===2?x._features.push(j.pos):k===3?x._keys.push(j.readString()):k===4&&x._values.push(function(A){let L=null;const O=A.readVarint()+A.pos;for(;A.pos>3;L=$===1?A.readString():$===2?A.readFloat():$===3?A.readDouble():$===4?A.readVarint64():$===5?A.readVarint():$===6?A.readSVarint():$===7?A.readBoolean():null}if(L==null)throw new Error("unknown feature value");return L}(j))}class bl{constructor(x,j){this.layers=x.readFields(Zi,{},j)}}function Zi(k,x,j){if(k===3){const A=new Yd(j,j.readVarint()+j.pos);A.length&&(x[A.name]=A)}}const Xi="3d_elevation_id",Uc="level";class uu{constructor(){this._valid=!1}reset(x){return this.feature=x,this._valid=!0,this._geometry=x.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(x,j){return this._valid&&x(j(this._geometry)),this}require(x,j,A){return this.get(x,!0,j,A)}optional(x,j,A){return this.get(x,!1,j,A)}success(){return this._valid}get(x,j,A,L){const O=this.feature.properties.hasOwnProperty(x)?+this.feature.properties[x]:void 0;return this._valid&&O!==void 0&&!Number.isNaN(O)?A(L?L(O):O):j&&(this._valid=!1),this}}class _l{constructor(x,j){this.featureFunc=x,this.vertexFunc=j}parseFeature(x,j,A){return this.featureFunc(x,j,A)}parseVertex(x,j,A){return this.vertexFunc(x,j,A)}}const Fi=new _l((k,x,j)=>k.reset(x).require(Xi,A=>{j.id=A}).optional("fixed_height_relative",A=>{j.constantHeight=A},wc.decodeRelativeHeight).geometry(A=>{j.bounds=A},qu).success(),(k,x,j)=>k.reset(x).require(Xi,A=>{j.id=A}).require("elevation_idx",A=>{j.idx=A}).require("extent",A=>{j.extent=A}).require("height_relative",A=>{j.height=A},wc.decodeRelativeHeight).geometry(A=>{j.position=A},wc.getPoint).success()),Rd=new _l((k,x,j)=>k.reset(x).require(Xi,A=>{j.id=A}).optional("fixed_height",A=>{j.constantHeight=A},wc.decodeMetricHeight).geometry(A=>{j.bounds=A},qu).success(),(k,x,j)=>k.reset(x).require(Xi,A=>{j.id=A}).require("elevation_idx",A=>{j.idx=A}).require("extent",A=>{j.extent=A}).require("height",A=>{j.height=A},wc.decodeMetricHeight).geometry(A=>{j.position=A},wc.getPoint).success());class wc{static getPoint(x){return Us(x[0][0].x,x[0][0].y)}static decodeRelativeHeight(x){return 1e-4*x*5}static decodeMetricHeight(x){return 1e-4*x}static getVersionSchema(x){return x?x==="1.0.1"?Rd:void 0:Fi}static parse(x){const j=[],A=[],L=x.length,O=new uu;for(let $=0;$=0);if(O===0)return 0;O!==x.length&&(j=!1)}return j?2:1}function Gm(k,x){for(const j of k.projections){const A=km(x,k.points[0],j.axis);if(j.projection[1]A[1])return 0}return 1}function bf(k,x){let j=0;const A=[0,0,0,0];for(let L=0;L=0&&j++;return j}class $v{constructor(x,j){this.points=x||new Array(8).fill([0,0,0]),this.planes=j||new Array(6).fill([0,0,0,0]),this.bounds=Kl.fromPoints(this.points),this.projections=[],this.frustumEdges=[qe([],this.points[2],this.points[3]),qe([],this.points[0],this.points[3]),qe([],this.points[4],this.points[0]),qe([],this.points[5],this.points[1]),qe([],this.points[6],this.points[2]),qe([],this.points[7],this.points[3])];for(const A of this.frustumEdges){const L=[0,-A[2],A[1]],O=[A[2],0,-A[0]];this.projections.push({axis:L,projection:km(this.points,this.points[0],L)}),this.projections.push({axis:O,projection:km(this.points,this.points[0],O)})}}static fromInvProjectionMatrix(x,j,A,L){const O=Math.pow(2,A),$=[[-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(le=>{const xe=Je([],le,x),je=1/xe[3]/j*O;return(Ce=xe)[0]=(Ie=xe)[0]*(Fe=[je,je,L?1/xe[3]:je,je])[0],Ce[1]=Ie[1]*Fe[1],Ce[2]=Ie[2]*Fe[2],Ce[3]=Ie[3]*Fe[3],Ce;var Ce,Ie,Fe}),Y=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(le=>{const xe=Ne([],Oe([],qe([],$[le[0]],$[le[1]]),qe([],$[le[2]],$[le[1]]))),je=-Pe(xe,$[le[1]]);return xe.concat(je)}),X=[];for(let le=0;le<$.length;le++)X.push([$[le][0],$[le][1],$[le][2]]);return new $v(X,Y)}intersectsPrecise(x,j,A){for(let L=0;Lle[1]||le[0]>X[1])return 0}return 1}containsPoint(x){for(const j of this.planes){const A=j[3];if(Pe([j[0],j[1],j[2]],x)+A<0)return!1}return!0}}class Kl{static fromPoints(x){const j=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0];for(const L of x)J(j,j,L),te(A,A,L);return new Kl(j,A)}static fromTileIdAndHeight(x,j,A){const L=1<x.max[j]||x.min[j]>this.max[j])return!1;return!0}intersectsAabbXY(x){return!(this.min[0]>x.max[0]||x.min[0]>this.max[0]||this.min[1]>x.max[1]||x.min[1]>this.max[1])}encapsulate(x){for(let j=0;j<3;j++)this.min[j]=Math.min(this.min[j],x.min[j]),this.max[j]=Math.max(this.max[j],x.max[j])}encapsulatePoint(x){for(let j=0;j<3;j++)this.min[j]=Math.min(this.min[j],x[j]),this.max[j]=Math.max(this.max[j],x[j])}closestPoint(x){return[Math.max(Math.min(this.max[0],x[0]),this.min[0]),Math.max(Math.min(this.max[1],x[1]),this.min[1]),Math.max(Math.min(this.max[2],x[2]),this.min[2])]}}kr(Kl,"Aabb");class B1{constructor(x,j){this.feature=x,this.metersToTile=j,this.index=0}get(){const x=this.feature.vertices[this.index],j=this.feature.vertexProps[this.index].dir,A=j[1],L=-j[0],O=(x.extent+1)*this.metersToTile;return[new Ss(Math.trunc(x.position[0]+A*O),Math.trunc(x.position[1]+L*O)),new Ss(Math.trunc(x.position[0]-A*O),Math.trunc(x.position[1]-L*O))]}next(){this.index++}valid(){return this.index{return Y.a0?ce(X,X,1/le):Z(X,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(x){if(this.edges.length===0)return;let j=0,A=Number.POSITIVE_INFINITY,L=0;const[O,$,Y,X,le,xe,je]=this._tmpVec2;Es(je,x.x,x.y);const Ce=new Dh(je,null);for(let Ie=0;Ie0?cn(X,Y)/At:0,Bt=gt(Rt,0,1),Ns=Math.abs((Rt-Bt)*this.edgeProps[Ie].len);Sn(le,je,et),Es(xe,Ke[1],-Ke[0]);const us=Ns+Math.abs(cn(le,xe));us=0;--$){const Y=this.edges[$].a,X=this.edges[$].b,{position:le,height:xe,extent:je}=this.vertices[Y],{position:Ce,height:Ie,extent:Fe}=this.vertices[X],Ke=this.vertexProps[Y].dir,et=this.vertexProps[X].dir;if(Z(j,le[0]/x,le[1]/x,xe),Z(A,Ce[0]/x,Ce[1]/x,Ie),Z(L,Ke[1],-Ke[0],0),ce(L,L,je),Z(O,et[1],-et[0],0),ce(O,O,Fe),this.distSqLines(K(j[0]+.5*L[0],j[1]+.5*L[1],j[2]+.5*L[2]),K(A[0]-.5*O[0],A[1]-.5*O[1],A[2]-.5*O[2]),K(j[0]-.5*L[0],j[1]-.5*L[1],j[2]-.5*L[2]),K(A[0]+.5*O[0],A[1]+.5*O[1],A[2]+.5*O[2]))<=.0025000000000000005)continue;const at=this.vertices.length,vt=kn(wt(),le,Ce);this.vertices.push({position:bn(vt,vt,.5),height:.5*(xe+Ie),extent:.5*(je+Fe)});const pt=kn(wt(),Ke,et);this.vertexProps.push({dir:Fs(pt,pt)}),this.edges.splice($,1),this.edgeProps.splice($,1),this.edges.push({a:Y,b:at}),this.edges.push({a:at,b:X});const At=Sn(wt(),this.vertices[at].position,le),Rt=cr(At),Bt={vec:At,dir:bn(wt(),At,1/Rt),len:Rt};this.edgeProps.push(Bt),this.edgeProps.push(Bt)}}distSqLines(x,j,A,L){const O=re(G(),j,x),$=re(G(),L,A),Y=re(G(),x,A),X=Pe(O,O),le=Pe(O,$),xe=Pe(O,Y),je=Pe($,$),Ce=Pe($,Y),Ie=X*je-le*le;if(Ie===0)return he(ke(O,A,L,Pe(Y,$)/Pe($,$)),x);const Fe=(X*Ce-le*xe)/Ie;return he(ke(O,x,j,(le*Ce-xe*je)/Ie),ke($,A,L,Fe))}}class Xc{static parseFrom(x,j){const A=wc.parse(x);if(!A)return[];let{vertices:L,features:O}=A;const $=1/Kn(j);O.sort((xe,je)=>xe.id-je.id),L.sort((xe,je)=>xe.id-je.id||xe.idx-je.idx),L=L.filter((xe,je,Ce)=>je===Ce.findIndex(Ie=>Ie.id===xe.id&&Ie.idx===xe.idx));const Y=new Array;let X=0;const le=L.length;for(const xe of O){if(xe.constantHeight){Y.push(new $1(xe.id,xe.bounds,xe.constantHeight));continue}for(;X!==le&&L[X].idL.id===A)}}class cd{constructor(x,j){this.zScale=1,this.xOffset=0,this.yOffset=0,x.equals(j)||(this.zScale=Math.pow(2,j.z-x.z),this.xOffset=(x.x*this.zScale-j.x)*fr,this.yOffset=(x.y*this.zScale-j.y)*fr)}constantElevation(x,j){if(x.constantHeight!=null)return this.computeBiasedHeight(x.constantHeight,j)}pointElevation(x,j,A){const L=this.constantElevation(j,A);return L??(x.x=x.x*this.zScale+this.xOffset,x.y=x.y*this.zScale+this.yOffset,this.computeBiasedHeight(j.pointElevation(x),A))}computeBiasedHeight(x,j){return j<=0?x:x+j*ft(0,j,x>=0?x:Math.abs(.5*x))}}kr($1,"ElevationFeature");class lc{constructor(x){this.zoom=x.zoom,this.overscaling=x.overscaling,this.layers=x.layers,this.layerIds=this.layers.map(j=>j.fqid),this.index=x.index,this.hasPattern=!1,this.projection=x.projection,this.layoutVertexArray=new ao,this.indexArray=new Qu,this.segments=new Bc,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Jl),this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,j){}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,j,A,L){const O=this.layers[0],$=[];let Y=null;O.type==="circle"&&(Y=O.layout.get("circle-sort-key"));for(const{feature:le,id:xe,index:je,sourceLayerIndex:Ce}of x){const Ie=this.layers[0]._featureFilter.needGeometry,Fe=oo(le,Ie);if(!this.layers[0]._featureFilter.filter(new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),Fe,A))continue;const Ke=Y?Y.evaluate(Fe,{},A):void 0,et={id:xe,properties:le.properties,type:le.type,sourceLayerIndex:Ce,index:je,geometry:Ie?Fe.geometry:ti(le,A,L),patterns:{},sortKey:Ke};$.push(et)}Y&&$.sort((le,xe)=>le.sortKey-xe.sortKey);let X=null;L.projection.name==="globe"&&(this.globeExtVertexArray=new Rz,X=L.projection);for(const le of $){const{geometry:xe,index:je,sourceLayerIndex:Ce}=le,Ie=x[je].feature;this.addFeature(le,xe,je,j.availableImages,A,X,j.brightness,j.elevationFeatures),j.featureIndex.insert(Ie,xe,je,Ce,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(x,j,A,L,O,$,Y){this.programConfigurations.updatePaintArrays(x,j,O,A,L,$,Y,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,Tie.members),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=x.createVertexBuffer(this.globeExtVertexArray,BDe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=x.createVertexBuffer(this.elevatedLayoutVertexArray,zDe.members))),this.programConfigurations.upload(x),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(x,j,A,L,O,$,Y,X){let le;this.elevationMode!=="none"&&(le=Xc.getElevationFeature(x,X));for(const xe of j)for(const je of xe){const Ce=je.x,Ie=je.y;if(Ce<0||Ce>=fr||Ie<0||Ie>=fr)continue;if($){const et=$.projectTilePoint(Ce,Ie,O),at=$.upVector(O,Ce,Ie);this.addGlobeExtVertex(et,at),this.addGlobeExtVertex(et,at),this.addGlobeExtVertex(et,at),this.addGlobeExtVertex(et,at)}const Fe=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,x.sortKey),Ke=Fe.vertexLength;if(this.addCircleVertex(Ce,Ie,-1,-1),this.addCircleVertex(Ce,Ie,1,-1),this.addCircleVertex(Ce,Ie,1,1),this.addCircleVertex(Ce,Ie,-1,1),this.elevationMode!=="none"){const et=le?le.pointElevation(new Ss(Ce,Ie)):0;this.hasElevation=this.hasElevation||et!==0;for(let at=0;at<4;at++)this.elevatedLayoutVertexArray.emplaceBack(et)}this.indexArray.emplaceBack(Ke,Ke+1,Ke+2),this.indexArray.emplaceBack(Ke,Ke+2,Ke+3),Fe.vertexLength+=4,Fe.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,x,A,{},L,O,Y,void 0,this.worldview)}addCircleVertex(x,j,A,L){this.layoutVertexArray.emplaceBack(2*x+(A+1)/2,2*j+(L+1)/2)}addGlobeExtVertex(x,j){this.globeExtVertexArray.emplaceBack(x.x,x.y,x.z,j[0]*16384,j[1]*16384,j[2]*16384)}}function vh(k,x){for(let j=0;j1){if(u5(k,x))return!0;for(let A=0;A1?j:j.sub(x)._mult(L)._add(x))}function uT(k,x){let j,A,L,O=!1;for(let $=0;$x.y!=L.y>x.y&&x.x<(L.x-A.x)*(x.y-A.y)/(L.y-A.y)+A.x&&(O=!O)}return O}function Y0(k,x){let j=!1;for(let A=0,L=k.length-1;Ax.y!=$.y>x.y&&x.x<($.x-O.x)*(x.y-O.y)/($.y-O.y)+O.x&&(j=!j)}return j}function h5(k,x,j,A,L){for(const $ of k)if(x<=$.x&&j<=$.y&&A>=$.x&&L>=$.y)return!0;const O=[new Ss(x,j),new Ss(x,L),new Ss(A,L),new Ss(A,j)];if(k.length>2){for(const $ of O)if(Y0(k,$))return!0}for(let $=0;$L.x&&x.x>L.x||k.yL.y&&x.y>L.y)return!1;const O=Kr(k,x,j[0]);return O!==Kr(k,x,j[1])||O!==Kr(k,x,j[2])||O!==Kr(k,x,j[3])}function p5(k,x,j,A,L,O){let $=x.y-k.y,Y=k.x-x.x;if(O=O||0){const X=$*$+Y*Y;if(X===0)return!0;const le=Math.sqrt(X);$/=le,Y/=le}return!((j.x-k.x)*$+(j.y-k.y)*Y-O<0||(A.x-k.x)*$+(A.y-k.y)*Y-O<0||(L.x-k.x)*$+(L.y-k.y)*Y-O<0)}function Hz(k,x,j,A,L,O,$){return!(p5(k,x,A,L,O,$)||p5(x,j,A,L,O,$)||p5(j,k,A,L,O,$)||p5(A,L,k,x,j,$)||p5(L,O,k,x,j,$)||p5(O,A,k,x,j,$))}function hT(k,x,j){const A=x.paint.get(k).value;return A.kind==="constant"?A.value:j.programConfigurations.get(x.id).getMaxValue(k)}function Mie(k){return Math.sqrt(k[0]*k[0]+k[1]*k[1])}function Oot(k,x,j,A,L){if(!x[0]&&!x[1])return k;const O=Ss.convert(x)._mult(L);j==="viewport"&&O._rotate(-A);const $=[];for(let Y=0;Y>j&&x.y===this.y>>j}url(x,j){const A=function(O,$,Y){const X=2**Y,le=2*Math.PI*6378137,xe=le*(O/X-.5),je=le*(.5-($+1)/X);return`${xe},${je},${xe+le/X},${je+le/X}`}(this.x,this.y,this.z),L=function(O,$,Y){let X,le="";for(let xe=O;xe>0;xe--)X=1<this.canonical.z?new Yy(x,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Yy(x,this.wrap,x,this.canonical.x>>j,this.canonical.y>>j)}calculateScaledKey(x,j=!0){if(this.overscaledZ===x&&j)return this.key;if(x>this.canonical.z)return Gz(this.wrap*+j,x,this.canonical.z,this.canonical.x,this.canonical.y);{const A=this.canonical.z-x;return Gz(this.wrap*+j,x,x,this.canonical.x>>A,this.canonical.y>>A)}}isChildOf(x){if(x.wrap!==this.wrap)return!1;const j=this.canonical.z-x.canonical.z;return x.overscaledZ===0||x.overscaledZ>j&&x.canonical.y===this.canonical.y>>j}children(x){if(this.overscaledZ>=x)return[new Yy(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const j=this.canonical.z+1,A=2*this.canonical.x,L=2*this.canonical.y;return[new Yy(j,this.wrap,j,A,L),new Yy(j,this.wrap,j,A+1,L),new Yy(j,this.wrap,j,A,L+1),new Yy(j,this.wrap,j,A+1,L+1)]}isLessThan(x){return this.wrapx.wrap)&&(this.overscaledZx.overscaledZ)&&(this.canonical.xx.canonical.x)&&this.canonical.y{let x=k.canonical.x-1,j=k.wrap;return x<0&&(x=(1<{let x=k.canonical.x+1,j=k.wrap;return x===1<new Yy(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,(k.canonical.y===0?1<new Yy(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,k.canonical.y===(1<1?null:function(A,L,O,$){const Y=Math.sin(O);return A*(Math.sin((1-$)*O)/Y)+L*(Math.sin($*O)/Y)}(k.a[x],k.b[x],k.angle,gt(j,0,1))+k.center[x]}function f5(k){if(k.z<=1)return bcs[k.z+2*k.y+k.x];const x=WDe(Iie(k));return Kl.fromPoints(x)}function c3(k,x,j){return ce(k,k,1-j),ve(k,k,x,j)}function Hot(k,x){const j=d3(x.zoom);if(j===0)return f5(k);const A=Iie(k),L=WDe(A),O=Un(A.getWest())*x.worldSize,$=Un(A.getEast())*x.worldSize,Y=Xn(A.getNorth())*x.worldSize,X=Xn(A.getSouth())*x.worldSize,le=[O,Y,0],xe=[$,Y,0],je=[O,X,0],Ce=[$,X,0],Ie=y([],x.globeMatrix);return Ve(le,le,Ie),Ve(xe,xe,Ie),Ve(je,je,Ie),Ve(Ce,Ce,Ie),L[0]=c3(L[0],je,j),L[1]=c3(L[1],Ce,j),L[2]=c3(L[2],xe,j),L[3]=c3(L[3],le,j),Kl.fromPoints(L)}function Got(k,x,j){for(const A of k)Ve(A,A,x),ce(A,A,j)}function Wot(k,x,j,A){const L=x/k.worldSize,O=k.globeMatrix;if(j.z<=1){const ws=f5(j).getCorners();return Got(ws,O,L),Kl.fromPoints(ws)}const $=Iie(j,A),Y=WDe($,Xt+Lie(k._tileCoverLift));Got(Y,O,L);const X=Number.MAX_VALUE,le=[-X,-X,-X],xe=[X,X,X];if($.contains(k.center)){for(const vs of Y)J(xe,xe,vs),te(le,le,vs);le[2]=0;const ws=k.point,ys=[ws.x*L,ws.y*L,0];return J(xe,xe,ys),te(le,le,ys),new Kl(xe,le)}if(k._tileCoverLift>0){for(const ws of Y)J(xe,xe,ws),te(le,le,ws);return new Kl(xe,le)}const je=[O[12]*L,O[13]*L,O[14]*L],Ce=$.getCenter(),Ie=gt(k.center.lat,-85.051129,In),Fe=gt(Ce.lat,-85.051129,In),Ke=Un(k.center.lng),et=Xn(Ie);let at=Ke-Un(Ce.lng);const vt=et-Xn(Fe);at>.5?at-=1:at<-.5&&(at+=1);let pt=0;Math.abs(at)>Math.abs(vt)?pt=at>=0?1:3:(pt=vt>=0?0:2,ve(je,je,[O[4]*L,O[5]*L,O[6]*L],-Math.sin(Gs(vt>=0?$.getSouth():$.getNorth()))*Xt));const At=Y[pt],Rt=Y[(pt+1)%4],Bt=new _cs(At,Rt,je),Ns=[GDe(Bt,0)||At[0],GDe(Bt,1)||At[1],GDe(Bt,2)||At[2]],us=d3(k.zoom);if(us>0){const ws=function({x:vs,y:vn,z:Nn},Rn,$n,Fn,sr){const gn=1/(1<.5?ra=-1:Er<-.5&&(ra=1),Bn=((Bn+ra)*Rn-(Fn*=Rn))*$n+Fn,Vn=((Vn+ra)*Rn-Fn)*$n+Fn,nr=(nr*Rn-(sr*=Rn))*$n+sr,yr=(yr*Rn-sr)*$n+sr,[[Bn,yr,0],[Vn,yr,0],[Vn,nr,0],[Bn,nr,0]]}(j,x,k._pixelsPerMercatorPixel,Ke,et);for(let vs=0;vsMath.PI/2*1.01}const Qot=Gs(85),wcs=Math.cos(Qot),jcs=Math.sin(Qot),Ncs=f(),Jot=k=>{const x=[];return k.paint.get("circle-pitch-alignment")==="map"&&x.push("PITCH_WITH_MAP"),k.paint.get("circle-pitch-scale")==="map"&&x.push("SCALE_WITH_MAP"),x};function elt(k,x,j,A,L,O,$,Y,X){if(O&&k.queryGeometry.isAboveHorizon)return!1;O&&(X*=k.pixelToTileUnitsFactor);const le=k.tileID.canonical,xe=j.projection.upVectorScale(le,j.center.lat,j.worldSize).metersToTile;for(const je of x)for(const Ce of je){const Ie=Ce.add(Y),Fe=L&&j.elevation?j.elevation.exaggeration()*L.getElevationAt(Ie.x,Ie.y,!0):0,Ke=j.projection.projectTilePoint(Ie.x,Ie.y,le);if(Fe>0){const pt=j.projection.upVector(le,Ie.x,Ie.y);Ke.x+=pt[0]*xe*Fe,Ke.y+=pt[1]*xe*Fe,Ke.z+=pt[2]*xe*Fe}const et=O?Ie:kcs(Ke.x,Ke.y,Ke.z,A),at=O?k.tilespaceRays.map(pt=>Ccs(pt,Fe)):k.queryGeometry.screenGeometry,vt=Je([],[Ke.x,Ke.y,Ke.z,1],A);if(!$&&O?X*=vt[3]/j.cameraToCenterDistance:$&&!O&&(X*=j.cameraToCenterDistance/vt[3]),O){const pt=yn((Ce.y/fr+le.y)/(1<k.width||L.height>k.height||j.x>k.width-L.width||j.y>k.height-L.height)throw new RangeError("out of range source coordinates for image copy");if(L.width>x.width||L.height>x.height||A.x>x.width-L.width||A.y>x.height-L.height)throw new RangeError("out of range destination coordinates for image copy");const X=k.data,le=x.data,xe=O===4&&Y;for(let je=0;je{x[k.evaluationKey]=X;const le=k.expression.evaluate(x),xe=le?le.toNonPremultipliedRenderColor(null):null;xe&&(L.data[$+Y+0]=Math.floor(255*xe.r),L.data[$+Y+1]=Math.floor(255*xe.g),L.data[$+Y+2]=Math.floor(255*xe.b),L.data[$+Y+3]=Math.floor(255*xe.a))};if(k.clips)for(let $=0,Y=0;$80*j){Y=k[0],X=k[1];let xe=Y,je=X;for(let Ce=j;Cexe&&(xe=Ie),Fe>je&&(je=Fe)}le=Math.max(xe-Y,je-X),le=le!==0?32767/le:0}return VK(O,$,j,Y,X,le,0),$}function dlt(k,x,j,A,L){let O;if(L===function($,Y,X,le){let xe=0;for(let je=Y,Ce=X-le;je0)for(let $=x;$=x;$-=A)O=plt($/A|0,k[$],k[$+1],O);return O&&Kz(O,O.next)&&(WK(O),O=O.next),O}function xI(k,x){if(!k)return k;x||(x=k);let j,A=k;do if(j=!1,A.steiner||!Kz(A,A.next)&&_f(A.prev,A,A.next)!==0)A=A.next;else{if(WK(A),A=x=A.prev,A===A.next)break;j=!0}while(j||A!==x);return x}function VK(k,x,j,A,L,O,$){if(!k)return;!$&&O&&function(X,le,xe,je){let Ce=X;do Ce.z===0&&(Ce.z=QDe(Ce.x,Ce.y,le,xe,je)),Ce.prevZ=Ce.prev,Ce.nextZ=Ce.next,Ce=Ce.next;while(Ce!==X);Ce.prevZ.nextZ=null,Ce.prevZ=null,function(Ie){let Fe,Ke=1;do{let et,at=Ie;Ie=null;let vt=null;for(Fe=0;at;){Fe++;let pt=at,At=0;for(let Bt=0;Bt0||Rt>0&&pt;)At!==0&&(Rt===0||!pt||at.z<=pt.z)?(et=at,at=at.nextZ,At--):(et=pt,pt=pt.nextZ,Rt--),vt?vt.nextZ=et:Ie=et,et.prevZ=vt,vt=et;at=pt}vt.nextZ=null,Ke*=2}while(Fe>1)}(Ce)}(k,A,L,O);let Y=k;for(;k.prev!==k.next;){const X=k.prev,le=k.next;if(O?Lcs(k,A,L,O):Pcs(k))x.push(X.i,k.i,le.i),WK(k),k=le.next,Y=le.next;else if((k=le)===Y){$?$===1?VK(k=Ics(xI(k),x),x,j,A,L,O,2):$===2&&Dcs(k,x,j,A,L,O):VK(xI(k),x,j,A,L,O,1);break}}}function Pcs(k){const x=k.prev,j=k,A=k.next;if(_f(x,j,A)>=0)return!1;const L=x.x,O=j.x,$=A.x,Y=x.y,X=j.y,le=A.y,xe=Math.min(L,O,$),je=Math.min(Y,X,le),Ce=Math.max(L,O,$),Ie=Math.max(Y,X,le);let Fe=A.next;for(;Fe!==x;){if(Fe.x>=xe&&Fe.x<=Ce&&Fe.y>=je&&Fe.y<=Ie&&HK(L,Y,O,X,$,le,Fe.x,Fe.y)&&_f(Fe.prev,Fe,Fe.next)>=0)return!1;Fe=Fe.next}return!0}function Lcs(k,x,j,A){const L=k.prev,O=k,$=k.next;if(_f(L,O,$)>=0)return!1;const Y=L.x,X=O.x,le=$.x,xe=L.y,je=O.y,Ce=$.y,Ie=Math.min(Y,X,le),Fe=Math.min(xe,je,Ce),Ke=Math.max(Y,X,le),et=Math.max(xe,je,Ce),at=QDe(Ie,Fe,x,j,A),vt=QDe(Ke,et,x,j,A);let pt=k.prevZ,At=k.nextZ;for(;pt&&pt.z>=at&&At&&At.z<=vt;){if(pt.x>=Ie&&pt.x<=Ke&&pt.y>=Fe&&pt.y<=et&&pt!==L&&pt!==$&&HK(Y,xe,X,je,le,Ce,pt.x,pt.y)&&_f(pt.prev,pt,pt.next)>=0||(pt=pt.prevZ,At.x>=Ie&&At.x<=Ke&&At.y>=Fe&&At.y<=et&&At!==L&&At!==$&&HK(Y,xe,X,je,le,Ce,At.x,At.y)&&_f(At.prev,At,At.next)>=0))return!1;At=At.nextZ}for(;pt&&pt.z>=at;){if(pt.x>=Ie&&pt.x<=Ke&&pt.y>=Fe&&pt.y<=et&&pt!==L&&pt!==$&&HK(Y,xe,X,je,le,Ce,pt.x,pt.y)&&_f(pt.prev,pt,pt.next)>=0)return!1;pt=pt.prevZ}for(;At&&At.z<=vt;){if(At.x>=Ie&&At.x<=Ke&&At.y>=Fe&&At.y<=et&&At!==L&&At!==$&&HK(Y,xe,X,je,le,Ce,At.x,At.y)&&_f(At.prev,At,At.next)>=0)return!1;At=At.nextZ}return!0}function Ics(k,x){let j=k;do{const A=j.prev,L=j.next.next;!Kz(A,L)&&hlt(A,j,j.next,L)&&GK(A,L)&&GK(L,A)&&(x.push(A.i,j.i,L.i),WK(j),WK(j.next),j=k=L),j=j.next}while(j!==k);return xI(j)}function Dcs(k,x,j,A,L,O){let $=k;do{let Y=$.next.next;for(;Y!==$.prev;){if($.i!==Y.i&&Bcs($,Y)){let X=mlt($,Y);return $=xI($,$.next),X=xI(X,X.next),VK($,x,j,A,L,O,0),void VK(X,x,j,A,L,O,0)}Y=Y.next}$=$.next}while($!==k)}function Rcs(k,x){let j=k.x-x.x;return j===0&&(j=k.y-x.y,j===0)&&(j=(k.next.y-k.y)/(k.next.x-k.x)-(x.next.y-x.y)/(x.next.x-x.x)),j}function Fcs(k,x){const j=function(L,O){let $=O;const Y=L.x,X=L.y;let le,xe=-1/0;if(Kz(L,$))return $;do{if(Kz(L,$.next))return $.next;if(X<=$.y&&X>=$.next.y&&$.next.y!==$.y){const Ke=$.x+(X-$.y)*($.next.x-$.x)/($.next.y-$.y);if(Ke<=Y&&Ke>xe&&(xe=Ke,le=$.x<$.next.x?$:$.next,Ke===Y))return le}$=$.next}while($!==O);if(!le)return null;const je=le,Ce=le.x,Ie=le.y;let Fe=1/0;$=le;do{if(Y>=$.x&&$.x>=Ce&&Y!==$.x&&ult(Xle.x||$.x===le.x&&Ocs(le,$)))&&(le=$,Fe=Ke)}$=$.next}while($!==je);return le}(k,x);if(!j)return x;const A=mlt(j,k);return xI(A,A.next),xI(j,j.next)}function Ocs(k,x){return _f(k.prev,k,x.prev)<0&&_f(x.next,k,k.next)<0}function QDe(k,x,j,A,L){return(k=1431655765&((k=858993459&((k=252645135&((k=16711935&((k=(k-j)*L|0)|k<<8))|k<<4))|k<<2))|k<<1))|(x=1431655765&((x=858993459&((x=252645135&((x=16711935&((x=(x-A)*L|0)|x<<8))|x<<4))|x<<2))|x<<1))<<1}function zcs(k){let x=k,j=k;do(x.x=(k-$)*(O-Y)&&(k-$)*(A-Y)>=(j-$)*(x-Y)&&(j-$)*(O-Y)>=(L-$)*(A-Y)}function HK(k,x,j,A,L,O,$,Y){return!(k===$&&x===Y)&&ult(k,x,j,A,L,O,$,Y)}function Bcs(k,x){return k.next.i!==x.i&&k.prev.i!==x.i&&!function(j,A){let L=j;do{if(L.i!==j.i&&L.next.i!==j.i&&L.i!==A.i&&L.next.i!==A.i&&hlt(L,L.next,j,A))return!0;L=L.next}while(L!==j);return!1}(k,x)&&(GK(k,x)&&GK(x,k)&&function(j,A){let L=j,O=!1;const $=(j.x+A.x)/2,Y=(j.y+A.y)/2;do L.y>Y!=L.next.y>Y&&L.next.y!==L.y&&$<(L.next.x-L.x)*(Y-L.y)/(L.next.y-L.y)+L.x&&(O=!O),L=L.next;while(L!==j);return O}(k,x)&&(_f(k.prev,k,x.prev)||_f(k,x.prev,x))||Kz(k,x)&&_f(k.prev,k,k.next)>0&&_f(x.prev,x,x.next)>0)}function _f(k,x,j){return(x.y-k.y)*(j.x-x.x)-(x.x-k.x)*(j.y-x.y)}function Kz(k,x){return k.x===x.x&&k.y===x.y}function hlt(k,x,j,A){const L=Fie(_f(k,x,j)),O=Fie(_f(k,x,A)),$=Fie(_f(j,A,k)),Y=Fie(_f(j,A,x));return L!==O&&$!==Y||!(L!==0||!Rie(k,j,x))||!(O!==0||!Rie(k,A,x))||!($!==0||!Rie(j,k,A))||!(Y!==0||!Rie(j,x,A))}function Rie(k,x,j){return x.x<=Math.max(k.x,j.x)&&x.x>=Math.min(k.x,j.x)&&x.y<=Math.max(k.y,j.y)&&x.y>=Math.min(k.y,j.y)}function Fie(k){return k>0?1:k<0?-1:0}function GK(k,x){return _f(k.prev,k,k.next)<0?_f(k,x,k.next)>=0&&_f(k,k.prev,x)>=0:_f(k,x,k.prev)<0||_f(k,k.next,x)<0}function mlt(k,x){const j=JDe(k.i,k.x,k.y),A=JDe(x.i,x.x,x.y),L=k.next,O=x.prev;return k.next=x,x.prev=k,j.next=L,L.prev=j,A.next=j,j.prev=A,O.next=A,A.prev=O,A}function plt(k,x,j,A){const L=JDe(k,x,j);return A?(L.next=A.next,L.prev=A,A.next.prev=L,A.next=L):(L.prev=L,L.next=L),L}function WK(k){k.next.prev=k.prev,k.prev.next=k.next,k.prevZ&&(k.prevZ.nextZ=k.nextZ),k.nextZ&&(k.nextZ.prevZ=k.prevZ)}function JDe(k,x,j){return{i:k,x,y:j,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function KK(k,x){const j=k.length;if(j<=1)return[k];const A=[];let L,O;for(let $=0;$1)for(let $=0;$=fr&&j>=fr}static evaluate(x){if(x.length===0)return new u3;let j=[];for(const X of x)j.push(...X.portals);if(j.length===0)return new u3;for(const X of j){const le=X.va,xe=X.vb;(u3.isOnBorder(le.x,xe.x)||u3.isOnBorder(le.y,xe.y))&&(X.type="border")}const A=j.filter(X=>X.type!=="unevaluated"),L=j.filter(X=>X.type==="unevaluated");if(L.length===0)return new u3;L.sort((X,le)=>X.hash===le.hash?X.isTunnel===le.isTunnel?0:X.isTunnel?-1:1:X.hashX.hashO!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new tt(j,{zoom:A,lut:L},O=>O!=="fill-bridge-guard-rail-color")}addVertices(x,j){const A=this.unevalVertices.length;for(let L=0;L=O.min.x&&je.x<=O.max.x&&je.y>=O.min.y&&je.y<=O.max.y||Ce.x>=O.min.x&&Ce.x<=O.max.x&&Ce.y>=O.min.y&&Ce.y<=O.max.y||m5(je,Ce,Y))||this.isOnBorder(je.x,Ce.x)||this.isOnBorder(je.y,Ce.y))continue;const Ie=U1.computeEdgeHash(this.unevalVertices[le],this.unevalVertices[xe]);let Fe,Ke=this.vertexHashLookup.get(U1.computePosHash(je));Ke!=null?Fe=Ke.next:(Ke=this.vertexHashLookup.get(U1.computePosHash(Ce)),Fe=Ke!=null?Ke.prev:Ie),this.unevalEdges.push({polygonIdx:x,a:le,b:xe,hash:Ie,portalHash:Fe,isTunnel:L,type:"unevaluated",featureInfo:$})}}addPortalCandidates(x,j,A,L,O){if(j.length!==0){this.vertexHashLookup.clear();for(const $ of j){if($.length===0)continue;const Y=$[0];let X=U1.computeEdgeHash(Y[Y.length-2],Y[Y.length-1]);for(let le=0;le({vertexOffset:0,primitiveOffset:this.indexArray.length}),A=Ce=>{Ce.primitiveLength=this.indexArray.length-Ce.primitiveOffset},L=new Ucs(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(x.portals,this.unevalEdges);const O=j(),$=j(),Y=j(),X=(Ce,Ie)=>{Ce.sort((Ke,et)=>Ke.type===Ie&&et.type!==Ie?-1:Ke.type!==Ie&&et.type===Ie?1:0);const Fe=Ce.findIndex(Ke=>Ke.type!==Ie);return Fe>=0?Fe:Ce.length};let le=0;this.unevalEdges.length>0&&(le=X(this.unevalEdges,"none"),this.constructBridgeStructures(L,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:le},this.tileToMeters)),A(Y);const xe=j(),je=j();if(this.unevalEdges.length>0){const Ce=this.unevalEdges.splice(le),Ie=X(Ce,"tunnel")+le;this.unevalEdges.push(...Ce),this.constructTunnelStructures(L,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:le},{min:le,max:Ie})}A(xe),L.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),A(je),L.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),A($),L.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),A(O),this.maskSegments=Bc.simpleSegment(0,je.primitiveOffset,0,je.primitiveLength),this.depthSegments=Bc.simpleSegment(0,$.primitiveOffset,0,$.primitiveLength),this.renderableBridgeSegments=Bc.simpleSegment(0,Y.primitiveOffset,0,Y.primitiveLength),this.renderableTunnelSegments=Bc.simpleSegment(0,xe.primitiveOffset,0,xe.primitiveLength),this.shadowCasterSegments=Bc.simpleSegment(0,O.primitiveOffset,0,O.primitiveLength)}update(x,j,A,L,O,$,Y,X){this.bridgeProgramConfigurations.updatePaintArrays(x,j,O,A,L,$,Y,X),this.tunnelProgramConfigurations.updatePaintArrays(x,j,O,A,L,$,Y,X)}upload(x){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=x.createVertexBuffer(this.vertexPositions,Tcs.members),this.vertexBufferNormal=x.createVertexBuffer(this.vertexNormals,Mcs.members),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(x),this.tunnelProgramConfigurations.upload(x))}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(x,j,A,L,O){const $=(Y,X)=>{for(let le=0;leZ($n,j[Fn].x,j[Fn].y,A[Fn]*X),je=G(),Ce=G(),Ie=G(),Fe=G(),Ke=G(),et=($n,Fn)=>{const sr=Y.get(U1.computePosHash(j[Fn])),gn=sr.from,Bn=sr.to;if(!gn||!Bn)return;xe(je,gn),xe(Ce,Fn),xe(Ie,Bn),Se(Fe),We(je,Ce)||(qe(Ke,Ce,je),Ne(Fe,Ke)),We(Ie,Ce)||(qe(Ke,Ie,Ce),oe(Fe,Fe,Ne(Ke,Ke)));const Vn=Ze(Fe);return Vn>0?ce($n,Fe,1/Vn):void 0};let at=Number.POSITIVE_INFINITY;this.sortSubarray(L,O.min,O.max,($n,Fn)=>$n.featureInfo.featureIndex-Fn.featureInfo.featureIndex);const vt=G(),pt=G(),At=G(),Rt=G(),Bt=G(),Ns=G(),us=G(),ws=G(),ys=G(),vs=[G(),G(),G(),G()],vn=[G(),G(),G(),G()],Nn=[{coord:new Ss(0,0),height:0},{coord:new Ss(0,0),height:0}],Rn=($n,Fn)=>$n>Fn;for(let $n=O.min;$nat.featureInfo.featureIndex-vt.featureInfo.featureIndex;this.sortSubarray(L,O.min,O.max,X),this.sortSubarray(L,$.min,$.max,X);const le=at=>Ne(at,at),xe=[{coord:new Ss(0,0),height:0},{coord:new Ss(0,0),height:0}],je=(at,vt)=>atY.hash===X.hash?X.polygonIdx-Y.polygonIdx:X.hash>Y.hash?1:-1);let A=0,L=0,O=0,$=j[A].polygonIdx;do L++,(L===j.length||j[A].hash!==j[L].hash)&&((L-A===1||j[L-1].polygonIdx!==$)&&(Ole.portalHashxe.hash?Y++:xe.hash>le.portalHash?X++:(le.type=xe.type,Y++)}}}isOnBorder(x,j){return x<=0&&j<=0||x>=fr&&j>=fr}addFeatureSection(x,j,A,L){return x!==j&&(j=x,A.push({featureIndex:x,vertexStart:L.getVertexCount()}),L.clearVertexLookup()),j}sortSubarray(x,j,A,L){const O=x.slice(j,A);O.sort(L),x.splice(j,O.length,...O)}static computeEdgeHash(x,j){return(x.y===j.y&&x.x>j.x||x.y>j.y)&&([x,j]=[j,x]),BigInt(U1.computePosHash(x))<<32n|BigInt(U1.computePosHash(j))}static computePosHash(x){return((65535&x.x)<<16|65535&x.y)>>>0}}function qcs(k,x){return k>x?1:k0))return j;j=j.left}}return null}contains(x){for(var j=this._root,A=this._compare;j;){var L=A(x,j.key);if(L===0)return!0;j=L<0?j.left:j.right}return!1}remove(x){var j=this.find(x);if(!j)return!1;if(this.splay(j),j.left)if(j.right){var A=this.minNode(j.right);A.parent!==j&&(this.replace(A,A.right),A.right=j.right,A.right.parent=A),this.replace(j,A),A.left=j.left,A.left.parent=A}else this.replace(j,j.left);else this.replace(j,j.right);return this._size--,!0}removeNode(x){if(!x)return!1;if(this.splay(x),x.left)if(x.right){var j=this.minNode(x.right);j.parent!==x&&(this.replace(j,j.right),j.right=x.right,j.right.parent=j),this.replace(x,j),j.left=x.left,j.left.parent=j}else this.replace(x,x.left);else this.replace(x,x.right);return this._size--,!0}erase(x){var j=this.find(x);if(j){this.splay(j);var A=j.left,L=j.right,O=null;A&&(A.parent=null,O=this.maxNode(A),this.splay(O),this._root=O),L&&(A?O.right=L:this._root=L,L.parent=O),this._size--}}pop(){var x=this._root,j=null;if(x){for(;x.left;)x=x.left;j={key:x.key,data:x.data},this.remove(x.key)}return j}next(x){var j=x;if(j)if(j.right)for(j=j.right;j&&j.left;)j=j.left;else for(j=x.parent;j&&j.right===x;)x=j,j=j.parent;return j}prev(x){var j=x;if(j)if(j.left)for(j=j.left;j&&j.right;)j=j.right;else for(j=x.parent;j&&j.left===x;)x=j,j=j.parent;return j}forEach(x){for(var j=this._root,A=[],L=!1,O=0;!L;)j?(A.push(j),j=j.left):A.length>0?(x(j=A.pop(),O++),j=j.right):L=!0;return this}range(x,j,A,L){const O=[],$=this._compare;let Y,X=this._root;for(;O.length!==0||X;)if(X)O.push(X),X=X.left;else{if(X=O.pop(),Y=$(X.key,j),Y>0)break;if($(X.key,x)>=0&&A.call(L,X))return this;X=X.right}return this}keys(){for(var x=this._root,j=[],A=[],L=!1;!L;)x?(j.push(x),x=x.left):j.length>0?(x=j.pop(),A.push(x.key),x=x.right):L=!0;return A}values(){for(var x=this._root,j=[],A=[],L=!1;!L;)x?(j.push(x),x=x.left):j.length>0?(x=j.pop(),A.push(x.data),x=x.right):L=!0;return A}at(x){for(var j=this._root,A=[],L=!1,O=0;!L;)if(j)A.push(j),j=j.left;else if(A.length>0){if(j=A.pop(),O===x)return j;O++,j=j.right}else L=!0;return null}load(x=[],j=[],A=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const L=x.length;return A&&rRe(x,j,0,L-1,this._compare),this._root=nRe(null,x,j,0,L),this._size=L,this}min(){var x=this.minNode(this._root);return x?x.key:null}max(){var x=this.maxNode(this._root);return x?x.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(x,j,A,L,O){return new sRe(A,O).load(x,j,L)}}function nRe(k,x,j,A,L){const O=L-A;if(O>0){const $=A+Math.floor(O/2),Y={key:x[$],data:j[$],parent:k};return Y.left=nRe(Y,x,j,A,$),Y.right=nRe(Y,x,j,$+1,L),Y}return null}function rRe(k,x,j,A,L){if(j>=A)return;const O=k[j+A>>1];let $=j-1,Y=A+1;for(;;){do $++;while(L(k[$],O)<0);do Y--;while(L(k[Y],O)>0);if($>=Y)break;let X=k[$];k[$]=k[Y],k[Y]=X,X=x[$],x[$]=x[Y],x[Y]=X}rRe(k,x,j,Y,L),rRe(k,x,Y+1,A,L)}const xlt=11102230246251565e-32,qv=134217729,Vcs=(3+8*xlt)*xlt;function aRe(k,x,j,A,L){let O,$,Y,X,le=x[0],xe=A[0],je=0,Ce=0;xe>le==xe>-le?(O=le,le=x[++je]):(O=xe,xe=A[++Ce]);let Ie=0;if(jele==xe>-le?($=le+O,Y=O-($-le),le=x[++je]):($=xe+O,Y=O-($-xe),xe=A[++Ce]),O=$,Y!==0&&(L[Ie++]=Y);jele==xe>-le?($=O+le,X=$-O,Y=O-($-X)+(le-X),le=x[++je]):($=O+xe,X=$-O,Y=O-($-X)+(xe-X),xe=A[++Ce]),O=$,Y!==0&&(L[Ie++]=Y);for(;je0:(A[0]-x[0])*(j[1]-x[1])-(j[0]-x[0])*(A[1]-x[1])>0}isAbove(x){return!this.isBelow(x)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const x=new Zz(this.point,this.left,this.otherEvent,this.isSubject,this.type);return x.contourId=this.contourId,x.resultTransition=this.resultTransition,x.prevInResult=this.prevInResult,x.isExteriorRing=this.isExteriorRing,x.inOut=this.inOut,x.otherInOut=this.otherInOut,x}}function x5(k,x){return k[0]===x[0]&&k[1]===x[1]}function iRe(k,x,j){const A=function(L,O,$,Y,X,le){const xe=(O-le)*($-X),je=(L-X)*(Y-le),Ce=xe-je;if(xe===0||je===0||xe>0!=je>0)return Ce;const Ie=Math.abs(xe+je);return Math.abs(Ce)>=33306690738754716e-32*Ie?Ce:-function(Fe,Ke,et,at,vt,pt,At){let Rt,Bt,Ns,us,ws,ys,vs,vn,Nn,Rn,$n,Fn,sr,gn,Bn,Vn,nr,yr;const ra=Fe-vt,Er=et-vt,Cr=Ke-pt,vr=at-pt;gn=ra*vr,ys=qv*ra,vs=ys-(ys-ra),vn=ra-vs,ys=qv*vr,Nn=ys-(ys-vr),Rn=vr-Nn,Bn=vn*Rn-(gn-vs*Nn-vn*Nn-vs*Rn),Vn=Cr*Er,ys=qv*Cr,vs=ys-(ys-Cr),vn=Cr-vs,ys=qv*Er,Nn=ys-(ys-Er),Rn=Er-Nn,nr=vn*Rn-(Vn-vs*Nn-vn*Nn-vs*Rn),$n=Bn-nr,ws=Bn-$n,Yz[0]=Bn-($n+ws)+(ws-nr),Fn=gn+$n,ws=Fn-gn,sr=gn-(Fn-ws)+($n-ws),$n=sr-Vn,ws=sr-$n,Yz[1]=sr-($n+ws)+(ws-Vn),yr=Fn+$n,ws=yr-Fn,Yz[2]=Fn-(yr-ws)+($n-ws),Yz[3]=yr;let ta=function(Xo,Bi){let sl=Bi[0];for(let lo=1;lo<4;lo++)sl+=Bi[lo];return sl}(0,Yz),fa=22204460492503146e-32*At;if(ta>=fa||-ta>=fa||(ws=Fe-ra,Rt=Fe-(ra+ws)+(ws-vt),ws=et-Er,Ns=et-(Er+ws)+(ws-vt),ws=Ke-Cr,Bt=Ke-(Cr+ws)+(ws-pt),ws=at-vr,us=at-(vr+ws)+(ws-pt),Rt===0&&Bt===0&&Ns===0&&us===0)||(fa=11093356479670487e-47*At+Vcs*Math.abs(ta),ta+=ra*us+vr*Rt-(Cr*Ns+Er*Bt),ta>=fa||-ta>=fa))return ta;gn=Rt*vr,ys=qv*Rt,vs=ys-(ys-Rt),vn=Rt-vs,ys=qv*vr,Nn=ys-(ys-vr),Rn=vr-Nn,Bn=vn*Rn-(gn-vs*Nn-vn*Nn-vs*Rn),Vn=Bt*Er,ys=qv*Bt,vs=ys-(ys-Bt),vn=Bt-vs,ys=qv*Er,Nn=ys-(ys-Er),Rn=Er-Nn,nr=vn*Rn-(Vn-vs*Nn-vn*Nn-vs*Rn),$n=Bn-nr,ws=Bn-$n,q1[0]=Bn-($n+ws)+(ws-nr),Fn=gn+$n,ws=Fn-gn,sr=gn-(Fn-ws)+($n-ws),$n=sr-Vn,ws=sr-$n,q1[1]=sr-($n+ws)+(ws-Vn),yr=Fn+$n,ws=yr-Fn,q1[2]=Fn-(yr-ws)+($n-ws),q1[3]=yr;const ei=aRe(4,Yz,4,q1,glt);gn=ra*us,ys=qv*ra,vs=ys-(ys-ra),vn=ra-vs,ys=qv*us,Nn=ys-(ys-us),Rn=us-Nn,Bn=vn*Rn-(gn-vs*Nn-vn*Nn-vs*Rn),Vn=Cr*Ns,ys=qv*Cr,vs=ys-(ys-Cr),vn=Cr-vs,ys=qv*Ns,Nn=ys-(ys-Ns),Rn=Ns-Nn,nr=vn*Rn-(Vn-vs*Nn-vn*Nn-vs*Rn),$n=Bn-nr,ws=Bn-$n,q1[0]=Bn-($n+ws)+(ws-nr),Fn=gn+$n,ws=Fn-gn,sr=gn-(Fn-ws)+($n-ws),$n=sr-Vn,ws=sr-$n,q1[1]=sr-($n+ws)+(ws-Vn),yr=Fn+$n,ws=yr-Fn,q1[2]=Fn-(yr-ws)+($n-ws),q1[3]=yr;const Aa=aRe(ei,glt,4,q1,ylt);gn=Rt*us,ys=qv*Rt,vs=ys-(ys-Rt),vn=Rt-vs,ys=qv*us,Nn=ys-(ys-us),Rn=us-Nn,Bn=vn*Rn-(gn-vs*Nn-vn*Nn-vs*Rn),Vn=Bt*Ns,ys=qv*Bt,vs=ys-(ys-Bt),vn=Bt-vs,ys=qv*Ns,Nn=ys-(ys-Ns),Rn=Ns-Nn,nr=vn*Rn-(Vn-vs*Nn-vn*Nn-vs*Rn),$n=Bn-nr,ws=Bn-$n,q1[0]=Bn-($n+ws)+(ws-nr),Fn=gn+$n,ws=Fn-gn,sr=gn-(Fn-ws)+($n-ws),$n=sr-Vn,ws=sr-$n,q1[1]=sr-($n+ws)+(ws-Vn),yr=Fn+$n,ws=yr-Fn,q1[2]=Fn-(yr-ws)+($n-ws),q1[3]=yr;const zi=aRe(Aa,ylt,4,q1,vlt);return vlt[zi-1]}(L,O,$,Y,X,le,Ie)}(k[0],k[1],x[0],x[1],j[0],j[1]);return A>0?-1:A<0?1:0}function pT(k,x){const j=k.point,A=x.point;return j[0]>A[0]?1:j[0]A[1]?1:-1:function(L,O,$){return L.left!==O.left?L.left?1:-1:iRe($,L.otherEvent.point,O.otherEvent.point)!==0?L.isBelow(O.otherEvent.point)?-1:1:!L.isSubject&&O.isSubject?1:-1}(k,x,j)}function fT(k,x,j){const A=new Zz(x,!1,k,k.isSubject),L=new Zz(x,!0,k.otherEvent,k.isSubject);return x5(k.point,k.otherEvent.point)&&console.warn("what is that, a collapsed segment?",k),A.contourId=L.contourId=k.contourId,pT(L,k.otherEvent)>0&&(k.otherEvent.left=!0,L.left=!1),k.otherEvent.otherEvent=L,k.otherEvent=A,j.push(L),j.push(A),j}function Oie(k,x){return k[0]*x[1]-k[1]*x[0]}function oRe(k,x){return k[0]*x[0]+k[1]*x[1]}function lRe(k,x,j){const A=function(X,le,xe,je){const Ce=[le[0]-X[0],le[1]-X[1]],Ie=[je[0]-xe[0],je[1]-xe[1]];function Fe(Ns,us,ws){return[Ns[0]+us*ws[0],Ns[1]+us*ws[1]]}const Ke=[xe[0]-X[0],xe[1]-X[1]];let et=Oie(Ce,Ie),at=et*et;const vt=oRe(Ce,Ce);if(at>0){const Ns=Oie(Ke,Ie)/et;if(Ns<0||Ns>1)return null;const us=Oie(Ke,Ce)/et;return us<0||us>1?null:Ns===0||Ns===1?[Fe(X,Ns,Ce)]:us===0||us===1?[Fe(xe,us,Ie)]:[Fe(X,Ns,Ce)]}if(et=Oie(Ke,Ce),at=et*et,at>0)return null;const pt=oRe(Ce,Ke)/vt,At=pt+oRe(Ce,Ie)/vt,Rt=Math.min(pt,At),Bt=Math.max(pt,At);return Rt<=1&&Bt>=0?Rt===1?[Fe(X,Rt>0?Rt:0,Ce)]:Bt===0?[Fe(X,Bt<1?Bt:1,Ce)]:[Fe(X,Rt>0?Rt:0,Ce),Fe(X,Bt<1?Bt:1,Ce)]:null}(k.point,k.otherEvent.point,x.point,x.otherEvent.point),L=A?A.length:0;if(L===0||L===1&&(x5(k.point,x.point)||x5(k.otherEvent.point,x.otherEvent.point))||L===2&&k.isSubject===x.isSubject)return 0;if(L===1)return!x5(k.point,A[0])&&!x5(k.otherEvent.point,A[0])&&fT(k,A[0],j),!x5(x.point,A[0])&&!x5(x.otherEvent.point,A[0])&&fT(x,A[0],j),1;const O=[];let $=!1,Y=!1;return x5(k.point,x.point)?$=!0:pT(k,x)===1?O.push(x,k):O.push(k,x),x5(k.otherEvent.point,x.otherEvent.point)?Y=!0:pT(k.otherEvent,x.otherEvent)===1?O.push(x.otherEvent,k.otherEvent):O.push(k.otherEvent,x.otherEvent),$&&Y||$?(x.type=1,k.type=x.inOut===k.inOut?2:3,$&&!Y&&fT(O[1].otherEvent,O[0].point,j),2):Y?(fT(O[0],O[1].point,j),3):O[0]!==O[3].otherEvent?(fT(O[0],O[1].point,j),fT(O[1],O[2].point,j),3):(fT(O[0],O[1].point,j),fT(O[3].otherEvent,O[2].point,j),3)}function Hcs(k,x){if(k===x)return 0;if(iRe(k.point,k.otherEvent.point,x.point)!==0||iRe(k.point,k.otherEvent.point,x.otherEvent.point)!==0)return x5(k.point,x.point)?k.isBelow(x.otherEvent.point)?-1:1:k.point[0]===x.point[0]?k.point[1](x.contourId??0)?1:-1}return pT(k,x)===1?1:-1}class Gcs{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Wcs(k,x,j,A){let L,O=k+1,$=x[k].point;const Y=x.length;for(OA;)O--;return O}function Kcs(k,x,j){const A=new Gcs;if(k.prevInResult!=null){const L=k.prevInResult,O=L.outputContourId;if(L.resultTransition>0){const $=x[O];if($.holeOf!=null){const Y=$.holeOf;x[Y].holeIds.push(j),A.holeOf=Y,A.depth=x[O].depth}else x[O].holeIds.push(j),A.holeOf=O,A.depth=x[O].depth+1}else A.holeOf=null,A.depth=x[O].depth}else A.holeOf=null,A.depth=0;return A}const _lt=Math.max,wlt=Math.min;let zie=0;function jlt(k,x,j,A,L,O){let $,Y,X,le,xe,je;for($=0,Y=k.length-1;$0?je.left=!0:xe.left=!0;const Ce=X[0],Ie=X[1];L[0]=wlt(L[0],Ce),L[1]=wlt(L[1],Ie),L[2]=_lt(L[2],Ce),L[3]=_lt(L[3],Ie),A.push(xe),A.push(je)}}const Bie=[];function Nlt(k,x,j){let A=k,L=x;typeof k[0][0][0]=="number"&&(A=[k]),typeof x[0][0][0]=="number"&&(L=[x]);let O=function(Ce,Ie,Fe){let Ke=null;return Ce.length*Ie.length===0&&(Fe===0?Ke=Bie:Fe===2?Ke=Ce:(Fe===1||Fe===3)&&(Ke=Ce.length===0?Ie:Ce)),Ke}(A,L,j);if(O)return O===Bie?null:O;const $=[1/0,1/0,-1/0,-1/0],Y=[1/0,1/0,-1/0,-1/0],X=function(Ce,Ie,Fe,Ke,et){const at=new jm(void 0,pT);let vt,pt,At,Rt,Bt,Ns;for(At=0,Rt=Ce.length;AtKe[2]||Ke[0]>Fe[2]||Fe[1]>Ke[3]||Ke[1]>Fe[3])&&(et===0?at=Bie:et===2?at=Ce:(et===1||et===3)&&(at=Ce.concat(Ie))),at}(A,L,$,Y,j),O)return O===Bie?null:O;const le=function(Ce,Ie,Fe,Ke,et,at){const vt=new sRe(Hcs),pt=[],At=Math.min(Ke[2],et[2]);let Rt,Bt,Ns;for(;Ce.length!==0;){let us=Ce.pop();if(pt.push(us),at===0&&us.point[0]>At||at===2&&us.point[0]>Ke[2])break;if(us.left){Bt=Rt=vt.insert(us),Ns=vt.minNode(),Rt=Rt!==Ns?vt.prev(Rt):null,Bt=vt.next(Bt);const ws=Rt?Rt.key:null;let ys;if(ZK(us,ws,at),Bt&&lRe(us,Bt.key,Ce)===2&&(ZK(us,ws,at),ZK(Bt.key,us,at)),Rt&&lRe(Rt.key,us,Ce)===2){let vs=Rt;vs=vs!==Ns?vt.prev(vs):null,ys=vs?vs.key:null,ZK(ws,ys,at),ZK(us,ws,at)}}else us=us.otherEvent,Bt=Rt=vt.find(us),Rt&&Bt&&(Rt=Rt!==Ns?vt.prev(Rt):null,Bt=vt.next(Bt),vt.remove(us),Bt&&Rt&&lRe(Rt.key,Bt.key,Ce))}return pt}(X,0,0,$,Y,j),xe=function(Ce){let Ie,Fe;const Ke=function(vt){let pt,At,Rt,Bt,Ns;const us=[];for(At=0,Rt=vt.length;At{et[Ns]=!0,Ns=Ke.length)&&Ke[Rt];);at.push(pt)}return at}(le),je=[];for(let Ce=0;Ce{$.push(new Ss(je,X+(je-Y)/(le-Y)*(xe-X)))}:($,Y,X,le,xe,je)=>{$.push(new Ss(Y+(je-X)/(xe-X)*(le-Y),je))};for(const $ of k){const Y=[];for(const X of $){if(X.length<=2)continue;const le=[];for(let Ce=0;Cex&&O(le,Ie,Fe,Ke,et,x):at>j?vt=x&&O(le,Ie,Fe,Ke,et,x),vt>j&&at<=j&&O(le,Ie,Fe,Ke,et,j)}let xe=X[X.length-1];const je=A===0?xe.x:xe.y;je>=x&&je<=j&&le.push(xe),le.length&&(xe=le[le.length-1],le[0].x===xe.x&&le[0].y===xe.y||le.push(le[0]),Y.push(le))}Y.length&&L.push(Y)}return L}function Ycs(k,x){const j=Nlt(cRe(k),cRe([x]),0);return j==null?[]:klt(j)}function Zcs(k,x,j=0){let L=cRe(k,65536);const O=[];for(;x.valid();x.next()){const[$,Y]=x.get();let X=$.x*65536,le=$.y*65536,xe=Y.x*65536,je=Y.y*65536;const Ce=xe-X,Ie=je-le,Fe=Math.hypot(Ce,Ie);if(Fe===0)continue;X-=Ce*j,le-=Ie*j,xe+=Ce*j,je+=Ie*j;const Ke=Math.trunc(Ie/Fe*3),et=-Math.trunc(Ce/Fe*3);O.push([[[X,le],[xe,je],[xe+Ke,je+et],[X+Ke,le+et],[X,le]]])}return O.length>0&&(L=Nlt(L,O,2)),klt(L,1/65536,128)}function cRe(k,x=1){return[k.map(j=>j.map(A=>[A.x*x,A.y*x]))]}function klt(k,x=1,j){return k.map(A=>A.map((L,O)=>{const $=L.map(Y=>{let X=Y[0],le=Y[1];return j&&(X=Math.round(X/j)*j,le=Math.round(le/j)*j),new Ss(X*x,le*x)._round()});return O>0&&$.reverse(),$}))}class dRe{constructor(x,j){this.layoutVertexArray=new ao,this.indexArray=new Qu,this.lineIndexArray=new Qb,this.triangleSegments=new Bc,this.lineSegments=new Bc,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.uploaded=!1,j&&(this.elevatedLayoutVertexArray=new Jl)}update(x,j,A,L,O,$,Y,X){this.programConfigurations.updatePaintArrays(x,j,O,A,L,$,Y,X)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,Acs.members),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.lineIndexBuffer=x.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=x.createVertexBuffer(this.elevatedLayoutVertexArray,Ecs.members))),this.programConfigurations.upload(x),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(x,j,A,L,O,$,Y){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,x,j,A,L,O,$,void 0,Y)}}class Uie{constructor(x){this.zoom=x.zoom,this.pixelRatio=x.pixelRatio,this.overscaling=x.overscaling,this.layers=x.layers,this.layerIds=this.layers.map(j=>j.fqid),this.index=x.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=x.lut,this.bufferData=new dRe(x,!1),this.elevationBufferData=new dRe(x,!0),this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.id),this.projection=x.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=x.sourceLayerIndex,this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,j){}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,j,A,L){this.hasPattern=eRe("fill",this.layers,this.pixelRatio,j);const O=this.layers[0].layout.get("fill-sort-key"),$=[];for(const{feature:Y,id:X,index:le,sourceLayerIndex:xe}of x){const je=this.layers[0]._featureFilter.needGeometry,Ce=oo(Y,je);if(!this.layers[0]._featureFilter.filter(new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),Ce,A))continue;const Ie=O?O.evaluate(Ce,{},A,j.availableImages):void 0,Fe={id:X,properties:Y.properties,type:Y.type,sourceLayerIndex:xe,index:le,geometry:je?Ce.geometry:ti(Y,A,L),patterns:{},sortKey:Ie};$.push(Fe)}O&&$.sort((Y,X)=>Y.sortKey-X.sortKey);for(const Y of $){const{geometry:X,index:le,sourceLayerIndex:xe}=Y;if(this.hasPattern){const je=tRe("fill",this.layers,Y,this.zoom,this.pixelRatio,j);this.patternFeatures.push(je)}else this.addFeature(Y,X,le,A,{},j.availableImages,j.brightness,j.elevationFeatures);j.featureIndex.insert(x[le].feature,X,le,xe,this.index)}}update(x,j,A,L,O,$,Y){this.bufferData.update(x,j,A,L,O,$,Y,this.worldview),this.elevationBufferData.update(x,j,A,L,O,$,Y,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(x,j,A,L,O,$,Y,this.worldview)}addFeatures(x,j,A,L,O,$){for(const Y of this.patternFeatures)this.addFeature(Y,Y.geometry,Y.index,j,A,L,$,x.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(x){this.bufferData.upload(x),this.elevationBufferData.upload(x),this.elevatedStructures&&this.elevatedStructures.upload(x)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(x,j,A,L,O,$=[],Y,X){const le=KK(j,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(x,le,L,A,X):this.addGeometry(le,this.bufferData),this.bufferData.populatePaintArrays(x,A,O,$,L,Y,this.worldview),this.elevationBufferData.populatePaintArrays(x,A,O,$,L,Y,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(x,j,A,L,O){this.elevatedStructures&&(this.elevatedStructures.construct(x),this.elevatedStructures.populatePaintArrays(j,A,L,O,this.worldview))}addElevatedRoadFeature(x,j,A,L,O){const $=new Array,Y=Xc.getElevationFeature(x,O);if(!Y)return void this.addGeometry(j,this.bufferData);{const le=this.clipPolygonsToTile(j,1);le.length>0&&$.push({polygons:le,elevationFeature:Y,elevationTileID:A})}const X={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(x,{},A),featureIndex:L};for(const le of $)if(le.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new U1(le.elevationTileID,this.layers,this.zoom,this.lut));const je=le.elevationFeature.isTunnel();let Ce=0;x.properties.hasOwnProperty(Uc)&&(Ce=+x.properties[Uc]),this.elevatedStructures.addPortalCandidates(le.elevationFeature.id,le.polygons,je,le.elevationFeature,Ce)}le.elevationFeature.constantHeight==null&&(le.polygons=this.prepareElevatedPolygons(le.polygons,le.elevationFeature,le.elevationTileID));const xe=new cd(A,le.elevationTileID);this.addElevatedGeometry(le.polygons,xe,le.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,L,X)}}addElevatedGeometry(x,j,A,L,O,$){const Y={elevation:A,elevationSampler:j,bias:L,index:O,featureInfo:$},[X,le]=this.addGeometry(x,this.elevationBufferData,Y);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:X,max:le}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,X),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,le))}addGeometry(x,j,A){let L=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,$=null;A&&($=A.elevationSampler.constantElevation(A.elevation,A.bias),$!=null&&(L=$,O=$));const Y=(X,le,xe)=>{if(A!=null)if(le.push(X),$!=null)j.elevatedLayoutVertexArray.emplaceBack($),xe.push($);else{const je=A.elevationSampler.pointElevation(X,A.elevation,A.bias);j.elevatedLayoutVertexArray.emplaceBack(je),xe.push(je),L=Math.min(L,je),O=Math.max(O,je)}};for(const X of x){let le=0;for(const pt of X)le+=pt.length;const xe=j.triangleSegments.prepareSegment(le,j.layoutVertexArray,j.indexArray),je=xe.vertexLength,Ce=[],Ie=[],Fe=[],Ke=[],et=[],at=j.layoutVertexArray.length;for(const pt of X){if(pt.length===0)continue;pt!==X[0]&&Ie.push(Ce.length/2);const At=j.lineSegments.prepareSegment(pt.length,j.layoutVertexArray,j.lineIndexArray),Rt=At.vertexLength;A&&et.push(j.layoutVertexArray.length-at),Y(pt[0],Fe,Ke),j.layoutVertexArray.emplaceBack(pt[0].x,pt[0].y),j.lineIndexArray.emplaceBack(Rt+pt.length-1,Rt),Ce.push(pt[0].x),Ce.push(pt[0].y);for(let Bt=1;Bt0&&A&&this.elevationMode==="hd-road-base"){const pt=A.elevation.isTunnel(),At=A.elevation.safeArea,Rt=this.elevatedStructures.addVertices(Fe,Ke);this.elevatedStructures.addTriangles(vt,Rt,pt);const Bt=et.length;if(Bt>0){for(let Ns=0;Ns=A&&Ie.max.x<=O&&Ie.min.y>=L&&Ie.max.y<=$?X:le).push(Ce)}if(X.length===x.length)return x;const xe=[new Ss(A,L),new Ss(O,L),new Ss(O,$),new Ss(A,$),new Ss(A,L)],je=X;for(const Ce of le)je.push(...Ycs(Ce,xe));return je}}let Slt,Clt,Alt,Elt;kr(Uie,"FillBucket",{omit:["layers","patternFeatures"]}),kr(dRe,"FillBufferData"),kr(U1,"ElevatedStructures");class qie{constructor(x,j,A,L){if(this.triangleCount=j.length/3,this.min=new Ss(0,0),this.max=new Ss(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||x.length===0)return;const[O,$]=[x[0].clone(),x[0].clone()];for(let je=1;jeje.cellIdx-Ce.cellIdx||je.triIdx-Ce.triIdx);let xe=0;for(;xethis.max.x||this.min.x>x.x||x.y>this.max.y||this.min.y>x.y)return;const A=g5(x.x-this.min.x,this.xScale,this.cellsX),L=g5(x.y-this.min.y,this.yScale,this.cellsY),O=this.cells[L*this.cellsX+A];if(O){this._lazyInitLookup();for(let $=0;$this.max.x||this.min.x>j.x||x.y>this.max.y||this.min.y>j.y)return;this._lazyInitLookup();const L=g5(x.x-this.min.x,this.xScale,this.cellsX),O=g5(j.x-this.min.x,this.xScale,this.cellsX),$=g5(x.y-this.min.y,this.yScale,this.cellsY),Y=g5(j.y-this.min.y,this.yScale,this.cellsY);for(let X=$;X<=Y;X++)for(let le=L;le<=O;le++){const xe=this.cells[X*this.cellsX+le];if(xe)for(let je=0;jej.fqid),this.index=x.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.id),this.footprints=[],this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,j){for(const A of this.footprints)j.push({footprint:A,id:x})}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,j,A,L){const O=[];for(const{feature:$,id:Y,index:X,sourceLayerIndex:le}of x){const xe=this.layers[0]._featureFilter.needGeometry,je=oo($,xe);if(!this.layers[0]._featureFilter.filter(new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),je,A))continue;const Ce={id:Y,properties:$.properties,type:$.type,sourceLayerIndex:le,index:X,geometry:xe?je.geometry:ti($,A,L),patterns:{}};O.push(Ce)}for(const $ of O){const{geometry:Y,index:X,sourceLayerIndex:le}=$;this.addFeature($,Y,X,A,{},j.availableImages,j.brightness),j.featureIndex.insert(x[X].feature,Y,X,le,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(x){}update(x,j,A,L,O,$,Y){}destroy(){}addFeature(x,j,A,L,O,$=[],Y){for(const X of KK(j,2)){const le=[],xe=[],je=[],Ce=new Ss(1/0,1/0),Ie=new Ss(-1/0,-1/0);for(const et of X)if(et.length!==0){et!==X[0]&&je.push(xe.length/2);for(let at=0;atx.max.x||k.max.xx.max.y||k.max.ynew Ss((X.x+O.x*fr)*Y-$.x*fr,(X.y+O.y*fr)*Y-$.y*fr))}return hRe(j,L,k.indices,0,k.indices.length,0,0)}function Dlt(k,x,j,A){const L=Math.pow(2,A.z-j.z);return new Ss((k+j.x*fr)*L-A.x*fr,(x+j.y*fr)*L-A.y*fr)}function Rlt(k,x){const j=[];x.grid.queryPoint(k,j);const A=x.indices,L=x.vertices;for(let O=0;O0&&(A.length>1&&j.push(A),A=[])}return A.length>1&&j.push(A),j}const pRe=Si.types,ods=["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"],lds=["fill-extrusion-flood-light-ground-radius"],cds=Math.pow(2,13),dds=Math.pow(2,15)-1,Wie=new Ss(0,1),h3=2147483648,Kie=1073741824;function QK(k,x,j,A,L,O,$,Y){k.emplaceBack((x<<1)+$,(j<<1)+O,(Math.floor(A*cds)<<1)+L,Math.round(Y))}function JK(k,x,j){k.emplaceBack(x.x*fr,x.y*fr,j?1:0)}function Yie(k,x,j,A,L,O){k.emplaceBack(x.x,x.y,(j.x<<1)+A,(j.y<<1)+L,O)}function eY(k,x,j){k.emplaceBack(x.x,x.y,x.z,j[0]*16384,j[1]*16384,j[2]*16384)}class Olt{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class fRe{constructor(){this.centroidXY=new Ss(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 Ss(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Ss(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Ss(0,0)}span(){return new Ss(this.max.x-this.min.x,this.max.y-this.min.y)}}class xRe{constructor(){this.acc=new Ss(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(x,j){x.min.x===Number.MAX_VALUE&&(x.min.x=x.max.x=j.x,x.min.y=x.max.y=j.y)}appendEdge(x,j,A){this.accCount++,this.acc._add(j);let L=!!this.borders;j.xx.max.x&&(x.max.x=j.x,L=!0),j.yx.max.y&&(x.max.y=j.y,L=!0),((j.x===0||j.x===fr)&&j.x===A.x)!=((j.y===0||j.y===fr)&&j.y===A.y)&&this.processBorderOverlap(j,A),L&&this.checkBorderIntersection(j,A)}checkBorderIntersection(x,j){j.x<0!=x.x<0&&this.addBorderIntersection(0,Pr(j.y,x.y,(0-j.x)/(x.x-j.x))),j.x>fr!=x.x>fr&&this.addBorderIntersection(1,Pr(j.y,x.y,(fr-j.x)/(x.x-j.x))),j.y<0!=x.y<0&&this.addBorderIntersection(2,Pr(j.x,x.x,(0-j.y)/(x.y-j.y))),j.y>fr!=x.y>fr&&this.addBorderIntersection(3,Pr(j.x,x.x,(fr-j.y)/(x.y-j.y)))}addBorderIntersection(x,j){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 A=this.borders[x];jA[1]&&(A[1]=j)}processBorderOverlap(x,j){if(x.x===j.x){if(x.y===j.y)return;const A=x.x===0?0:1;this.addBorderIntersection(A,j.y),this.addBorderIntersection(A,x.y)}else{const A=x.y===0?2:3;this.addBorderIntersection(A,j.x),this.addBorderIntersection(A,x.x)}}centroid(){return this.accCount===0?new Ss(0,0):new Ss(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((x,j)=>x+ +(j[0]!==Number.MAX_VALUE),0):0}}function zlt(k,x){const j=k.add(x)._unit(),A=gt(k.x*j.x+k.y*j.y,-1,1);var L,O,$;return $=Math.acos(A),Math.min(4,Math.max(-4,Math.tan($)))/4*dds*((L=k).x*(O=x).y-L.y*O.x<0?-1:1)}const uds=[k=>k.x<0,k=>k.x>fr,k=>k.y<0,k=>k.y>fr];function hds(k,x,j,A){const L=[4];if(A===0)return L;j._mult(A);const O=k.sub(j),$=x.sub(j),Y=[k,x,O,$];for(let X=0;X<4;X++)for(const le of Y)if(uds[X](le)){L.push(X);break}return L}class gRe{constructor(x){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new nI,this.indexArray=new Qu,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut},j=>lds.includes(j)),this._segments=new Bc,this.hiddenByLandmarkVertexArray=new Uz,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Bc}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(x,j,A,L=!1){const O=x.length;if(O>2){let $=Math.max(0,this._segments.get().length-1);const Y=this._segments._prepareSegment(4*O,this.vertexArray.length,2*this._segmentToGroundQuads[$].length);let X;$!==this._segments.get().length-1&&($++,this._segmentToGroundQuads[$]=[],this._segmentToRegionTriCounts[$]=[0,0,0,0,0]);{const le=x[0],xe=x[1];X=zlt(le.sub(x[O-1])._perp()._unit(),xe.sub(le)._perp()._unit())}for(let le=0;leL.region-O.region);for(let A=0;AX+le,0);let Y=0;for(let X=0;X<=4;X++){const le=$[X];if(le!==0){let xe=this.regionSegments[X];xe||(xe=this.regionSegments[X]=new Bc);const je={vertexOffset:O.vertexOffset,primitiveOffset:O.primitiveOffset+Y,vertexLength:O.vertexLength,primitiveLength:le};xe.get().push(je)}Y+=le}for(let X=0;X0?this.hiddenByLandmarkVertexBuffer=x.createVertexBuffer(this.hiddenByLandmarkVertexArray,sds.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 x=0;x<=4;x++){const j=this.regionSegments[x];j&&j.destroy()}}}}class Zie{constructor(x){this.zoom=x.zoom,this.canonical=x.canonical,this.overscaling=x.overscaling,this.layers=x.layers,this.pixelRatio=x.pixelRatio,this.layerIds=this.layers.map(j=>j.fqid),this.index=x.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=x.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new Qu,this.footprintVertices=new ao,this.footprintSegments=[],this.layoutVertexArray=new Zb,this.centroidVertexArray=new Eie,this.wallVertexArray=new OK,this.indexArray=new Qu,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut},j=>ods.includes(j)),this.segments=new Bc,this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.id),this.groundEffect=new gRe(x),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,j){}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,j,A,L){this.features=[],this.hasPattern=eRe("fill-extrusion",this.layers,this.pixelRatio,j),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=Kn(A),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:O,id:$,index:Y,sourceLayerIndex:X}of x){const le=this.layers[0]._featureFilter.needGeometry,xe=oo(O,le);if(!this.layers[0]._featureFilter.filter(new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),xe,A))continue;const je={id:$,sourceLayerIndex:X,index:Y,geometry:le?xe.geometry:ti(O,A,L),properties:O.properties,type:O.type,patterns:{}},Ce=this.layoutVertexArray.length,Ie=pRe[je.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:O.id,feature:tRe("fill-extrusion",this.layers,je,this.zoom,this.pixelRatio,j)});else if(this.wallMode)for(const Fe of je.geometry)for(const Ke of Flt(Fe,Ie))this.addFeature(O.id,je,[Ke],Y,A,{},j.availableImages,L,j.brightness);else this.addFeature(O.id,je,je.geometry,Y,A,{},j.availableImages,L,j.brightness);j.featureIndex.insert(O,je.geometry,Y,X,this.index,Ce)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(x,j,A,L,O,$){for(const{featureId:Y,feature:X}of this.features){const le=pRe[X.type]==="Polygon",{geometry:xe}=X;if(this.wallMode)for(const je of xe)for(const Ce of Flt(je,le))this.addFeature(Y,X,[Ce],X.index,j,A,L,O,$);else this.addFeature(Y,X,xe,X.index,j,A,L,O,$)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(x,j,A,L,O,$,Y){this.programConfigurations.updatePaintArrays(x,j,O,A,L,$,Y,this.worldview),this.groundEffect.update(x,j,O,A,L,$,Y,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,rds),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.wallVertexBuffer=x.createVertexBuffer(this.wallVertexArray,tds.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=x.createVertexBuffer(this.layoutVertexExtArray,nds.members,!0)),this.groundEffect.upload(x)),this.groundEffect.uploadPaintProperties(x),this.programConfigurations.upload(x),this.uploaded=!0}uploadCentroid(x){this.groundEffect.uploadHiddenByLandmark(x),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=x.createVertexBuffer(this.centroidVertexArray,eds.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(x,j,A,L,O,$,Y,X,le){const xe=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(j,{})/this.tileToMeter,je=[new Ss(0,0),new Ss(fr,fr)],Ce=X.projection,Ie=Ce.name==="globe",Fe=this.wallMode||pRe[j.type]==="Polygon",Ke=new xRe;Ke.centroidDataIndex=this.centroidData.length;const et=new fRe;et.buildingId=x,j.properties&&j.properties.hasOwnProperty("building_id")&&(et.buildingId=Number(j.properties.building_id)),Ke.buildingId=et.buildingId;const at=this.layers[0].paint.get("fill-extrusion-base").evaluate(j,{},O)<=0,vt=this.layers[0].paint.get("fill-extrusion-height").evaluate(j,{},O);let pt;if(et.height=vt,et.vertexArrayOffset=this.layoutVertexArray.length,et.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Ie&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new Rz),this.wallMode){if(Ie)return void aa("Non zero fill-extrusion-line-width is not yet supported on globe.");if(A.length!==1)return;pt=function(ys){const vs=ys[0].x===ys[ys.length-1].x&&ys[0].y===ys[ys.length-1].y;(function(Cr){let vr=0;const ta=Cr.length;for(let fa=0;fa=0})(ys)||(ys=ys.reverse());const Nn={geometry:[],joinNormals:[],indices:[]},Rn=[],$n=[],Fn=[];let sr=ys.length;for(;sr>=2&&ys[sr-1].equals(ys[sr-2]);)sr--;if(sr<(vs?3:2))return Nn;let gn,Bn,Vn,nr,yr,ra=0;for(;ra0;let Aa="miter";const zi=2;Aa==="miter"&&fa>zi&&(Aa="bevel"),Aa==="bevel"&&(fa>100&&(Aa="flipbevel"),fa{const Dl=new Ss(Bi.x,Bi.y),hl=new Ss(Bi.x,Bi.y);Dl.x+=sl.x*Lu,Dl.y+=sl.y*Lu,hl.x-=sl.x*Math.max(lo,1),hl.y-=sl.y*Math.max(lo,1),Fn.push(sl),Rn.push(Dl),$n.push(hl)};if(Aa==="miter")vr._mult(fa),Xo(gn,vr,0,0);else if(Aa==="flipbevel")vr=yr.mult(-1),Xo(gn,vr,0,0),Xo(gn,vr.mult(-1),0,0);else{const Bi=-Math.sqrt(fa*fa-1),sl=ei?Bi:0,lo=ei?0:Bi;Bn&&Xo(gn,nr,sl,lo),Vn&&Xo(gn,yr,sl,lo)}}Nn.geometry=[...Rn,...$n.reverse(),Rn[0]],Nn.joinNormals=[...Fn,...Fn.reverse(),Fn[Fn.length-1]];const Er=Nn.geometry.length-1;for(let Cr=0;Crys<(vs.length-1)/2||ys===vs.length-1,Rt=this.wallMode?[A]:KK(A,500);for(let ys=Rt.length-1;ys>=0;ys--){const vs=Rt[ys];(vs.length===0||pds(vs[0]))&&Rt.splice(ys,1)}let Bt;if(Ie)Bt=Glt(Rt,je,O);else{Bt=[];for(const ys of Rt)Bt.push({polygon:ys,bounds:je})}const Ns=Fe?this.edgeRadius:0,us=Ns>0&&this.zoom<17,ws=(ys,vs)=>{if(ys.length===0)return!1;const vn=ys[ys.length-1];return vs.x===vn.x&&vs.y===vn.y};for(const{polygon:ys,bounds:vs}of Bt){let vn=0,Nn=0;for(const sr of ys)Fe&&!sr[0].equals(sr[sr.length-1])&&sr.push(sr[0]),Nn+=Fe?sr.length-1:sr.length;const Rn=this.segments.prepareSegment((Fe?5:4)*Nn,this.layoutVertexArray,this.indexArray);et.footprintSegIdx<0&&(et.footprintSegIdx=this.footprintSegments.length),et.polygonSegIdx<0&&(et.polygonSegIdx=this.polygonSegments.length);const $n={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Fn=new Olt;if(Fn.vertexOffset=this.footprintVertices.length,Fn.indexOffset=3*this.footprintIndices.length,Fn.ringIndices=[],Fe){const sr=[],gn=[];vn=Rn.vertexLength;for(let Vn=0;Vn4&&qlt(gn[gn.length-2],gn[0],gn[1]),Vn=Ns?mds(gn[gn.length-2],gn[0],gn[1],Ns):0;const nr=[];let yr,ra,Er;ra=gn[1].sub(gn[0])._perp()._unit();let Cr=!0;for(let vr=1,ta=0;vr0?1:0,sl=fa.dist(ei);if(ta+sl>32768&&(ta=0),Ns){Er=Aa.sub(ei)._perp()._unit();let hl=$lt(fa,ei,Aa,Blt(ra,Er),Ns);isNaN(hl)&&(hl=0);const qc=ei.sub(fa)._unit();fa=fa.add(qc.mult(Vn))._round(),ei=ei.add(qc.mult(-hl))._round(),Vn=hl,ra=Er,at&&this.zoom>=17&&(ws(nr,fa)||nr.push(fa),ws(nr,ei)||nr.push(ei))}const lo=Rn.vertexLength,Lu=gn.length>4&&qlt(fa,ei,Aa);let Dl=Vlt(ta,Bn,Cr);if(QK(this.layoutVertexArray,fa.x,fa.y,Xo,Bi,0,0,Dl),QK(this.layoutVertexArray,fa.x,fa.y,Xo,Bi,0,1,Dl),this.wallMode){const hl=At(vr-1,gn),qc=pt.joinNormals[vr-1];JK(this.wallVertexArray,qc,hl),JK(this.wallVertexArray,qc,hl)}if(ta+=sl,Dl=Vlt(ta,Lu,!Cr),Bn=Lu,QK(this.layoutVertexArray,ei.x,ei.y,Xo,Bi,0,0,Dl),QK(this.layoutVertexArray,ei.x,ei.y,Xo,Bi,0,1,Dl),this.wallMode){const hl=At(vr,gn),qc=pt.joinNormals[vr];JK(this.wallVertexArray,qc,hl),JK(this.wallVertexArray,qc,hl)}if(Rn.vertexLength+=4,this.indexArray.emplaceBack(lo+0,lo+1,lo+2),this.indexArray.emplaceBack(lo+1,lo+3,lo+2),Rn.primitiveLength+=2,Ns){const hl=vn+(vr===1?gn.length-2:vr-2),qc=vr===1?vn:hl+1;if(this.indexArray.emplaceBack(lo+1,hl,lo+3),this.indexArray.emplaceBack(hl,qc,lo+3),Rn.primitiveLength+=2,yr===void 0&&(yr=lo),!yRe(Aa,gn[vr],vs)){const ku=vr===gn.length-1?yr:Rn.vertexLength;this.indexArray.emplaceBack(lo+2,lo+3,ku),this.indexArray.emplaceBack(lo+3,ku+1,ku),this.indexArray.emplaceBack(lo+3,qc,ku+1),Rn.primitiveLength+=3}Cr=!Cr}if(Ie){const hl=this.layoutVertexExtArray,qc=Ce.projectTilePoint(fa.x,fa.y,O),ku=Ce.projectTilePoint(ei.x,ei.y,O),Hp=Ce.upVector(O,fa.x,fa.y),Su=Ce.upVector(O,ei.x,ei.y);eY(hl,qc,Hp),eY(hl,qc,Hp),eY(hl,ku,Su),eY(hl,ku,Su)}}Fe&&(vn+=gn.length-1),at&&Ns&&this.zoom>=17&&(nr.length!==0&&ws(nr,nr[0])&&nr.pop(),this.groundEffect.addData(nr,vs,xe,Ns>0))}this.footprintSegments.push(Fn),$n.triangleCount=this.indexArray.length-$n.triangleArrayOffset,this.polygonSegments.push($n),++et.footprintSegLen,++et.polygonSegLen}if(et.vertexCount=this.layoutVertexArray.length-et.vertexArrayOffset,et.groundVertexCount=this.groundEffect.vertexArray.length-et.groundVertexArrayOffset,et.vertexCount!==0){if(et.centroidXY=Ke.borders?Wie:this.encodeCentroid(Ke,et),j.properties&&j.properties.hasOwnProperty("building_id")){const ys=et.buildingId;let vs=this.buildingGroups.get(ys);vs||(vs={accX:0,accY:0,accCount:0,mergedMin:new Ss(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Ss(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(ys,vs)),vs.accX+=Ke.acc.x,vs.accY+=Ke.acc.y,vs.accCount+=Ke.accCount,vs.mergedMin.x=Math.min(vs.mergedMin.x,et.min.x),vs.mergedMin.y=Math.min(vs.mergedMin.y,et.min.y),vs.mergedMax.x=Math.max(vs.mergedMax.x,et.max.x),vs.mergedMax.y=Math.max(vs.mergedMax.y,et.max.y),vs.partIndices.push(this.centroidData.length)}if(this.centroidData.push(et),Ke.borders){this.featuresOnBorder.push(Ke);const ys=this.featuresOnBorder.length-1;for(let vs=0;vsthis.featuresOnBorder[j].borders[x][0]-this.featuresOnBorder[A].borders[x][0])}splitToSubtiles(){const x=[];for(let Y=0;Yfr),xe=2*le+(+(X.min.x+X.max.x>fr)^le);for(let je=0;jeY.triangleSegmentIdx===X.triangleSegmentIdx?Y.subtile-X.subtile:Y.triangleSegmentIdx-X.triangleSegmentIdx);let A=0,L=0,O=0;for(const Y of x){if(Y.triangleSegmentIdx!==A)break;O++}const $=x.length;for(;L!==x.length;){A=x[L].triangleSegmentIdx;let Y=0,X=L,le=L;for(let xe=X;xe0&&this.triangleSubSegments.push({segment:Ie,min:je,max:Ce}),X=le;for(let Fe=X;Fe[Ke[0]*(1-at[0])+et[0]*at[0],Ke[1]*(1-at[1])+et[1]*at[1]],Ie=[],Fe=[];for(const Ke of this.triangleSubSegments){Ie[0]=Ke.min.x/fr,Ie[1]=Ke.min.y/fr,Fe[0]=Ke.max.x/fr,Fe[1]=Ke.max.y/fr;const et=Ce(xe,je,Ie),at=Ce(xe,je,Fe);if(new Kl([et[0],et[1],O],[at[0],at[1],$]).intersectsPrecise(A)===0){le&&(L.segments.push(le),le=void 0);continue}const vt=Ke.segment;le&&le.vertexOffset!==vt.vertexOffset&&(L.segments.push(le),le=void 0),le?(le.vertexLength+=vt.vertexLength,le.primitiveLength+=vt.primitiveLength):le={vertexOffset:vt.vertexOffset,primitiveLength:vt.primitiveLength,vertexLength:vt.vertexLength,primitiveOffset:vt.primitiveOffset,sortKey:void 0,vaos:{}}}return le&&L.segments.push(le),L}encodeCentroid(x,j){const A=x.centroid(),L=j.span(),O=Math.min(7,Math.round(L.x*this.tileToMeter/10)),$=Math.min(6,Math.round(L.y*this.tileToMeter/10));return new Ss(gt(A.x,1,8191)<<3|O,gt(A.y,1,8191)<<3|$)}encodeBorderCentroid(x){if(!x.borders)return new Ss(0,0);const j=x.borders,A=Number.MAX_VALUE;if(j[0][0]!==A||j[1][0]!==A){const L=j[0][0]!==A?0:1;return new Ss(6|(j[0][0]!==A?0:65528),(j[L][0]+j[L][1])/2<<3|6)}{const L=j[2][0]!==A?2:3;return new Ss((j[L][0]+j[L][1])/2<<3|6,6|(j[2][0]!==A?0:65528))}}showCentroid(x){const j=this.centroidData[x.centroidDataIndex];if(j.flags&=h3,j.groupCentroidPos.x!==0||j.groupCentroidPos.y!==0){const A=j.span(),L=Math.min(7,Math.round(A.x*this.tileToMeter/10)),O=Math.min(6,Math.round(A.y*this.tileToMeter/10));j.centroidXY=new Ss(gt(j.groupCentroidPos.x,1,8191)<<3|L,gt(j.groupCentroidPos.y,1,8191)<<3|O)}else j.centroidXY=new Ss(0,0);this.writeCentroidToBuffer(j)}writeCentroidToBuffer(x){this.groundEffect.updateHiddenByLandmark(x);const j=x.vertexArrayOffset,A=x.vertexCount+x.vertexArrayOffset,L=-1073741824&x.flags?Wie:x.centroidXY,O=this.centroidVertexArray.geta_centroid_pos0(j);if(this.centroidVertexArray.geta_centroid_pos1(j)!==L.y||O!==L.x){for(let $=j;$X.max.x||X.min.x>$.max.x||$.min.y>X.max.y||X.min.y>$.max.y||$.footprint.buildingIds.has(X.buildingId)&&(X.flags|=$.clipMask!==Gie.None?-1073741824:h3);else for(const X of this.centroidData)if(!(X.flags&h3||X.flags&Kie||$.min.x>X.max.x||X.min.x>$.max.x||$.min.y>X.max.y||X.min.y>$.max.y))for(let le=0;lej!=Ie>j&&x<(this.footprintVertices.int16[2*(xe+$.vertexOffset)+0]-je)*(j-Ce)/(Ie-Ce)+je&&(L=!L)}Y=X}}return L}getHeightAtTileCoord(x,j){let A=Number.NEGATIVE_INFINITY,L=!0;const O=4*(x+fr)*fr+(j+fr);if(this.partLookup.hasOwnProperty(O)){const $=this.partLookup[O];return $?{height:$.height,hidden:!!($.flags&h3)}:void 0}for(const $ of this.centroidData)x>$.max.x||$.min.x>x||j>$.max.y||$.min.y>j||$.height<=A||this.footprintContainsPoint(x,j,$)&&(A=$.height,this.partLookup[O]=$,L=!!($.flags&h3));if(A!==Number.NEGATIVE_INFINITY)return{height:A,hidden:L};this.partLookup[O]=void 0}}function Blt(k,x){const j=k.add(x)._unit();return k.x*j.x+k.y*j.y}function mds(k,x,j,A){const L=x.sub(k)._perp()._unit(),O=j.sub(x)._perp()._unit();return $lt(k,x,j,Blt(L,O),A)}function $lt(k,x,j,A,L){const O=Math.sqrt(1-A*A);return Math.min(k.dist(x)/3,x.dist(j)/3,L*O/A)}function yRe(k,x,j){return k.xj[1].x&&x.x>j[1].x||k.yj[1].y&&x.y>j[1].y}function Ult(k,x){return k.xx[1].x||k.yx[1].y}function pds(k){return k.every(x=>x.x<=0)||k.every(x=>x.x>=fr)||k.every(x=>x.y<=0)||k.every(x=>x.y>=fr)}function qlt(k,x,j){if(k.x<0||k.x>=fr||x.x<0||x.x>=fr||j.x<0||j.x>=fr)return!1;const A=j.sub(x),L=A.perp(),O=k.sub(x);return(A.x*O.x+A.y*O.y)/Math.sqrt((A.x*A.x+A.y*A.y)*(O.x*O.x+O.y*O.y))>-.866&&L.x*O.x+L.y*O.y<0}function Vlt(k,x,j){const A=x?2|k:-3&k;return j?1|A:-2&A}function Hlt(){const k=Math.PI/32,x=Math.tan(k),j=_s;return j*Math.sqrt(1+2*x*x)-j}function Glt(k,x,j){const A=1<{for(const us of Bt)Fe.push({polygon:us,bounds:Ns})},et=Math.ceil(Math.log2(xe)),at=Math.ceil(Math.log2(je)),vt=et-at,pt=[];for(let Bt=0;Bt0?0:1);for(let Bt=0;BtNs+1?Rt.push({polygons:Rn,bounds:Fn,depth:Ns+1}):Ke(Rn,Fn)}if($n.length){const Fn=[new Ss(us===0?Nn:ws.x,us===1?Nn:ws.y),ys];pt.length>Ns+1?Rt.push({polygons:$n,bounds:Fn,depth:Ns+1}):Ke($n,Fn)}}return Fe}(k,x,Math.ceil((O-L)/11.25),Math.ceil(($-Y)/11.25),1,(X,le,xe)=>{if(X===0)return .5*(le+xe);{const je=yn((j.y+le/fr)/A);return(Xn(.5*(yn((j.y+xe/fr)/A)+je))*A-j.y)*fr}})}function fds(k,x,j,A,L,O){const $=Math.pow(2,A.z-L.z);for(let Y=0;Y=X[$]&&(Y=x,X=k),Y[$]L&&Zlt(Y,X,$,L),Y[$]O&&Zlt(X,Y,$,O)}}function Xie(k,x,j,A,L,O){const $=[];for(let Y=0;Y=A&&Fe.x>=A||(Ie.x>=A?Ie=new Ss(A,Ie.y+(A-Ie.x)/(Fe.x-Ie.x)*(Fe.y-Ie.y))._round():Fe.x>=A&&(Fe=new Ss(A,Ie.y+(A-Ie.x)/(Fe.x-Ie.x)*(Fe.y-Ie.y))._round()),Ie.y>=L&&Fe.y>=L||(Ie.y>=L?Ie=new Ss(Ie.x+(L-Ie.y)/(Fe.y-Ie.y)*(Fe.x-Ie.x),L)._round():Fe.y>=L&&(Fe=new Ss(Ie.x+(L-Ie.y)/(Fe.y-Ie.y)*(Fe.x-Ie.x),L)._round()),le&&Ie.equals(le[le.length-1])||(le=[Ie],$.push(le),O&&O.push({progress:{min:et+Qlt(at,vt,Ie)*Ke,max:1},parentIndex:Y,prevPoint:at,nextPoint:vt})),le.push(Fe),O&&(O[O.length-1].progress.max=et+Qlt(at,vt,Fe)*Ke,O[O.length-1].nextPoint=vt)))))}if(O&&je>0)for(let Ce=xe;Ce<$.length;Ce++)O[Ce].progress.min/=je,O[Ce].progress.max/=je}return $}function xds(k,x,j,A,L){if(k.length<2)return void A.push(k);const O=[];for(;x.valid();){const[le,xe]=x.get();for(let je=0;jele.t-xe.t);let $=0,Y=0,X=[];for(A.push(X);$!==k.length;){if(Y===O.length){for(;$!==k.length;)X.length!==0&&X[X.length-1].equals(k[$])||X.push(k[$]),$++;break}O[Y].t<=$?(X.length!==0&&X[X.length-1].equals(O[Y].point)||X.push(O[Y].point),Math.trunc(O[Y].t),Y++):(X.length!==0&&X[X.length-1].equals(k[$])||X.push(k[$]),$++)}}function Qlt(k,x,j){return k.x!==x.x?(j.x-k.x)/(x.x-k.x):k.y!==x.y?(j.y-k.y)/(x.y-k.y):0}function tY(k,x){return k.x*x.x+k.y*x.y}function Jlt(k,x){if(k.length===1){let j=0;const A=x[j++];let L;for(;!L||A.equals(L);)if(L=x[j++],!L)return 1/0;for(;j{Nn[0]=Rn,Nn[1]=$n,Nn[2]=Fn,Nn[3]=1},vn=Hlt();Ie>0&&(Ie+=vn),Fe+=vn;for(const Nn of Ce){const Rn=[],$n=[];for(const Fn of Nn){const sr=Fn.x+Ke.x,gn=Fn.y+Ke.y,Bn=je.projection.projectTilePoint(sr,gn,Rt),Vn=je.projection.upVector(Rt,Fn.x,Fn.y);let nr=Ie,yr=Fe;if(at){const ra=sct(sr,gn,Ie,Fe,at,vt,pt,At);nr+=ra.base,yr+=ra.top}Ie!==0?vs(ws,Bn.x+Vn[0]*us*nr,Bn.y+Vn[1]*us*nr,Bn.z+Vn[2]*us*nr):vs(ws,Bn.x,Bn.y,Bn.z),vs(ys,Bn.x+Vn[0]*us*yr,Bn.y+Vn[1]*us*yr,Bn.z+Vn[2]*us*yr),Ve(ws,ws,et),Ve(ys,ys,et),Rn.push(new gI(ws[0],ws[1],ws[2])),$n.push(new gI(ys[0],ys[1],ys[2]))}Bt.push(Rn),Ns.push($n)}return[Bt,Ns]}(k,x,j,A,L,O,$,Y,X,le,xe):$?function(je,Ce,Ie,Fe,Ke,et,at,vt,pt){const At=[],Rt=[],Bt=[0,0,0,1];for(const Ns of je){const us=[],ws=[];for(const ys of Ns){const vs=ys.x+Fe.x,vn=ys.y+Fe.y,Nn=sct(vs,vn,Ce,Ie,et,at,vt,pt);Bt[0]=vs,Bt[1]=vn,Bt[2]=Nn.base,Bt[3]=1,Je(Bt,Bt,Ke),Bt[3]=Math.max(Bt[3],1e-5);const Rn=new gI(Bt[0]/Bt[3],Bt[1]/Bt[3],Bt[2]/Bt[3]);Bt[0]=vs,Bt[1]=vn,Bt[2]=Nn.top,Bt[3]=1,Je(Bt,Bt,Ke),Bt[3]=Math.max(Bt[3],1e-5);const $n=new gI(Bt[0]/Bt[3],Bt[1]/Bt[3],Bt[2]/Bt[3]);us.push(Rn),ws.push($n)}At.push(us),Rt.push(ws)}return[At,Rt]}(x,j,A,L,O,$,Y,X,le):function(je,Ce,Ie,Fe,Ke){const et=[],at=[],vt=Ke[8]*Ce,pt=Ke[9]*Ce,At=Ke[10]*Ce,Rt=Ke[11]*Ce,Bt=Ke[8]*Ie,Ns=Ke[9]*Ie,us=Ke[10]*Ie,ws=Ke[11]*Ie;for(const ys of je){const vs=[],vn=[];for(const Nn of ys){const Rn=Nn.x+Fe.x,$n=Nn.y+Fe.y,Fn=Ke[0]*Rn+Ke[4]*$n+Ke[12],sr=Ke[1]*Rn+Ke[5]*$n+Ke[13],gn=Ke[2]*Rn+Ke[6]*$n+Ke[14],Bn=Ke[3]*Rn+Ke[7]*$n+Ke[15],Vn=Fn+vt,nr=sr+pt,yr=gn+At,ra=Math.max(Bn+Rt,1e-5),Er=Fn+Bt,Cr=sr+Ns,vr=gn+us,ta=Math.max(Bn+ws,1e-5);vs.push(new gI(Vn/ra,nr/ra,yr/ra)),vn.push(new gI(Er/ta,Cr/ta,vr/ta))}et.push(vs),at.push(vn)}return[et,at]}(x,j,A,L,O)}function sct(k,x,j,A,L,O,$,Y){const X=$*L.getElevationAt(k,x,!0,!0),le=O[0]!==0,xe=le?O[1]===0?$*(O[0]/7-450):$*function(je,Ce,Ie){const Fe=Math.floor(Ce[0]/8),Ke=Math.floor(Ce[1]/8),et=10*(Ce[0]-8*Fe),at=10*(Ce[1]-8*Ke),vt=je.getElevationAt(Fe,Ke,!0,!0),pt=je.getMeterToDEM(Ie),At=Math.floor(.5*(et*pt-1)),Rt=Math.floor(.5*(at*pt-1)),Bt=je.tileCoordToPixel(Fe,Ke),Ns=2*At+1,us=2*Rt+1,ws=function($n,Fn,sr,gn,Bn){return[$n.getElevationAtPixel(Fn,sr,!0),$n.getElevationAtPixel(Fn+Bn,sr,!0),$n.getElevationAtPixel(Fn,sr+Bn,!0),$n.getElevationAtPixel(Fn+gn,sr+Bn,!0)]}(je,Bt.x-At,Bt.y-Rt,Ns,us),ys=Math.abs(ws[0]-ws[1]),vs=Math.abs(ws[2]-ws[3]),vn=Math.abs(ws[0]-ws[2])+Math.abs(ws[1]-ws[3]),Nn=Math.min(.25,.5*pt*(ys+vs)/Ns),Rn=Math.min(.25,.5*pt*vn/us);return vt+Math.max(Nn*et,Rn*at)}(L,O,Y):X;return{base:X+(j===0?-1:j),top:le?Math.max(xe+A,X+j+2):X+A}}const vRe=4096;class gds{constructor(x){this.module=x,this.memoryStack=this.module.malloc(vRe),this.memoryStackNextFree=this.memoryStack}createIntArray(x){const j=this.memoryStackNextFree;return this.memoryStackNextFree+=x.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>vRe?-1:(new Int32Array(this.module.heap32.buffer,j,x.length).set(x),j)}createFloatArray(x){const j=this.memoryStackNextFree;return this.memoryStackNextFree+=x.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>vRe?-1:(new Float32Array(this.module.heapF32.buffer,j,x.length).set(x),j)}readStringBuffer(x){let j="";for(;this.module.heapU8[x]!==0;)j+=String.fromCharCode(this.module.heapU8[x]),++x;return j}setStyle(x){const j=x.normalScale;this.module.setStyle(j[0],j[1],j[2],x.tileToMeters)}setAOOptions(x,j){this.module.setAOOptions(x?1:0,j)}setMetricOptions(x,j){this.module.setMetricOptions(x?1:0,j)}setStructuralOptions(x){this.module.setStructuralOptions(x?1:0)}setFacadeOptions(x,j){this.module.setFacadeOptions(x,j?1:0)}setFauxFacadeOptions(x,j,A){this.module.setFauxFacadeOptions(x?1:0,j?1:0,A)}setFacadeClassifierOptions(x){this.module.setFacadeClassifierOptions(x)}generateMesh(x,j){this.memoryStackNextFree=this.memoryStack;for(const Y of x){const X=this.createIntArray(Y.ringIndices),le=this.createFloatArray(Y.coordinates);if(X===-1||le===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(Y.id,Y.sourceId,Y.minHeight,Y.height,Y.roofType,le,X,Y.ringIndices.length-1)}for(const Y of j){let X;X=Y.entrances?JSON.parse(Y.entrances):[];const le=this.createFloatArray(X),xe=this.createFloatArray(Y.coordinates);if(le===-1||xe===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(Y.sourceId,Y.crossPerc,Y.distanceToRoad,le,X.length,xe,Y.coordinates.length)}if(!this.module.generateMesh()){const Y=this.module.getLastError();return this.readStringBuffer(Y)}const A=this.module.getMeshCount(),L=new Array(A);for(let Y=0;Y>2)-3,et=Ie[Fe++]>>2;if(Fe++,L.json=JSON.parse(hct.decode(Ie.subarray(Fe,Fe+et))),Fe+=et,Fe>>0,Math.ceil(1.2*At)),Bt=Math.ceil((Rt-At)/65536);try{return Ke.grow(Bt),et(),!0}catch{return!1}},b:at}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Ie,vt):Ie.then(pt=>pt.arrayBuffer()).then(pt=>WebAssembly.instantiate(pt,vt))).then(pt=>{const{Rb:At,Qb:Rt,P:Bt,T:Ns,X:us,Ja:ws,La:ys,Qa:vs,Va:vn,Wa:Nn,eb:Rn,jb:$n,f:Fn,e:sr,yb:gn,zb:Bn,Ab:Vn,Bb:nr,Db:yr,Gb:ra}=pt.instance.exports;Ke=sr;const Er=(()=>{let Cr=0,vr=0,ta=0,fa=0;return ei=>{ta&&(At(fa),At(Cr),vr+=ta,ta=Cr=0),Cr||(vr+=128,Cr=Rt(vr));const Aa=ei.length+7&-8;let zi=Cr;Aa>=vr&&(ta=Aa,zi=fa=Rt(Aa));for(let Xo=0;Xo{hk=Ie,sY=void 0}))}()),Ce&&xe.push(function(){if(bRe)return;const Ie=function(Fe){let Ke;const et=WebAssembly.instantiateStreaming(Fe,{}).then(pt=>{Ke=pt.instance,Ke.exports.__wasm_call_ctors()}),at={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},vt={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:et,supported:!0,decodeGltfBuffer(pt,At,Rt,Bt,Ns,us){(function(ws,ys,vs,vn,Nn,Rn,$n){const Fn=ws.exports.sbrk,sr=vn+3&-4,gn=Fn(sr*Nn),Bn=Fn(Rn.length),Vn=new Uint8Array(ws.exports.memory.buffer);Vn.set(Rn,Bn);const nr=ys(gn,vn,Nn,Bn,Rn.length);if(nr===0&&$n&&$n(gn,sr,Nn),vs.set(Vn.subarray(gn,gn+vn*Nn)),Fn(gn-Fn(0)),nr!==0)throw new Error(`Malformed buffer data: ${nr}`)})(Ke,Ke.exports[vt[Ns]],pt,At,Rt,Bt,Ke.exports[at[us]])}}}(fetch(ui()));return Ie.ready.then(()=>{bRe=Ie})}()),$)for(let Ie=0;Ie<$.length;Ie++)xe.push(jds($[Ie],L,Ie,j,A));if(xe.length&&await Promise.all(xe),A&&A.aborted)throw new DOMException("Aborted","AbortError");if(je&&Y)for(const{primitives:Ie}of Y)for(const Fe of Ie)bds(Fe,L);if(Ce&&Y&&le)for(const Ie of le)_ds(Ie,L);return L}async function xct(k,x){const j=await async function(A,L){if(L&&L.aborted)throw new DOMException("Aborted","AbortError");return new Promise((O,$)=>{const Y=vm(A,(X,le)=>{X?$(X):O(le)});L&&L.addEventListener("abort",()=>{Y.cancel(),$(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:k,type:"arrayBuffer"},x);return fct(j,0,k,x)}function wRe(k){switch(k){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 jRe(k){switch(k){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 y5{constructor(x,j,A,L){this.context=x,this.format=A,this.useMipmap=L&&L.useMipmap,this.texture=x.gl.createTexture(),this.update(j,{premultiply:L&&L.premultiply})}update(x,j){const A=x&&x instanceof HTMLVideoElement&&x.width===0?x.videoWidth:x.width,L=x&&x instanceof HTMLVideoElement&&x.height===0?x.videoHeight:x.height,{context:O}=this,{gl:$}=O,{x:Y,y:X}=j&&j.position?j.position:{x:0,y:0},le=Y+A,xe=X+L;this.size&&(this.size[0]!==le||this.size[1]!==xe)&&(!j||j.recreateWhenResize===void 0||j.recreateWhenResize)&&($.bindTexture($.TEXTURE_2D,null),$.deleteTexture(this.texture),this.texture=$.createTexture(),this.size=null),$.bindTexture($.TEXTURE_2D,this.texture),O.pixelStoreUnpackFlipY.set(!1),O.pixelStoreUnpack.set(1),O.pixelStoreUnpackPremultiplyAlpha.set(this.format===$.RGBA8&&(!j||j.premultiply!==!1));const je=x instanceof HTMLImageElement||x instanceof HTMLCanvasElement||x instanceof HTMLVideoElement||x instanceof ImageData||ImageBitmap&&x instanceof ImageBitmap;if(!this.size&&le>0&&xe>0){const Ce=this.useMipmap?Math.floor(Math.log2(Math.max(le,xe)))+1:1;$.texStorage2D($.TEXTURE_2D,Ce,this.format,le,xe),this.size=[le,xe]}this.size&&(je?$.texSubImage2D($.TEXTURE_2D,0,Y,X,wRe(this.format),jRe(this.format),x):"data"in x&&x.data&&$.texSubImage2D($.TEXTURE_2D,0,Y,X,A,L,wRe(this.format),jRe(this.format),x.data)),this.useMipmap&&$.generateMipmap($.TEXTURE_2D)}bind(x,j,A=!1){const{context:L}=this,{gl:O}=L;O.bindTexture(O.TEXTURE_2D,this.texture),x!==this.minFilter&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MAG_FILTER,x),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MIN_FILTER,this.useMipmap&&!A?x===O.NEAREST?O.NEAREST_MIPMAP_NEAREST:O.LINEAR_MIPMAP_LINEAR:x),this.minFilter=x),j!==this.wrapS&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_S,j),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_T,j),this.wrapS=j)}bindExtraParam(x,j,A,L,O){const{context:$}=this,{gl:Y}=$;Y.bindTexture(Y.TEXTURE_2D,this.texture),j!==this.magFilter&&(Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_MAG_FILTER,j),this.magFilter=j),x!==this.minFilter&&(Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_MIN_FILTER,this.useMipmap?x===Y.NEAREST?Y.NEAREST_MIPMAP_NEAREST:Y.LINEAR_MIPMAP_LINEAR:x),this.minFilter=x),A!==this.wrapS&&(Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_WRAP_S,A),this.wrapS=A),L!==this.wrapT&&(Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_WRAP_T,L),this.wrapT=L),O!==this.compareMode&&(O?(Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_COMPARE_MODE,Y.COMPARE_REF_TO_TEXTURE),Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_COMPARE_FUNC,O)):Y.texParameteri(Y.TEXTURE_2D,Y.TEXTURE_COMPARE_MODE,Y.NONE),this.compareMode=O)}destroy(){const{gl:x}=this.context;x.deleteTexture(this.texture),this.texture=null}}class rY{constructor(x,j){this.context=x,this.texture=j}bind(x,j){const{context:A}=this,{gl:L}=A;L.bindTexture(L.TEXTURE_2D,this.texture),x!==this.minFilter&&(L.texParameteri(L.TEXTURE_2D,L.TEXTURE_MAG_FILTER,x),L.texParameteri(L.TEXTURE_2D,L.TEXTURE_MIN_FILTER,x),this.minFilter=x),j!==this.wrapS&&(L.texParameteri(L.TEXTURE_2D,L.TEXTURE_WRAP_S,j),L.texParameteri(L.TEXTURE_2D,L.TEXTURE_WRAP_T,j),this.wrapS=j)}}const Nds=Wn([{name:"a_pos_3f",components:3,type:"Float32"}]),kds=Wn([{name:"a_color_3f",components:3,type:"Float32"}]),Sds=Wn([{name:"a_color_4f",components:4,type:"Float32"}]),Cds=Wn([{name:"a_uv_2f",components:2,type:"Float32"}]),Ads=Wn([{name:"a_normal_3f",components:3,type:"Float32"}]),Eds=Wn([{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"}]),Tds=Wn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function gct(k,x){const j=toe(k.projection,k.zoom,k.width,k.height),A=function(O,$,Y,X,le){const xe=new Ds(Y.lng-180*xT,Y.lat),je=new Ds(Y.lng+180*xT,Y.lat),Ce=O.project(xe.lng,xe.lat),Ie=O.project(je.lng,je.lat),Fe=-Math.atan2(Ie.y-Ce.y,Ie.x-Ce.x),Ke=pa.fromLngLat(Y);Ke.y=gt(Ke.y,-1+xT,1-xT);const et=Ke.toLngLat(),at=O.project(et.lng,et.lat),vt=pa.fromLngLat(et);vt.x+=xT;const pt=vt.toLngLat(),At=O.project(pt.lng,pt.lat),Rt=vct(At.x-at.x,At.y-at.y,Fe),Bt=pa.fromLngLat(et);Bt.y+=xT;const Ns=Bt.toLngLat(),us=O.project(Ns.lng,Ns.lat),ws=vct(us.x-at.x,us.y-at.y,Fe),ys=Math.abs(Rt.x)/Math.abs(ws.y),vs=v([]);P(vs,vs,-Fe*(1-(le?0:X)));const vn=v([]);return S(vn,vn,[1,1-(1-ys)*X,1]),vn[4]=-ws.x/ws.y*X,P(vn,vn,Fe),b(vn,vs,vn),vn}(k.projection,0,k.center,j,x),L=yct(k);return S(A,A,[L,L,1]),A}function yct(k){const x=k.projection,j=toe(k.projection,k.zoom,k.width,k.height),A=NRe(x,k.center),L=NRe(x,Ds.convert(x.center));return Math.pow(2,A*j+(1-j)*L)}function toe(k,x,j,A,L=1/0){const O=k.range;if(!O)return 0;const $=Math.min(L,Math.max(j,A)),Y=Math.log2($/1024);return ft(O[0]+Y,O[1]+Y,x)}const xT=1/4e4;function NRe(k,x){const j=gt(x.lat,-85.051129,In),A=new Ds(x.lng-180*xT,j),L=new Ds(x.lng+180*xT,j),O=k.project(A.lng,j),$=k.project(L.lng,j),Y=pa.fromLngLat(A),X=pa.fromLngLat(L),le=$.x-O.x,xe=$.y-O.y,je=X.x-Y.x,Ce=X.y-Y.y,Ie=Math.sqrt((je*je+Ce*Ce)/(le*le+xe*xe));return Math.log2(Ie)}function vct(k,x,j){const A=Math.cos(j),L=Math.sin(j);return{x:k*A-x*L,y:k*L+x*A}}function bct(k,x,j){v(k),P(k,k,Gs(x[2])),C(k,k,Gs(x[0])),E(k,k,Gs(x[1])),S(k,k,j),b(k,k,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function soe(k,x,j,A,L,O,$,Y){const X=[j[0]-x[0],j[1]-x[1],0],le=[A[0]-x[0],A[1]-x[1],0];if(H(X)<1e-12||H(le)<1e-12)return lt(k);const xe=Oe([],X,le);Ne(xe,xe),re(le,A,x),X[2]=(O-L)*Y,le[2]=($-L)*Y;const je=X;return Oe(je,X,le),Ne(je,je),qs(k,xe,je)}function noe(k,x,j=!1){const A=d3(x.zoom),L=function(O,$,Y){const X=$.worldSize,le=[O[12],O[13],O[14]],xe=yn(le[1]/X),je=Bs(le[0]/X),Ce=v([]),Ie=nn(1,xe)*X,Fe=nn(1,0)*X*xr(xe,$.zoom),Ke=1/YDe(X);let et=Fe*Ke;if(Y){const At=toe($.projection,$.zoom,$.width,$.height,1024);et=Ke*$.projection.pixelSpaceConversion($.center.lat,X,At)}const at=is(xe,je);oe(at,at,ce([],Ne([],at),Ie*et*le[2]));const vt=function(At){const Rt=[At[0],At[1],At[2]];let Bt=[0,1,0];const Ns=Oe([],Bt,Rt);return Oe(Bt,Rt,Ns),ge(Bt)===0&&(Bt=[0,1,0],Oe(Ns,Rt,Bt)),Ne(Ns,Ns),Ne(Bt,Bt),Ne(Rt,Rt),[Ns[0],Ns[1],Ns[2],0,Bt[0],Bt[1],Bt[2],0,Rt[0],Rt[1],Rt[2],0,At[0],At[1],At[2],1]}(at);S(Ce,Ce,[et,et,et*Ie]),w(Ce,Ce,[-le[0],-le[1],-le[2]]);const pt=b([],$.globeMatrix,vt);return b(pt,pt,Ce),b(pt,pt,O),pt}(k,x,j);if(A>0){const O=function($,Y){const X=Y.worldSize,le=nn(1,0)*X*xr(Y.center.lat,Y.zoom)/YDe(X),xe=nn(1,Y.center.lat)*X,je=v([]);E(je,je,Gs(Y.center.lng)),C(je,je,Gs(Y.center.lat)),w(je,je,[0,0,Xt]),S(je,je,[le,le,le*xe]);const Ce=Y.point;return w(je,je,[-Ce.x,-Ce.y,0]),b(je,je,$),b(je,Y.globeMatrix,je)}(k,x);return function($,Y,X){const le=(Fe,Ke,et)=>{const at=H(Fe),vt=H(Ke),pt=c3(Fe,Ke,et);return ce(pt,pt,1/H(pt)*Pr(at,vt,et))},xe=le([$[0],$[1],$[2]],[Y[0],Y[1],Y[2]],X),je=le([$[4],$[5],$[6]],[Y[4],Y[5],Y[6]],X),Ce=le([$[8],$[9],$[10]],[Y[8],Y[9],Y[10]],X),Ie=c3([$[12],$[13],$[14]],[Y[12],Y[13],Y[14]],X);return[xe[0],xe[1],xe[2],0,je[0],je[1],je[2],0,Ce[0],Ce[1],Ce[2],0,Ie[0],Ie[1],Ie[2],1]}(L,O,A)}return L}function kRe(k,x,j,A){const L=Kl.projectAabbCorners(A,j);let O=Number.MAX_VALUE;for(let Y=0;Y0||et===0&&Fe[0]*Ke[0]+Fe[1]*Ke[1]>=0&&Fe[0]*Fe[0]+Fe[1]*Fe[1]>Ke[0]*Ke[0]+Ke[1]*Ke[1])&&(xe=Ie)}je=xe}while(je!==le);return X.length>0&&X.push(X[0]),X}(L);if(vh(k,$))return O}const yI=64,Qz={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function roe(k,x,j,A,L,O,$,Y,X,le=!1){const xe=j.zoom,je=j.project(A),Ce=xr(A.lat,xe),Ie=1/Ce;v(k),w(k,k,[je.x+$[0]*Ie,je.y+$[1]*Ie,$[2]]);let Fe=1,Ke=1;const et=j.worldSize;if(le){if(j.projection.name==="mercator"){let At=0;j.elevation&&(At=j.elevation.getAtPointOrZero(new pa(je.x/et,je.y/et),0));const Rt=Je([],[je.x,je.y,At,1],j.projMatrix)[3]/j.cameraToCenterDistance;Fe=Rt,Ke=Rt*xr(j.center.lat,xe)}else if(j.projection.name==="globe"){const At=noe(k,j),Rt=[0,0,0,1];Je(Rt,Rt,b([],j.projMatrix,At));const Bt=Rt[3]/j.cameraToCenterDistance,Ns=d3(xe),us=j.projection.pixelsPerMeter(A.lat,et)*xr(A.lat,xe),ws=j.projection.pixelsPerMeter(j.center.lat,et)*xr(j.center.lat,xe);Fe=Bt/Pr(us,Sr(j.center.lat),Ns),Ke=Bt*Ce/us,Fe*=ws,Ke*=ws}}else Fe=Ie;S(k,k,[Fe,Fe,Ke]);const at=[...k],vt=x.orientation,pt=[];if(bct(pt,[vt[0]+(L?L[0]:0),vt[1]+(L?L[1]:0),vt[2]+(L?L[2]:0)],O),b(k,at,pt),Y&&j.elevation){let At=0;const Rt=[];if(X&&j.elevation){At=function(Ns,us,ws,ys,vs){const vn=us.elevation;if(!vn)return 0;const Nn=Kl.projectAabbCorners(ws,ys),Rn=nn(1,vs.lat)*us.worldSize,$n=function(vr,ta){const fa=[0,0,1],ei=[{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 Aa of ei){const zi=vr[Aa.corners[0]],Xo=vr[Aa.corners[1]],Bi=vr[Aa.corners[2]],sl=[Xo[0]-zi[0],Xo[1]-zi[1],ta*(Xo[2]-zi[2])],lo=Oe(sl,sl,[Bi[0]-zi[0],Bi[1]-zi[1],ta*(Bi[2]-zi[2])]);Ne(lo,lo),Aa.dotProductWithUp=Pe(lo,fa)}return ei.sort((Aa,zi)=>Aa.dotProductWithUp-zi.dotProductWithUp),ei[0].corners}(Nn,Rn),Fn=Nn[$n[0]],sr=Nn[$n[1]],gn=Nn[$n[2]],Bn=Nn[$n[3]],Vn=vn.getAtPointOrZero(new pa(Fn[0]/us.worldSize,Fn[1]/us.worldSize),0),nr=vn.getAtPointOrZero(new pa(sr[0]/us.worldSize,sr[1]/us.worldSize),0),yr=vn.getAtPointOrZero(new pa(gn[0]/us.worldSize,gn[1]/us.worldSize),0),ra=vn.getAtPointOrZero(new pa(Bn[0]/us.worldSize,Bn[1]/us.worldSize),0),Er=(Vn+ra)/2,Cr=(nr+yr)/2;return Er>Cr?nr=x.gl.NEAREST_MIPMAP_NEAREST}),k.uploaded=!0,k.image=null)}function Mds(k,x,j){k.indexBuffer=x.createIndexBuffer(k.indexArray,!1,!0),k.vertexBuffer=x.createVertexBuffer(k.vertexArray,Nds.members,!1,!0),k.normalArray&&(k.normalBuffer=x.createVertexBuffer(k.normalArray,Ads.members,!1,!0)),k.texcoordArray&&(k.texcoordBuffer=x.createVertexBuffer(k.texcoordArray,Cds.members,!1,!0)),k.colorArray&&(k.colorBuffer=x.createVertexBuffer(k.colorArray,(k.colorArray.bytesPerElement===12?kds:Sds).members,!1,!0)),k.featureArray&&(k.pbrBuffer=x.createVertexBuffer(k.featureArray,Tds.members,!0)),k.segments=Bc.simpleSegment(0,0,k.vertexArray.length,k.indexArray.length);const A=k.material;A.pbrMetallicRoughness.baseColorTexture&&aY(A.pbrMetallicRoughness.baseColorTexture,x),A.pbrMetallicRoughness.metallicRoughnessTexture&&aY(A.pbrMetallicRoughness.metallicRoughnessTexture,x),A.normalTexture&&aY(A.normalTexture,x),A.occlusionTexture&&aY(A.occlusionTexture,x,j),A.emissionTexture&&aY(A.emissionTexture,x)}function SRe(k,x,j){if(k.meshes)for(const A of k.meshes)Mds(A,x,j);if(k.children)for(const A of k.children)SRe(A,x,j)}function aoe(k){if(k.meshes)for(const x of k.meshes)x.indexArray.destroy(),x.vertexArray.destroy(),x.colorArray&&x.colorArray.destroy(),x.normalArray&&x.normalArray.destroy(),x.texcoordArray&&x.texcoordArray.destroy(),x.featureArray&&x.featureArray.destroy();if(k.children)for(const x of k.children)aoe(x)}function Pds(k){k.pbrMetallicRoughness.baseColorTexture&&k.pbrMetallicRoughness.baseColorTexture.gfxTexture&&k.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),k.pbrMetallicRoughness.metallicRoughnessTexture&&k.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&k.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),k.normalTexture&&k.normalTexture.gfxTexture&&k.normalTexture.gfxTexture.destroy(),k.emissionTexture&&k.emissionTexture.gfxTexture&&k.emissionTexture.gfxTexture.destroy(),k.occlusionTexture&&k.occlusionTexture.gfxTexture&&k.occlusionTexture.gfxTexture.destroy()}function CRe(k){if(k.meshes)for(const x of k.meshes)x.vertexBuffer&&(x.vertexBuffer.destroy(),x.indexBuffer.destroy(),x.normalBuffer&&x.normalBuffer.destroy(),x.texcoordBuffer&&x.texcoordBuffer.destroy(),x.colorBuffer&&x.colorBuffer.destroy(),x.pbrBuffer&&x.pbrBuffer.destroy(),x.segments.destroy(),x.material&&Pds(x.material));if(k.footprintDebugMesh&&(k.footprintDebugMesh.vertexBuffer.destroy(),k.footprintDebugMesh.indexBuffer.destroy(),k.footprintDebugMesh.segments.destroy()),k.children)for(const x of k.children)CRe(x)}function vI(k,x){const j=k.json.bufferViews[x.bufferView],A=Jie[x.componentType];return new A(k.buffers[j.buffer],(x.byteOffset||0)+(j.byteOffset||0),x.count*(j.byteStride&&j.byteStride!==nY[x.type]*A.BYTES_PER_ELEMENT?j.byteStride/A.BYTES_PER_ELEMENT:nY[x.type]))}function ARe(k,x,j,A){const L=Jie[x.componentType],O=function(xe){switch(xe){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(L),$=k.json.bufferViews[x.bufferView],Y=$.byteStride?$.byteStride/L.BYTES_PER_ELEMENT:nY[x.type],X=j.float32,le=X.length/j.capacity;for(let xe=0,je=0;xe0){for(let et=0;et0){O.texcoordArray=new a3;const Ce=x.json.accessors[L.TEXCOORD_0];O.texcoordArray.resize(Ce.count);const Ie=vI(x,Ce);ARe(x,Ce,O.texcoordArray,Ie)}if(L._FEATURE_ID_RGBA4444!==void 0){const Ce=x.json.accessors[L._FEATURE_ID_RGBA4444];x.json.extensionsUsed&&x.json.extensionsUsed.includes("EXT_meshopt_compression")&&(O.featureData=vI(x,Ce))}L._FEATURE_RGBA4444!==void 0&&(O.featureData=new Uint32Array(vI(x,x.json.accessors[L._FEATURE_RGBA4444]).buffer));const je=k.material;return O.material=function(Ce,Ie){const{emissiveFactor:Fe=[0,0,0],alphaMode:Ke="OPAQUE",alphaCutoff:et=.5,normalTexture:at,occlusionTexture:vt,emissiveTexture:pt,doubleSided:At,name:Rt}=Ce,{baseColorFactor:Bt=[1,1,1,1],metallicFactor:Ns=1,roughnessFactor:us=1,baseColorTexture:ws,metallicRoughnessTexture:ys}=Ce.pbrMetallicRoughness||{},vs=vt?Ie[vt.index]:void 0;if(vt&&vt.extensions&&vt.extensions.KHR_texture_transform&&vs){const vn=vt.extensions.KHR_texture_transform;vs.offsetScale=[vn.offset[0],vn.offset[1],vn.scale[0],vn.scale[1]]}return{name:Rt,pbrMetallicRoughness:{baseColorFactor:new Js(...Bt),metallicFactor:Ns,roughnessFactor:us,baseColorTexture:ws?Ie[ws.index]:void 0,metallicRoughnessTexture:ys?Ie[ys.index]:void 0},doubleSided:At,emissiveFactor:new Js(...Fe),alphaMode:Ke,alphaCutoff:et,normalTexture:at?Ie[at.index]:void 0,occlusionTexture:vs,emissionTexture:pt?Ie[pt.index]:void 0,defined:Ce.defined===void 0}}(je!==void 0?x.json.materials[je]:{defined:!1},j),O}function wct(k,x,j){const{matrix:A,rotation:L,translation:O,scale:$,mesh:Y,extras:X,children:le,name:xe}=k,je={};if(je.name=xe,je.localMatrix=A||function(Ce,Ie,Fe,Ke){var et=Ie[0],at=Ie[1],vt=Ie[2],pt=Ie[3],At=et+et,Rt=at+at,Bt=vt+vt,Ns=et*At,us=et*Rt,ws=et*Bt,ys=at*Rt,vs=at*Bt,vn=vt*Bt,Nn=pt*At,Rn=pt*Rt,$n=pt*Bt,Fn=Ke[0],sr=Ke[1],gn=Ke[2];return Ce[0]=(1-(ys+vn))*Fn,Ce[1]=(us+$n)*Fn,Ce[2]=(ws-Rn)*Fn,Ce[3]=0,Ce[4]=(us-$n)*sr,Ce[5]=(1-(Ns+vn))*sr,Ce[6]=(vs+Nn)*sr,Ce[7]=0,Ce[8]=(ws+Rn)*gn,Ce[9]=(vs-Nn)*gn,Ce[10]=(1-(Ns+ys))*gn,Ce[11]=0,Ce[12]=Fe[0],Ce[13]=Fe[1],Ce[14]=Fe[2],Ce[15]=1,Ce}([],L||[0,0,0,1],O||[0,0,0],$||[1,1,1]),je.globalMatrix=g(je.localMatrix),Y!==void 0){je.meshes=j[Y];const Ce=je.anchor=[0,0];for(const Ie of je.meshes){const{min:Fe,max:Ke}=Ie.aabb;Ce[0]+=Fe[0]+Ke[0],Ce[1]+=Fe[1]+Ke[1]}Ce[0]=Math.floor(Ce[0]/je.meshes.length/2),Ce[1]=Math.floor(Ce[1]/je.meshes.length/2)}if(X&&(X.id&&(je.id=X.id),X.lights&&(je.lights=function(Ce){if(!Ce.length)return[];const Ie=function(vt){const pt=atob(vt),At=new Uint8Array(pt.length);for(let Rt=0;Rt1&&A[A.length-1].equals(A[0])&&A.pop();let L=0;for(let $=0;$0&&A.reverse();const O=Wz(A.flatMap($=>[$.x,$.y]),[]);return O.length===0?null:{vertices:A,indices:O}}function Rds(k,x){const j=[],A=[];let L=0;const O=[];for(const $ of k){L=j.length;const Y=$.vertexArray.float32,X=$.indexArray.uint16;for(let le=0;le<$.vertexArray.length;le++)O[0]=Y[3*le+0],O[1]=Y[3*le+1],O[2]=Y[3*le+2],Ve(O,O,x),j.push(new Ss(O[0],O[1]));for(let le=0;le<3*$.indexArray.length;le++)A.push(X[le]+L)}if(A.length%3!=0)return null;for(let $=0;$0&&([A[$+1],A[$+2]]=[A[$+2],A[$+1]])}return{vertices:j,indices:A}}function ERe(k){const x=function(X,le){const xe=[],je=WebGL2RenderingContext;if(X.json.textures)for(const Ce of X.json.textures){const Ie={magFilter:je.LINEAR,minFilter:je.NEAREST,wrapS:je.REPEAT,wrapT:je.REPEAT};Ce.sampler!==void 0&&Object.assign(Ie,X.json.samplers[Ce.sampler]),xe.push({image:le[Ce.source],sampler:Ie,uploaded:!1})}return xe}(k,k.images),j=function(X,le){const xe=[];for(const je of X.json.meshes){const Ce=[];for(const Ie of je.primitives)Ce.push(Lds(Ie,X,le));xe.push(Ce)}return xe}(k,x),{scenes:A,scene:L,nodes:O}=k.json,$=A?A[L||0].nodes:[...O.keys()],Y=[];for(const X of $)Y.push(wct(O[X],k,j));return function(X,le,xe){const je={},Ce=new Set;for(let Ie=0;Ie0){const Ie=Array.from(Ce.values()).sort((Fe,Ke)=>Fe-Ke);for(let Fe=Ie.length-1;Fe>=0;Fe--)X.splice(Ie[Fe],1)}}(Y,$,k.json.nodes),Y}function Fds(k){k.heightmap=new Float32Array(4096),k.heightmap.fill(-1);const x=k.vertexArray.float32,j=k.aabb.min[0]-1,A=k.aabb.min[1]-1,L=yI/(k.aabb.max[0]-j+2),O=yI/(k.aabb.max[1]-A+2);for(let $=0;$k.heightmap[le*yI+X]&&(k.heightmap[le*yI+X]=Y)}}function jct(k,x,j,A,L){j.reserve(j.length+4*k.length),A.reserve(A.length+10*k.length),L.reserve(L.length+10*k.length);let O=A.length;for(const $ of k){const Y=Math.min(10,Math.max(4,1.3*$.height))*x,X=[-$.normal[1],$.normal[0],0],le=Math.min(.29,.1*$.width/$.depth),xe=$.width-2*$.depth*x*(le+.01),je=ve([],$.pos,X,xe/2),Ce=ve([],$.pos,X,-xe/2),Ie=[je[0],je[1],je[2]+$.height],Fe=[Ce[0],Ce[1],Ce[2]+$.height],Ke=ve([],$.normal,X,le);ce(Ke,Ke,Y);const et=ve([],$.normal,X,-le);ce(et,et,Y),oe(Ke,je,Ke),oe(et,Ce,et),je[2]+=.1,Ce[2]+=.1,A.emplaceBack(Ke[0],Ke[1],Ke[2]),A.emplaceBack(et[0],et[1],et[2]),A.emplaceBack(je[0],je[1],je[2]),A.emplaceBack(Ce[0],Ce[1],Ce[2]),A.emplaceBack(Ie[0],Ie[1],Ie[2]),A.emplaceBack(Fe[0],Fe[1],Fe[2]),A.emplaceBack(je[0],je[1],je[2]),A.emplaceBack(Ce[0],Ce[1],Ce[2]),A.emplaceBack(Ke[0],Ke[1],Ke[2]),A.emplaceBack(et[0],et[1],et[2]);const at=xe/Y/2;L.emplaceBack(-at-le,-1,at,.8),L.emplaceBack(at+le,-1,at,.8),L.emplaceBack(-at,0,at,1.3),L.emplaceBack(at,0,at,1.3),L.emplaceBack(at+le,-.8,at,.7),L.emplaceBack(at+le,-.8,at,.7),L.emplaceBack(0,0,at,1.3),L.emplaceBack(0,0,at,1.3),L.emplaceBack(at+le,-1.2,at,.8),L.emplaceBack(at+le,-1.2,at,.8),j.emplaceBack(6+O,4+O,8+O),j.emplaceBack(7+O,9+O,5+O),j.emplaceBack(0+O,1+O,2+O),j.emplaceBack(1+O,3+O,2+O),O+=10}}function Ods(k,x){const j={};j.indexArray=new Qu,j.vertexArray=new Xb,j.colorArray=new dk,jct(k,x,j.indexArray,j.vertexArray,j.colorArray);const A={defined:!0};A.emissiveFactor=Js.black;const L={};return L.baseColorFactor=Js.white,A.pbrMetallicRoughness=L,j.material=A,j.aabb=new Kl([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),j}const Nct=Wn([{name:"a_pos_3f",components:3,type:"Float32"}]),zds=Wn([{name:"a_normal_3",components:3,type:"Int16"}]),Bds=Wn([{name:"a_centroid_3",components:3,type:"Int16"}]),kct=Wn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),$ds=Wn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Uds=Wn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),qds=Wn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Vds=Wn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),Hds=Wn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),Sct=Si.types,ioe=32767;function Gds(k,x){const j=fr+x;for(const A of k)for(const L of A)if(L.x<-x||L.x>j||L.y<-x||L.y>j)return!1;return!0}function Wds(k){switch(k){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: ${k}`)}}class TRe{constructor(){this.layoutVertexArray=new Xb,this.layoutAttenuationArray=new dk,this.layoutColorArray=new Qb,this.indexArray=new Qu,this.indexArrayForConflation=new Qu,this.segmentsBucket=new Bc}}class MRe{constructor(x){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Bc,this.entranceBloom=new TRe;const j=66560;this.layoutVertexArray=new Xb,this.layoutVertexArray.reserve(j),this.layoutNormalArray=new xl,this.layoutNormalArray.reserve(j),this.layoutCentroidArray=new xl,this.layoutCentroidArray.reserve(j),this.layoutColorArray=new Qb,this.layoutColorArray.reserve(j),this.layoutFloodLightDataArray=new $z,this.layoutFloodLightDataArray.reserve(j),this.layoutAOArray=new Uz,this.layoutAOArray.reserve(j),this.indexArray=new Qu,this.indexArray.reserve(66560),this.indexArrayForConflation=new Qu,this.segmentsBucket=new Bc,this.entranceBloom=new TRe,x&&(this.layoutFacadePaintArray=new Qb,this.layoutFacadeDataArray=new cT,this.layoutFacadeVerticalRangeArray=new Qb)}reserve(x,j,A){this.layoutVertexArray.reserveForAdditional(x),this.layoutCentroidArray.reserveForAdditional(x),this.layoutFloodLightDataArray.reserveForAdditional(x),this.layoutNormalArray.reserveForAdditional(x),this.layoutAOArray.reserveForAdditional(x),this.layoutColorArray.reserveForAdditional(x),this.indexArray.reserveForAdditional(j),A&&(this.layoutFacadePaintArray.reserveForAdditional(x),this.layoutFacadeDataArray.reserveForAdditional(x),this.layoutFacadeVerticalRangeArray.reserveForAdditional(x))}}class Cct{constructor(x){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new a3,this.footprintsIndices=new i3,this.footprintsMin=new Ss(1/0,1/0),this.footprintsMax=new Ss(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new MRe(!1),this.buildingWithFacade=new MRe(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=x.zoom,this.canonical=x.canonical,this.layers=x.layers,this.layerIds=this.layers.map(j=>j.fqid),this.index=x.index,this.hasPattern=!1,this.worldview=x.worldview,this.lut=x.lut,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.id),this.projection=x.projection,this.groundEffect=new gRe(x),this.groundEffect.groundRadiusArray=new Jl,this.hasAppearances=null}updateFootprints(x,j){const A=new qie([],[],1),L={vertices:[],indices:new Uint32Array(0),grid:A,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};j.push({footprint:L,id:x})}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(Qie!=null||nct!=null)return null;if(Xz!=null)return Xz;const x=fetch(zo());return Xz=function(j){let A,L,O,$,Y;function X(){A=new Uint8Array(Y.buffer),L=new Int16Array(Y.buffer),O=new Int32Array(Y.buffer),$=new Float32Array(Y.buffer)}function le(){throw new Error("Unexpected BuildingGen error.")}const xe=()=>{},je={a:{a:le,f:function(Ce){const Ie=A.length,Fe=Math.max(Ce>>>0,Math.ceil(1.2*Ie)),Ke=Math.ceil((Fe-Ie)/65536);try{return Y.grow(Ke),X(),!0}catch{return!1}},g:le,b:xe,c:xe,d:xe,e:xe}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(j,je):j.then(Ce=>Ce.arrayBuffer()).then(Ce=>WebAssembly.instantiate(Ce,je))).then(Ce=>{const Ie=Ce.instance.exports;return(0,Ie.g)(),Y=Ie.f,X(),new gds({setStyle:Ie.h,setAOOptions:Ie.i,setMetricOptions:Ie.j,setStructuralOptions:Ie.k,setFacadeOptions:Ie.l,setFauxFacadeOptions:Ie.m,setFacadeClassifierOptions:Ie.n,addFeature:Ie.o,addFacade:Ie.p,generateMesh:Ie.q,getLastError:Ie.r,getOuterRingLength:Ie.s,getMeshCount:Ie.t,getPositionsPtr:Ie.u,getPositionsLength:Ie.v,getNormalsPtr:Ie.w,getNormalsLength:Ie.x,getAOPtr:Ie.y,getAOLength:Ie.z,getUVPtr:Ie.A,getUVLength:Ie.B,getFauxFacadePtr:Ie.C,getFauxFacadeLength:Ie.D,getIndicesPtr:Ie.E,getIndicesLength:Ie.F,getBuildingPart:Ie.G,getRingCount:Ie.H,getRingPtr:Ie.I,getRingLength:Ie.J,malloc:Ie.K,free:Ie.L,heapU8:A,heap16:L,heap32:O,heapF32:$})})}(x).then(j=>(Xz=null,Qie=j,Qie)).catch(j=>{aa("Could not load building-gen"),Xz=null,nct=j instanceof Error?j:new Error("Unknown error")}),Xz}()}populate(x,j,A,L){const O=yds();if(!O)return;const $=Kn(A);this.tileToMeter=$,this.brightness=j.brightness,O.setStyle({normalScale:[1,-1,$],tileToMeters:$}),O.setAOOptions(!1,.3),O.setMetricOptions(!1,16),O.setStructuralOptions(!0),O.setFacadeClassifierOptions(3);const Y=new Map,X=new Map;let le=0;for(const{feature:at}of x){if(Sct[at.type]!=="LineString"){Y.set(at.id,at.properties.source_id);continue}const vt=this.layers[0]._featureFilter.needGeometry;if(vt&&!this.layers[0]._featureFilter.filter(new Vi(this.zoom),at,A))continue;const pt=oo(at,vt);if(!vt&&!this.layers[0]._featureFilter.filter(new Vi(this.zoom),pt,A))continue;const At=vt?pt.geometry:ti(at,A,L),Rt=[];for(const ws of At)for(const ys of ws)Rt.push(ys.x),Rt.push(ys.y);const Bt={coordinates:Rt,crossPerc:at.properties.cross_perc,distanceToRoad:at.properties.distance_to_road,entrances:at.properties.entrances,sourceId:0},Ns=at.properties.source_id;let us=X.get(Ns);us||(us=[],X.set(Ns,us)),us.push(Bt),++le}this.maxHeight=0;const xe=new Array,je=new Set,Ce=at=>{at!=null&&je.add(at)},Ie=(at,vt)=>{at!=null&&xe.push({buildingId:at,footprintIndex:vt})},Fe=64*(x.length-le),Ke=Fe/2;this.buildingWithFacade.reserve(Fe,Ke,!0),this.buildingWithoutFacade.reserve(2*Fe,2*Ke,!1),this.footprintsIndices.reserve(16*(x.length-le)),this.footprintsVertices.reserve(8*(x.length-le));for(const{feature:at,id:vt,index:pt,sourceLayerIndex:At}of x){if(Sct[at.type]==="LineString")continue;const Rt=this.layers[0]._featureFilter.needGeometry;if(Rt&&!this.layers[0]._featureFilter.filter(new Vi(this.zoom),at,A))continue;let Bt=null;if(at.properties&&at.properties.hasOwnProperty("building_id")&&(Bt=Number(at.properties.building_id),je.has(Bt)))continue;const Ns=oo(at,Rt);if(!Rt&&!this.layers[0]._featureFilter.filter(new Vi(this.zoom),Ns,A))continue;const us=Rt?Ns.geometry:ti(at,A,L),ws=KK(us,500);let ys=!1;for(const _o of ws)if(_o.length!==1){ys=!0;break}if(ys){Ce(Bt);continue}if(!Gds(us,163)){Ce(Bt);continue}const vs=this.layers[0],vn=Wds(vs.layout.get("building-roof-shape").evaluate(at,{},A)),Nn=vs.layout.get("building-base").evaluate(at,{},A),Rn=vs.layout.get("building-height").evaluate(at,{},A),$n=vs.layout.get("building-flood-light-ground-radius").evaluate(at,{},A),Fn=vs.paint.get("building-ambient-occlusion-intensity"),sr=$n/this.tileToMeter;at.properties["building-part"]="roof";const gn=vs.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),Bn=vs.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="wall";const Vn=vs.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),nr=vs.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="window";const yr=vs.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),ra=vs.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="door";const Er=vs.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),Cr=vs.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);let vr=vs.layout.get("building-flood-light-wall-radius").evaluate(at,{},A);vr=gt(vr,0,2048);const ta=vr/2048*ioe,fa=Y.get(vt),ei=X.get(fa)||[],Aa=ei.length!==0&&vs.layout.get("building-facade").evaluate(at,{},A);O.setFacadeOptions(4,!0),O.setFauxFacadeOptions(Aa,!1,1);let zi=0,Xo=0,Bi=0,sl=0,lo=0,Lu=0,Dl=0,hl=0,qc=0,ku=0,Hp=0;if(Aa){let _o=Math.round(vs.layout.get("building-facade-floors").evaluate(at,{},A));if(Nn===0){_o=Math.max(1,_o-(ei.length>0?1:0));let th=4;if(Rn>100){const vp=[10,13,15];th=vp[at.id?at.id%vp.length:0]}else Rn<=10&&(th=3);O.setFacadeOptions(th,!0),lo=(Rn<15?1.3:1.61803)*th/$}else lo=Nn/$;Lu=Rn/$,lo=Math.min(lo,Lu),Bi=vs.layout.get("building-facade-unit-width").evaluate(at,{},A)/$,sl=(Lu-lo)/_o,O.setFauxFacadeOptions(!0,!0,Bi);const Nf=vs.layout.get("building-facade-window").evaluate(at,{},A);zi=Nf[0],Xo=Nf[1],Dl=Math.floor(65535*Math.min(1,lo/fr)),hl=Math.floor(65535*Math.min(1,Lu/fr)),qc=Math.floor(255*zi)<<8|Math.floor(255*Xo),ku=Math.floor(65535*Math.min(1,Bi/fr)),Hp=Math.floor(65535*Math.min(1,sl/fr))}const Su=Array(ws.length),Ju={x:1/0,y:1/0},sm={x:-1/0,y:-1/0},eh={x:0,y:0};let Zx=0;for(let _o=0;_o0){const th=[],vp=Array(Nf.length+1);vp[0]=0;for(let gw=0;gwfr||Ju.y<0||sm.y>fr)&&this.featuresOnBorder.push({featureId:at.id,footprintIndex:this.footprints.length});{const _o=Wz(x3,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+_o.length),this.footprintsIndices.uint16.set(_o,uB),this.buildingIds.add(Bt??at.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,fw.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,fw.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,xw.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,xw.y);const Nf={footprintVertexOffset:f3,footprintVertexLength:this.footprintsVertices.length-f3,footprintIndexOffset:uB,footprintIndexLength:this.footprintsIndices.length-uB,min:fw,max:xw,hiddenFlags:0,indicesOffset:Doe,indicesLength:_Fe,bloomIndicesOffset:Xx,bloomIndicesLength:Iu,groundEffectVertexOffset:SI,groundEffectVertexLength:hB,hasFauxFacade:Aa,height:dB,promoteId:vt,feature:Ns,parts:wf,buildingBloom:Xy},th=this.footprints.length;at.id!==void 0&&this.featureFootprintLookup.set(at.id,th),Ie(Bt,th),this.footprints.push(Nf)}this.programConfigurations.populatePaintArrays(xo.layoutVertexArray.length,at,pt,{},j.availableImages,A,j.brightness),this.groundEffect.addPaintPropertiesData(at,pt,{},j.availableImages,A,j.brightness),j.featureIndex.insert(at,us,pt,At,this.index,ty)}xe.forEach(({buildingId:at,footprintIndex:vt})=>{je.has(at)&&(this.footprints[vt].hiddenFlags|=4)});const et=new Set;this.buildingIds.forEach((at,vt,pt)=>{je.has(at)||et.add(at)}),this.buildingIds=et,this.groundEffect.prepareBorderSegments()}update(x,j,A,L,O,$,Y){this.programConfigurations.updatePaintArrays(x,j,O,A,L,$,Y),this.groundEffect.update(x,j,O,A,L,$,Y),this.evaluate(this.layers[0],x),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(x){const j=A=>{A.layoutVertexBuffer=x.createVertexBuffer(A.layoutVertexArray,Nct.members),A.layoutNormalBuffer=x.createVertexBuffer(A.layoutNormalArray,zds.members),A.layoutCentroidBuffer=x.createVertexBuffer(A.layoutCentroidArray,Bds.members),A.layoutFloodLightDataBuffer=x.createVertexBuffer(A.layoutFloodLightDataArray,Hds.members),A.layoutFacadeDataArray&&A.layoutFacadeDataArray.length&&(A.layoutFacadeDataBuffer=x.createVertexBuffer(A.layoutFacadeDataArray,Uds.members)),A.layoutFacadeVerticalRangeArray&&A.layoutFacadeVerticalRangeArray.length&&(A.layoutFacadeVerticalRangeBuffer=x.createVertexBuffer(A.layoutFacadeVerticalRangeArray,qds.members)),A.entranceBloom.layoutVertexArray.length&&(A.entranceBloom.layoutVertexBuffer=x.createVertexBuffer(A.entranceBloom.layoutVertexArray,Nct.members),A.entranceBloom.layoutAttenuationBuffer=x.createVertexBuffer(A.entranceBloom.layoutAttenuationArray,Vds.members)),this.uploadUpdatedColorBuffer(x),this.uploadUpdatedIndexBuffer(x)};this.uploaded||(j(this.buildingWithoutFacade),j(this.buildingWithFacade),this.groundEffect.upload(x)),this.groundEffect.uploadPaintProperties(x),this.programConfigurations.upload(x),this.uploaded=!0}destroy(){const x=j=>{j.layoutVertexBuffer&&(j.layoutVertexBuffer.destroy(),j.layoutNormalBuffer.destroy(),j.layoutColorBuffer.destroy(),j.segmentsBucket.destroy(),j.indexBuffer&&j.indexBuffer.destroy(),j.entranceBloom.layoutVertexBuffer&&(j.entranceBloom.layoutVertexBuffer.destroy(),j.entranceBloom.layoutColorBuffer.destroy(),j.entranceBloom.layoutAttenuationBuffer.destroy(),j.entranceBloom.indexBuffer.destroy(),j.entranceBloom.segmentsBucket.destroy()))};x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(x,j,A=!0){let L=!1;const O=A?j:0,$=0|(A?-1:~j);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const Y of x){const X=this.footprints[Y],le=X.hiddenFlags&$|O;X.hiddenFlags!==le&&(X.hiddenFlags=le,L=!0,this.groundEffect.updateHiddenByLandmarkRange(X.groundEffectVertexOffset,X.groundEffectVertexLength,X.hiddenFlags!==0))}return L&&(this.indexArrayForConflationUploaded=!1),L}uploadUpdatedIndexBuffer(x){if(this.groundEffect.uploadHiddenByLandmark(x),this.indexArrayForConflationUploaded)return;const j=L=>{L.indexArray.length!==0&&(L.indexArrayForConflation.resize(L.indexArray.length),L.indexArrayForConflation.uint16.set(L.indexArray.uint16),L.entranceBloom.indexArrayForConflation.resize(L.entranceBloom.indexArray.length),L.entranceBloom.indexArrayForConflation.uint16.set(L.entranceBloom.indexArray.uint16))};j(this.buildingWithoutFacade),j(this.buildingWithFacade);for(const L of this.footprints){const O=L.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,$=L.indicesOffset+L.indicesLength;if(L.hiddenFlags!==0){for(let X=L.indicesOffset;X<$;X++)O.indexArrayForConflation.uint16[3*X+0]=0,O.indexArrayForConflation.uint16[3*X+1]=0,O.indexArrayForConflation.uint16[3*X+2]=0;const Y=L.bloomIndicesOffset+L.bloomIndicesLength;for(let X=L.bloomIndicesOffset;X{L.indexArray.length!==0&&(L.indexBuffer?L.indexBuffer.updateData(L.indexArrayForConflation):L.indexBuffer=x.createIndexBuffer(L.indexArrayForConflation,!0),L.entranceBloom.indexBuffer?L.entranceBloom.indexBuffer.updateData(L.entranceBloom.indexArrayForConflation):L.entranceBloom.indexBuffer=x.createIndexBuffer(L.entranceBloom.indexArrayForConflation,!0))};A(this.buildingWithoutFacade),A(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(x){const j=A=>{A.layoutColorBuffer?A.layoutColorBuffer.updateData(A.layoutColorArray):A.layoutColorBuffer=x.createVertexBuffer(A.layoutColorArray,kct.members,!0),A.layoutFacadePaintArray&&(A.layoutFacadePaintBuffer?A.layoutFacadePaintBuffer.updateData(A.layoutFacadePaintArray):A.layoutFacadePaintBuffer=x.createVertexBuffer(A.layoutFacadePaintArray,$ds.members,!0)),A.entranceBloom.layoutColorBuffer?A.entranceBloom.layoutColorBuffer.updateData(A.entranceBloom.layoutColorArray):A.entranceBloom.layoutColorBuffer=x.createVertexBuffer(A.entranceBloom.layoutColorArray,kct.members,!0)};j(this.buildingWithoutFacade),j(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(x,j){const A=x.paint.get("building-ambient-occlusion-intensity");for(const L of this.footprints){if(4&L.hiddenFlags)continue;const O=j[L.promoteId],$=L.feature;$.properties["building-part"]="roof";const Y=x.paint.get("building-color").evaluate($,O,this.canonical).toPremultipliedRenderColor(this.lut),X=x.paint.get("building-emissive-strength").evaluate($,O,this.canonical);$.properties["building-part"]="wall";const le=x.paint.get("building-color").evaluate($,O,this.canonical).toPremultipliedRenderColor(this.lut),xe=x.paint.get("building-emissive-strength").evaluate($,O,this.canonical);$.properties["building-part"]="window";const je=x.paint.get("building-color").evaluate($,O,this.canonical).toPremultipliedRenderColor(this.lut),Ce=x.paint.get("building-emissive-strength").evaluate($,O,this.canonical);$.properties["building-part"]="door";const Ie=x.paint.get("building-color").evaluate($,O,this.canonical).toPremultipliedRenderColor(this.lut),Fe=x.paint.get("building-emissive-strength").evaluate($,O,this.canonical),Ke=L.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const at of L.parts){let vt,pt=Y;at.part===1?(pt=Y,vt=X):at.part===0?(pt=le,vt=xe):at.part===2?(pt=je,vt=Ce):at.part===3&&(pt=Ie,vt=Fe),vt=gt(vt,0,1);for(let At=0;At$.max.x||X.max.x<$.min.x||X.min.y>$.max.y||X.max.y<$.min.y||(O.length=0,Yds(this.footprintsVertices,X.footprintVertexOffset,X.footprintVertexLength,$.footprintTileId.canonical,x.canonical,O),hRe($.footprint,O,this.footprintsIndices.uint16,X.footprintIndexOffset,X.footprintIndexLength,0,-Y)&&(X.hiddenFlags|=1))}this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const $ of this.footprints)this.groundEffect.updateHiddenByLandmarkRange($.groundEffectVertexOffset,$.groundEffectVertexLength,$.hiddenFlags!==0);this.indexArrayForConflationUploaded=!1}getFootprint(x){if(x.id!==void 0){const j=this.featureFootprintLookup.get(x.id);return this.footprints[j]}return null}getHeightAtTileCoord(x,j){let A=Number.NEGATIVE_INFINITY,L=!0;const O=4*(x+fr)*fr+(j+fr);if(this.footprintLookup.hasOwnProperty(O)){const Y=this.footprintLookup[O];return Y?{height:Y.height,hidden:Y.hiddenFlags!==0}:void 0}const $=new Ss(x,j);for(const Y of this.footprints)x>Y.max.x||Y.min.x>x||j>Y.max.y||Y.min.y>j||Y.height<=A||Kds($,this.footprintsVertices.float32.subarray(2*Y.footprintVertexOffset,2*(Y.footprintVertexOffset+Y.footprintVertexLength)),this.footprintsIndices.uint16.subarray(Y.footprintIndexOffset,Y.footprintIndexOffset+Y.footprintIndexLength))&&(A=Y.height,this.footprintLookup[O]=Y,L=Y.hiddenFlags!==0);if(A!==Number.NEGATIVE_INFINITY)return{height:A,hidden:L};this.footprintLookup[O]=void 0}}function Kds(k,x,j){for(let A=0;A1&&(X=x[++Y]);const xe=Math.abs(le-X.left),je=Math.abs(le-X.right),Ce=Math.min(xe,je);let Ie;const Fe=O/A*(L+1);if(X.isDash){const Ke=L-Math.abs(Fe);Ie=Math.sqrt(Ce*Ce+Ke*Ke)}else Ie=L-Math.sqrt(Ce*Ce+Fe*Fe);this.image.data[$+le]=Math.max(0,Math.min(255,Ie+128))}}}addRegularDash(x,j){for(let X=x.length-1;X>=0;--X){const le=x[X],xe=x[X+1];le.zeroLength?x.splice(X,1):xe&&xe.isDash===le.isDash&&(xe.left=le.left,x.splice(X,1))}const A=x[0],L=x[x.length-1];A.isDash===L.isDash&&(A.left=L.left-this.width,L.right=A.right+this.width);const O=this.width*this.nextRow;let $=0,Y=x[$];for(let X=0;X1&&(Y=x[++$]);const le=Math.abs(X-Y.left),xe=Math.abs(X-Y.right),je=Math.min(le,xe);this.image.data[O+X]=Math.max(0,Math.min(255,(Y.isDash?je:-je)+j+128))}}addDash(x,j){const A=this.getKey(x,j);if(this.positions[A])return this.positions[A];const L=j==="round",O=L?7:0,$=2*O+1;if(this.nextRow+$>this.height)return aa("LineAtlas out of space"),null;x.length===0&&x.push(1);let Y=0;for(let je=0;jej.fqid),this.index=x.index,this.projection=x.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(j=>{this.gradients[j.id]={}}),this.layoutVertexArray=new rI,this.layoutVertexArray2=new Xb,this.patternVertexArray=new Xb,this.indexArray=new Qu,this.programConfigurations=new tt(x.layers,{zoom:x.zoom,lut:x.lut}),this.segments=new Bc,this.maxLineLength=0,this.zOffsetVertexArray=new Xb,this.elevationGroundScaleVertexArray=new Jl,this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.id),this.tessellationStep=x.tessellationStep?x.tessellationStep:128,this.worldview=x.worldview,this.hasAppearances=null}updateFootprints(x,j){}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,j,A,L){this.hasPattern=eRe("line",this.layers,this.pixelRatio,j);const O=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Kn(A);const $=this.layers[0].layout.get("line-elevation-reference");if($==="hd-road-markup")this.elevationType="road";else{const Ce=this.layers[0].layout.get("line-z-offset"),Ie=Ce.isConstant()&&!Ce.constantOr(0);this.elevationType=$!=="sea"&&$!=="ground"&&Ie?"none":"offset",this.elevationType==="offset"&&$==="none"&&aa(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=$==="sea"}const Y=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&Y!==void 0;const X=[];for(const{feature:Ce,id:Ie,index:Fe,sourceLayerIndex:Ke}of x){const et=this.layers[0]._featureFilter.needGeometry,at=oo(Ce,et);if(!this.layers[0]._featureFilter.filter(new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),at,A))continue;const vt=O?O.evaluate(at,{},A):void 0,pt={id:Ie,properties:Ce.properties,type:Ce.type,sourceLayerIndex:Ke,index:Fe,geometry:et?at.geometry:ti(Ce,A,L),patterns:{},sortKey:vt};X.push(pt)}O&&X.sort((Ce,Ie)=>Ce.sortKey-Ie.sortKey);const{lineAtlas:le,featureIndex:xe}=j,je=this.addConstantDashes(le);for(const Ce of X){const{geometry:Ie,index:Fe,sourceLayerIndex:Ke}=Ce;if(je&&this.addFeatureDashes(Ce,le),this.hasPattern){const et=tRe("line",this.layers,Ce,this.zoom,this.pixelRatio,j);this.patternFeatures.push(et)}else this.addFeature(Ce,Ie,Fe,A,le.positions,j.availableImages,j.brightness,j.elevationFeatures);xe.insert(x[Fe].feature,Ie,Fe,Ke,this.index)}}addConstantDashes(x){let j=!1;for(const A of this.layers){const L=A.paint.get("line-dasharray").value,O=A.layout.get("line-cap").value;if(L.kind!=="constant"||O.kind!=="constant")j=!0;else{const $=O.value,Y=L.value;if(!Y)continue;x.addDash(Y,$)}}return j}addFeatureDashes(x,j){const A=this.zoom;for(const L of this.layers){const O=L.paint.get("line-dasharray").value,$=L.layout.get("line-cap").value;if(O.kind==="constant"&&$.kind==="constant")continue;let Y,X;if(O.kind==="constant"){if(Y=O.value,!Y)continue}else Y=O.evaluate({zoom:A},x);X=$.kind==="constant"?$.value:$.evaluate({zoom:A},x),j.addDash(Y,X),x.patterns[L.id]=[j.getKey(Y,X)]}}update(x,j,A,L,O,$,Y,X,le){this.programConfigurations.updatePaintArrays(x,j,O,A,L,$,Y,le)}addFeatures(x,j,A,L,O,$){for(const Y of this.patternFeatures)this.addFeature(Y,Y.geometry,Y.index,j,A,L,$,x.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(x){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=x.createVertexBuffer(this.layoutVertexArray2,tus)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=x.createVertexBuffer(this.patternVertexArray,nus)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=x.createVertexBuffer(this.zOffsetVertexArray,Xds.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=x.createVertexBuffer(this.elevationGroundScaleVertexArray,Qds.members,!0)),this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,Jds),this.indexBuffer=x.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(x),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(x,j){let A,L;if(j&&j>0?(A=`mapbox_clip_start_${j}`,L=`mapbox_clip_end_${j}`):(A="mapbox_clip_start",L="mapbox_clip_end"),x.properties&&x.properties.hasOwnProperty(A)&&x.properties.hasOwnProperty(L))return{start:+x.properties[A],end:+x.properties[L]}}addFeature(x,j,A,L,O,$,Y,X){const le=this.layers[0].layout,xe=le.get("line-join").evaluate(x,{}),je=le.get("line-cap").evaluate(x,{}),Ce=le.get("line-miter-limit"),Ie=le.get("line-round-limit");this.lineClips=this.lineFeatureClips(x),this.lineFeature=x;const Fe=!(!x.properties||!x.properties.hasOwnProperty("mapbox_line_metrics"))&&x.properties.mapbox_line_metrics;this.zOffsetValue=le.get("line-z-offset").value;const Ke=this.layers[0].paint.get("line-width").value;if(Ke.kind!=="constant"&&Ke.isLineProgressConstant===!1&&(this.variableWidthValue=Ke),this.isSeaLevelReference){const et=le.get("line-elevation-ground-scale").value;et.kind==="constant"&&et.value===0||(this.elevationGroundScaleValue=et)}if(this.elevationType==="road"){const et=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(x,j,L,X,xe,je,Ce,Ie)){const[at,vt]=this.clipRuntimeLinesToTile(j,1);for(let pt=0;pt0?Rt.parentIndex:null)}this.fillNonElevatedRoadSegment(et)}}else for(let et=0;et0?et:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,x,A,O,$,L,Y,void 0,this.worldview)}computeSegNextDir(x,j){return x.nextPoint.sub(j.at(-2)).unit()}computeSegPrevDir(x,j){return j[1].sub(x.prevPoint).unit()}clipLinesToTile(x,j){return Xie(x,-j,-j,fr+j,fr+j)}clipRuntimeLinesToTile(x,j){const A=[];return[Xie(x,-j,-j,fr+j,fr+j,A),A]}addElevatedRoadFeature(x,j,A,L,O,$,Y,X){const le=[],xe=Xc.getElevationFeature(x,L);if(xe){const je=this.clipLinesToTile(j,1),Ce=this.prepareElevatedLines(je,xe,A);for(const Ie of Ce)le.push({geometry:Ie,elevation:xe,elevationTileID:A,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(le.length===0)return!1;for(const je of le){const Ce=this.layoutVertexArray.length;this.addLine(je.geometry,x,A,O,$,Y,X);const Ie=new cd(A,je.elevationTileID);if(je.elevation)for(let Fe=Ce;Fe>1,this.layoutVertexArray.int16[6*Fe+1]>>1),et=Ie.pointElevation(Ke,je.elevation,.05);this.updateHeightRange(et),this.zOffsetVertexArray.emplaceBack(et,0,0)}else this.fillNonElevatedRoadSegment(Ce)}return!0}prepareElevatedLines(x,j,A){if(j.constantHeight!=null)return x;const L=[],O=1/Kn(A);for(const $ of x)xds($,new B1(j,O),0,L);return L}fillNonElevatedRoadSegment(x){for(let j=x;j0,Ce=X&&X.progress.max<1;if(this.lineClips){let ws={min:this.lineClips.start,max:this.lineClips.end},ys=1;if(X){const Nn=this.lineClips.end-this.lineClips.start;ws=function(Rn,$n,Fn){return{min:Ji(Rn.min,$n,Fn),max:Ji(Rn.max,$n,Fn)}}(X.progress,{min:0,max:1},ws),Nn>0&&(ys=(ws.max-ws.min)/Nn)}const vs=+j.properties.mapbox_clip_feature_len,vn=+j.properties.mapbox_clip_seg_len;if(Number.isNaN(vs)||Number.isNaN(vn)){for(let Rn=0;Rn=2&&x[Fe-1].equals(x[Fe-2]);)Fe--;let Ke=0;for(;Ke0,Bn=this.overscaling<=16?122880/(512*this.overscaling):0;if(ys&&vs==="round"){if($n$&&(vs="bevel"),vs==="bevel"&&($n>2&&(vs="flipbevel"),$n<$&&(vs="miter")),vt&&!(vs==="miter"&&sr)&&this.updateDistance(vt,at),vs==="miter")if(sr){const Vn=at.dist(vt);if(Vn>2*Bn){const yr=at.sub(at.sub(vt)._mult(Bn/Vn)._round());this.updateDistance(vt,yr),this.addCurrentVertex(yr,At,0,0,et,us),vt=yr}this.updateDistance(vt,at),Nn._mult($n),this.addCurrentVertex(at,Nn,0,0,et,us);const nr=at.dist(pt);if(nr>2*Bn){const yr=at.add(pt.sub(at)._mult(Bn/nr)._round());this.updateDistance(at,yr),this.addCurrentVertex(yr,Rt,0,0,et,us),at=yr}}else Nn._mult($n),this.addCurrentVertex(at,Nn,0,0,et,us);else if(vs==="flipbevel"){if($n>100)Nn=Rt.mult(-1);else{const Vn=$n*At.add(Rt).mag()/At.sub(Rt).mag();Nn._perp()._mult(Vn*(gn?-1:1))}this.addCurrentVertex(at,Nn,0,0,et,us),this.addCurrentVertex(at,Nn.mult(-1),0,0,et,us)}else if(vs==="bevel"||vs==="fakeround"){const Vn=at.dist(vt);let nr=1;if(this.elevationType==="offset"&&vs==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&us!=null&&vt&&pt){const ta=4*Bn;Vn1){this.lineSoFar=x.w;const Ke=(j.x-x.x)/je,et=(j.y-x.y)/je,at=(j.z-x.z)/je,vt=(j.w-x.w)/je,pt=j.x-x.x,At=j.y-x.y,Rt=Math.sqrt(pt*pt+At*At);if(Rt===0)return;const Bt=-At/Rt,Ns=pt/Rt,us=Bt,ws=Ns,ys=-Bt,vs=-Ns;for(let vn=1;vn=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,xe),X.primitiveLength++),$?this.e2=xe:this.e1=xe,le!=null&&this.zOffsetVertexArray.emplaceBack(le.zOffset,le.variableWidth,le.variableWidth),this.elevationGroundScaleValue){const je=le?le.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(je)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(x,j){this.prevDistance=this.distance,this.distance+=x.dist(j),this.updateScaledDistance()}}function PRe(k,x,j){return k.xj||k.yj}let Mct,Pct;function Lct(k,x,j){return x*(fr/(k.tileSize*Math.pow(2,j-k.tileID.overscaledZ)))}kr(ooe,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const Ict=(k,x,j)=>(1-j)*k+j*x;function Dct(k,x){return 1/Lct(k,1,x.tileZoom)}function Rct(k,x,j,A){return k.translatePosMatrix(A||x.tileID.projMatrix,x,j.paint.get("line-translate"),j.paint.get("line-translate-anchor"))}const Fct=k=>{const x=[];Oct(k)&&x.push("RENDER_LINE_DASH"),k.paint.get("line-gradient")&&x.push("RENDER_LINE_GRADIENT"),k.paint.get("line-blend-mode")==="multiply"&&x.push("LINE_BLEND_MULTIPLY");const j=k.paint.get("line-trim-offset");j[0]===0&&j[1]===0||x.push("RENDER_LINE_TRIM_OFFSET"),k.paint.get("line-border-width").constantOr(1)!==0&&x.push("RENDER_LINE_BORDER");const A=k.layout.get("line-join").constantOr("miter")==="none",L=!!k.paint.get("line-pattern").constantOr(1);return A&&L&&x.push("LINE_JOIN_NONE"),x};function Oct(k){const x=k.paint.get("line-dasharray").value;return x.kind!=="constant"||x.value}let LRe;const zct=()=>LRe||(LRe={layout:Mct||(Mct=new ld({"line-cap":new dr(Ws.layout_line["line-cap"]),"line-join":new dr(Ws.layout_line["line-join"]),"line-miter-limit":new ur(Ws.layout_line["line-miter-limit"]),"line-round-limit":new ur(Ws.layout_line["line-round-limit"]),"line-sort-key":new dr(Ws.layout_line["line-sort-key"]),"line-z-offset":new dr(Ws.layout_line["line-z-offset"]),"line-elevation-reference":new ur(Ws.layout_line["line-elevation-reference"]),"line-cross-slope":new ur(Ws.layout_line["line-cross-slope"]),visibility:new ur(Ws.layout_line.visibility),"line-width-unit":new ur(Ws.layout_line["line-width-unit"]),"line-elevation-ground-scale":new dr(Ws.layout_line["line-elevation-ground-scale"])})),paint:Pct||(Pct=new ld({"line-opacity":new dr(Ws.paint_line["line-opacity"]),"line-color":new dr(Ws.paint_line["line-color"]),"line-translate":new ur(Ws.paint_line["line-translate"]),"line-translate-anchor":new ur(Ws.paint_line["line-translate-anchor"]),"line-width":new dr(Ws.paint_line["line-width"]),"line-gap-width":new dr(Ws.paint_line["line-gap-width"]),"line-offset":new dr(Ws.paint_line["line-offset"]),"line-blur":new dr(Ws.paint_line["line-blur"]),"line-dasharray":new dr(Ws.paint_line["line-dasharray"]),"line-pattern":new dr(Ws.paint_line["line-pattern"]),"line-pattern-cross-fade":new ur(Ws.paint_line["line-pattern-cross-fade"]),"line-gradient":new W0(Ws.paint_line["line-gradient"]),"line-trim-offset":new ur(Ws.paint_line["line-trim-offset"]),"line-trim-fade-range":new ur(Ws.paint_line["line-trim-fade-range"]),"line-trim-color":new ur(Ws.paint_line["line-trim-color"]),"line-emissive-strength":new dr(Ws.paint_line["line-emissive-strength"]),"line-border-width":new dr(Ws.paint_line["line-border-width"]),"line-border-color":new dr(Ws.paint_line["line-border-color"]),"line-occlusion-opacity":new ur(Ws.paint_line["line-occlusion-opacity"]),"line-blend-mode":new ur(Ws.paint_line["line-blend-mode"]),"line-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},LRe);class ous extends dr{possiblyEvaluate(x,j){return j=new Vi(Math.floor(j.zoom),{now:j.now,fadeDuration:j.fadeDuration,transition:j.transition,worldview:j.worldview}),super.possiblyEvaluate(x,j)}evaluate(x,j,A,L){return j=Object.assign({},j,{zoom:Math.floor(j.zoom)}),super.evaluate(x,j,A,L)}}let iY;function Bct(k,x){return x>0?x+2*k:k}const lus=Wn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),cus=Wn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),dus=Wn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Wn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const uus=Wn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),hus=Wn([{name:"a_feature_index",components:1,type:"Float32"}],4),mus=Wn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),pus=Wn([{name:"a_texb",components:2,type:"Uint16"}]),fus=Wn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),xus=Wn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Wn([{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 $ct=Wn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),gus=Wn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Wn([{name:"triangle",components:3,type:"Uint16"}]),Wn([{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"}]),Wn([{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"}]),Wn([{type:"Float32",name:"offsetX"}]),Wn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const IRe=class D4e{constructor(x=null,j=0,A=4096){this.batchIndex=j,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=x||null,this.propsDwords=A,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(D4e.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let L=0;Lx.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${x.maxUniformBlockSize}`);if(this.headerBuffer=j.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(j.bindBuffer(j.UNIFORM_BUFFER,this.headerBuffer),j.bufferData(j.UNIFORM_BUFFER,D4e.HEADER_BYTES,j.DYNAMIC_DRAW),this.propertiesBuffer=j.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(j.bindBuffer(j.UNIFORM_BUFFER,this.propertiesBuffer),j.bufferData(j.UNIFORM_BUFFER,this.totalBytes,j.DYNAMIC_DRAW),this.blockIndicesBuffer=j.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");j.bindBuffer(j.UNIFORM_BUFFER,this.blockIndicesBuffer),j.bufferData(j.UNIFORM_BUFFER,this.totalBytes,j.DYNAMIC_DRAW),j.bindBuffer(j.UNIFORM_BUFFER,null)}writeHeader(x){const j=this.headerData;j[0]=x.dataDrivenMask,j[1]=x.zoomDependentMask,j[2]=x.dataDrivenBlockSizeVec4,j[3]=x.offsets[0],j[4]=x.offsets[1],j[5]=x.offsets[2],j[6]=x.offsets[3],j[7]=x.offsets[4],j[8]=x.offsets[5],j[9]=x.offsets[6],j[10]=x.offsets[7],j[11]=x.offsets[8]}writeDataDrivenBlock(x,j,A){const L=4*A.dataDrivenBlockSizeVec4;if(L===0)return;const O=j*L;if(O+L>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${j} exceeds propertiesData capacity`);for(let $=0;$<9;$++)A.dataDrivenMask&1<<$&&x[$]!=null&&this._writeProperty(O+A.offsets[$],$,x[$],A.zoomDependentMask)}static getMaxFeatureCount(x,j=4096-D4e.HEADER_DWORDS){const A=4*x.dataDrivenBlockSizeVec4;return A===0?1/0:Math.floor(j/A)}_writeProperty(x,j,A,L){const O=this.propertiesData,$=j===8,Y=!!(L&1<{if(!Y)return;const le=A.getUniformBlockIndex(j,$);le!==A.INVALID_INDEX&&(A.uniformBlockBinding(j,le,X),A.bindBufferBase(A.UNIFORM_BUFFER,X,Y))},O=3*this.batchIndex;L("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,O),L("SymbolPaintPropertiesUniform",this.propertiesBuffer,O+1),L("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,O+2)}destroy(){if(this.context){const x=this.context.gl;this.headerBuffer&&(x.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(x.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(x.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};IRe.HEADER_DWORDS=12,IRe.HEADER_BYTES=48;let DRe=IRe;function RRe(k,x,j,A){return[qz(255*k,255*x),qz(255*j,255*A)]}function Uct(k,x,j,A,L,O,$,Y){return!!k&&(k.kind==="constant"?k.value==="none":k.kind==="composite"||k.kind==="source"?k.evaluate({zoom:0,brightness:O,worldview:Y},x,j,L,A,$)==="none":typeof k=="string"&&k==="none")}kr(DRe,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class FRe{constructor(x,j,A,L,O="",$,Y){this.layer=x,this.zoom=j,this.lut=A,this.isText=L,this.propDefs=this._getPropDefs(),this.worldview=O,this.maxUniformBufferBindings=$||24,this.uboSizeDwords=Y||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(x,L),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 x=this.isText?"text":"icon";return[{name:`${x}-color`,useThemeName:`${x}-color-use-theme`,isColor:!0},{name:`${x}-halo-color`,useThemeName:`${x}-halo-color-use-theme`,isColor:!0},{name:`${x}-opacity`,useThemeName:null,isColor:!1},{name:`${x}-halo-width`,useThemeName:null,isColor:!1},{name:`${x}-halo-blur`,useThemeName:null,isColor:!1},{name:`${x}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${x}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${x}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const x=this.layer.paint,j=this.propDefs;let A=0,L=0,O=0,$=0;const Y=[0,0,0,0,0,0,0,0,0];for(let X=0;X<9;X++){const{name:le,isColor:xe,isVec2:je}=j[X],Ce=x.get(le),Ie=!(!Ce||typeof Ce.isConstant!="function"||Ce.isConstant()),Fe=this._appearancesHavePaintProperties(le),Ke=Ie||Fe,et=!(!Ce||!Ce.value||Ce.value.kind!=="composite"),at=this.layer._transitionablePaint._values[le],vt=!Ke&&(at&&at.value&&at.value.expression&&at.value.expression.kind)==="camera";Ke?(A|=1<j.hasPaintProperty(x):this.isText?j=>j.hasTextPaintProperties():j=>j.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(x,j){const A=x.paint,L=j?"text":"icon",O=[`${L}-color`,`${L}-halo-color`,`${L}-opacity`,`${L}-halo-width`,`${L}-halo-blur`,`${L}-emissive-strength`,`${L}-occlusion-opacity`,"symbol-z-offset",`${L}-translate`];for(const $ of O){const Y=A.get($);if(Y&&typeof Y=="object"&&"isConstant"in Y&&!Y.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(x,j){if(j.dataDrivenMask===0)return"";const A=[];for(let L=0;L<9;L++){if(!(j.dataDrivenMask&1<=Fe){aa(`Too many symbol features: batch ${Ce} requires binding points up to ${3*Ce+2}, device limit ${Fe}. Some features will render incorrectly.`);const et={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:j,featureId:X};return this.allFeatures.push(et),X!=null&&(this.featureVertexRangesFromId.has(X)||this.featureVertexRangesFromId.set(X,[]),this.featureVertexRangesFromId.get(X).push(et)),0}this.ubos[Ce]||(this.ubos[Ce]=new DRe(Y,Ce,this.uboSizeDwords),this.ubos[Ce].writeHeader(le)),this.ubos[Ce].writeDataDrivenBlock(xe,Ie,le);const Ke={batchIndex:Ce,localFeatureIndex:Ie,vtFeatureIndex:j,featureId:X};return this.allFeatures.push(Ke),X!=null&&(this.featureVertexRangesFromId.has(X)||this.featureVertexRangesFromId.set(X,[]),this.featureVertexRangesFromId.get(X).push(Ke)),Ie}updateFeatures(x,j,A,L,O,$,Y){if(this.layer=j,this.cachedConstantUniforms=null,!this.cachedHeader)return;const X=this.cachedHeader;for(const le of x){const xe=this.featureVertexRangesFromId.get(le);if(!xe)continue;const je=$[le]||{};for(const Ce of xe){if(!A)continue;const Ie=A.feature(Ce.vtFeatureIndex);if(!Ie)continue;const Fe={type:Ie.type,id:le,properties:Ie.properties||{},geometry:[]},Ke=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(Ce.vtFeatureIndex):void 0,et=this.evaluateAllProperties(Fe,je,L,O,Y,void 0,Ke);this.ubos[Ce.batchIndex]&&this.ubos[Ce.batchIndex].writeDataDrivenBlock(et,Ce.localFeatureIndex,X)}}}updateDynamicExpressions(x,j,A,L,O,$){if(this.layer=x,this.cachedConstantUniforms=null,!this.cachedHeader)return;const Y=this.cachedHeader;for(const X of this.allFeatures){if(!j)continue;const le=j.feature(X.vtFeatureIndex);if(!le)continue;const xe=X.featureId!=null&&O[X.featureId]||{},je={type:le.type,id:X.featureId,properties:le.properties||{},geometry:[]},Ce=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(X.vtFeatureIndex):void 0,Ie=this.evaluateAllProperties(je,xe,A,L,$,void 0,Ce);this.ubos[X.batchIndex]&&this.ubos[X.batchIndex].writeDataDrivenBlock(Ie,X.localFeatureIndex,Y)}}updateFeaturePaintForAppearance(x,j,A,L,O,$,Y){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(x,Y||null),!this.cachedHeader))return!1;const X=this.cachedHeader;if(X.dataDrivenMask===0)return!1;let le=!1;for(const xe of this.allFeatures){if(xe.vtFeatureIndex!==x)continue;const je=this.evaluateAllProperties(j,A,L,O,$,void 0,Y);this.ubos[xe.batchIndex]&&(this.ubos[xe.batchIndex].writeDataDrivenBlock(je,xe.localFeatureIndex,X),le=!0)}return le}getConstantUniformValues(x,j){const A=this.cachedHeader,L=!(!A||!A.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===j&&(!L||this.cachedConstantRenderZoom===x))return this.cachedConstantUniforms;const O=this.layer.paint,$=this.propDefs,Y=L?new Vi(x,{brightness:j,worldview:this.worldview}):null,X={type:1,id:void 0,properties:{},geometry:[]},le=Ce=>{const Ie=$[Ce],Fe=O.get(Ie.name);if(!Fe)return[0,0,0,1];const Ke=Ie.useThemeName?O.get(Ie.useThemeName):void 0,et=Uct(Ke&&typeof Ke!="string"?Ke.value:void 0,X,{},[],void 0,j,void 0,this.worldview)?null:this.lut;let at;at=A&&A.cameraMask&1<{const Fe=O.get($[Ce].name);if(!Fe)return Ie;if(A&&A.cameraMask&1<{A.text=function(L,O,$){const Y=O.layout.get("text-transform").evaluate($,{});return Y==="uppercase"?L=L.toLocaleUpperCase():Y==="lowercase"&&(L=L.toLocaleLowerCase()),ey.applyArabicShaping&&(L=ey.applyArabicShaping(L)),L}(A.text,x,j)}),k}const oY={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function vus(k){return k==="︶"||k==="﹈"||k==="︸"||k==="﹄"||k==="﹂"||k==="︾"||k==="︼"||k==="︺"||k==="︘"||k==="﹀"||k==="︐"||k==="︓"||k==="︔"||k==="`"||k===" ̄"||k==="︑"||k==="︒"}function bus(k){return k==="︵"||k==="﹇"||k==="︷"||k==="﹃"||k==="﹁"||k==="︽"||k==="︻"||k==="︹"||k==="︗"||k==="︿"}const ORe=4294967296,qct=1/ORe,Vct=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let loe=class{constructor(k=new Uint8Array(16)){this.buf=ArrayBuffer.isView(k)?k:new Uint8Array(k),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(k,x,j=this.length){for(;this.pos>3,O=this.pos;this.type=7&A,k(L,x,this),this.pos===O&&this.skip(A)}return x}readMessage(k,x){return this.readFields(k,x,this.readVarint()+this.pos)}readFixed32(){const k=this.dataView.getUint32(this.pos,!0);return this.pos+=4,k}readSFixed32(){const k=this.dataView.getInt32(this.pos,!0);return this.pos+=4,k}readFixed64(){const k=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*ORe;return this.pos+=8,k}readSFixed64(){const k=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*ORe;return this.pos+=8,k}readFloat(){const k=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,k}readDouble(){const k=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,k}readVarint(k){const x=this.buf;let j,A;return A=x[this.pos++],j=127&A,A<128?j:(A=x[this.pos++],j|=(127&A)<<7,A<128?j:(A=x[this.pos++],j|=(127&A)<<14,A<128?j:(A=x[this.pos++],j|=(127&A)<<21,A<128?j:(A=x[this.pos],j|=(15&A)<<28,function(L,O,$){const Y=$.buf;let X,le;if(le=Y[$.pos++],X=(112&le)>>4,le<128||(le=Y[$.pos++],X|=(127&le)<<3,le<128)||(le=Y[$.pos++],X|=(127&le)<<10,le<128)||(le=Y[$.pos++],X|=(127&le)<<17,le<128)||(le=Y[$.pos++],X|=(127&le)<<24,le<128)||(le=Y[$.pos++],X|=(1&le)<<31,le<128))return Jz(L,X,O);throw new Error("Expected varint not more than 10 bytes")}(j,k,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const k=this.readVarint();return k%2==1?(k+1)/-2:k/2}readBoolean(){return!!this.readVarint()}readString(){const k=this.readVarint()+this.pos,x=this.pos;return this.pos=k,k-x>=12&&Vct?Vct.decode(this.buf.subarray(x,k)):function(j,A,L){let O="",$=A;for(;$239?4:Y>223?3:Y>191?2:1;if($+Ce>L)break;Ce===1?Y<128&&(je=Y):Ce===2?(X=j[$+1],(192&X)==128&&(je=(31&Y)<<6|63&X,je<=127&&(je=null))):Ce===3?(X=j[$+1],le=j[$+2],(192&X)==128&&(192&le)==128&&(je=(15&Y)<<12|(63&X)<<6|63&le,(je<=2047||je>=55296&&je<=57343)&&(je=null))):Ce===4&&(X=j[$+1],le=j[$+2],xe=j[$+3],(192&X)==128&&(192&le)==128&&(192&xe)==128&&(je=(15&Y)<<18|(63&X)<<12|(63&le)<<6|63&xe,(je<=65535||je>=1114112)&&(je=null))),je===null?(je=65533,Ce=1):je>65535&&(je-=65536,O+=String.fromCharCode(je>>>10&1023|55296),je=56320|1023&je),O+=String.fromCharCode(je),$+=Ce}return O}(this.buf,x,k)}readBytes(){const k=this.readVarint()+this.pos,x=this.buf.subarray(this.pos,k);return this.pos=k,x}readPackedVarint(k=[],x){const j=this.readPackedEnd();for(;this.pos127;);else if(x===2)this.pos=this.readVarint()+this.pos;else if(x===5)this.pos+=4;else{if(x!==1)throw new Error(`Unimplemented type: ${x}`);this.pos+=8}}writeTag(k,x){this.writeVarint(k<<3|x)}realloc(k){let x=this.length||16;for(;x268435455||k<0?function(x,j){let A,L;if(x>=0?(A=x%4294967296|0,L=x/4294967296|0):(A=~(-x%4294967296),L=~(-x/4294967296),4294967295^A?A=A+1|0:(A=0,L=L+1|0)),x>=18446744073709552e3||x<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");j.realloc(10),function(O,$,Y){Y.buf[Y.pos++]=127&O|128,O>>>=7,Y.buf[Y.pos++]=127&O|128,O>>>=7,Y.buf[Y.pos++]=127&O|128,O>>>=7,Y.buf[Y.pos++]=127&O|128,Y.buf[Y.pos]=127&(O>>>=7)}(A,0,j),function(O,$){const Y=(7&O)<<4;$.buf[$.pos++]|=Y|((O>>>=3)?128:0),O&&($.buf[$.pos++]=127&O|((O>>>=7)?128:0),O&&($.buf[$.pos++]=127&O|((O>>>=7)?128:0),O&&($.buf[$.pos++]=127&O|((O>>>=7)?128:0),O&&($.buf[$.pos++]=127&O|((O>>>=7)?128:0),O&&($.buf[$.pos++]=127&O)))))}(L,j)}(k,this):(this.realloc(4),this.buf[this.pos++]=127&k|(k>127?128:0),k<=127||(this.buf[this.pos++]=127&(k>>>=7)|(k>127?128:0),k<=127||(this.buf[this.pos++]=127&(k>>>=7)|(k>127?128:0),k<=127||(this.buf[this.pos++]=k>>>7&127))))}writeSVarint(k){this.writeVarint(k<0?2*-k-1:2*k)}writeBoolean(k){this.writeVarint(+k)}writeString(k){k=String(k),this.realloc(4*k.length),this.pos++;const x=this.pos;this.pos=function(A,L,O){for(let $,Y,X=0;X55295&&$<57344){if(!Y){$>56319||X+1===L.length?(A[O++]=239,A[O++]=191,A[O++]=189):Y=$;continue}if($<56320){A[O++]=239,A[O++]=191,A[O++]=189,Y=$;continue}$=Y-55296<<10|$-56320|65536,Y=null}else Y&&(A[O++]=239,A[O++]=191,A[O++]=189,Y=null);$<128?A[O++]=$:($<2048?A[O++]=$>>6|192:($<65536?A[O++]=$>>12|224:(A[O++]=$>>18|240,A[O++]=$>>12&63|128),A[O++]=$>>6&63|128),A[O++]=63&$|128)}return O}(this.buf,k,this.pos);const j=this.pos-x;j>=128&&Hct(x,j,this),this.pos=x-1,this.writeVarint(j),this.pos+=j}writeFloat(k){this.realloc(4),this.dataView.setFloat32(this.pos,k,!0),this.pos+=4}writeDouble(k){this.realloc(8),this.dataView.setFloat64(this.pos,k,!0),this.pos+=8}writeBytes(k){const x=k.length;this.writeVarint(x),this.realloc(x);for(let j=0;j=128&&Hct(j,A,this),this.pos=j-1,this.writeVarint(A),this.pos+=A}writeMessage(k,x,j){this.writeTag(k,2),this.writeRawMessage(x,j)}writePackedVarint(k,x){x.length&&this.writeMessage(k,_us,x)}writePackedSVarint(k,x){x.length&&this.writeMessage(k,wus,x)}writePackedBoolean(k,x){x.length&&this.writeMessage(k,kus,x)}writePackedFloat(k,x){x.length&&this.writeMessage(k,jus,x)}writePackedDouble(k,x){x.length&&this.writeMessage(k,Nus,x)}writePackedFixed32(k,x){x.length&&this.writeMessage(k,Sus,x)}writePackedSFixed32(k,x){x.length&&this.writeMessage(k,Cus,x)}writePackedFixed64(k,x){x.length&&this.writeMessage(k,Aus,x)}writePackedSFixed64(k,x){x.length&&this.writeMessage(k,Eus,x)}writeBytesField(k,x){this.writeTag(k,2),this.writeBytes(x)}writeFixed32Field(k,x){this.writeTag(k,5),this.writeFixed32(x)}writeSFixed32Field(k,x){this.writeTag(k,5),this.writeSFixed32(x)}writeFixed64Field(k,x){this.writeTag(k,1),this.writeFixed64(x)}writeSFixed64Field(k,x){this.writeTag(k,1),this.writeSFixed64(x)}writeVarintField(k,x){this.writeTag(k,0),this.writeVarint(x)}writeSVarintField(k,x){this.writeTag(k,0),this.writeSVarint(x)}writeStringField(k,x){this.writeTag(k,2),this.writeString(x)}writeFloatField(k,x){this.writeTag(k,5),this.writeFloat(x)}writeDoubleField(k,x){this.writeTag(k,1),this.writeDouble(x)}writeBooleanField(k,x){this.writeVarintField(k,+x)}};function Jz(k,x,j){return j?4294967296*x+(k>>>0):4294967296*(x>>>0)+(k>>>0)}function Hct(k,x,j){const A=x<=16383?1:x<=2097151?2:x<=268435455?3:Math.floor(Math.log(x)/(7*Math.LN2));j.realloc(A);for(let L=j.pos-1;L>=k;L--)j.buf[L+A]=j.buf[L]}function _us(k,x){for(let j=0;j=0&&A>=x&&coe[this.text.charCodeAt(A)];A--)j--;this.text=this.text.substring(x,j),this.sectionIndex=this.sectionIndex.slice(x,j)}substring(x,j){const A=new eB;return A.text=this.text.substring(x,j),A.sectionIndex=this.sectionIndex.slice(x,j),A.sections=this.sections,A}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((x,j)=>Math.max(x,this.sections[j].scale),0)}addTextSection(x,j){this.text+=x.text,this.sections.push(lY.forText(x.scale,x.fontStack||j));const A=this.sections.length-1;for(let L=0;L=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function zRe(k,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke=1,et=1){const at=eB.fromFeature(k,L,Ke,et);je===V1.vertical&&at.verticalizePunctuation(Ce);let vt=[];const pt=function(us,ws,ys,vs,vn,Nn,Rn=1){if(!us)return[];const $n=[],Fn=function(Bn,Vn,nr,yr,ra,Er,Cr=1){let vr=0;for(let ta=0;ta=0;let gn=0;for(let Bn=0;Bn0&&ty>lo&&(lo=ty)}else{const wf=ys[ku.fontStack];if(!wf)continue;wf[Su]&&(eh=wf[Su]);const Xy=ws[ku.fontStack];if(!Xy)continue;const Xx=Xy.glyphs[Su];if(!Xx)continue;if(sm=Xx.metrics,Gp=Su!==8203?Vp:0,Cr){const Iu=Xy.ascender!==void 0?Math.abs(Xy.ascender):0,ty=Xy.descender!==void 0?Math.abs(Xy.descender):0,jf=(Iu+ty)*Ju;Lu-j/2;){if($--,$<0)return!1;Y-=k[$].dist(O),O=k[$]}Y+=k[$].dist(k[$+1]),$++;const X=[];let le=0;for(;YA;)le-=X.shift().angleDelta;if(le>L)return!1;$++,Y+=xe.dist(je)}return!0}function tdt(k){let x=0;for(let j=0;jle){const Fe=(le-X)/Ie,Ke=Pr(je.x,Ce.x,Fe),et=Pr(je.y,Ce.y,Fe),at=new p3(Ke,et,0,Ce.angleTo(je),xe);return!$||edt(k,at,Y,$,x)?at:void 0}X+=Ie}}function Rus(k,x,j,A,L,O,$,Y,X){const le=sdt(A,O,$),xe=ndt(A,L),je=xe*$,Ce=k[0].x===0||k[0].x===X||k[0].y===0||k[0].y===X;return x-je=0&&At=0&&Rt=0&&Ce+le<=xe){const Bt=new p3(At,Rt,0,vt,Fe);A&&!edt(k,Bt,O,A,L)||Ie.push(Bt)}}je+=at}return Y||Ie.length||$||(Ie=rdt(k,je/2,j,A,L,O,$,!0,X)),Ie}function adt(k){let x=0,j=0;for(const $ of k)x+=$.w*$.h,j=Math.max(j,$.w);k.sort(($,Y)=>Y.h-$.h);const A=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(x/.95)),j),h:1/0}];let L=0,O=0;for(const $ of k)for(let Y=A.length-1;Y>=0;Y--){const X=A[Y];if(!($.w>X.w||$.h>X.h)){if($.x=X.x,$.y=X.y,O=Math.max(O,$.y+$.h),L=Math.max(L,$.x+$.w),$.w===X.w&&$.h===X.h){const le=A.pop();le&&Yx.id?1:k.versionx.version?1:k.sxx.sx?1:k.syx.sy?1:0}function VRe(k){let x=0;for(let j=0;j0,idt(x,A,this.iconDescriptors,O),idt(j,A,this.patternDescriptors,O),this.iconDescriptors.sort(uoe),this.patternDescriptors.sort(uoe);let $=0;const Y=L?L.data:"";Y&&($=mk($,VRe(Y))),$=mk($,1);for(const X of this.iconDescriptors)$=mk($,VRe(X.id)),$=mk($,X.version),$=mk($,X.sx),$=mk($,X.sy);$=mk($,1);for(const X of this.patternDescriptors)$=mk($,VRe(X.id)),$=mk($,X.version),$=mk($,X.sx),$=mk($,X.sy);this.hash=$}subsetOf(x){return this.isSubsetArray(this.iconDescriptors,x.iconDescriptors,uoe)&&this.isSubsetArray(this.patternDescriptors,x.patternDescriptors,uoe)}isSubsetArray(x,j,A){let L=0,O=0;if(x.length>j.length)return!1;for(;L{const $=L.variant.id.toString().localeCompare(O.variant.id.toString());return $!==0?$:L.variant.sx!==O.variant.sx?L.variant.sx-O.variant.sx:L.variant.sy!==O.variant.sy?L.variant.sy-O.variant.sy:0});const A=new Map;for(const L of j)A.set(L.key,L.value);return A}class odt{constructor(x){this.sourceAtlasHash=x}}class ldt{constructor(x,j,A,L){const O=new Map,$=new Map;this.haveRenderCallbacks=[];const Y=[],X=L!==void 0,le=X?new Map:void 0,xe=X?WRe(x,le):x,je=X?WRe(j,le):j;this.addImages(xe,O,1,Y),this.addImages(je,$,2,Y);const{w:Ce,h:Ie}=adt(Y),Fe=new Cg({width:Ce||1,height:Ie||1});for(const[Ke,et]of xe.entries()){const at=O.get(Ke).paddedRect;Cg.copy(et.data,Fe,{x:0,y:0},{x:at.x+1,y:at.y+1},et.data,null,et.sdf)}for(const[Ke,et]of je.entries()){const at=$.get(Ke),vt=at.paddedRect;let pt=at.padding;const At=vt.x+pt,Rt=vt.y+pt,Bt=et.data.width,Ns=et.data.height;pt=pt>1?pt-1:pt,Cg.copy(et.data,Fe,{x:0,y:0},{x:At,y:Rt},et.data,A),Cg.copy(et.data,Fe,{x:0,y:Ns-pt},{x:At,y:Rt-pt},{width:Bt,height:pt},A),Cg.copy(et.data,Fe,{x:0,y:0},{x:At,y:Rt+Ns},{width:Bt,height:pt},A),Cg.copy(et.data,Fe,{x:Bt-pt,y:0},{x:At-pt,y:Rt},{width:pt,height:Ns},A),Cg.copy(et.data,Fe,{x:0,y:0},{x:At+Bt,y:Rt},{width:pt,height:Ns},A),Cg.copy(et.data,Fe,{x:Bt-pt,y:Ns-pt},{x:At-pt,y:Rt-pt},{width:pt,height:pt},A),Cg.copy(et.data,Fe,{x:0,y:Ns-pt},{x:At+Bt,y:Rt-pt},{width:pt,height:pt},A),Cg.copy(et.data,Fe,{x:0,y:0},{x:At+Bt,y:Rt+Ns},{width:pt,height:pt},A),Cg.copy(et.data,Fe,{x:Bt-pt,y:0},{x:At-pt,y:Rt+Ns},{width:pt,height:pt},A)}this.lut=A,this.image=Fe,this.iconPositions=O,this.patternPositions=$,X&&(this.contentDescriptor=new HRe(xe,je,L,A,le))}addImages(x,j,A,L){for(const[O,$]of x.entries()){const{bin:Y,imagePosition:X,imageVariant:le}=GRe(O,$,A);j.set(O,X),L.push(Y),$.hasRenderCallback&&this.haveRenderCallbacks.push(le.id)}}patchUpdatedImages(x,j,A,L){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(O=>x.hasImage(O,A)),x.dispatchRenderCallbacks(this.haveRenderCallbacks,A);for(const O of x.getUpdatedImages(A)){for(const $ of this.iconPositions.keys()){const Y=Hd.parse($);if(qm.isEqual(Y.id,O)){const X=x.getImage(O,A);this.patchUpdatedImage(this.iconPositions.get($),X,j,null)}}for(const $ of this.patternPositions.keys()){const Y=Hd.parse($);if(qm.isEqual(Y.id,O)){const X=x.getImage(O,A);this.patchUpdatedImage(this.patternPositions.get($),X,j,L||this.lut)}}}}patchUpdatedImage(x,j,A,L=null){if(!x||!j||x.version===j.version)return;x.version=j.version;const[O,$]=x.tl,Y=x.sdf;if(this.lut||Y){const X={width:j.data.width,height:j.data.height},le=new Cg(X);Cg.copy(j.data,le,{x:0,y:0},{x:0,y:0},X,L,Y),A.update(le,{position:{x:O,y:$},recreateWhenResize:!1})}else A.update(j.data,{position:{x:O,y:$},recreateWhenResize:!1})}}kr(cY,"ImagePosition"),kr(ldt,"ImageAtlas",{omit:["lut"]}),kr(odt,"ImageAtlasReference");class dY{constructor(x){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!x||x.useServerFontComposition===void 0||x.useServerFontComposition}loadGlyphRange(x,j,A,L,O){if(this.useServerFontComposition)return void dY.loadGlyphRange(x,j,A,L,O);const $=x.split(",").map(Y=>Y.trim()).filter(Y=>Y.length>0);$.length!==0?$.length!==1?this._loadMultipleFonts($,j,A,L,O):this._loadFont($[0],j,A,L,O):O(new Error("Empty fontstack"))}_loadMultipleFonts(x,j,A,L,O){const $=x.map(()=>null),Y={completed:0,firstError:null,callbackCalled:!1},X=(le,xe,je)=>{if(!Y.callbackCalled&&(xe&&!Y.firstError&&(Y.firstError=xe),je&&($[le]=je),Y.completed++,Y.completed===x.length)){Y.callbackCalled=!0;const Ce=$.filter(Fe=>Fe!==null);if(Ce.length===0)return void O(Y.firstError||new Error("All fonts failed to load"));const Ie=this._composeGlyphs(Ce);O(null,Ie)}};for(let le=0;le{X(le,xe,je)})}_loadFont(x,j,A,L,O){const $=`${x}:${j}`;if(this.cachedRanges.has($)){const X=this.cachedRanges.get($);return void wu.frame(()=>O(null,X))}const Y=this.pendingRequests.get($);Y?Y.push(O):(this.pendingRequests.set($,[O]),dY.loadGlyphRange(x,j,A,L,(X,le)=>{X||this.cachedRanges.set($,le||null);const xe=this.pendingRequests.get($);if(this.pendingRequests.delete($),xe)for(const je of xe)je(X,le)}))}_composeGlyphs(x){const j={};let A,L;for(const O of x)if(A===void 0&&O.ascender!==void 0&&(A=O.ascender),L===void 0&&O.descender!==void 0&&(L=O.descender),O.glyphs)for(const $ in O.glyphs)j[$]===void 0&&(j[$]=O.glyphs[$]);return{glyphs:j,ascender:A,descender:L}}}dY.loadGlyphRange=function(k,x,j,A,L){const O=256*x,$=O+255,Y=A.transformRequest(A.normalizeGlyphsURL(j).replace("{fontstack}",k).replace("{range}",`${O}-${$}`),_g.Glyphs);Yg(Y,(X,le)=>{if(X)L(X);else if(le){const xe={},je=function(Ce){return new loe(Ce).readFields(Tus,{})}(le);for(const Ce of je.glyphs)xe[Ce.id]=Ce;L(null,{glyphs:xe,ascender:je.ascender,descender:je.descender})}})};const uY=1e20;function cdt(k,x,j,A,L,O,$,Y,X){for(let le=x;le-1);X++,O[X]=Y,$[X]=le,$[X+1]=uY}for(let Y=0,X=0;Y{if($){L.ascender=$.ascender,L.descender=$.descender;for(const Y in $.glyphs)this._doesCharSupportLocalGlyph(+Y)||(L.glyphs[+Y]=$.glyphs[+Y]);L.ranges[j]=!0}for(const Y of L.requests[j]||[])Y(O,$);delete L.requests[j]}))}getGlyphs(x,j){const A=[],L=this.url||qa.GLYPHS_URL;for(const O in x)for(const $ of x[O])A.push({stack:O,id:$});Mt(A,({stack:O,id:$},Y)=>{let X=this.entries[O];X||(X=this.entries[O]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let le=X.glyphs[$];if(le!==void 0)return void Y(null,{stack:O,id:$,glyph:le});if(le=this._tinySDF(X,O,$),le)return X.glyphs[$]=le,void Y(null,{stack:O,id:$,glyph:le});const xe=Math.floor($/256);if(256*xe>65535)return aa("glyphs > 65535 not supported"),void Y(null,{stack:O,id:$,glyph:le});if(X.ranges[xe])return void Y(null,{stack:O,id:$,glyph:le});let je=X.requests[xe];je||(je=X.requests[xe]=[],this.glyphLoader.loadGlyphRange(O,xe,L,this.requestManager,(Ce,Ie)=>{if(Ie){X.ascender=Ie.ascender,X.descender=Ie.descender;for(const Fe in Ie.glyphs)this._doesCharSupportLocalGlyph(+Fe)||(X.glyphs[+Fe]=Ie.glyphs[+Fe]);X.ranges[xe]=!0}for(const Fe of je)Fe(Ce,Ie);delete X.requests[xe]})),je.push((Ce,Ie)=>{Ce?Y(Ce):Ie&&Y(null,{stack:O,id:$,glyph:Ie.glyphs[$]||null})})},(O,$)=>{if(O)j(O);else if($){const Y={};for(const{stack:X,id:le,glyph:xe}of $)Y[X]===void 0&&(Y[X]={}),Y[X].glyphs===void 0&&(Y[X].glyphs={}),Y[X].glyphs[le]=xe&&{id:xe.id,bitmap:xe.bitmap.clone(),metrics:xe.metrics},Y[X].ascender=this.entries[X].ascender,Y[X].descender=this.entries[X].descender;j(null,Y)}})}_doesCharSupportLocalGlyph(x){return this.localGlyphMode!==KRe.none&&(this.localGlyphMode===KRe.all?!!this.localFontFamily:!!this.localFontFamily&&(Ng(x)||mw(x)||D1(x)||$p(x)||Hb(x)||d2(x)||(j=x)>=131072&&j<=173791||(A=>A>=66736&&A<=66815)(x)));var j}_tinySDF(x,j,A){const L=this.localFontFamily;if(!L||!this._doesCharSupportLocalGlyph(A))return;let O=x.tinySDF;if(!O){let et="400";/bold/i.test(j)?et="900":/medium/i.test(j)?et="500":/light/i.test(j)&&(et="200"),O=x.tinySDF=new hoe.TinySDF({fontFamily:L,fontWeight:et,fontSize:48,buffer:6,radius:16}),O.fontWeight=et}const $=O.fontWeight;if(this.localGlyphs[$][A])return this.localGlyphs[$][A];const Y=String.fromCodePoint(A),{data:X,width:le,height:xe,glyphWidth:je,glyphHeight:Ce,glyphLeft:Ie,glyphTop:Fe,glyphAdvance:Ke}=O.draw(Y);return this.localGlyphs[$][A]={id:A,bitmap:new mT({width:le,height:xe},X),metrics:{width:je/2,height:Ce/2,left:Ie/2,top:Fe/2-27,advance:Ke/2,localGlyph:!0}}}}function udt(k,x){return k+x[1]-x[0]}function YRe(k,x,j,A,L=1){const O=[],$=k.imagePrimary,Y=$.pixelRatio,X=$.paddedRect.w-2,le=$.paddedRect.h-2,xe=(k.right-k.left)*L,je=(k.bottom-k.top)*L,Ce=$.stretchX||[[0,X]],Ie=$.stretchY||[[0,le]],Fe=Ce.reduce(udt,0),Ke=Ie.reduce(udt,0),et=X-Fe,at=le-Ke;let vt=0,pt=Fe,At=0,Rt=Ke,Bt=0,Ns=et,us=0,ws=at;if($.content&&A){const vs=$.content;vt=moe(Ce,0,vs[0]),At=moe(Ie,0,vs[1]),pt=moe(Ce,vs[0],vs[2]),Rt=moe(Ie,vs[1],vs[3]),Bt=vs[0]-vt,us=vs[1]-At,Ns=vs[2]-vs[0]-pt,ws=vs[3]-vs[1]-Rt}const ys=(vs,vn,Nn,Rn)=>{const $n=poe(vs.stretch-vt,pt,xe,k.left*L),Fn=foe(vs.fixed-Bt,Ns,vs.stretch,Fe),sr=poe(vn.stretch-At,Rt,je,k.top*L),gn=foe(vn.fixed-us,ws,vn.stretch,Ke),Bn=poe(Nn.stretch-vt,pt,xe,k.left*L),Vn=foe(Nn.fixed-Bt,Ns,Nn.stretch,Fe),nr=poe(Rn.stretch-At,Rt,je,k.top*L),yr=foe(Rn.fixed-us,ws,Rn.stretch,Ke),ra=new Ss($n,sr),Er=new Ss(Bn,sr),Cr=new Ss(Bn,nr),vr=new Ss($n,nr),ta=new Ss(Fn/Y,gn/Y),fa=new Ss(Vn/Y,yr/Y),ei=x*Math.PI/180;if(ei){const lo=Math.sin(ei),Lu=Math.cos(ei),Dl=[Lu,-lo,lo,Lu];ra._matMult(Dl),Er._matMult(Dl),vr._matMult(Dl),Cr._matMult(Dl)}const Aa=vs.stretch+vs.fixed,zi=Nn.stretch+Nn.fixed,Xo=vn.stretch+vn.fixed,Bi=Rn.stretch+Rn.fixed,sl=k.imageSecondary;return{tl:ra,tr:Er,bl:vr,br:Cr,texPrimary:{x:$.paddedRect.x+1+Aa,y:$.paddedRect.y+1+Xo,w:zi-Aa,h:Bi-Xo},texSecondary:sl?{x:sl.paddedRect.x+1+Aa,y:sl.paddedRect.y+1+Xo,w:zi-Aa,h:Bi-Xo}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:ta,pixelOffsetBR:fa,minFontScaleX:Ns/Y/xe,minFontScaleY:ws/Y/je,isSDF:j}};if($.stretchX||$.stretchY){const vs=hdt(Ce,et,Fe),vn=hdt(Ie,at,Ke);for(let Nn=0;Nn0?[vt,-pt]:At<0?[-vt,pt]:vt===0?[pt,vt]:[pt,-vt]}(j);let Ie=Math.abs(x.top-x.bottom);for(const at of x.positionedLines)Ie-=at.lineOffset;const Fe=x.positionedLines.length,Ke=Ie/Fe;let et=x.top-j[1];for(let at=0;atO)&&(O=Fe.x),(!Ie||Fe.y>$)&&($=Fe.y)}const X=Math.min(O-A,$-L);let le=X/2;const xe=new jm([],Bus);if(X===0)return new Ss(A,L);for(let Ie=A;Ieje.d||!je.d)&&(je=Ie,j&&console.log("found best %d after %d probes",Math.round(1e4*Ie.d)/1e4,Ce)),Ie.max-je.d<=x||(le=Ie.h/2,xe.push(new sB(Ie.p.x-le,Ie.p.y-le,le,k)),xe.push(new sB(Ie.p.x+le,Ie.p.y-le,le,k)),xe.push(new sB(Ie.p.x-le,Ie.p.y+le,le,k)),xe.push(new sB(Ie.p.x+le,Ie.p.y+le,le,k)),Ce+=4)}return j&&(console.log(`num probes: ${Ce}`),console.log(`best distance: ${je.d}`)),je.p}function Bus(k,x){return x.max-k.max}hoe.TinySDF=class{constructor({fontSize:k=24,buffer:x=3,radius:j=8,cutoff:A=.25,fontFamily:L="sans-serif",fontWeight:O="normal",fontStyle:$="normal",lang:Y=null}={}){this.buffer=x,this.cutoff=A,this.radius=j,this.lang=Y;const X=this.size=k+4*x,le=this._createCanvas(X),xe=this.ctx=le.getContext("2d",{willReadFrequently:!0});xe.font=`${$} ${O} ${k}px ${L}`,xe.textBaseline="alphabetic",xe.textAlign="left",xe.fillStyle="black",this.gridOuter=new Float64Array(X*X),this.gridInner=new Float64Array(X*X),this.f=new Float64Array(X),this.z=new Float64Array(X+1),this.v=new Uint16Array(X)}_createCanvas(k){const x=document.createElement("canvas");return x.width=x.height=k,x}draw(k){const{width:x,actualBoundingBoxAscent:j,actualBoundingBoxDescent:A,actualBoundingBoxLeft:L,actualBoundingBoxRight:O}=this.ctx.measureText(k),$=Math.ceil(j),Y=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(O-L))),X=Math.min(this.size-this.buffer,$+Math.ceil(A)),le=Y+2*this.buffer,xe=X+2*this.buffer,je=Math.max(le*xe,0),Ce=new Uint8ClampedArray(je),Ie={data:Ce,width:le,height:xe,glyphWidth:Y,glyphHeight:X,glyphTop:$,glyphLeft:0,glyphAdvance:x};if(Y===0||X===0)return Ie;const{ctx:Fe,buffer:Ke,gridInner:et,gridOuter:at}=this;this.lang&&(Fe.lang=this.lang),Fe.clearRect(Ke,Ke,Y,X),Fe.fillText(k,Ke,Ke+$);const vt=Fe.getImageData(Ke,Ke,Y,X);at.fill(uY,0,je),et.fill(0,0,je);for(let pt=0;pt0?Ns*Ns:0,et[Bt]=Ns<0?Ns*Ns:0}}cdt(at,0,0,le,xe,le,this.f,this.v,this.z),cdt(et,Ke,Ke,Y,X,le,this.f,this.v,this.z);for(let pt=0;ptO.y!=Ke.y>O.y&&O.x<(Ke.x-Fe.x)*(O.y-Fe.y)/(Ke.y-Fe.y)+Fe.x&&(Y=!Y),X=Math.min(X,m2(O,Fe,Ke))}}return(Y?1:-1)*Math.sqrt(X)}(this.p,L),this.max=this.d+this.h*Math.SQRT2}}const $us=Object.keys,ZRe=Number.POSITIVE_INFINITY,Uus=Math.sqrt(2);function gT(k,x,j,A,L,O){const $=$Re(k)&&k.collisionPadding?k.collisionPadding:[0,0,0,0],Y={top:k.top-$[1],bottom:k.bottom+$[3],left:k.left-$[0],right:k.right+$[2],scaled:!1};return A!==void 0&&function(X,le){X.top*=le,X.bottom*=le,X.left*=le,X.right*=le,X.scaled=!0}(Y,A),O&&(Y.left+=O[0],Y.right+=O[0],Y.top+=O[1],Y.bottom+=O[1]),j&&function(X,le,xe){if(!le)return;const je=Gs(le),Ce=new Ss(xe?xe[0]:0,xe?xe[1]:0),Ie=new Ss(X.left,X.top),Fe=new Ss(X.right,X.top),Ke=new Ss(X.left,X.bottom),et=new Ss(X.right,X.bottom);Ie._rotateAround(je,Ce),Fe._rotateAround(je,Ce),Ke._rotateAround(je,Ce),et._rotateAround(je,Ce),X.left=Math.min(Ie.x,Fe.x,Ke.x,et.x),X.right=Math.max(Ie.x,Fe.x,Ke.x,et.x),X.top=Math.min(Ie.y,Fe.y,Ke.y,et.y),X.bottom=Math.max(Ie.y,Fe.y,Ke.y,et.y)}(Y,j,L),x?{top:Math.min(x.top,Y.top),bottom:Math.max(x.bottom,Y.bottom),left:Math.min(x.left,Y.left),right:Math.max(x.right,Y.right),scaled:x.scaled||Y.scaled}:Y}function fdt(k,[x,j]){let A=0,L=0;if(j===ZRe){x<0&&(x=0);const O=x/Uus;switch(k){case"top-right":case"top-left":L=O-7;break;case"bottom-right":case"bottom-left":L=7-O;break;case"bottom":L=7-x;break;case"top":L=x-7}switch(k){case"top-right":case"bottom-right":A=-O;break;case"top-left":case"bottom-left":A=O;break;case"left":A=x;break;case"right":A=-x}}else{switch(x=Math.abs(x),j=Math.abs(j),k){case"top-right":case"top-left":case"top":L=j-7;break;case"bottom-right":case"bottom-left":case"bottom":L=7-j}switch(k){case"top-right":case"bottom-right":case"right":A=-x;break;case"top-left":case"bottom-left":case"left":A=x}}return[A,L]}function qus(k,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe){const Ke=k.layers[0],et=Ke.appearances;if(et.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const at={iconBBox:null,iconVerticalBBox:null},vt={textBBox:null,textVerticalBBox:null},{baseIconRotate:pt,baseTextRotate:At,iconScaleFactor:Rt}=function(Ns,us,ws){const ys=Ns.get("icon-rotate").evaluate(us,{},ws),vs=Ns.get("text-rotate").evaluate(us,{},ws),[vn,Nn]=Ns.get("icon-size-scale-range");return{baseIconRotate:ys,baseTextRotate:vs,iconScaleFactor:gt(1,vn,Nn)}}(A,L,O);x&&(at.iconBBox=gT(x,at.iconBBox,pt),j)&&(at.iconVerticalBBox=gT(j,at.iconVerticalBBox,pt+90));const Bt=goe(je.horizontal);Bt&&(vt.textBBox=gT(Bt,vt.textBBox,At,1,Ie)),je.vertical&&(vt.textVerticalBBox=gT(je.vertical,vt.textVerticalBBox,At+90,1,Ie));for(const Ns of et)Ns.hasIconLayoutProperties()&&Vus(at,k,Ke,Ns,L,O,Y,pt,$,X,x,le,Rt,xe,Fe),Ns.hasTextLayoutProperties()&&Hus(vt,Ke,Ns,L,O,Ie,At,Ce,Bt,je.vertical);return{iconBBox:at.iconBBox,iconVerticalBBox:at.iconVerticalBBox,textBBox:vt.textBBox,textVerticalBBox:vt.textVerticalBBox}}function Vus(k,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe){const{appearanceIconOffset:Ke,appearanceIconRotate:et,appearanceIconSize:at}=xdt(A,j,L,O,$,Y,X,le.iconScaleFactor);let vt=null,pt=null,At=null;A.hasLayoutProperty("icon-image")?At=function(Bt,Ns,us,ws,ys,vs,vn,Nn){let Rn=null;const $n=Ns.getAppearanceValueAndResolveTokens(us,"icon-image",ws,ys,Nn);if($n){const Fn=Bt.getResolvedImageFromTokens($n),sr=us.hasLayoutProperty("icon-size")?us.getUnevaluatedLayoutProperty("icon-size"):Ns._unevaluatedLayout._values["icon-size"],gn=hY(Fn,bI(Bt.zoom,sr,Bt.worldview,Nn),sr,ys,Bt.zoom,ws,Bt.pixelRatio,vn,Bt.worldview,Nn);Rn=vs.get(gn.iconPrimary.toString())}return Rn}(x,j,A,L,O,je,Ce,Fe):xe&&(At=xe.imagePrimary),At&&(vt=doe(At,null,Ke,Ie),x.allowVerticalPlacement&&(pt=doe(At,null,Ke,Ie)));const Rt=X>0?at/X:1;vt&&(k.iconBBox=gT(vt,k.iconBBox,et,Rt!==1?Rt:void 0)),pt&&(k.iconVerticalBBox=gT(pt,k.iconVerticalBBox,et+90,Rt!==1?Rt:void 0))}function xdt(k,x,j,A,L,O,$,Y){const X=k.hasLayoutProperty("icon-offset")?x.getAppearanceValueAndResolveTokens(k,"icon-offset",j,A,[]):null,le=X&&Array.isArray(X)?X:L,xe=k.hasLayoutProperty("icon-rotate")?x.getAppearanceValueAndResolveTokens(k,"icon-rotate",j,A,[]):null,je=typeof xe=="number"?xe:O,Ce=k.hasLayoutProperty("icon-size")?x.getAppearanceValueAndResolveTokens(k,"icon-size",j,A,[]):null;return{appearanceIconOffset:le,appearanceIconRotate:je,appearanceIconSize:typeof Ce=="number"?Ce*Y:$}}function Hus(k,x,j,A,L,O,$,Y,X,le){const{appearanceTextOffset:xe,appearanceTextRotate:je,appearanceTextSize:Ce}=gdt(j,x,A,L,O,$,Y),Ie=Ce/Y,Fe=[(xe[0]-O[0])*Ie,(xe[1]-O[1])*Ie],Ke=Fe[0]!==0||Fe[1]!==0;X&&(k.textBBox=gT(X,k.textBBox,je,Ie,xe,Ke?Fe:void 0)),le&&(k.textVerticalBBox=gT(le,k.textVerticalBBox,je+90,Ie,xe,Ke?Fe:void 0))}function gdt(k,x,j,A,L,O,$){const Y=k.hasLayoutProperty("text-offset")?x.getAppearanceValueAndResolveTokens(k,"text-offset",j,A,[]):null,X=Y&&Array.isArray(Y)?[Y[0]*Vp,Y[1]*Vp]:L,le=k.hasLayoutProperty("text-rotate")?x.getAppearanceValueAndResolveTokens(k,"text-rotate",j,A,[]):null,xe=typeof le=="number"?le:O,je=k.hasLayoutProperty("text-size")?x.getAppearanceValueAndResolveTokens(k,"text-size",j,A,[]):null;return{appearanceTextOffset:X,appearanceTextRotate:xe,appearanceTextSize:typeof je=="number"?je:$}}function xoe(k,x,j,A,L,O,$,Y,X){if(!x||!x.usvg)return;const le=Jct(A),xe=Jct(L),je=O!=="both"&&O!=="width"||!Xct(A)?1:xe.width/le.width,Ce=O!=="both"&&O!=="height"||!Qct(A)?1:xe.height/le.height;j.scaleSelf(je,Ce);const Ie=j.toString();$.set(Ie,j),Y.set(Ie,x);const{imagePosition:Fe}=GRe(Ie,x,1);X.set(Ie,Fe)}function ydt(k,x,j,A,L,O,$,Y,X,le){if(!k)return;const xe=function(je,Ce,Ie,Fe,Ke,et,at){if(je.kind==="camera")return je.maxSize;if(je.kind==="composite"){const vt=Ce.possiblyEvaluate(new Vi(je.maxZoom,{worldview:et}),Ie,at).evaluate(Ke,{},Ie,at),pt=Ce.possiblyEvaluate(new Vi(je.minZoom,{worldview:et}),Ie,at).evaluate(Ke,{},Ie,at);return Math.max(vt,pt)}return Ce.possiblyEvaluate(new Vi(Fe,{worldview:et}),Ie,at).evaluate(Ke,{},Ie,at)}(x,j,A,L,O,X,le);return k.scaleSelf(xe*Y*$)}function hY(k,x,j,A,L,O,$,Y,X,le){return{iconPrimary:ydt(k.getPrimary(),x,j,A,L,O,$,Y,X,le),iconSecondary:ydt(k.getSecondary(),x,j,A,L,O,$,Y,X,le)}}function Gus(k,x,j){if(!x)return;const A=j.get(k.toString()),L=j.get(x.toString());A&&L&&(A.paddedRect.w===L.paddedRect.w&&A.paddedRect.h===L.paddedRect.h||aa(`Mismatch in icon variant sizes: ${k.toString()} and ${x.toString()}`),A.usvg!==L.usvg&&aa(`Mismatch in icon variant image types: ${k.id} and ${x.id}`))}function vdt(k,x,j,A){if(!k)return;const L=x.get(j.toString());if(L&&(k.imagePrimary=L),A){const O=x.get(A.toString());k.imageSecondary=O}}function Wus(k,x){for(const j in k.horizontal)bdt(k.horizontal[j],x);bdt(k.vertical,x)}function bdt(k,x){if(k){for(const j of k.positionedLines)for(const A of j.positionedGlyphs)if(A.image!==null){const L=A.image.toString();A.rect=x.get(L).paddedRect}}}function XRe(k){switch(k){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function Kus(k,x,j,A,L,O,$,Y,X){const le=goe(O.horizontal)||O.vertical,xe=j.get("icon-text-fit-padding").evaluate(A,{},L);let je,Ce=x;return x&&X!=="none"&&(k.allowVerticalPlacement&&O.vertical&&(je=URe(x,O.vertical,X,xe,Y,$)),le&&(Ce=URe(x,le,X,xe,Y,$))),{defaultShapedIcon:Ce,verticallyShapedIcon:je}}function _dt(k,x){return k*x/24}function Yus(k,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt,pt,At,Rt,Bt,Ns){let us=$.textMaxSize.evaluate(x,{},Ce);us===void 0?us=Y*$.textScaleFactor:us*=$.textScaleFactor;const ws=k.layers[0].layout,ys=_dt(Y,$.textScaleFactor),vs=goe(j.horizontal)||j.vertical,vn=k.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Nn=k.getAppearanceFeatureData(x.index);(et!=="none"||vn)&&Nn&&(Nn.textShaping=vs,Nn.iconTextFitPadding=ws.get("icon-text-fit-padding").evaluate(x,{},Ce),Nn.fontScale=ys,Nn.textScaleFactor=$.textScaleFactor);const Rn=Ie.name==="globe",$n=k.tilePixelRatio*us/24,Fn=(yr=k.overscaling,k.zoom>18&&yr>2&&(yr>>=1),Math.max(fr/(512*yr),1)*ws.get("symbol-spacing")),sr=ws.get("text-padding")*k.tilePixelRatio,gn=ws.get("icon-padding")*k.tilePixelRatio,Bn=Gs(ws.get("text-max-angle")),Vn=ws.get("icon-rotation-alignment")==="map"&&pt!=="point",nr=Fn/2;var yr;k.hasAnyIconTextFit===!1&&et!=="none"&&(k.hasAnyIconTextFit=!0);const ra=x.properties?+x.properties[Xi]:null,Er=ra&&k.elevationFeatureIdToIndex?k.elevationFeatureIdToIndex.get(ra):65535,Cr=(vr,ta,fa)=>{if(ta.x<0||ta.x>=fr||ta.y<0||ta.y>=fr)return;let ei=null;if(Rn){const{x:Aa,y:zi,z:Xo}=Ie.projectTilePoint(ta.x,ta.y,fa);ei={anchor:new p3(Aa,zi,Xo,0,void 0),up:Ie.upVector(fa,ta.x,ta.y)}}(function(Aa,zi,Xo,Bi,sl,lo,Lu,Dl,hl,qc,ku,Hp,Su,Ju,sm,eh,Zx,Gp,xo,Zy,bh,wf,Xy,Xx,Iu,ty,jf,Doe,dB,Z0,_Fe,uB){const f3=Aa.addToLineVertexArray(zi,Bi);let x3,fw,xw,SI,hB,_o,Nf,th=0,vp=0,gw=0,H1=0,G1=-1,W1=-1;const x2={};let Roe=mc("");const gk=Xo?Xo.anchor:zi,mB=Doe!=="none";let pB=0,Wm=0;if(hl._unevaluatedLayout.getValue("text-radial-offset")===void 0){const _h=hl.layout.get("text-offset").evaluate(bh,{},Iu);pB=_h[0]*Vp,Wm=_h[1]*Vp}else pB=hl.layout.get("text-radial-offset").evaluate(bh,{},Iu)*Vp,Wm=ZRe;if(Aa.allowVerticalPlacement&&sl.vertical){const _h=sl.vertical;if(sm)_o=eFe(_h),Dl&&(Nf=eFe(Dl));else{const Qy=hl.layout.get("text-rotate").evaluate(bh,{},Iu)+90;xw=yoe(qc,gk,zi,ku,Hp,Su,_h,Ju,Qy,eh,uB),Dl&&(SI=yoe(qc,gk,zi,ku,Hp,Su,Dl,Gp,Qy,null,_Fe))}}if(lo){const _h=hl.layout.get("icon-rotate").evaluate(bh,{},Iu),Qy=YRe(lo,_h,Xy,mB,wf.iconScaleFactor),X0=Dl?YRe(Dl,_h,Xy,mB,wf.iconScaleFactor):void 0;fw=yoe(qc,gk,zi,ku,Hp,Su,lo,Gp,_h,null,Z0);const y2=function(yk,CY,fB,dms,ums,Uut,qut,hms,M_r,jFe){const Vut=yk.layers[0],Hut=Vut.appearances;let xB=CY.length;if(fB&&(xB=Math.max(xB,fB.length)),Hut.length===0)return xB;const[mms,pms]=dms.get("icon-size-scale-range"),fms=gt(1,mms,pms);for(const Boe of Hut)if(Boe.hasLayoutProperty("icon-image")){const Gut=Vut.getAppearanceValueAndResolveTokens(Boe,"icon-image",Uut,qut,jFe);if(Gut){const Wut=yk.getResolvedImageFromTokens(Gut);if(Wut){const Kut=Boe.hasLayoutProperty("icon-size")?Boe.getUnevaluatedLayoutProperty("icon-size"):ums._values["icon-size"],xms=hY(Wut,bI(yk.zoom,Kut,yk.worldview,jFe),Kut,qut,yk.zoom,Uut,yk.pixelRatio,fms,yk.worldview,jFe),Yut=hms.get(xms.iconPrimary.toString());Yut&&(xB=Math.max(xB,Fus(Yut)))}}}return xB}(Aa,Qy,X0,hl.layout,hl._unevaluatedLayout,bh,Iu,Aa.iconAtlasPositions,0,Xx);th=4*y2;const Foe=hl.layout.get("icon-size").evaluate(bh,{},Iu,Xx),Ooe=wf.compositeIconSizes?wf.compositeIconSizes[0].evaluate(bh,{},Iu,Xx):0,wFe=wf.compositeIconSizes?wf.compositeIconSizes[1].evaluate(bh,{},Iu,Xx):0,zoe=JRe(Aa.layerIds[0],Aa.iconSizeData,Foe,wf.iconScaleFactor,Ooe,wFe);Aa.addSymbols(Aa.icon,Qy,zoe,Zy,xo,bh,void 0,Xo,zi,f3.lineStartIndex,f3.lineLength,-1,Xx,Iu,ty,jf,Aa.symbolInstances.length,y2),G1=Aa.icon.placedSymbolArray.length-1,X0&&(vp=4*y2,Aa.addSymbols(Aa.icon,X0,zoe,Zy,xo,bh,V1.vertical,Xo,zi,f3.lineStartIndex,f3.lineLength,-1,Xx,Iu,ty,jf,Aa.symbolInstances.length,y2),W1=Aa.icon.placedSymbolArray.length-1)}for(const _h in sl.horizontal){const Qy=_h,X0=sl.horizontal[Qy];x3||(Roe=mc(X0.text),sm?hB=eFe(X0):x3=yoe(qc,gk,zi,ku,Hp,Su,X0,Ju,hl.layout.get("text-rotate").evaluate(bh,{},Iu),eh,uB));const y2=X0.positionedLines.length===1;if(gw+=wdt(Aa,Xo,zi,X0,Lu,hl,sm,bh,eh,f3,sl.vertical?V1.horizontal:V1.horizontalOnly,y2?$us(sl.horizontal):[Qy],x2,G1,wf,Xx,Iu,Aa.symbolInstances.length,ty),y2)break}sl.vertical&&(H1+=wdt(Aa,Xo,zi,sl.vertical,Lu,hl,sm,bh,eh,f3,V1.vertical,["vertical"],x2,W1,wf,Xx,Iu,Aa.symbolInstances.length,ty));let Sm=-1;const bp=(_h,Qy)=>_h?Math.max(_h,Qy):Qy;Sm=bp(hB,Sm),Sm=bp(_o,Sm),Sm=bp(Nf,Sm);const g2=Sm>-1?1:0;Aa.glyphOffsetArray.length>=65535&&aa("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),bh.sortKey!==void 0&&Aa.addToSortKeyRanges(Aa.symbolInstances.length,bh.sortKey),Aa.symbolInstances.emplaceBack(zi.x,zi.y,gk.x,gk.y,gk.z,x2.right>=0?x2.right:-1,x2.center>=0?x2.center:-1,x2.left>=0?x2.left:-1,x2.vertical>=0?x2.vertical:-1,G1,W1,Roe,x3!==void 0?x3:Aa.collisionBoxArray.length,x3!==void 0?x3+1:Aa.collisionBoxArray.length,xw!==void 0?xw:Aa.collisionBoxArray.length,xw!==void 0?xw+1:Aa.collisionBoxArray.length,fw!==void 0?fw:Aa.collisionBoxArray.length,fw!==void 0?fw+1:Aa.collisionBoxArray.length,SI||Aa.collisionBoxArray.length,SI?SI+1:Aa.collisionBoxArray.length,ku,gw,H1,th,vp,g2,0,pB,Wm,Sm,0,mB?1:0,dB)})(k,ta,ei,vr,j,A,O,L,k.layers[0],k.collisionBoxArray,x.index,x.sourceLayerIndex,k.index,sr,vt,le,0,gn,Vn,at,x,$,xe,je,Ce,Fe,Ke,et,Er,At,Rt,Bt)};if(pt==="line")for(const vr of Xie(x.geometry,0,0,fr,fr)){const ta=Rus(vr,Fn,Bn,j.vertical||vs,A,24,$n,k.overscaling,fr);for(const fa of ta)vs&&Zus(k,vs.text,nr,fa)||Cr(vr,fa,Ce)}else if(pt==="line-center"){for(const vr of x.geometry)if(vr.length>1){const ta=Dus(vr,Bn,j.vertical||vs,A,24,$n);ta&&Cr(vr,ta,Ce)}}else if(x.type==="Polygon")for(const vr of KK(x.geometry,0)){const ta=zus(vr,16);Cr(vr[0],new p3(ta.x,ta.y,0,0,void 0),Ce)}else if(x.type==="LineString")for(const vr of x.geometry)Cr(vr,new p3(vr[0].x,vr[0].y,0,0,void 0),Ce);else if(x.type==="Point")for(const vr of x.geometry)for(const ta of vr)Cr([ta],new p3(ta.x,ta.y,0,0,void 0),Ce)}const QRe=255,_I=QRe*m3;function wdt(k,x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt){const pt=pdt(0,A,X,O,$,Y,L,k.allowVerticalPlacement,void 0,Fe.textScaleFactor),At=O.layout.get("text-size").evaluate(Y,{},et),Rt=Fe.compositeTextSizes?Fe.compositeTextSizes[0].evaluate(Y,{},et):0,Bt=Fe.compositeTextSizes?Fe.compositeTextSizes[1].evaluate(Y,{},et):0,Ns=JRe(k.layerIds[0],k.textSizeData,At,Fe.textScaleFactor,Rt,Bt);k.addSymbols(k.text,pt,Ns,X,$,Y,xe,x,j,le.lineStartIndex,le.lineLength,Ie,Ke,et,vt,!1,at,pt.length);for(const us of je)Ce[us]=k.text.placedSymbolArray.length-1;return 4*pt.length}function JRe(k,x,j,A,L,O){const $=x;let Y=null;return $.kind==="source"?(Y=[m3*j*A],Y[0]>_I&&aa(`${k}: Value for "text-size" is >= ${QRe}. Reduce your "text-size".`)):$.kind==="composite"&&(Y=[m3*L*A,m3*O*A],(Y[0]>_I||Y[1]>_I)&&aa(`${k}: Value for "text-size" is >= ${QRe}. Reduce your "text-size".`)),Y}function goe(k){for(const x in k)return k[x];return null}function yoe(k,x,j,A,L,O,$,Y,X,le,xe){let je,Ce,Ie,Fe;if(je=xe?xe.top:$.top,Ce=xe?xe.bottom:$.bottom,Ie=xe?xe.left:$.left,Fe=xe?xe.right:$.right,$Re($)&&$.collisionPadding){const Ke=$.collisionPadding;Ie-=Ke[0],je-=Ke[1],Fe+=Ke[2],Ce+=Ke[3]}if(X){const Ke=new Ss(Ie,je),et=new Ss(Fe,je),at=new Ss(Ie,Ce),vt=new Ss(Fe,Ce),pt=Gs(X);let At=new Ss(0,0);le&&(At=new Ss(le[0],le[1])),Ke._rotateAround(pt,At),et._rotateAround(pt,At),at._rotateAround(pt,At),vt._rotateAround(pt,At),Ie=Math.min(Ke.x,et.x,at.x,vt.x),Fe=Math.max(Ke.x,et.x,at.x,vt.x),je=Math.min(Ke.y,et.y,at.y,vt.y),Ce=Math.max(Ke.y,et.y,at.y,vt.y)}return k.emplaceBack(x.x,x.y,x.z,j.x,j.y,Ie,je,Fe,Ce,Y,A,L,O),k.length-1}function eFe(k){$Re(k)&&k.collisionPadding&&(k.top-=k.collisionPadding[1],k.bottom+=k.collisionPadding[3]);const x=k.bottom-k.top;return x>0?Math.max(10,x):null}function Zus(k,x,j,A){const L=k.compareText;if(x in L){const O=L[x];for(let $=O.length-1;$>=0;$--)if(A.dist(O[$])pt&&(At(Bt,Rn,us,ws,vn,Nn),At(Rn,Ns,vn,Nn,ys,vs))}At(je,Ce,A,O,L,O),At(Ce,Ie,L,O,L,$),At(Ie,Fe,L,$,A,$),At(Fe,je,A,$,A,O),Ke-=pt,et-=pt,at+=pt,vt+=pt;const Rt=1/Math.max(at-Ke,vt-et);return{scale:Rt,x:Ke*Rt,y:et*Rt,x2:at*Rt,y2:vt*Rt,projection:x}}function Ndt(k,{x,y:j},A=0){return new Ss(((x-A)*k.scale-k.x)*fr,(j*k.scale-k.y)*fr)}const Xus=v(new Float32Array(16));class yT{constructor(x){this.spec=x,this.name=x.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(x,j){return{x:0,y:0,z:0}}unproject(x,j){return new Ds(0,0)}projectTilePoint(x,j,A){return{x,y:j,z:0}}locationPoint(x,j,A,L=!0){return x._coordinatePoint(x.locationCoordinate(j,A),L)}pixelsPerMeter(x,j){return nn(1,x)*j}pixelSpaceConversion(x,j,A){return 1}farthestPixelDistance(x){return jdt(x,x.pixelsPerMeter)}pointCoordinate(x,j,A,L){const O=x.horizonLineFromTop(!1),$=new Ss(j,Math.max(O,A));return x.rayIntersectionCoordinate(x.pointRayIntersection($,L))}pointCoordinate3D(x,j,A){const L=new Ss(j,A);if(x.elevation)return x.elevation.pointCoordinate(L);{const O=this.pointCoordinate(x,L.x,L.y,0);return[O.x,O.y,O.z]}}isPointAboveHorizon(x,j){if(x.elevation&&x.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(x,j.x,j.y);const A=x.horizonLineFromTop();return j.y0?j<-nB+A&&(j=-nB+A):j>nB-A&&(j=nB-A);const $=O/Math.pow(boe(j),L);let Y=$*Math.sin(L*x),X=O-$*Math.cos(L*x);return Y=.5*(Y/Math.PI+.5),X=.5*(X/Math.PI+.5),{x:Y,y:this.southernCenter?X:1-X,z:0}}unproject(x,j){x=(2*x-.5)*Math.PI,this.southernCenter&&(j=1-j),j=(2*(1-j)-.5)*Math.PI;const{n:A,f:L}=this,O=L-j,$=Math.sign(O),Y=Math.sign(A)*Math.sqrt(x*x+O*O);let X=Math.atan2(x,Math.abs(O))*$;O*A<0&&(X-=Math.PI*Math.sign(x)*$);const le=gt(an(X/A)+this.center[0],-180,180),xe=gt(an(2*Math.atan(Math.pow(L/Y,1/A))-nB),-85.051129,In);return new Ds(le,this.southernCenter?-xe:xe)}}class kdt extends yT{constructor(x){super(x),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(x,j){return{x:Un(x),y:Xn(j),z:0}}unproject(x,j){const A=Bs(x),L=yn(j);return new Ds(A,L)}}const Sdt=Gs(In);class shs extends yT{project(x,j){const A=(j=Gs(j))*j,L=A*A;return{x:.5*((x=Gs(x))*(.8707-.131979*A+L*(L*(.003971*A-.001529*L)-.013791))/Math.PI+.5),y:1-.5*(j*(1.007226+A*(.015085+L*(.028874*A-.044475-.005916*L)))/Math.PI+1),z:0}}unproject(x,j){x=(2*x-.5)*Math.PI;let A=j=(2*(1-j)-1)*Math.PI,L=25,O=0,$=A*A;do{$=A*A;const le=$*$;O=(A*(1.007226+$*(.015085+le*(.028874*$-.044475-.005916*le)))-j)/(1.007226+$*(.045255+le*(.259866*$-.311325-.005916*11*le))),A=gt(A-O,-Sdt,Sdt)}while(Math.abs(O)>1e-6&&--L>0);$=A*A;const Y=gt(an(x/(.8707+$*($*($*$*$*(.003971-.001529*$)-.013791)-.131979))),-180,180),X=an(A);return new Ds(Y,X)}}const Cdt=Gs(In);class nhs extends yT{project(x,j){j=Gs(j),x=Gs(x);const A=Math.cos(j),L=2/Math.PI,O=Math.acos(A*Math.cos(x/2)),$=Math.sin(O)/O,Y=.5*(x*L+2*A*Math.sin(x/2)/$)||0,X=.5*(j+Math.sin(j)/$)||0;return{x:.5*(Y/Math.PI+.5),y:1-.5*(X/Math.PI+1),z:0}}unproject(x,j){let A=x=(2*x-.5)*Math.PI,L=j=(2*(1-j)-1)*Math.PI,O=25;const $=1e-6;let Y=0,X=0;do{const le=Math.cos(L),xe=Math.sin(L),je=2*xe*le,Ce=xe*xe,Ie=le*le,Fe=Math.cos(A/2),Ke=Math.sin(A/2),et=2*Fe*Ke,at=Ke*Ke,vt=1-Ie*Fe*Fe,pt=vt?1/vt:0,At=vt?Math.acos(le*Fe)*Math.sqrt(1/vt):0,Rt=.5*(2*At*le*Ke+2*A/Math.PI)-x,Bt=.5*(At*xe+L)-j,Ns=.5*pt*(Ie*at+At*le*Fe*Ce)+1/Math.PI,us=pt*(et*je/4-At*xe*Ke),ws=.125*pt*(je*Ke-At*xe*Ie*et),ys=.5*pt*(Ce*Fe+At*at*le)+.5,vs=us*ws-ys*Ns;Y=(Bt*us-Rt*ys)/vs,X=(Rt*ws-Bt*Ns)/vs,A=gt(A-Y,-Math.PI,Math.PI),L=gt(L-X,-Cdt,Cdt)}while((Math.abs(Y)>$||Math.abs(X)>$)&&--O>0);return new Ds(an(A),an(L))}}class Adt extends yT{constructor(x){super(x),this.center=x.center||[0,0],this.parallels=x.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Gs(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(x,j){const{scale:A,cosPhi:L}=this;return{x:Gs(x)*L*A+.5,y:-Math.sin(Gs(j))/L*A+.5,z:0}}unproject(x,j){const{scale:A,cosPhi:L}=this,O=-(j-.5)/A,$=gt(an((x-.5)/A)/L,-180,180),Y=Math.asin(gt(O*L,-1,1)),X=gt(an(Y),-85.051129,In);return new Ds($,X)}}class rhs extends kdt{constructor(x){super(x),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(x,j,A){const L=$K(x,j,A);return Ve(L,L,UK(f5(A))),{x:L[0],y:L[1],z:L[2]}}locationPoint(x,j,A){const L=is(j.lat,j.lng),O=Ne([],L),$=A?x._centerAltitude+A:x.elevation?x.elevation.getAtPointOrZero(x.locationCoordinate(j),x._centerAltitude):x._centerAltitude;ve(L,L,O,nn(1,0)*fr*$);const Y=v(new Float64Array(16));return b(Y,x.pixelMatrix,x.globeMatrix),Ve(L,L,Y),new Ss(L[0],L[1])}pixelsPerMeter(x,j){return nn(1,0)*j}pixelSpaceConversion(x,j,A){const L=nn(1,x)*j,O=Pr(nn(1,45)*j,L,A);return this.pixelsPerMeter(x,j)/O}createTileMatrix(x,j,A){const L=KDe(f5(A.canonical));return b(new Float64Array(16),x.globeMatrix,L)}createInversionMatrix(x,j){const{center:A}=x,L=UK(f5(j));return E(L,L,Gs(A.lng)),C(L,L,Gs(A.lat)),S(L,L,[x._pixelsPerMercatorPixel,x._pixelsPerMercatorPixel,1]),Float32Array.from(L)}pointCoordinate(x,j,A,L){return Vot(x,j,A,!0)||new pa(0,0)}pointCoordinate3D(x,j,A){const L=this.pointCoordinate(x,j,A,0);return[L.x,L.y,L.z]}isPointAboveHorizon(x,j){return!Vot(x,j.x,j.y,!1)}farthestPixelDistance(x){const j=function(L,O){const $=L.cameraToCenterDistance,Y=L._centerAltitude*O,X=L._camera,le=L._camera.forward(),xe=oe([],ce([],le,-$),[0,0,Y]),je=L.worldSize/(2*Math.PI),Ce=[0,0,-je],Ie=L.width/L.height,Fe=Math.tan(L.fovAboveCenter),Ke=ce([],X.up(),Fe),et=ce([],X.right(),Fe*Ie),at=Ne([],oe([],oe([],le,Ke),et)),vt=[];let pt;if(new jo(xe,at).closestPointOnSphere(Ce,je,vt)){const At=oe([],vt,Ce),Rt=qe([],At,xe);pt=Math.cos(L.fovAboveCenter)*H(Rt)}else{const At=qe([],xe,Ce),Rt=qe([],Ce,xe);Ne(Rt,Rt);const Bt=H(At)-je;pt=Math.sqrt(Bt*(Bt+2*je));const Ns=Math.acos(pt/(je+Bt))-Math.acos(Pe(le,Rt));pt*=Math.cos(Ns)}return 1.01*pt}(x,this.pixelsPerMeter(x.center.lat,x.worldSize)),A=d3(x.zoom);if(A>0){const L=jdt(x,nn(1,x.center.lat)*x.worldSize),O=x.worldSize/(2*Math.PI),$=Math.max(x.width,x.height)/x.worldSize*Math.PI;return Pr(j,L+O*(1-Math.cos($)),Math.pow(A,10))}return j}upVector(x,j,A){return $K(j,A,x,1)}upVectorScale(x){return{metersToTile:Lie(Die(f5(x)))}}}function Edt(k){const x=k.parallels,j=!!x&&Math.abs(x[0]+x[1])<.01;switch(k.name){case"mercator":return new kdt(k);case"equirectangular":return new ehs(k);case"naturalEarth":return new shs(k);case"equalEarth":return new Jus(k);case"winkelTripel":return new nhs(k);case"albers":return j?new Adt(k):new Qus(k);case"lambertConformalConic":return j?new Adt(k):new ths(k);case"globe":return new rhs(k)}throw new Error(`Invalid projection name: ${k.name}`)}class ahs{constructor(x,j){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=j,this.appearances=x;const A=x.map(L=>function(O){if(!O.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const $=O.condition.expression;return{featureDependent:!Vb($),stateDependent:!Gx($),zoomDependent:!Yu($,["zoom"]),pitchDependent:!Yu($,["pitch"]),brightnessDependent:!Yu($,["brightness","measure-light"]),worldviewDependent:!Yu($,["worldview"])}}(L));this.anyFeatureDependent=A.some(L=>L.featureDependent),this.anyStateDependent=A.some(L=>L.stateDependent)}update(x,j){const A=this.lastParams,L=!A||A.zoom!==x.zoom||A.pitch!==(x.pitch||0)||A.brightness!==(x.brightness||0)||A.worldview!==x.worldview;this.lastParams={zoom:x.zoom,pitch:x.pitch||0,brightness:x.brightness||0,worldview:x.worldview};const O=j&&this.anyStateDependent;if(!L&&!O&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!O){const $=this.evaluateAllFeatures(x);return $===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=$,{kind:"all-features",appearanceIndex:$})}return{kind:"per-feature"}}evaluateAllFeatures(x){for(let j=0;j{for(let L=0;L$-Y),O=new Map;for(const $ of L){const Y=A.get($);O.set($,new Bc(Y))}return j&&(this.cachedBatchIndices=L,this.cachedBatchSegments=O),{batchIndices:L,batchSegments:O}}snapshotSymbolVertexData(x,j){const A=x*aB;return this.layoutVertexArray.uint16.slice(A,A+j*aB)}restoreSymbolVertexData(x,j){this.layoutVertexArray.uint16.set(j,x*aB)}updateSymbolVertexData(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie){const Fe=this.layoutVertexArray.uint16,Ke=x*aB;Fe[Ke]=j,Fe[Ke+1]=A,Fe[Ke+2]=L,Fe[Ke+3]=O,Fe[Ke+4]=$,Fe[Ke+5]=Y,Fe[Ke+6]=X,Fe[Ke+7]=le,Fe[Ke+8]=xe,Fe[Ke+9]=je,Fe[Ke+10]=Ce,Fe[Ke+11]=Ie}upload(x,j,A,L,O,$){this.isEmpty()||(A&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,lus.members,!!$),this.indexBuffer=x.createIndexBuffer(this.indexArray,j),this.dynamicLayoutVertexBuffer=x.createVertexBuffer(this.dynamicLayoutVertexArray,dus.members,!0),this.opacityVertexBuffer=x.createVertexBuffer(this.opacityVertexArray,ohs,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=x.createVertexBuffer(this.iconTransitioningVertexArray,pus.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=x.createVertexBuffer(this.globeExtVertexArray,cus.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||O)&&(this.zOffsetVertexBuffer=x.createVertexBuffer(this.zOffsetVertexArray,uus.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=x.createVertexBuffer(this.orientationVertexArray,mus.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=x.createVertexBuffer(this.featureIdArray,hus.members,!1))),(A||L)&&(this.programConfigurations.upload(x),this.uboBinder&&this.uboBinder.upload(x)))}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())}}kr(tFe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class sFe{constructor(x,j,A){this.layoutVertexArray=new x,this.layoutAttributes=j,this.indexArray=new A,this.segments=new Bc,this.collisionVertexArray=new oI,this.collisionVertexArrayExt=new dk}upload(x){this.layoutVertexBuffer=x.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=x.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=x.createVertexBuffer(this.collisionVertexArray,fus.members,!0),this.collisionVertexBufferExt=x.createVertexBuffer(this.collisionVertexArrayExt,xus.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}kr(sFe,"CollisionBuffers");class pk{constructor(x){this.collisionBoxArray=x.collisionBoxArray,this.zoom=x.zoom,this.overscaling=x.overscaling,this.layers=x.layers,this.layerIds=this.layers.map($=>$.fqid),this.index=x.index,this.pixelRatio=x.pixelRatio,this.sourceLayerIndex=x.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=v([]),this.placementViewportMatrix=v([]);const j=this.layers[0]._unevaluatedLayout._values;this.worldview=x.worldview,this.localizable=x.localizable,this.maxUniformBufferBindings=x.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=x.maxUniformBlockSizeDwords,this.disableSymbolUBO=x.disableSymbolUBO,this.textSizeData=bI(this.zoom,j["text-size"],this.worldview,x.availableImages),this.iconSizeData=bI(this.zoom,j["icon-size"],this.worldview,x.availableImages);const A=this.layers[0].layout,L=A.get("symbol-sort-key"),O=A.get("symbol-z-order");this.lut=x.lut,this.canOverlap=A.get("text-allow-overlap")||A.get("icon-allow-overlap")||A.get("text-ignore-placement")||A.get("icon-ignore-placement"),this.sortFeaturesByKey=O!=="viewport-y"&&L.constantOr(1)!==void 0,this.sortFeaturesByY=(O==="viewport-y"||O==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=A.get("text-writing-mode").map($=>V1[$]),this.stateDependentLayerIds=this.layers.filter($=>$.isStateDependent()).map($=>$.id),this.sourceID=x.sourceID,this.projection=x.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(x){const j=this.layers[0].getAppearances();if(!j||j.length===0)return!1;const A=Array.isArray(x)?x:[x];return j.some(L=>A.some(O=>L.hasLayoutProperty(O)))}getAppearanceFeatureData(x){return this.featureAppearanceData.get(x)}createArrays(){this.text=new tFe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},x=>x.startsWith("text")||x.startsWith("symbol"))),this.icon=new tFe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},x=>x.startsWith("icon")||x.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new FRe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new FRe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new Cie,this.lineVertexArray=new dI,this.symbolInstances=new Sie}calculateGlyphDependencies(x,j,A,L,O){for(const $ of x){const Y=$.codePointAt(0);if(Y===void 0)break;if(j[Y]=!0,L&&O&&Y<=65535){const X=oY[$];X&&(j[X.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(x,j,A,L,O,$,Y){if(!x.hasLayoutProperty("icon-size"))return Y*$;let X=1;const le=x.getUnevaluatedLayoutProperty("icon-size"),xe=bI(this.zoom,le,this.worldview,O),je=tB(xe,j);if(xe.kind!=="constant"&&xe.kind!=="camera"||(X=je.uSize),xe.kind==="composite"){const{minZoom:Ce,maxZoom:Ie}=xe,Fe=le.possiblyEvaluate(new Vi(Ce,{worldview:this.worldview}),L),Ke=le.possiblyEvaluate(new Vi(Ie,{worldview:this.worldview}),L),et=Fe.evaluate(A,{},L,O);X=et+(Ke.evaluate(A,{},L,O)-et)*je.uSizeT}return xe.kind==="source"&&(X=le.possiblyEvaluate(new Vi(this.zoom,{worldview:this.worldview}),L).evaluate(A,{},L,O)),X*$}updateFootprints(x,j){}updateReplacement(x,j){if(j.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=j.updateTime;const A=j.getReplacementRegionsForTile(x.toUnwrapped(),!0);return!Hie(this.activeReplacements,A)&&(this.activeReplacements=A,!0)}getResolvedImageFromTokens(x){return typeof x=="string"?Th.build(x):x}populate(x,j,A,L){const O=this.layers[0],$=O.layout,Y=this.projection.name==="globe",X=$.get("text-font"),le=$.get("text-field"),xe=$.get("icon-image"),[je,Ce]=$.get("icon-size-scale-range"),Ie=gt(j.scaleFactor||1,je,Ce),[Fe,Ke]=$.get("text-size-scale-range"),et=gt(j.scaleFactor||1,Fe,Ke),at=(le.value.kind!=="constant"||le.value.value instanceof gd&&!le.value.value.isEmpty()||le.value.value.toString().length>0)&&(X.value.kind!=="constant"||X.value.value.length>0),vt=xe.value.kind!=="constant"||!!xe.value.value||Object.keys(xe.parameters).length>0,pt=this.hasAnyAppearanceLayoutProperty("icon-image"),At=$.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!at&&!vt&&!pt)return;const Rt=j.iconDependencies,Bt=j.glyphDependencies,Ns=j.availableImages,us=new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),ws=ys=>{const vs=ys.id.toString();Rt.has(vs)?Rt.get(vs).push(ys):Rt.set(vs,[ys])};for(const ys of x){const{feature:vs,id:vn,index:Nn,sourceLayerIndex:Rn}=ys,$n=O._featureFilter.needGeometry,Fn=oo(vs,$n);if(!O._featureFilter.filter(us,Fn,A))continue;if($n||(Fn.geometry=ti(vs,A,L)),Y&&vs.type!==1&&A.z<=5){const Er=Fn.geometry,Cr=.98078528056,vr=(ta,fa)=>Pe($K(ta.x,ta.y,A,1),$K(fa.x,fa.y,A,1)){if(!Er.getLayoutProperty("icon-image"))return;const Cr=this.getCombinedIconPrimary(Er,Bn,Fn,A,Ns,yr,Ie);Cr&&ws(Cr)}),sr){const Er=X.evaluate(Fn,{},A).join(","),Cr=$.get("text-rotation-alignment")==="map"&&$.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(V1.vertical)>=0;for(const vr of sr.sections)if(vr.image){const ta=vr.image.getPrimary().scaleSelf(this.pixelRatio*et),fa=ta.id.toString(),ei=Rt.get(fa)||[];ei.push(ta),Rt.set(fa,ei)}else{const ta=hx(sr.toString()),fa=vr.fontStack||Er,ei=Bt[fa]=Bt[fa]||{};this.calculateGlyphDependencies(vr.text,ei,Cr,this.allowVerticalPlacement,ta)}}}if($.get("symbol-placement")==="line"&&(this.features=function(ys){const vs={},vn={},Nn=[];let Rn=0;function $n(Bn){Nn.push(ys[Bn]),Rn++}function Fn(Bn,Vn,nr){const yr=vn[Bn];return delete vn[Bn],vn[Vn]=yr,Nn[yr].geometry[0].pop(),Nn[yr].geometry[0]=Nn[yr].geometry[0].concat(nr[0]),yr}function sr(Bn,Vn,nr){const yr=vs[Vn];return delete vs[Vn],vs[Bn]=yr,Nn[yr].geometry[0].shift(),Nn[yr].geometry[0]=nr[0].concat(Nn[yr].geometry[0]),yr}function gn(Bn,Vn,nr){const yr=nr?Vn[0][Vn[0].length-1]:Vn[0][0];return`${Bn}:${yr.x}:${yr.y}`}for(let Bn=0;BnBn.geometry)}(this.features)),$.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",j.elevationFeatures){!this.elevationFeatures&&j.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const ys of j.elevationFeatures)this.elevationFeatureIdToIndex.set(ys.id,this.elevationFeatures.length),this.elevationFeatures.push(ys)}}else $.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((ys,vs)=>ys.sortKey-vs.sortKey)}getCombinedIconPrimary(x,j,A,L,O,$,Y){let X,le;if(x.hasLayoutProperty("icon-image")){const xe=j.getAppearanceValueAndResolveTokens(x,"icon-image",A,L,O);X=this.getResolvedImageFromTokens(xe)}else{const xe=j.getValueAndResolveTokens("icon-image",A,L,O);X=this.getResolvedImageFromTokens(xe)}if(X){const xe=x.hasLayoutProperty("icon-size")?x.getUnevaluatedLayoutProperty("icon-size"):j._unevaluatedLayout._values["icon-size"];le=hY(X,bI(this.zoom,xe,this.worldview,O),xe,L,this.zoom,$,this.pixelRatio,Y,this.worldview,O).iconPrimary}return le}updateSymbolInstanceIconVertices(x,j,A,L,O,$){const{canonical:Y,availableImages:X,globalProperties:le,layer:xe,iconScaleFactor:je,featureState:Ce,layoutIconOffset:Ie,layoutIconSize:Fe,layoutIconRotate:Ke}=$;if(x.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(j.activeAppearanceIndex===A)return{vertexOffsetDelta:x.numIconVertices,hasChanges:!1};const et=A>=0?xe.appearances[A]:null;if(et){const at=this.getCombinedIconPrimary(et,xe,L,Y,X,{sortKey:void 0,text:void 0,icon:null,index:x.featureIndex,sourceLayerIndex:x.featureIndex,geometry:[],properties:j.properties,type:"Point",id:j.id},je);if(!at)return{vertexOffsetDelta:0,hasChanges:!1};const vt=at.toString(),pt=this.iconAtlasPositions&&this.iconAtlasPositions.get(vt);if(pt){const{appearanceIconOffset:At,appearanceIconRotate:Rt}=xdt(et,xe,L,Y,Ie,Ke,Fe,je);let Bt=doe(pt,void 0,At,xe.layout.get("icon-anchor").evaluate(L,Ce,Y));const Ns=pt.sdf,us=xe.layout.get("icon-text-fit").constantOr("none");us!=="none"&&j.textShaping&&j.iconTextFitPadding&&j.fontScale&&(Bt=URe(Bt,j.textShaping,us,j.iconTextFitPadding,At,j.fontScale));const ws=this.calculateEffectiveAppearanceIconSize(et,le.zoom,L,Y,X,je,Fe),ys=0,vs=1+(Math.min(_I,Math.round(ws*m3))<<1),vn=YRe(Bt,Rt,Ns,us!=="none",je);j.isUsingAppearanceIconVertexData||(j.isUsingAppearanceIconVertexData=!0,j.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(O,x.numIconVertices));const Nn=Math.floor(x.numIconVertices/4),Rn=Math.min(vn.length,Nn);let $n=O;for(let sr=0;sr0||x.numVerticalGlyphVertices>0;if(!At)return{vertexOffsetDelta:At?x.numHorizontalGlyphVertices+x.numVerticalGlyphVertices:0,hasChanges:!1};if(j.activeAppearanceIndex===A)return{vertexOffsetDelta:x.numHorizontalGlyphVertices+x.numVerticalGlyphVertices,hasChanges:!1};const Rt=A>=0?X.appearances[A]:null;if(Rt&&j.textShaping){const{appearanceTextOffset:Bt,appearanceTextRotate:Ns,appearanceTextSize:us}=gdt(Rt,X,L,Y,Ce,Fe,Ie);j.fontScale=_dt(us,j.textScaleFactor);const ws=Rt.getUnevaluatedLayoutProperty("text-size");let ys=this.textSizeData,vs=at,vn=vt;Rt.hasLayoutProperty("text-size")&&(ys=bI(this.zoom,ws,this.worldview,pt),vs=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,vn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Nn=j.textShaping.bottom-Ce[1],Rn=j.textShaping.left-Ce[0],$n=j.textShaping.right-Ce[0];j.textShaping.top=Bt[1]+(j.textShaping.top-Ce[1]),j.textShaping.bottom=Bt[1]+Nn,j.textShaping.left=Bt[0]+Rn,j.textShaping.right=Bt[0]+$n;const Fn=pdt(0,j.textShaping,Bt,X,!1,L,xe,this.allowVerticalPlacement,Ns),sr=us&&ys.kind==="composite"?ws.possiblyEvaluate(new Vi(vs,{}),Y).evaluate(L,je,Y):Ke,gn=us&&ys.kind==="composite"?ws.possiblyEvaluate(new Vi(vn,{}),Y).evaluate(L,je,Y):et,Bn=JRe(Rt.name,ys,us,le,sr,gn),Vn=Array.isArray(Bn)?Bn[1]:us,nr=0,yr=1+(Math.min(_I,Math.round(Vn*m3))<<1);j.isUsingAppearanceTextVertexData||(j.isUsingAppearanceTextVertexData=!0,j.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(O,x.numHorizontalGlyphVertices+x.numVerticalGlyphVertices));for(let ra=0;ra0){const le=new Set(Object.keys(x).map(xe=>{const je=Number(xe);return!isNaN(je)&&Number.isSafeInteger(je)&&String(je)===xe?je:xe}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(le,O[0],j,X,A,x,Y),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(le,O[0],j,X,A,x,Y)}}}updateRoadElevation(x){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let j=!1;const A=Kn(x),L=1/A;let O=!1,$=!1;for(let Y=0;Y0||Ce>0,et=Ie>0,at=this.elevationFeatures[X.elevationFeatureIndex];if(at){const vt=new Ss(X.tileAnchorX,X.tileAnchorY),pt=.075+at.pointElevation(vt);X.zOffset!==pt&&(j=!0,X.zOffset=pt),pt!==0&&(this.hasAnyZOffset=!0);const At=at.computeSlopeNormal(vt,L),Rt=qs(ut(),K(0,0,1),At);Ae(le,le,Rt),Ae(xe,xe,Rt),le[2]*=A,xe[2]*=A,le[0]===1&&le[1]===0&&le[2]===0&&xe[0]===0&&xe[1]===1&&xe[2]===0||(O=O||Ke,$=$||et)}if(Ke&&(_oe(this.text.orientationVertexArray,je,le,xe),_oe(this.text.orientationVertexArray,Ce,le,xe)),et){const{placedIconSymbolIndex:vt,verticalPlacedIconSymbolIndex:pt}=X;vt>=0&&_oe(this.icon.orientationVertexArray,Ie,le,xe),pt>=0&&_oe(this.icon.orientationVertexArray,Fe,le,xe)}}O||(this.text.orientationVertexArray=void 0),$||(this.icon.orientationVertexArray=void 0),j&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const x=(O,$,Y)=>{A+=$,A>O.length&&O.resize(A);for(let X=-$;X<0;X++)O.emplace(X+A,Y)},j=(O,$,Y)=>{L+=$,L>O.length&&O.resize(L);for(let X=-$;X<0;X++)O.emplace(X+L,Y)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let A=0,L=0;for(let O=0;O0;if((Y>0||X>0)&&(x(this.text.zOffsetVertexArray,Y,xe),x(this.text.zOffsetVertexArray,X,xe)),je){const{placedIconSymbolIndex:Ce,verticalPlacedIconSymbolIndex:Ie}=$;Ce>=0&&j(this.icon.zOffsetVertexArray,le,xe),Ie>=0&&j(this.icon.zOffsetVertexArray,$.numVerticalIconVertices,xe)}}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(x,j,A,L,O){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(x),this.iconCollisionBox.upload(x)),this.text.upload(x,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some($=>$.appearances&&$.appearances.length>0)),this.icon.upload(x,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(x,j,A,L,O,$=!1){const Y={hasLayoutChanges:!1,hasUboChanges:!1};if(!x||!A||!this.featureAppearanceData)return Y;const X=j||{},le=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,xe=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!le&&!xe)return Y;const je=this.layers[0],Ce=je.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===je.appearancesVersion||(this.featureAppearances=new ahs(je.appearances,je.appearancesVersion));const Ie=this.featureAppearances.update(L,$);if(Ie.kind==="no-changes")return Y;let Fe=1,Ke=0,et=!1,at=!1;if(le){const[Bt,Ns]=Ce.get("icon-size-scale-range");Fe=gt(1,Bt,Ns)}let vt=1,pt=0,At=!1;if(xe){const[Bt,Ns]=Ce.get("text-size-scale-range");vt=gt(1,Bt,Ns)}const Rt=new Map;if(O&&A)for(const Bt of A){const Ns=O.getImage(Bt,je.scope);if(Ns){const us=new Hd(Bt.toString());Rt.set(us.toString(),Ns)}}for(let Bt=0;Bt$n.isActive({globals:L,feature:vs,canonical:x,featureState:ys})):-1;vn=Rn>=0?Rn:-1}const Nn=us.activeAppearanceIndex!==vn;if(xe){const Rn=Ce.get("text-size"),$n=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Fn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,sr={canonical:x,layer:je,featureState:ys,availableImages:A,textScaleFactor:vt,imageMap:Rt,layoutTextOffset:Ce.get("text-offset").evaluate(vs,ys,x).map(Bn=>Bn*Vp),layoutTextSize:Rn.evaluate(vs,ys,x),layoutTextRotate:Ce.get("text-rotate").evaluate(vs,ys,x),layoutMinZoomSize:Rn.evaluate(vs,{zoom:$n},x),layoutMaxZoomSize:Rn.evaluate(vs,{zoom:Fn},x),layoutTextSizeMinZoom:$n,layoutTextSizeMaxZoom:Fn},gn=this.updateSymbolInstanceTextVertices(Ns,us,vn,vs,pt,sr);pt+=gn.vertexOffsetDelta,At=At||gn.hasChanges}if(le){const Rn={canonical:x,layer:je,featureState:ys,availableImages:A,globalProperties:L,iconScaleFactor:Fe,layoutIconOffset:Ce.get("icon-offset").evaluate(vs,ys,x),layoutIconSize:Ce.get("icon-size").evaluate(vs,ys,x,A),layoutIconRotate:Ce.get("icon-rotate").evaluate(vs,ys,x)},$n=this.updateSymbolInstanceIconVertices(Ns,us,vn,vs,Ke,Rn);Ke+=$n.vertexOffsetDelta,et=et||$n.hasChanges}if(Nn){const Rn=Ns.featureIndex,$n=L?L.brightness:null,Fn=ys||{},sr=vn>=0?je.appearances[vn]:null;this.text.uboBinder&&(this.text.uboBinder.layer=je,at=this.text.uboBinder.updateFeaturePaintForAppearance(Rn,vs,Fn,x,A,$n,sr)||at),this.icon.uboBinder&&(this.icon.uboBinder.layer=je,at=this.icon.uboBinder.updateFeaturePaintForAppearance(Rn,vs,Fn,x,A,$n,sr)||at)}us.activeAppearanceIndex=vn}return et&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),At&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:et||At,hasUboChanges:at}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=Edt(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(x,j){const A=this.lineVertexArray.length;if(x.segment!==void 0)for(const{x:L,y:O}of j)this.lineVertexArray.emplaceBack(L,O);return{lineStartIndex:A,lineLength:this.lineVertexArray.length-A}}addSymbols(x,j,A,L,O,$,Y,X,le,xe,je,Ce,Ie,Fe,Ke,et,at,vt){const pt=x.indexArray,At=x.layoutVertexArray,Rt=x.globeExtVertexArray,Bt=vt,Ns=x.uboBinder?x.uboBinder.getCurrentBatchIndex():void 0,us=x.segments.prepareSegment(4*Bt,At,pt,this.canOverlap?$.sortKey:void 0,Ns),ws=this.glyphOffsetArray.length,ys=us.vertexLength,vs=this.allowVerticalPlacement&&Y===V1.vertical?Math.PI/2:0,vn=$.text&&$.text.sections;let Nn=At.length,Rn=-1;for(let sr=0;sr=0)){const sr=4*$n;for(let gn=0;gn=0?j.rightJustifiedTextSymbolIndex:j.centerJustifiedTextSymbolIndex>=0?j.centerJustifiedTextSymbolIndex:j.leftJustifiedTextSymbolIndex>=0?j.leftJustifiedTextSymbolIndex:j.verticalPlacedTextSymbolIndex>=0?j.verticalPlacedTextSymbolIndex:L),$=qRe(this.textSizeData,x,O)/Vp;return this.tilePixelRatio*$}getSymbolInstanceIconSize(x,j,A){const L=this.icon.placedSymbolArray.get(A),O=qRe(this.iconSizeData,x,L);return this.tilePixelRatio*O}_commitDebugCollisionVertexUpdate(x,j,A,L){x.emplaceBack(j,-A,-A,L),x.emplaceBack(j,A,-A,L),x.emplaceBack(j,A,A,L),x.emplaceBack(j,-A,A,L)}_updateTextDebugCollisionBoxes(x,j,A,L,O,$,Y){for(let X=L;X0}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(x,j){const A=x.placedSymbolArray.get(j),L=A.vertexStartIndex+4*A.numGlyphs;for(let O=A.vertexStartIndex;OL[Y]-L[X]||O[X]-O[Y]),$}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let x=0;xthis.symbolInstances.get(j).zOffset-this.symbolInstances.get(x).zOffset)}addToSortKeyRanges(x,j){const A=this.sortKeyRanges[this.sortKeyRanges.length-1];A&&A.sortKey===j?A.symbolInstanceEnd=x+1:this.sortKeyRanges.push({sortKey:j,symbolInstanceStart:x,symbolInstanceEnd:x+1})}sortFeatures(x){if(this.sortFeaturesByY&&this.sortedAngle!==x)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(x),this.sortedAngle=x,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const j of this.symbolInstanceIndexes){const A=this.symbolInstances.get(j);this.featureSortOrder.push(A.featureIndex);const{rightJustifiedTextSymbolIndex:L,centerJustifiedTextSymbolIndex:O,leftJustifiedTextSymbolIndex:$,verticalPlacedTextSymbolIndex:Y,placedIconSymbolIndex:X,verticalPlacedIconSymbolIndex:le}=A;L>=0&&this.addIndicesForPlacedSymbol(this.text,L),O>=0&&O!==L&&this.addIndicesForPlacedSymbol(this.text,O),$>=0&&$!==O&&$!==L&&this.addIndicesForPlacedSymbol(this.text,$),Y>=0&&this.addIndicesForPlacedSymbol(this.text,Y),X>=0&&this.addIndicesForPlacedSymbol(this.icon,X),le>=0&&this.addIndicesForPlacedSymbol(this.icon,le)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(x,j){const A=(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 L of this.symbolsByBatch.values())for(const O of L){const $=this.symbolInstances.get(O.index);O.rotatedY=0|Math.round(x*$.tileAnchorX+j*$.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let L=0;LO.rotatedY-$.rotatedY||$.featureIndex-O.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(x,j){for(const A of x){const L=A.batchIndex;if(L===void 0)continue;const O=j.get(L);if(!O){A.primitiveOffset=this.text.indexArray.length,A.primitiveLength=0;continue}A.primitiveOffset=this.text.indexArray.length;const $=this.text.indexArray.length;for(const{index:Y}of O){const X=this.symbolInstances.get(Y),{rightJustifiedTextSymbolIndex:le,centerJustifiedTextSymbolIndex:xe,leftJustifiedTextSymbolIndex:je,verticalPlacedTextSymbolIndex:Ce}=X;le>=0&&this.addIndicesForPlacedSymbol(this.text,le),xe>=0&&xe!==le&&this.addIndicesForPlacedSymbol(this.text,xe),je>=0&&je!==xe&&je!==le&&this.addIndicesForPlacedSymbol(this.text,je),Ce>=0&&this.addIndicesForPlacedSymbol(this.text,Ce)}A.primitiveLength=this.text.indexArray.length-$}}rebuildIconSegmentIndices(x,j){for(const A of x){const L=A.batchIndex;if(L===void 0)continue;const O=j.get(L);if(!O){A.primitiveOffset=this.icon.indexArray.length,A.primitiveLength=0;continue}A.primitiveOffset=this.icon.indexArray.length;const $=this.icon.indexArray.length;for(const{index:Y}of O){const X=this.symbolInstances.get(Y),{placedIconSymbolIndex:le,verticalPlacedIconSymbolIndex:xe}=X;le>=0&&this.addIndicesForPlacedSymbol(this.icon,le),xe>=0&&this.addIndicesForPlacedSymbol(this.icon,xe)}A.primitiveLength=this.icon.indexArray.length-$}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const x=Math.sin(this.sortedAngle),j=Math.cos(this.sortedAngle),A=this.getOrCreateSortedSymbolsByBatch(x,j),L=Array.from(A.keys()).sort((O,$)=>O-$);for(const O of L){const $=A.get(O);for(const{index:Y}of $){const X=this.symbolInstances.get(Y);this.featureSortOrder.push(X.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),A),this.rebuildIconSegmentIndices(this.icon.segments.get(),A),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(x){const j=this.symbolInstances.get(this.text.symbolInstanceIndices[x]).elevationFeatureIndex;let A;return this.elevationFeatures&&jA in k?String(k[A]):"")}let Mdt,Pdt,nFe;kr(pk,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),pk.addDynamicAttributes=rB;class Ldt{constructor(x){this.type=x.property.overrides?x.property.overrides.runtimeType:xd,this.defaultValue=x}evaluate(x){if(x.formattedSection){const j=this.defaultValue.property.overrides;if(j&&j.hasOverride(x.formattedSection))return j.getOverride(x.formattedSection)}return x.feature&&x.featureState?this.defaultValue.evaluate(x.feature,x.featureState):this.defaultValue.property.specification.default}eachChild(x){this.defaultValue.isConstant()||x(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}kr(Ldt,"FormatSectionOverride",{omit:["defaultValue"]});const rFe=()=>nFe||(nFe={layout:Mdt||(Mdt=new ld({"symbol-placement":new ur(Ws.layout_symbol["symbol-placement"]),"symbol-spacing":new ur(Ws.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new ur(Ws.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new dr(Ws.layout_symbol["symbol-sort-key"]),"symbol-z-order":new ur(Ws.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new ur(Ws.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new ur(Ws.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new ur(Ws.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new ur(Ws.layout_symbol["icon-ignore-placement"]),"icon-optional":new ur(Ws.layout_symbol["icon-optional"]),"icon-rotation-alignment":new ur(Ws.layout_symbol["icon-rotation-alignment"]),"icon-size":new dr(Ws.layout_symbol["icon-size"]),"icon-size-scale-range":new ur(Ws.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new dr(Ws.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new dr(Ws.layout_symbol["icon-text-fit-padding"]),"icon-image":new dr(Ws.layout_symbol["icon-image"]),"icon-image-use-theme":new ur({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new dr(Ws.layout_symbol["icon-rotate"]),"icon-padding":new ur(Ws.layout_symbol["icon-padding"]),"icon-keep-upright":new ur(Ws.layout_symbol["icon-keep-upright"]),"icon-offset":new dr(Ws.layout_symbol["icon-offset"]),"icon-anchor":new dr(Ws.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new ur(Ws.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new ur(Ws.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new ur(Ws.layout_symbol["text-rotation-alignment"]),"text-field":new dr(Ws.layout_symbol["text-field"]),"text-font":new dr(Ws.layout_symbol["text-font"]),"text-size":new dr(Ws.layout_symbol["text-size"]),"text-size-scale-range":new ur(Ws.layout_symbol["text-size-scale-range"]),"text-max-width":new dr(Ws.layout_symbol["text-max-width"]),"text-line-height":new dr(Ws.layout_symbol["text-line-height"]),"text-letter-spacing":new dr(Ws.layout_symbol["text-letter-spacing"]),"text-justify":new dr(Ws.layout_symbol["text-justify"]),"text-radial-offset":new dr(Ws.layout_symbol["text-radial-offset"]),"text-variable-anchor":new ur(Ws.layout_symbol["text-variable-anchor"]),"text-anchor":new dr(Ws.layout_symbol["text-anchor"]),"text-max-angle":new ur(Ws.layout_symbol["text-max-angle"]),"text-writing-mode":new ur(Ws.layout_symbol["text-writing-mode"]),"text-rotate":new dr(Ws.layout_symbol["text-rotate"]),"text-padding":new ur(Ws.layout_symbol["text-padding"]),"text-keep-upright":new ur(Ws.layout_symbol["text-keep-upright"]),"text-transform":new dr(Ws.layout_symbol["text-transform"]),"text-offset":new dr(Ws.layout_symbol["text-offset"]),"text-allow-overlap":new ur(Ws.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new ur(Ws.layout_symbol["text-ignore-placement"]),"text-optional":new ur(Ws.layout_symbol["text-optional"]),visibility:new ur(Ws.layout_symbol.visibility)})),paint:Pdt||(Pdt=new ld({"icon-opacity":new dr(Ws.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new dr(Ws.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new dr(Ws.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new dr(Ws.paint_symbol["text-emissive-strength"]),"icon-color":new dr(Ws.paint_symbol["icon-color"]),"icon-halo-color":new dr(Ws.paint_symbol["icon-halo-color"]),"icon-halo-width":new dr(Ws.paint_symbol["icon-halo-width"]),"icon-halo-blur":new dr(Ws.paint_symbol["icon-halo-blur"]),"icon-translate":new ur(Ws.paint_symbol["icon-translate"]),"icon-translate-anchor":new ur(Ws.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new ur(Ws.paint_symbol["icon-image-cross-fade"]),"text-opacity":new dr(Ws.paint_symbol["text-opacity"]),"text-occlusion-opacity":new dr(Ws.paint_symbol["text-occlusion-opacity"]),"text-color":new dr(Ws.paint_symbol["text-color"],{runtimeType:rc,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new dr(Ws.paint_symbol["text-halo-color"]),"text-halo-width":new dr(Ws.paint_symbol["text-halo-width"]),"text-halo-blur":new dr(Ws.paint_symbol["text-halo-blur"]),"text-translate":new ur(Ws.paint_symbol["text-translate"]),"text-translate-anchor":new ur(Ws.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new ur(Ws.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new ur(Ws.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new ur(Ws.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new ur(Ws.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new dr(Ws.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},nFe);class woe extends oc{constructor(x,j,A,L){super(x,rFe(),j,A,L,x.layout?x.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=v([]),this.hasOcclusionOpacityProperties=x.paint!==void 0&&("icon-occlusion-opacity"in x.paint||"text-occlusion-opacity"in x.paint)}_handleSpecialPaintPropertyUpdate(x){x!=="icon-occlusion-opacity"&&x!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(x,j){super.recalculate(x,j),this.appearances&&this.appearances.forEach(L=>{L.recalculate(x,j,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 A=this.layout.get("text-writing-mode");if(A){const L=[];for(const O of A)L.indexOf(O)<0&&L.push(O);this.layout._values["text-writing-mode"]=L}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(x,j,A,L){return this._saturation===x&&this._contrast===j&&this._brightnessMin===A&&this._brightnessMax===L||(this._colorAdjustmentMatrix=function(O,$,Y,X){O=Eo(O),$=Ua($);const le=f(),xe=O/3,je=1-2*xe,Ce=[je,xe,xe,0,xe,je,xe,0,xe,xe,je,0,0,0,0,1],Ie=.5-.5*$,Fe=X-Y;return b(le,[Fe,0,0,0,0,Fe,0,0,0,0,Fe,0,Y,Y,Y,1],[$,0,0,0,0,$,0,0,0,0,$,0,Ie,Ie,Ie,1]),b(le,le,Ce),le}(x,j,A,L),this._saturation=x,this._contrast=j,this._brightnessMin=A,this._brightnessMax=L),this._colorAdjustmentMatrix}getValueAndResolveTokens(x,j,A,L){const O=this.layout.get(x).evaluate(j,{},A,L),$=this._unevaluatedLayout._values[x];return $.isDataDriven()||Op($.value)||!O?O:Tdt(j.properties,O)}getAppearanceValueAndResolveTokens(x,j,A,L,O){const $=x.getLayoutProperty(j);if(!$)return;const Y=$.evaluate(A,{},L,O),X=x.getUnevaluatedLayoutProperties()._values[j];return X.isDataDriven()||Op(X.value)||!Y||typeof Y!="string"?Y:Tdt(A.properties,Y)}createBucket(x){return new pk(x)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const x of rFe().paint.overridableProperties){if(!woe.hasPaintOverride(this.layout,x))continue;const j=this.paint.get(x),A=new Ldt(j),L=new Mh(A,j.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let O=null;O=j.value.kind==="constant"||j.value.kind==="source"?new tm("source",L):new Pc("composite",L,j.value.zoomStops,j.value.interpolationType),this.paint._values[x]=new lk(j.property,O,j.parameters)}}_handleOverridablePaintPropertyUpdate(x,j,A){return!(!this.layout||j.isDataDriven()||A.isDataDriven())&&woe.hasPaintOverride(this.layout,x)}static hasPaintOverride(x,j){const A=x.get("text-field"),L=rFe().paint.properties[j];let O=!1;const $=Y=>{for(const X of Y)if(L.overrides&&L.overrides.hasOverride(X))return void(O=!0)};if(A.value.kind==="constant"&&A.value.value instanceof gd)$(A.value.value.sections);else if(A.value.kind==="source"){const Y=le=>{O||(le instanceof Yr&&ac(le.value)===Gt?$(le.value.sections):le instanceof cu?$(le.sections):le.eachChild(Y))},X=A.value;X._styleExpression&&Y(X._styleExpression.expression)}return O}getProgramIds(){return["symbol"]}getDefaultProgramParams(x,j,A){return{config:new Ye(this,{zoom:j,lut:A}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let Idt,Ddt,Rdt,Fdt;var joe=Wn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function Noe(k,x,j,A,L,O,$,Y){const X=[k,x,1,j,A,1,L,O,1],le=[$,Y,1],xe=m([],X),[je,Ce,Ie]=_e(le,le,xe);return p(X,X,[je,0,0,0,Ce,0,0,0,Ie])}function Odt(k,x,j,A,L,O,$,Y){const X=function(le,xe,je,Ce,Ie,Fe,Ke,et){const at=Noe(0,0,1,0,1,1,0,1),vt=Noe(le,xe,je,Ce,Ie,Fe,Ke,et);return p(vt,vt,m([],at))}(k,x,j,A,L,O,$,Y);return[X[2]/X[8]/fr,X[5]/X[8]/fr]}function koe(k){return[k[0],Math.min(Math.max(k[1],-85.051129),In)]}class zdt extends Um{constructor(x,j,A,L){super(),this.id=x,this.dispatcher=A,this.coordinates=j.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(L),this.options=j,this._dirty=!1}load(x,j){if(this._loaded=j||!1,this.fire(new Sd("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return x&&(this.coordinates=x),this._loaded=!0,void this._finishLoading();this._imageRequest=fd(this.map._requestManager.transformRequest(this.url,_g.Image),(A,L)=>{this._imageRequest=null,this._loaded=!0,A?this.fire(new pf(A)):L&&(this.image=L,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,x&&(this.coordinates=x),this._finishLoading())})}loaded(){return this._loaded}updateImage(x){return x.url?(this._imageRequest&&x.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=x.url,this.load(x.coordinates,this._loaded),this):this}setTexture(x){if(!(x.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new rY(this.map.painter.context,x.handle),this.width=x.dimensions[0],this.height=x.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Sd("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(x){this.map=x,this.load()}onRemove(x){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof rY||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(x){if(this.coordinates=x,this._boundsArray=void 0,this._unsupportedCoords=!1,!x.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let j=x[0][1],A=x[0][1];for(const O of x)O[1]>A&&(A=O[1]),O[1]In?this.onNorthPole=!0:L<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const O=x.map(pa.fromLngLat);this.tileID=function($){let Y=1/0,X=1/0,le=-1/0,xe=-1/0;for(const Ke of $)Y=Math.min(Y,Ke.x),X=Math.min(X,Ke.y),le=Math.max(le,Ke.x),xe=Math.max(xe,Ke.y);const je=Math.max(le-Y,xe-X),Ce=Math.max(0,Math.floor(-Math.log2(je))),Ie=Math.pow(2,Ce);let Fe=Math.floor((Y+le)/2*Ie);return Fe>1&&(Fe-=1),new fI(Ce,Fe,Math.floor((X+xe)/2*Ie))}(O),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Sd("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof rY||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(x){for(const et in this.tiles){const at=this.tiles[et];at.state!=="loaded"&&(at.state="loaded",at.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const j=wI(new fI(0,0,0),this.map.transform.projection),A=[j.projection.project(this.coordinates[0][0],this.coordinates[0][1]),j.projection.project(this.coordinates[1][0],this.coordinates[1][1]),j.projection.project(this.coordinates[2][0],this.coordinates[2][1]),j.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(et){const at=et[1].x-et[0].x,vt=et[1].y-et[0].y,pt=et[2].x-et[1].x,At=et[2].y-et[1].y,Rt=et[3].x-et[2].x,Bt=et[3].y-et[2].y,Ns=et[0].x-et[3].x,us=et[0].y-et[3].y,ws=at*At-pt*vt,ys=pt*Bt-Rt*At,vs=Rt*us-Ns*Bt,vn=Ns*vt-at*us;return ws>0&&ys>0&&vs>0&&vn>0||ws<0&&ys<0&&vs<0&&vn<0}(A))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const L=wI(this.tileID,this.map.transform.projection),[O,$,Y,X]=this.coordinates.map(et=>{const at=L.projection.project(et[0],et[1]);return Ndt(L,at)._round()});this.perspectiveTransform=Odt(O.x,O.y,$.x,$.y,Y.x,Y.y,X.x,X.y);const le=this._boundsArray=new bo;le.emplaceBack(O.x,O.y,0,0),le.emplaceBack($.x,$.y,fr,0),le.emplaceBack(X.x,X.y,0,fr),le.emplaceBack(Y.x,Y.y,fr,fr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=x.createVertexBuffer(le,joe.members),this.boundsSegments=Bc.simpleSegment(0,0,4,2);const xe=[],je=function(et){return[koe(et[0]),koe(et[1]),koe(et[2]),koe(et[3])]}(this.coordinates),[Ce,Ie,Fe,Ke]=function(et){let at=et[0][0],vt=at,pt=et[0][1],At=pt;for(let Rt=1;Rtvt&&(vt=et[Rt][0]),et[Rt][1]At&&(At=et[Rt][1]);return[at,pt,vt-at,At-pt]}(je);{const et=new bo,[at,vt,pt,At]=function(Fn){let sr=Fn[0].x,gn=sr,Bn=Fn[0].y,Vn=Bn;for(let nr=1;nrgn&&(gn=Fn[nr].x),Fn[nr].yVn&&(Vn=Fn[nr].y);return[sr,Bn,gn-sr,Vn-Bn]}(A),Rt=Fn=>[(Fn.x-at)/pt,(Fn.y-vt)/At],[Bt,Ns,us,ws]=A.map(Rt),ys=function(Fn,sr,gn,Bn,Vn,nr,yr,ra){const Er=Noe(0,0,1,0,1,1,0,1);return p(Er,Er,m([],Noe(Fn,sr,gn,Bn,Vn,nr,yr,ra)))}(Bt[0],Bt[1],Ns[0],Ns[1],us[0],us[1],ws[0],ws[1]);this.elevatedGlobePerspectiveTransform=Odt(Bt[0],Bt[1],Ns[0],Ns[1],us[0],us[1],ws[0],ws[1]);const vs=(Fn,sr)=>{xe.push(Fn.lng);const gn=Math.round((Fn.lng-Ce)/Fe*fr),Bn=Math.round((Fn.lat-Ie)/Ke*fr),Vn=Rt(sr),nr=_e([],[Vn[0],Vn[1],1],ys),yr=Math.round(nr[0]/nr[2]*fr),ra=Math.round(nr[1]/nr[2]*fr);et.emplaceBack(gn,Bn,yr,ra)},vn=A[3].x-A[0].x,Nn=A[3].y-A[0].y,Rn=A[2].x-A[1].x,$n=A[2].y-A[1].y;for(let Fn=0;Fn<65;Fn++){const sr=Fn/64,gn=[A[0].x+sr*vn,A[0].y+sr*Nn],Bn=[A[1].x+sr*Rn,A[1].y+sr*$n],Vn=Bn[0]-gn[0],nr=Bn[1]-gn[1];for(let yr=0;yr<65;yr++){const ra=yr/64,Er={x:gn[0]+Vn*ra,y:gn[1]+nr*ra};vs(j.projection.unproject(Er.x,Er.y),Er)}}this.elevatedGlobeVertexBuffer=x.createVertexBuffer(et,joe.members)}{this.maxLongitudeTriangleSize=0;let et=[],at=new Qu;const vt=(pt,At,Rt)=>{at.emplaceBack(pt,At,Rt);const Bt=xe[pt],Ns=xe[At],us=xe[Rt],ws=Math.min(Math.min(Bt,Ns),us),ys=Math.max(Math.max(Bt,Ns),us)-ws;ys>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=ys),et.push(ws+ys/2)};for(let pt=0;pt<64;pt++)for(let At=0;At<64;At++){const Rt=65*pt+At,Bt=Rt+1,Ns=Rt+65,us=Ns+1;vt(Rt,Ns,Bt),vt(Bt,Ns,us)}[et,at]=function(pt,At){const Rt=Array.from({length:pt.length},(us,ws)=>ws);Rt.sort((us,ws)=>pt[us]-pt[ws]);const Bt=[],Ns=new Qu;for(let us=0;us{$.segments.push({vertexOffset:0,primitiveOffset:je,vertexLength:j.segments[0].vertexLength,primitiveLength:Ce,sortKey:void 0,vaos:{}})},X=.51*this.maxLongitudeTriangleSize;if(Math.abs(A[0]-L)<=X){const je=uo(A,0,A.length,L+X);return je===A.length||Y(je,Ao(A,je+1,A.length,L+360-X)-je),$}L0}}let $dt,Udt,qdt,Vdt,Hdt,Gdt,Wdt;class Kdt extends oc{constructor(x,j,A,L){super(x,{layout:$dt||($dt=new ld({visibility:new ur(Ws["layout_raster-particle"].visibility)})),paint:Udt||(Udt=new ld({"raster-particle-array-band":new ur(Ws["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new ur(Ws["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new W0(Ws["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new ur(Ws["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new ur(Ws["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new ur(Ws["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new ur(Ws["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new ur(Ws["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},j,A,L),this._updateColorRamp(),this.lastInvalidatedAt=wu.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(x){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(x){return!1}_handleSpecialPaintPropertyUpdate(x){x!=="raster-particle-color"&&x!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),x==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const x=this._transitionablePaint._values["raster-particle-color"].value.expression,j=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=qK({expression:x,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:j}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=wu.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class dhs extends oc{constructor(x,j){super(x,{},j,null),this.implementation=x,x.slot&&(this.slot=x.slot)}is3D(x){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(x){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(x){this.implementation.onAdd&&this.implementation.onAdd(x,x.painter.context.gl)}onRemove(x){this.implementation.onRemove&&this.implementation.onRemove(x,x.painter.context.gl)}}function iFe(k,x,j){const A=[0,0,1],L=lt([]);return zt(L,L,j?-Gs(k)+Math.PI:Gs(k)),qt(L,L,-Gs(x)),Ae(A,A,L),Ne(A,A)}class Soe{constructor(x,j,A,L){this.message=(x?`${x}: `:"")+A,L&&(this.identifier=L),j!=null&&j.__line__&&(this.line=j.__line__)}}function oFe(k,x){const j=k.indexOf("://")===-1;try{return new URL(k,j&&x?"http://example.com":void 0),!0}catch{return!1}}class Ydt{constructor(x,j){this.feature=x,this.instancedDataOffset=j,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class Zdt{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new IK,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(x){const j=16*x,A=this.instancedDataArray.float32;let L=Math.floor(A[j+2]);const O=1.05*(A[j+2]-L);return L/=100,[A[j]%1*1.05,A[j+1]%1*1.05,O,L]}tileCoordinatesForInstance(x){const j=16*x,A=this.instancedDataArray.float32;let L=A[j+0];return L=L>fr?L-fr:L,new Ss(Math.trunc(L),Math.trunc(A[j+1]))}translationForInstance(x){const j=16*x,A=this.instancedDataArray.float32;return[A[j+4],A[j+5],A[j+6]]}rotationScaleForInstance(x){const j=16*x,A=this.instancedDataArray.float32;return[A[j+7],A[j+8],A[j+9],A[j+10],A[j+11],A[j+12],A[j+13],A[j+14],A[j+15]]}transformForInstance(x){const j=16*x,A=this.instancedDataArray.float32;return[A[j+7],A[j+8],A[j+9],A[j+4],A[j+10],A[j+11],A[j+12],A[j+5],A[j+13],A[j+14],A[j+15],A[j+6],0,0,0,1]}}class lFe{constructor(x){this.zoom=x.zoom,this.canonical=x.canonical,this.overscaledZ=this.canonical.z+Math.log2(x.overscaling),this.layers=x.layers,this.layerIds=this.layers.map(j=>j.fqid),this.projection=x.projection,this.index=x.index,this.worldview=x.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(j=>j.isStateDependent()).map(j=>j.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=x.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(x,j){}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(x,j,A,L){this.tileToMeter=Kn(A);const O=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const $=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?j.elevationFeatures:void 0;for(const{feature:Y,id:X,index:le,sourceLayerIndex:xe}of x){const je=X??(Y.properties&&Y.properties.hasOwnProperty("id")?Y.properties.id:void 0),Ce=oo(Y,O);if(!this.layers[0]._featureFilter.filter(new Vi(this.zoom,{worldview:this.worldview,activeFloors:j.activeFloors}),Ce,A))continue;const Ie={id:je,sourceLayerIndex:xe,index:le,geometry:O?Ce.geometry:ti(Y,A,L),properties:Y.properties,type:Y.type,patterns:{}},Fe=this.addFeature(Ie,Ie.geometry,Ce,$,A);Fe&&j.featureIndex.insert(Y,Ie.geometry,le,xe,this.index,this.instancesPerModel[Fe].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const x=this.layers[0].modelManager,j=this.layers[0].scope;let A=0;for(const L of this.modelUris){const O=x.getModel(L,j);if(!O)continue;const $=this.instancesPerModel[L];if($){const Y=.5*me(O.aabb.max,O.aabb.min)*$.maxScale+$.maxXYTranslationDistance,X=Math.min(fr,Math.max(Y/this.tileToMeter,256));A=Math.max(X,A)}}return A}update(x,j,A,L){for(const O in this.instancesPerModel){const $=this.instancesPerModel[O];for(const Y in x)$.idToFeaturesIndex.hasOwnProperty(Y)&&(this.evaluate($.features[$.idToFeaturesIndex[Y]],x[Y],$,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let x=!1;for(const j in this.instancesPerModel){const A=this.instancesPerModel[j];for(const L of A.features){const O=this.layers[0],$=L.feature,Y=this.canonical,X=O.paint.get("model-rotation").evaluate($,{},Y),le=O.paint.get("model-scale").evaluate($,{},Y),xe=O.paint.get("model-translation").evaluate($,{},Y);We(L.rotation,X)&&We(L.scale,le)&&We(L.translation,xe)||(this.evaluate(L,L.featureStates,A,!0),x=!0)}}return x}updateReplacement(x,j,A,L){if(j.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=j.updateTime;const O=j.getReplacementRegionsForTile(x.toUnwrapped(),!0);if(Hie(this.activeReplacements,O))return!1;this.activeReplacements=O;let $=!1;for(const Y in this.instancesPerModel){const X=this.instancesPerModel[Y],le=X.instancedDataArray;for(const xe of X.features){const je=xe.instancedDataOffset,Ce=xe.instancedDataCount;for(let Ie=0;Iefr;Ke=et?Ke-fr:Ke;const at=Math.floor(Ke),vt=Math.floor(le.float32[Fe+1]);let pt=!1;for(const At of this.activeReplacements)if(!Mlt(At,A,Gie.Model,L)&&!(At.min.x>at||at>At.max.x||At.min.y>vt||vt>At.max.y)&&(pt=Rlt(Dlt(at,vt,x.canonical,At.footprintTileId.canonical),At.footprint),pt))break;le.float32[Fe]=pt?Ke+fr:Ke,$=$||pt!==et}}}return $}isEmpty(){for(const x in this.instancesPerModel)if(this.instancesPerModel[x].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(x){if(!this.uploaded)for(const j in this.instancesPerModel){const A=this.instancesPerModel[j];A.instancedDataArray.length<0||A.instancedDataArray.length===0||(A.instancedDataBuffer?A.instancedDataBuffer.updateData(A.instancedDataArray):A.instancedDataBuffer=x.createVertexBuffer(A.instancedDataArray,Eds.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(x){for(const A in this.instancesPerModel){const L=this.instancesPerModel[A];L.instancedDataArray.length!==0&&L.instancedDataBuffer&&L.instancedDataBuffer.destroy()}const j=this.layers[0].modelManager;if(x&&j&&this.modelUris&&this.modelsRequested)for(const A of this.modelUris)j.removeModel(A,"",!0)}addFeature(x,j,A,L,O){const $=this.layers[0],Y=$.layout.get("model-id"),X=$.layout.get("model-allow-density-reduction"),le=Y.evaluate(A,{},this.canonical);if(!le)return aa(`modelId is not evaluated for layer ${$.id} and it is not going to get rendered.`),le;(oFe(le,!1)||this.styleDefinedModelURLs[le]!==void 0)&&(this.modelUris.includes(le)||this.modelUris.push(le)),this.instancesPerModel[le]||(this.instancesPerModel[le]=new Zdt);const xe=this.instancesPerModel[le],je=xe.instancedDataArray,Ce=new Ydt(A,je.length);let Ie;L&&(Ie=Xc.getElevationFeature(x,L));for(const Fe of j)for(const Ke of Fe){if(Ke.x<0||Ke.x>=fr||Ke.y<0||Ke.y>=fr)continue;if(this.lookupDim!==0&&X){const at=(this.lookupDim-1)/fr,vt=this.lookupDim*(Ke.y*at|0)+Ke.x*at|0;if(this.lookup){if(this.lookup[vt]!==0)continue;this.lookup[vt]=1}}this.instanceCount++;const et=je.length;if(je.resize(et+1),L){xe.instancesRoadElevation||(xe.instancesRoadElevation=[]);const at=Ie?Ie.pointElevation(new Ss(Ke.x,Ke.y)):0;xe.instancesRoadElevation.push(at)}xe.instancesEvaluatedElevation.push(0),je.float32[16*et]=Ke.x,je.float32[16*et+1]=Ke.y}return Ce.instancedDataCount=xe.instancedDataArray.length-Ce.instancedDataOffset,Ce.instancedDataCount>0&&(x.id&&(xe.idToFeaturesIndex[x.id]=xe.features.length),xe.features.push(Ce),this.evaluate(Ce,{},xe,!1)),le}getModelUris(){return this.modelUris}evaluate(x,j,A,L){const O=this.layers[0],$=x.feature,Y=this.canonical,X=x.rotation=O.paint.get("model-rotation").evaluate($,j,Y),le=x.scale=O.paint.get("model-scale").evaluate($,j,Y),xe=x.translation=O.paint.get("model-translation").evaluate($,j,Y),je=Object.assign({},O.paint.get("model-color").evaluate($,j,Y));je.a=O.paint.get("model-color-mix-intensity").evaluate($,j,Y);const Ce=[];this.maxVerticalOffset0?Math.sqrt(Ie):0;A.maxScale=Math.max(Math.max(A.maxScale,le[0]),Math.max(le[1],le[2])),A.maxXYTranslationDistance=Math.max(A.maxXYTranslationDistance,Fe),this.maxScale=Math.max(Math.max(this.maxScale,le[0]),Math.max(le[1],le[2])),bct(Ce,X,le);const Ke=Math.round(100*je.a)+je.b/1.05;for(let et=0;et10?this.tileToMeter:Kn(Y,Rt)),pt[vt+4]=xe[0],pt[vt+5]=xe[1],pt[vt+6]=xe[2]+(A.instancesRoadElevation?A.instancesRoadElevation[at]:0)+At,pt[vt+7]=Ce[0],pt[vt+8]=Ce[1],pt[vt+9]=Ce[2],pt[vt+10]=Ce[4],pt[vt+11]=Ce[5],pt[vt+12]=Ce[6],pt[vt+13]=Ce[8],pt[vt+14]=Ce[9],pt[vt+15]=Ce[10],A.instancesEvaluatedElevation[at]=xe[2]}}}kr(lFe,"ModelBucket",{omit:["layers"]}),kr(Zdt,"PerModelAttributes"),kr(Ydt,"ModelFeature");class iB{constructor(x,j,A){this._demTile=x,this._dem=this._demTile.dem,this._scale=j,this._offset=A}static create(x,j,A){const L=A||x.findDEMTileFor(j);if(!L||!L.dem)return;const O=L.dem,$=L.tileID,Y=1<le.fqid),this.stateDependentLayerIds=this.layers.filter(le=>le.isStateDependent()).map(le=>le.id),this.modelTraits|=Qz.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,L&&(this.modelTraits|=Qz.HasMapboxMeshFeatures),O&&(this.modelTraits|=Qz.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=$,this.worldview=X,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const le of j)this.nodesInfo.push(new eut(le)),Qdt(le,Y.featureIndexArray.length,Y.grid),Y.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,Y.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(x,j){for(const A of this.getNodesInfo()){const L=A.node;L.footprint&&j.push({footprint:L.footprint,id:x})}}updateAppearances(x,j,A,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(x){const j=Object.keys(x).length!==0;if(j&&!this.stateDependentLayers.length)return;const A=j?this.stateDependentLayers:this.layers;if(!pr(x,this.states))for(const L of A)this.evaluate(L,x);this.states=structuredClone(x)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(x){if(!this.needsUpload)return;const j=this.getNodesInfo();for(const A of j){const L=A.node;this.uploaded?this.updatePbrBuffer(L):SRe(L,x,!0)}for(const A of j)aoe(A.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(x){let j=!1;if(!x.meshes)return j;for(const A of x.meshes)A.pbrBuffer&&(A.pbrBuffer.updateData(A.featureArray),j=!0);return j}needsReEvaluation(x,j,A){const L=x.transform.projectionOptions,O=x.style.getBrightness(),$=this.brightness!==O;if(!this.uploaded||this.dirty||L.name!==this.projection.name||bY(A.paint.get("model-color").value,$)||bY(A.paint.get("model-color-mix-intensity").value,$)||bY(A.paint.get("model-roughness").value,$)||bY(A.paint.get("model-emissive-strength").value,$)||bY(A.paint.get("model-height-based-emissive-strength-multiplier").value,$)){this.projection=L,this.brightness=O;const Y=this.getNodesInfo();for(const X of Y)X.state=null;return!0}return!1}evaluateTransform(x,j){if(x.transform.zoom===this.zoom)return;this.zoom=x.transform.zoom;const A=this.getNodesInfo(),L=this.id.canonical;for(const O of A){const $=O.feature;O.evaluatedTranslation=j.paint.get("model-translation").evaluate($,{},L),O.evaluatedScale=j.paint.get("model-scale").evaluate($,{},L)}}evaluate(x,j){const A=this.getNodesInfo();for(const L of A){if(!L.node.meshes)continue;const O=L.feature,$=j&&j[O.id];if(pr($,L.state))continue;L.state=structuredClone($);const Y=L.node.meshes&&L.node.meshes[0].featureData,X=L.evaluatedColor[2],le=L.evaluatedRMEA[2],xe=this.id.canonical;if(L.hasTranslucentParts=!1,Y){for(let je=0;je=Bt)continue;const sr=cFe[Fn],gn=Math.abs(sr);gn>vs&&(ys=sr,vs=gn,vn=$n,Nn=Rn)}if(vs>.1){const Rn=1-(Bt+.5*Math.abs(vn*Nn))/Fe;let $n=j._dem.get(us,Ns)+ys*Rn;const Fn=j._dem.get(us+vn,Ns+Nn),sr=j._dem.get(us-vn,Ns-Nn,!0);($n-Fn)*($n-sr)>0&&($n=(Fn+sr)/2),cFe[ws]=j._dem.set(us,Ns,$n),jI[ws]=Bt}}}}}Y&&(j._demTile.needsDEMTextureUpload=!0,j._dem._timestamp=wu.now())}setFilter(x){this.filter=x?iT(x):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(x=>this.filter.filter(new Vi(this.id.overscaledZ,{worldview:this.worldview}),x.feature,this.id.canonical)):this.nodesInfo}destroy(){const x=this.getNodesInfo();for(const j of x)aoe(j.node),CRe(j.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(x,j){if(j.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=j.updateTime;const A=j.getReplacementRegionsForTile(x.toUnwrapped());for(const L of this.getNodesInfo()){const O=L.node.footprint;L.hiddenByReplacement=!!O&&!A.find($=>$.footprint===O)}}getHeightAtTileCoord(x,j){const A=[],L=[0,0,0],O=v([]);for(const $ of this.getNodesInfo()){const Y=$.node.meshes[0],X=Y.transformedAabb;if(xX.max[0]||j>X.max[1])continue;if($.node.hidden===!0)return{height:1/0,maxHeight:$.feature.properties.height,hidden:!1,verticalScale:$.evaluatedScale[2]};y(O,$.node.globalMatrix),L[0]=x,L[1]=j,Ve(L,L,O);const le=(L[0]-Y.aabb.min[0])/(Y.aabb.max[0]-Y.aabb.min[0])*yI|0,xe=Math.min(63,(L[1]-Y.aabb.min[1])/(Y.aabb.max[1]-Y.aabb.min[1])*yI|0)*yI+Math.min(63,le),je=Y.heightmap[xe];if(!(je<0&&$.node.footprint))return $.hiddenByReplacement?void 0:{height:je,maxHeight:$.feature.properties.height,hidden:!1,verticalScale:$.evaluatedScale[2]};if($.node.footprint.grid.query(new Ss(x,j),new Ss(x,j),A),A.length>0)return{height:void 0,maxHeight:$.feature.properties.height,hidden:$.hiddenByReplacement,verticalScale:$.evaluatedScale[2]}}}}function bY(k,x){return k instanceof tm&&!k.isLightConstant&&x}function uhs(k,x,j,A,L,O,$,Y){let X=(61440&x|(61440&x)>>4)>>8,le=(3840&x|(3840&x)>>4)>>4,xe=240&x|(240&x)>>4;j[3]>0&&(X=Pr(X,255*j[0],j[3]),le=Pr(le,255*j[1],j[3]),xe=Pr(xe,255*j[2],j[3]));const je=X<<8|le,Ce=xe<<8|Math.floor(255*A[3]),Ie=function(Bt){const Ns=gt(Bt,0,2);return Math.min(Math.round(.5*Ns*255),255)}(A[2])<<8|15*A[0]<<4|15*A[1],Fe=gt(L[0],0,1),Ke=gt(L[1],0,1),et=gt(L[2],0,1),at=gt(L[3],0,1);let vt,pt,At,Rt;if(Fe!==Ke&&$!==O&&Ke!==Fe){const Bt=$-O;pt=1/(Bt*(Ke-Fe)),At=-(O+Bt*Fe)/(Bt*(Ke-Fe));const Ns=gt(L[4],-1,1);Rt=Math.pow(10,Ns),vt=255*et<<8|255*at}else vt=65535,pt=0,At=1,Rt=1;if(k.emplaceBack(je,Ce,Ie,vt,pt,At,Rt),Y){const Bt=Y.length;Y.clear();for(let Ns=0;Ns>16&65535,xe=O?X>>16&65535:65535&X,je=(15&xe)<8?15&xe:0,Ce=k.evaluatedRMEA[je],Ie=k.evaluatedColor[je],Fe=k.emissionHeightBasedParams[je];let Ke;if(Y&&je===2&&A.lights&&(Ke=new Bz,Ke.resize(10*A.lights.length)),uhs($.featureArray,le,Ie,Ce,Fe,$.aabb.min[2],$.aabb.max[2],Ke),Ke&&Y){Y=!1;const et=A.meshes[A.lightMeshIndex];et.featureArray=Ke,et.featureArray._trim()}}$.featureArray._trim(),L++}}kr(Coe,"Tiled3dModelBucket",{omit:["layers"]}),kr(eut,"Tiled3dModelFeature");const mhs=["id","tile","layer","source","sourceLayer","state"];class NI{constructor(x,j,A,L,O){this.type="Feature",this._vectorTileFeature=x,this._z=j,this._x=A,this._y=L,this.properties=x?x.properties:{},this.id=O}clone(){const x=new NI(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(x.state=Object.assign({},this.state)),this.layer&&(x.layer=Object.assign({},this.layer)),this.source&&(x.source=this.source),this.sourceLayer&&(x.sourceLayer=this.sourceLayer),x}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(x){this._geometry=x}toJSON(){const x={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const j of mhs)this[j]!==void 0&&(x[j]=this[j]);return x}}class kI extends Um{constructor(x,j,A,L){super(),this.id=x,this.type="model",this.models=[],this._options=j,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(x,j){return xct(this.map._requestManager.transformRequest(x,_g.Model).url,j)}async loadModel(x,j,A){try{const L=await this.loadGLTFFromURI(j.uri,A);if(A.aborted)return;const O=this._modelsInfo.get(x);if(!O)return;const $=ERe(L),Y=O.modelSpec,X=new _ct(x,Y.uri,Y.position,Y.orientation,$);kI.applyModelSpecification(X,Y),X.computeBoundsAndApplyParent(),this.models.push(X),O.model=X}catch(L){if(L instanceof Error&&L.name==="AbortError")return;const O=L instanceof Error?L.message:"Unknown error";this.fire(new pf(new Error(`Could not load model ${x} from ${j.uri}: ${O}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const x=this._abortController.signal,j=[];for(const A in this._options.models){const L=this._options.models[A],O=this._modelsInfo.get(A);if(O&&O.model){O.modelSpec=L;const $=O.model;$.position=L.position!=null?new Ds(L.position[0],L.position[1]):new Ds(0,0),$.orientation=L.orientation!=null?L.orientation:[0,0,0],kI.applyModelSpecification($,L),$.computeBoundsAndApplyParent(),this.models.push($)}else O?O.modelSpec=L:(this._modelsInfo.set(A,{modelSpec:L,model:null}),j.push(this.loadModel(A,L,x)))}j.length!==0?(await Promise.allSettled(j),x.aborted||this.fire(new Sd("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Sd("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(x,j){j.nodeOverrides&&kI.convertNodeOverrides(x,j.nodeOverrides),j.materialOverrides&&kI.convertMaterialOverrides(x,j.materialOverrides),j.nodeOverrideNames&&(x.nodeOverrideNames=[...j.nodeOverrideNames]),j.materialOverrideNames&&(x.materialOverrideNames=[...j.materialOverrideNames]),j.featureProperties&&(x.featureProperties=j.featureProperties)}static convertNodeOverrides(x,j){if(Array.isArray(j)&&j.every(A=>typeof A=="string")){x.nodeOverrideNames=[];for(const A of j)x.nodeOverrideNames.push(A)}else Object.entries(j).forEach(([A,L])=>{const O={orientation:[0,0,0]};if(L.hasOwnProperty("orientation")){const $=L.orientation;$&&(O.orientation=$)}x.nodeOverrides.set(A,O)})}static convertMaterialOverrides(x,j){if(Array.isArray(j)&&j.every(A=>typeof A=="string")){x.materialOverrideNames=[];for(const A of j)x.materialOverrideNames.push(A)}else Object.entries(j).forEach(([A,L])=>{const O={color:new Js(1,1,1),colorMix:0,emissionStrength:0,opacity:1},$=L["model-color"];$!==void 0&&(O.color.r=$[0],O.color.g=$[1],O.color.b=$[2]);const Y=L["model-color-mix-intensity"];Y!==void 0&&(O.colorMix=Y);const X=L["model-emissive-strength"];X!==void 0&&(O.emissionStrength=X);const le=L["model-opacity"];le!==void 0&&(O.opacity=le),x.materialOverrides.set(A,O)})}onAdd(x){this.map=x,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const x of this._modelsInfo.values())if(x.model==null)return!1;return!0}getModels(){return this.models}loadTile(x,j){}serialize(){return this._options}setProperty(x,j){return!1}reload(){this.cancelModelRequests();const x=Pt(this.id,this.scope);this.map.style.clearSource(x),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(x){this.cancelModelRequests()}setModels(x){this.models=[];const j=new Map;for(const A in x){const L=x[A],O=this._modelsInfo.get(A);O&&O.modelSpec.uri===L.uri&&j.set(A,O)}if(this._modelsInfo.size!==j.size){this.cancelModelRequests();for(const[A,L]of j)L.model||j.delete(A)}this._modelsInfo=j,this._options.models=x,this.load()}}function dFe(k,x,j,A){const L=1<X>=Rt.vertexArrayOffset&&XAt.polygon).flat());const et=Ie?Y:null,[at,vt]=tct(O,A,je,xe,le,$,et,Ce,Fe,O.center.lat,k.tileID.canonical),pt=k.queryGeometry;return ect(at,vt,pt.isPointQuery()?pt.screenBounds:pt.screenGeometry)}},building:class extends oc{constructor(k,x,j,A){super(k,{layout:Act||(Act=new ld({visibility:new ur(Ws.layout_building.visibility),"building-facade":new dr(Ws.layout_building["building-facade"]),"building-facade-floors":new dr(Ws.layout_building["building-facade-floors"]),"building-facade-unit-width":new dr(Ws.layout_building["building-facade-unit-width"]),"building-facade-window":new dr(Ws.layout_building["building-facade-window"]),"building-roof-shape":new dr(Ws.layout_building["building-roof-shape"]),"building-height":new dr(Ws.layout_building["building-height"]),"building-base":new dr(Ws.layout_building["building-base"]),"building-flood-light-wall-radius":new dr(Ws.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new dr(Ws.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new dr(Ws.layout_building["building-flip-roof-orientation"])})),paint:Ect||(Ect=new ld({"building-opacity":new ur(Ws.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new ur(Ws.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new ur(Ws.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new ur(Ws.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new ur(Ws.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new ur(Ws.paint_building["building-vertical-scale"]),"building-cast-shadows":new ur(Ws.paint_building["building-cast-shadows"]),"building-color":new dr(Ws.paint_building["building-color"]),"building-emissive-strength":new dr(Ws.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new ur(Ws.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new ur(Ws.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new ur(Ws.paint_building["building-front-cutoff"]),"building-flood-light-color":new ur(Ws.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new ur(Ws.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new ur(Ws.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new dr({type:"string",default:"default","property-type":"data-driven"})}))},x,j,A),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(k){return new Cct(k)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(k){return!0}queryRadius(k){return 0}queryIntersectsFeature(k,x,j,A,L,O,$,Y,X,le){let xe=this.layout.get("building-height").evaluate(x,j);const je=this.layout.get("building-base").evaluate(x,j),Ce=k.tile.getBucket(this).getFootprint(x);if(Ce){if(Ce.hiddenFlags!==0)return!1;xe=Ce.height}const[Ie,Fe]=tct(O,A,je,xe,new Ss(0,0),$,null,[0,0],1,O.center.lat,k.tileID.canonical),Ke=k.queryGeometry;return ect(Ie,Fe,Ke.isPointQuery()?Ke.screenBounds:Ke.screenGeometry)}},line:class extends oc{constructor(k,x,j,A){const L=zct();super(k,L,x,j,A),L.layout&&(this.layout=new Up(L.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(k){if(k==="line-gradient"){const x=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=x._styleExpression&&x._styleExpression.expression instanceof t2,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(k,x){super.recalculate(k,x),this.paint._values["line-floorwidth"]=(()=>{if(iY)return iY;const j=zct();return iY=new ous(j.paint.properties["line-width"].specification),iY.useIntegerZoom=!0,iY})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,k)}createBucket(k){return new ooe(k)}getProgramIds(){const k=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&k.push("lineBlendComposite"),k}getDefaultProgramParams(k,x,j){if(k==="lineBlendComposite")return{};const A=Fct(this);return{config:new Ye(this,{zoom:x,lut:j}),defines:A,overrideFog:!1}}queryRadius(k){const x=k,j=Bct(hT("line-width",this,x),hT("line-gap-width",this,x)),A=hT("line-offset",this,x);return j/2+Math.abs(A)+Mie(this.paint.get("line-translate"))}queryIntersectsFeature(k,x,j,A,L,O){if(k.queryGeometry.isAboveHorizon)return!1;const $=Oot(k.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),O.angle,k.pixelToTileUnitsFactor),Y=k.pixelToTileUnitsFactor/2*Bct(this.paint.get("line-width").evaluate(x,j),this.paint.get("line-gap-width").evaluate(x,j)),X=this.paint.get("line-offset").evaluate(x,j);return X&&(A=function(le,xe){const je=[],Ce=new Ss(0,0);for(let Ie=0;Ie=3){for(let Fe=0;Fe{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 tut{constructor(x){this._stringToNumber={},this._numberToString=[];for(let j=0;j=0&&Ce[3]>=0&&le.insert(X,Ce[0],Ce[1],Ce[2],Ce[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new bl(new loe(this.rawTileData)).layers,this.sourceLayerCoder=new tut(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const x in this.vtLayers)this.vtFeatures[x]=[]}return this.vtLayers}query(x,j){const{tilespaceGeometry:A,transform:L,tileTransform:O,pixelPosMatrix:$,availableImages:Y,worldview:X}=j;this.loadVTLayers(),this.serializedLayersCache.clear();const le=j.queryRadius?j.queryRadius:0,xe=A.bufferedTilespaceBounds,je=this.grid.query(xe.min.x,xe.min.y,xe.max.x,xe.max.y,(Ke,et,at,vt)=>h5(A.bufferedTilespaceGeometry,Ke-le,et-le,at+le,vt+le));je.sort(ghs);let Ce=null;L.elevation&&je.length>0&&(Ce=iB.create(L.elevation,this.tileID));const Ie={};let Fe;for(let Ke=0;Ke(vt||(vt=ti(pt,this.tileID.canonical,O)),At.queryIntersectsFeature(A,pt,Rt,vt,this.z,L,$,Ce,Bt,j.scope)))}return Ie}loadMatchingFeature(x,j,A,L,O,$){const{featureIndex:Y,bucketIndex:X,sourceLayerIndex:le,layoutVertexArrayOffset:xe}=j,je=this.bucketLayerIDs[X],Ce=A.layers,Ie=Object.keys(Ce);if(Ie.length&&!Or(Ie,je))return;const Fe=A.sourceCache,Ke=this.sourceLayerCoder.decode(le),et=this.vtLayers[Ke].feature(Y),at=this.getId(et,Ke);for(let vt=0;vt`${Y.key}: ${Y.message}`).join(", ");return void aa(`Failed to create expression for promoteId: ${$}`)}this.promoteIdExpression=O.value}A=this.promoteIdExpression.evaluate({zoom:0},x)}else A=x.properties[L];typeof A=="boolean"&&(A=Number(A))}return A}}function nut(k,x,j,A,L){return Vs(k,(O,$)=>{const Y=x instanceof Up?x.get($):null;return Y&&Y.evaluate?Y.evaluate(j,A,void 0,L):Y})}function ghs(k,x){return x-k}function rut(k,x){const j={};if(!x)return j;for(const A of k){const L=A.layerIds.map(O=>x.getLayer(O)).filter(Boolean);if(L.length!==0){A.layers=L,A.stateDependentLayerIds&&(A.stateDependentLayers=A.stateDependentLayerIds.map(O=>L.filter($=>$.id===O)[0]));for(const O of L)j[O.fqid]=A}}return j}kr(sut,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const p2=32,v5=33,vT=new Uint16Array(8184);for(let k=0;k<2046;k++){let x=k+2,j=0,A=0,L=0,O=0,$=0,Y=0;for(1&x?L=O=$=p2:j=A=Y=p2;(x>>=1)>1;){const le=j+L>>1,xe=A+O>>1;1&x?(L=j,O=A,j=$,A=Y):(j=L,A=O,L=$,O=Y),$=le,Y=xe}const X=4*k;vT[X+0]=j,vT[X+1]=A,vT[X+2]=L,vT[X+3]=O}const b5=new Uint16Array(2178),bT=new Uint8Array(1089),Aoe=new Uint16Array(1089);function aut(k){return k===0?-.03125:k===32?.03125:0}const iut={Other:0,Symbol:1,FillExtrusion:2},out={type:2,extent:fr,loadGeometry:()=>[[new Ss(0,0),new Ss(8193,0),new Ss(8193,8193),new Ss(0,8193),new Ss(0,0)]]};class yhs{constructor(){this.tasks={},this.taskQueue=[],Vt(["process"],this),this.invoker=new xhs(this.process),this.nextId=0}add(x,j){const A=this.nextId++,L=function({type:O,renderSourceType:$,zoom:Y}){Y=Y||0;const X=$===iut.Symbol;return O==="message"?0:O!=="maybePrepare"||X?O!=="parseTile"||X?O==="parseTile"&&X?300-Y:O==="maybePrepare"&&X?400-Y:500:200-Y:100-Y}(j);if(L===0){try{x()}finally{}return null}return this.tasks[A]={fn:x,metadata:j,priority:L,id:A},this.taskQueue.push(A),this.invoker.trigger(),{cancel:()=>{delete this.tasks[A]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(A=>!!this.tasks[A]),!this.taskQueue.length)return;const x=this.pick();if(x===null)return;const j=this.tasks[x];if(delete this.tasks[x],this.taskQueue.length&&this.invoker.trigger(),!j)return;j.fn()}finally{}}pick(){let x=null,j=1/0;for(let L=0;L>16&255)/255,(k>>8&255)/255,(255&k)/255,1)}function Ths(k,x,j){k===1?(x.rgb_color=Moe(j.readVarint()),x.paint="rgb_color"):k===2?(x.linear_gradient_idx=j.readVarint(),x.paint="linear_gradient_idx"):k===3?(x.radial_gradient_idx=j.readVarint(),x.paint="radial_gradient_idx"):k===5?j.readPackedFloat(x.dasharray):k===6?x.dashoffset=j.readFloat():k===7?x.miterlimit=j.readFloat():k===8?x.opacity=j.readVarint():k===9?x.width=j.readFloat():k===10?x.linecap=j.readVarint():k===11&&(x.linejoin=j.readVarint())}function Mhs(k,x,j){k===1?x.transform=Toe(j,j.readVarint()+j.pos):k===2?x.spread_method=j.readVarint():k===3?x.stops.push(dut(j,j.readVarint()+j.pos)):k===4?x.x1=j.readFloat():k===5?x.y1=j.readFloat():k===6?x.x2=j.readFloat():k===7&&(x.y2=j.readFloat())}function dut(k,x){return k.readFields(Phs,{offset:0,opacity:255,rgb_color:uFe},x)}function Phs(k,x,j){k===1?x.offset=j.readFloat():k===2?x.opacity=j.readVarint():k===3&&(x.rgb_color=Moe(j.readVarint()))}function Lhs(k,x,j){k===1?x.transform=Toe(j,j.readVarint()+j.pos):k===2?x.spread_method=j.readVarint():k===3?x.stops.push(dut(j,j.readVarint()+j.pos)):k===4?x.cx=j.readFloat():k===5?x.cy=j.readFloat():k===6?x.r=j.readFloat():k===7?x.fx=j.readFloat():k===8?x.fy=j.readFloat():k===9&&(x.fr=j.readFloat())}function Ihs(k,x,j){k===1?x.transform=Toe(j,j.readVarint()+j.pos):k===2?x.clip_path_idx=j.readVarint():k===3&&x.children.push(Eoe(j,j.readVarint()+j.pos))}function Dhs(k,x,j){k===1?x.left=x.top=j.readFloat():k===2?x.width=x.height=j.readFloat():k===3?x.top=j.readFloat():k===4?x.height=j.readFloat():k===5?x.mask_type=j.readVarint():k===6?x.mask_idx=j.readVarint():k===7&&x.children.push(Eoe(j,j.readVarint()+j.pos))}class Rhs{static calculate(x={},j=[]){const A=new Map,L=new Map;if(Object.keys(x).length===0)return A;j.forEach(O=>{L.set(O.name,O.rgb_color||new Js(0,0,0))});for(const[O,$]of Object.entries(x))L.has(O)?A.set(L.get(O).toString(),$):console.warn(`Ignoring unknown image variable "${O}"`);return A}}function oB(k,x=255,j){const A=x/255,L=k.toString(),O=j.has(L)?j.get(L).clone():k.clone();return O.a*=A,O.toString()}function _Y(k,x){if(!Sl()){const j=document.createElement("canvas");return j.width=k,j.height=x,j}return new OffscreenCanvas(k,x)}let hFe,wY=null;function mFe(k,x,j,A,L){for(const O of A.children)uut(k,x,j,O,L)}function uut(k,x,j,A,L){A.group?(k.save(),function(O,$,Y,X,le){const xe=X.mask_idx!=null?Y.masks[X.mask_idx]:null,je=X.clip_path_idx!=null?Y.clip_paths[X.clip_path_idx]:null;if(X.transform&&($=lB(X.transform).preMultiplySelf($)),!function(Fe,Ke,et){return Fe.opacity!==255||Ke||et}(X,je!=null,xe!=null))return void mFe(O,$,Y,X,le);const Ce=_Y(O.canvas.width,O.canvas.height),Ie=Ce.getContext("2d");mFe(Ie,$,Y,X,le),je&&yut(Ie,$,Y,je),xe&&vut(Ie,$,Y,xe,le),O.globalAlpha=X.opacity/255,O.drawImage(Ce,0,0)}(k,x,j,A.group,L),k.restore()):A.path&&(k.save(),function(O,$,Y,X,le){O.setTransform($),X.paint_order===1?(hut(O,Y,X,le),put(O,Y,X,le)):(put(O,Y,X,le),hut(O,Y,X,le))}(k,x,j,A.path,L),k.restore())}function hut(k,x,j,A){const L=j.fill;if(!L)return;const O=L.opacity/255;switch(k.save(),k.beginPath(),but(j,k),L.paint){case"rgb_color":k.fillStyle=oB(L.rgb_color,L.opacity,A);break;case"linear_gradient_idx":{const $=x.linear_gradients[L.linear_gradient_idx];$.transform&&k.setTransform(lB($.transform).preMultiplySelf(k.getTransform())),k.fillStyle=fut(k,$,O,A);break}case"radial_gradient_idx":{const $=x.radial_gradients[L.radial_gradient_idx];$.transform&&k.setTransform(lB($.transform).preMultiplySelf(k.getTransform())),k.fillStyle=xut(k,$,O,A)}}k.fill(mut(j)),k.restore()}function mut(k){return k.rule===1?"nonzero":k.rule===2?"evenodd":void 0}function put(k,x,j,A){const L=j.stroke;if(!L)return;const O=_ut(j);k.lineWidth=L.width,k.miterLimit=L.miterlimit,k.setLineDash(L.dasharray),k.lineDashOffset=L.dashoffset;const $=L.opacity/255;switch(L.paint){case"rgb_color":k.strokeStyle=oB(L.rgb_color,L.opacity,A);break;case"linear_gradient_idx":k.strokeStyle=fut(k,x.linear_gradients[L.linear_gradient_idx],$,A,!0);break;case"radial_gradient_idx":k.strokeStyle=xut(k,x.radial_gradients[L.radial_gradient_idx],$,A,!0)}switch(L.linejoin){case 2:case 1:k.lineJoin="miter";break;case 3:k.lineJoin="round";break;case 4:k.lineJoin="bevel"}switch(L.linecap){case 1:k.lineCap="butt";break;case 2:k.lineCap="round";break;case 3:k.lineCap="square"}k.stroke(O)}function fut(k,x,j,A,L=!1){if(x.stops.length===1){const Ce=x.stops[0];return oB(Ce.rgb_color,Ce.opacity*j,A)}const{x1:O,y1:$,x2:Y,y2:X}=x;let le=new DOMPoint(O,$),xe=new DOMPoint(Y,X);if(L){const Ce=lB(x.transform);le=Ce.transformPoint(le),xe=Ce.transformPoint(xe)}const je=k.createLinearGradient(le.x,le.y,xe.x,xe.y);for(const Ce of x.stops)je.addColorStop(Ce.offset,oB(Ce.rgb_color,Ce.opacity*j,A));return je}function xut(k,x,j,A,L=!1){if(x.stops.length===1){const at=x.stops[0];return oB(at.rgb_color,at.opacity*j,A)}const O=lB(x.transform),{fx:$,fy:Y,fr:X,cx:le,cy:xe,r:je}=x;let Ce=new DOMPoint($,Y),Ie=new DOMPoint(le,xe),Fe=X,Ke=je;if(L){Ce=O.transformPoint(Ce),Ie=O.transformPoint(Ie);const at=(O.a+O.d)/2;Fe=X*at,Ke=x.r*at}const et=k.createRadialGradient(Ce.x,Ce.y,Fe,Ie.x,Ie.y,Ke);for(const at of x.stops)et.addColorStop(at.offset,oB(at.rgb_color,at.opacity*j,A));return et}function gut(k,x,j,A){const L=A.transform?lB(A.transform).preMultiplySelf(x):x,O=_Y(k.canvas.width,k.canvas.height),$=O.getContext("2d");for(const X of A.children)if(X.group)gut($,L,j,X.group);else if(X.path){const le=X.path,xe=new Path2D;xe.addPath(_ut(le),L),$.fill(xe,mut(le))}const Y=A.clip_path_idx!=null?j.clip_paths[A.clip_path_idx]:null;Y&&yut($,L,j,Y),k.globalCompositeOperation="source-over",k.drawImage(O,0,0)}function yut(k,x,j,A){const L=_Y(k.canvas.width,k.canvas.height);gut(L.getContext("2d"),x,j,A),k.globalCompositeOperation="destination-in",k.drawImage(L,0,0)}function vut(k,x,j,A,L){if(A.children.length===0)return;const O=A.mask_idx!=null?j.masks[A.mask_idx]:null;O&&vut(k,x,j,O,L);const $=k.canvas.width,Y=k.canvas.height,X=_Y($,Y),le=X.getContext("2d"),xe=A.width,je=A.height,Ce=A.left,Ie=A.top,Fe=new Path2D,Ke=new Path2D;Ke.rect(Ce,Ie,xe,je),Fe.addPath(Ke,x),le.clip(Fe);for(const vt of A.children)uut(le,x,j,vt,L);const et=le.getImageData(0,0,$,Y),at=et.data;if(A.mask_type===1)for(let vt=0;vtx[$])return null}else{const Y=1/A[$];let X=(k[$]-j[$])*Y,le=(x[$]-j[$])*Y;if(X>le){const xe=X;X=le,le=xe}if(X>L&&(L=X),leO)return null}return L}function Nut(k,x,j,A,L,O,$,Y,X,le,xe){const je=A-k,Ce=L-x,Ie=O-j,Fe=$-k,Ke=Y-x,et=X-j,at=xe[1]*et-xe[2]*Ke,vt=xe[2]*Fe-xe[0]*et,pt=xe[0]*Ke-xe[1]*Fe,At=je*at+Ce*vt+Ie*pt;if(Math.abs(At)<1e-15)return null;const Rt=1/At,Bt=le[0]-k,Ns=le[1]-x,us=le[2]-j,ws=(Bt*at+Ns*vt+us*pt)*Rt;if(ws<0||ws>1)return null;const ys=Ns*Ie-us*Ce,vs=us*je-Bt*Ie,vn=Bt*Ce-Ns*je,Nn=(xe[0]*ys+xe[1]*vs+xe[2]*vn)*Rt;return Nn<0||ws+Nn>1?null:(Fe*ys+Ke*vs+et*vn)*Rt}function kut(k,x,j){return(k-x)/(j-x)}function Sut(k,x,j,A,L,O,$,Y,X){const le=1<{const vt=et?1:0,pt=(Ie+1)*Ke-vt,At=Fe*Ke,Rt=(Fe+1)*Ke-vt;at[0]=Ie*Ke,at[1]=At,at[2]=pt,at[3]=Rt};let je=new wut(X);const Ce=[];for(let Ie=0;Ie=1;X/=2){const Ie=Y[Y.length-1];je=new wut(X);for(let Fe=0;Fe0;){const{idx:Fe,t:Ke,nodex:et,nodey:at,depth:vt}=Ie.pop();if(this.leaves[Fe]){Sut(et,at,vt,x,j,A,L,je,Ce);const At=1<=Fn[2])return Ke}continue}let pt=0;for(let At=0;At=le[xe[us]]&&(xe.splice(us,0,At),Ns=!0);Ns||(xe[pt]=At),pt++}}for(let At=0;At=this.dim+1||j<-1||j>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(j+1)*this.stride+(x+1)}static pack(x,j){const A=[0,0,0,0],L=Loe.getUnpackVector(j);let O=Math.floor((x+L[3])/L[2]);return A[2]=O%256,O=Math.floor(O/256),A[1]=O%256,O=Math.floor(O/256),A[0]=O,A}getPixels(){return new clt({width:this.stride,height:this.stride},this.pixels)}backfillBorder(x,j,A){if(this.dim!==x.dim)throw new Error("dem dimension mismatch");let L=j*this.dim,O=j*this.dim+this.dim,$=A*this.dim,Y=A*this.dim+this.dim;switch(j){case-1:L=O-1;break;case 1:O=L+1}switch(A){case-1:$=Y-1;break;case 1:Y=$+1}const X=-j*this.dim,le=-A*this.dim;for(let xe=$;xe=1;A--){const L=A===1?1:0,O=A===2?1:0;for(let $=0;$>>1^-(1&k[x]);return k}function Zhs(k,x){switch(x){case"uint32":return k;case"uint16":for(let j=0;j>4|(61440&A)>>8|(240&L)<<4|61440&L,k[j+1]=15&A|(3840&A)>>4|(15&L)<<8|(3840&L)<<4}return k;case"uint8":for(let j=0;j>6|(192&L)>>4|(192&O)>>2|192&$,k[j+1]=(48&A)>>4|(48&L)>>2|48&O|(48&$)<<2,k[j+2]=(12&A)>>2|12&L|(12&O)<<2|(12&$)<<4,k[j+3]=3&A|(3&L)<<2|(3&O)<<4|(3&$)<<6}return k;default:throw new Error(`Invalid pixel format, "${x}"`)}}kr(Loe,"DEMData"),kr(Cut,"DemMinMaxQuadTree",{omit:["dem"]});var pw=Uint8Array,jY=Uint16Array,Xhs=Int32Array,Eut=new pw([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]),Tut=new pw([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]),Qhs=new pw([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Mut=function(k,x){for(var j=new jY(31),A=0;A<31;++A)j[A]=x+=1<>1|(21845&yp)<<1;Iut[yp]=((65280&(cB=(61680&(cB=(52428&cB)>>2|(13107&cB)<<2))>>4|(3855&cB)<<4))>>8|(255&cB)<<8)>>1}var NY=function(k,x,j){for(var A=k.length,L=0,O=new jY(x);L>X]=le;return $},kY=new pw(288);for(yp=0;yp<144;++yp)kY[yp]=8;for(yp=144;yp<256;++yp)kY[yp]=9;for(yp=256;yp<280;++yp)kY[yp]=7;for(yp=280;yp<288;++yp)kY[yp]=8;var Dut=new pw(32);for(yp=0;yp<32;++yp)Dut[yp]=5;var tms=NY(kY,9),sms=NY(Dut,5),fFe=function(k){for(var x=k[0],j=1;jx&&(x=k[j]);return x},fk=function(k,x,j){var A=x/8|0;return(k[A]|k[A+1]<<8)>>(7&x)&j},xFe=function(k,x){var j=x/8|0;return(k[j]|k[j+1]<<8|k[j+2]<<16)>>(7&x)},nms=function(k){return(k+7)/8|0},rms=["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"],xk=function(k,x,j){var A=new Error(x||rms[k]);if(A.code=k,Error.captureStackTrace&&Error.captureStackTrace(A,xk),!j)throw A;return A},ams=new pw(0),ims=typeof TextDecoder<"u"&&new TextDecoder;try{ims.decode(ams,{stream:!0})}catch{}const oms={gzip_data:"gzip"};class f2 extends Error{constructor(x){super(x),this.name="MRTError"}}const lms={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},Rut={uint32:1,uint16:2,uint8:4},cms={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let gFe;class Ioe{constructor(x=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=x}getLayer(x){const j=this.layers[x];if(!j)throw new f2(`Layer '${x}' not found`);return j}getHeaderLength(x){const j=new Uint8Array(x),A=new DataView(x);if(j[0]!==13)throw new f2("File is not a valid MRT.");return A.getUint32(1,!0)}parseHeader(x){const j=new Uint8Array(x),A=this.getHeaderLength(x);if(j.length= ${A} but got buffer of length ${j.length}`);const L=new gFe(j.subarray(0,A)).readFields(Bhs,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==L.x||this.y!==L.y||this.z!==L.z))throw new f2(`Invalid attempt to parse header ${L.z}/${L.x}/${L.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=L.x,this.y=L.y,this.z=L.z;for(const O of L.layers)this.layers[O.name]=new Fut(O,{cacheSize:this._cacheSize});return this}createDecodingTask(x){const j=[],A=this.getLayer(x.layerName);for(let L of x.blockIndices){const O=A.dataIndex[L],$=O.firstByte-x.firstByte,Y=O.lastByte-x.firstByte;if(A._blocksInProgress.has(L))continue;const X={layerName:A.name,firstByte:$,lastByte:Y,pixelFormat:A.pixelFormat,blockIndex:L,blockShape:[O.bands.length].concat(A.bandShape),buffer:A.buffer,codec:O.codec.codec,filters:O.filters.map(le=>le.filter)};A._blocksInProgress.add(L),j.push(X)}return new Out(j,()=>{j.forEach(L=>A._blocksInProgress.delete(L.blockIndex))},(L,O)=>{if(j.forEach($=>A._blocksInProgress.delete($.blockIndex)),L)throw L;O.forEach($=>{this.getLayer($.layerName).processDecodedData($)})})}}class Fut{constructor({version:x,name:j,units:A,tileSize:L,pixelFormat:O,buffer:$,dataIndex:Y},X){if(this.version=x,this.version!==1)throw new f2(`Cannot parse raster layer encoded with MRT version ${x}`);this.name=j,this.units=A,this.tileSize=L,this.buffer=$,this.pixelFormat=lms[O],this.dataIndex=Y,this.bandShape=[L+2*$,L+2*$,Rut[this.pixelFormat]],this._decodedBlocks=new Poe(X?X.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return Rut[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:x})=>x).flat()}processDecodedData(x){const j=x.blockIndex.toString();this._decodedBlocks.get(j)||this._decodedBlocks.put(j,x.data)}getBlockForBand(x){let j=0;switch(typeof x){case"string":for(const[A,L]of this.dataIndex.entries()){for(const[O,$]of L.bands.entries())if($===x)return{bandIndex:j+O,blockIndex:A,blockBandIndex:O};j+=L.bands.length}break;case"number":for(const[A,L]of this.dataIndex.entries()){if(x>=j&&xthis.cacheSize)throw new f2(`Number of blocks to decode (${O.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:j,lastByte:A,blockIndices:L}}hasBand(x){const{blockIndex:j}=this.getBlockForBand(x);return j>=0}hasDataForBand(x){const{blockIndex:j}=this.getBlockForBand(x);return j>=0&&!!this._decodedBlocks.get(j.toString())}getBandView(x){const{blockIndex:j,blockBandIndex:A}=this.getBlockForBand(x);if(j<0)throw new f2(`Band not found: ${JSON.stringify(x)}`);const L=this._decodedBlocks.get(j.toString());if(!L)throw new f2(`Data for band ${JSON.stringify(x)} of layer "${this.name}" not decoded.`);const O=this.dataIndex[j],$=this.bandShape.reduce((le,xe)=>le*xe,1),Y=A*$,X=L.subarray(Y,Y+$);return{data:X,bytes:new Uint8Array(X.buffer).subarray(X.byteOffset,X.byteOffset+X.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:O.offset,scale:O.scale}}}Ioe.setPbf=function(k){gFe=k};class Out{constructor(x,j,A){this.tasks=x,this._onCancel=j,this._onComplete=A,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(x,j){this._finalized||(this._onComplete(x,j),this._finalized=!0)}}Ioe.performDecoding=function(k,x){const j=new Uint8Array(k);return Promise.all(x.tasks.map(A=>{const{layerName:L,firstByte:O,lastByte:$,pixelFormat:Y,blockShape:X,blockIndex:le,filters:xe,codec:je}=A,Ce=j.subarray(O,$+1),Ie=new Uint32Array(X[0]*X[1]*X[2]);let Fe;if(je!=="gzip_data")throw new f2(`Unhandled codec: ${je}`);return Fe=function(Ke,et){if(!globalThis.DecompressionStream&&et==="gzip_data")return Promise.resolve((Rt=function(us){us[0]==31&&us[1]==139&&us[2]==8||xk(6,"invalid gzip data");var ws=us[3],ys=10;4&ws&&(ys+=2+(us[10]|us[11]<<8));for(var vs=(ws>>3&1)+(ws>>4&1);vs>0;vs-=!us[ys++]);return ys+(2&ws)}(at=Ke),Rt+8>at.length&&xk(6,"invalid gzip data"),function(us,ws,ys,vs){var vn=us.length;if(!vn||ws.f&&!ws.l)return ys||new pw(0);var Nn=!ys,Rn=Nn||ws.i!=2,$n=ws.i;Nn&&(ys=new pw(3*vn));var Fn=function(Iu){var ty=ys.length;if(Iu>ty){var jf=new pw(Math.max(2*ty,Iu));jf.set(ys),ys=jf}},sr=ws.f||0,gn=ws.p||0,Bn=ws.b||0,Vn=ws.l,nr=ws.d,yr=ws.m,ra=ws.n,Er=8*vn;do{if(!Vn){sr=fk(us,gn,1);var Cr=fk(us,gn+1,3);if(gn+=3,!Cr){var vr=us[(Dl=nms(gn)+4)-4]|us[Dl-3]<<8,ta=Dl+vr;if(ta>vn){$n&&xk(0);break}Rn&&Fn(Bn+vr),ys.set(us.subarray(Dl,ta),Bn),ws.b=Bn+=vr,ws.p=gn=8*ta,ws.f=sr;continue}if(Cr==1)Vn=tms,nr=sms,yr=9,ra=5;else if(Cr==2){var fa=fk(us,gn,31)+257,ei=fk(us,gn+10,15)+4,Aa=fa+fk(us,gn+5,31)+1;gn+=14;for(var zi=new pw(Aa),Xo=new pw(19),Bi=0;Bi>4)<16)zi[Bi++]=Dl;else{var qc=0,ku=0;for(Dl==16?(ku=3+fk(us,gn,3),gn+=2,qc=zi[Bi-1]):Dl==17?(ku=3+fk(us,gn,7),gn+=3):Dl==18&&(ku=11+fk(us,gn,127),gn+=7);ku--;)zi[Bi++]=qc}}var Hp=zi.subarray(0,fa),Su=zi.subarray(fa);yr=fFe(Hp),ra=fFe(Su),Vn=NY(Hp,yr),nr=NY(Su,ra)}else xk(1);if(gn>Er){$n&&xk(0);break}}Rn&&Fn(Bn+131072);for(var Ju=(1<>4;if((gn+=15&qc)>Er){$n&&xk(0);break}if(qc||xk(2),Zx<256)ys[Bn++]=Zx;else{if(Zx==256){eh=gn,Vn=null;break}var Gp=Zx-254;Zx>264&&(Gp=fk(us,gn,(1<<(bh=Eut[Bi=Zx-257]))-1)+Lut[Bi],gn+=bh);var xo=nr[xFe(us,gn)&sm],Zy=xo>>4;if(xo||xk(3),gn+=15&xo,Su=ems[Zy],Zy>3){var bh=Tut[Zy];Su+=xFe(us,gn)&(1<Er){$n&&xk(0);break}Rn&&Fn(Bn+131072);var wf=Bn+Gp;if(BnIu.length)&&(jf=Iu.length),new pw(Iu.subarray(0,jf))}(ys,0,Bn):ys.subarray(0,Bn)}(at.subarray(Rt,-8),{i:2},new pw(((pt=at)[(At=pt.length)-4]|pt[At-3]<<8|pt[At-2]<<16|pt[At-1]<<24)>>>0),vt)));var at,vt,pt,At,Rt;const Bt=oms[et];if(!Bt)throw new Error(`Unhandled codec: ${et}`);const Ns=new globalThis.DecompressionStream(Bt);return new Response(new Blob([Ke]).stream().pipeThrough(Ns)).arrayBuffer().then(us=>new Uint8Array(us))}(Ce,je).then(Ke=>(function(et,at){et.readFields(Ghs,at)}(new gFe(Ke),Ie),new cms[Y](Ie.buffer))),Fe.then(Ke=>{for(let et=xe.length-1;et>=0;et--)switch(xe[et]){case"delta_filter":Khs(Ke,X);break;case"zigzag_filter":Yhs(Ke);break;case"bitshuffle_filter":Zhs(Ke,Y);break;default:throw new f2(`Unhandled filter "${xe[et]}"`)}return{layerName:L,blockIndex:le,data:Ke}}).catch(Ke=>{throw Ke})}))},kr(Out,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),kr(Ioe,"MapboxRasterTile"),kr(Fut,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const zut=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class yFe{static from(x){if(!(x instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[j,A]=new Uint8Array(x,0,2);if(j!==219)throw new Error("Data does not appear to be in a KDBush format.");const L=A>>4;if(L!==1)throw new Error(`Got v${L} data when expected v1.`);const O=zut[15&A];if(!O)throw new Error("Unrecognized array type.");const[$]=new Uint16Array(x,2,1),[Y]=new Uint32Array(x,4,1);return new yFe(Y,$,O,x)}constructor(x,j=64,A=Float64Array,L){if(isNaN(x)||x<0)throw new Error(`Unpexpected numItems value: ${x}.`);this.numItems=+x,this.nodeSize=Math.min(Math.max(+j,2),65535),this.ArrayType=A,this.IndexArrayType=x<65536?Uint16Array:Uint32Array;const O=zut.indexOf(this.ArrayType),$=2*x*this.ArrayType.BYTES_PER_ELEMENT,Y=x*this.IndexArrayType.BYTES_PER_ELEMENT,X=(8-Y%8)%8;if(O<0)throw new Error(`Unexpected typed array class: ${A}.`);L&&L instanceof ArrayBuffer?(this.data=L,this.ids=new this.IndexArrayType(this.data,8,x),this.coords=new this.ArrayType(this.data,8+Y+X,2*x),this._pos=2*x,this._finished=!0):(this.data=new ArrayBuffer(8+$+Y+X),this.ids=new this.IndexArrayType(this.data,8,x),this.coords=new this.ArrayType(this.data,8+Y+X,2*x),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+O]),new Uint16Array(this.data,2,1)[0]=j,new Uint32Array(this.data,4,1)[0]=x)}add(x,j){const A=this._pos>>1;return this.ids[A]=A,this.coords[this._pos++]=x,this.coords[this._pos++]=j,A}finish(){const x=this._pos>>1;if(x!==this.numItems)throw new Error(`Added ${x} items when expected ${this.numItems}.`);return vFe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(x,j,A,L){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:O,coords:$,nodeSize:Y}=this,X=[0,O.length-1,0],le=[];for(;X.length;){const xe=X.pop()||0,je=X.pop()||0,Ce=X.pop()||0;if(je-Ce<=Y){for(let et=Ce;et<=je;et++){const at=$[2*et],vt=$[2*et+1];at>=x&&at<=A&&vt>=j&&vt<=L&&le.push(O[et])}continue}const Ie=Ce+je>>1,Fe=$[2*Ie],Ke=$[2*Ie+1];Fe>=x&&Fe<=A&&Ke>=j&&Ke<=L&&le.push(O[Ie]),(xe===0?x<=Fe:j<=Ke)&&(X.push(Ce),X.push(Ie-1),X.push(1-xe)),(xe===0?A>=Fe:L>=Ke)&&(X.push(Ie+1),X.push(je),X.push(1-xe))}return le}within(x,j,A){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:L,coords:O,nodeSize:$}=this,Y=[0,L.length-1,0],X=[],le=A*A;for(;Y.length;){const xe=Y.pop()||0,je=Y.pop()||0,Ce=Y.pop()||0;if(je-Ce<=$){for(let et=Ce;et<=je;et++)$ut(O[2*et],O[2*et+1],x,j)<=le&&X.push(L[et]);continue}const Ie=Ce+je>>1,Fe=O[2*Ie],Ke=O[2*Ie+1];$ut(Fe,Ke,x,j)<=le&&X.push(L[Ie]),(xe===0?x-A<=Fe:j-A<=Ke)&&(Y.push(Ce),Y.push(Ie-1),Y.push(1-xe)),(xe===0?x+A>=Fe:j+A>=Ke)&&(Y.push(Ie+1),Y.push(je),Y.push(1-xe))}return X}}function vFe(k,x,j,A,L,O){if(L-A<=j)return;const $=A+L>>1;But(k,x,$,A,L,O),vFe(k,x,j,A,$-1,1-O),vFe(k,x,j,$+1,L,1-O)}function But(k,x,j,A,L,O){for(;L>A;){if(L-A>600){const le=L-A+1,xe=j-A+1,je=Math.log(le),Ce=.5*Math.exp(2*je/3),Ie=.5*Math.sqrt(je*Ce*(le-Ce)/le)*(xe-le/2<0?-1:1);But(k,x,j,Math.max(A,Math.floor(j-xe*Ce/le+Ie)),Math.min(L,Math.floor(j+(le-xe)*Ce/le+Ie)),O)}const $=x[2*j+O];let Y=A,X=L;for(SY(k,x,A,j),x[2*L+O]>$&&SY(k,x,A,L);Y$;)X--}x[2*A+O]===$?SY(k,x,A,X):(X++,SY(k,x,X,L)),X<=j&&(A=X+1),j<=X&&(L=X-1)}}function SY(k,x,j,A){bFe(k,j,A),bFe(x,2*j,2*A),bFe(x,2*j+1,2*A+1)}function bFe(k,x,j){const A=k[x];k[x]=k[j],k[j]=A}function $ut(k,x,j,A){const L=k-j,O=x-A;return L*L+O*O}o.$=Gx,o.A=class{constructor(k,x,j){this.target=k,this.parent=x,this.mapId=j,this.callbacks={},this.cancelCallbacks={},Vt(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new yhs}send(k,x,j,A,L=!1,O){const $=Math.round(1e18*Math.random()).toString(36).substring(0,10);j&&(j.metadata=O,this.callbacks[$]=j);const Y=new Set;return this.target.postMessage({id:$,type:k,hasCallback:!!j,targetMapId:A,mustQueue:L,sourceMapId:this.mapId,data:Cd(x,Y)},Y),{cancel:()=>{j&&delete this.callbacks[$],this.target.postMessage({id:$,type:"",targetMapId:A,sourceMapId:this.mapId})}}}receive(k){const x=k.data;if(!x)return;const j=x.id;if(j&&(!x.targetMapId||this.mapId===x.targetMapId))if(x.type===""){const A=this.cancelCallbacks[j];delete this.cancelCallbacks[j],A&&A.cancel()}else if(x.mustQueue||Ba(self)){const A=this.callbacks[j],L=this.scheduler.add(()=>this.processTask(j,x),A&&A.metadata||{type:"message"});L&&(this.cancelCallbacks[j]=L)}else this.processTask(j,x)}processTask(k,x){if(delete this.cancelCallbacks[k],x.type===""){const j=this.callbacks[k];delete this.callbacks[k],j&&(x.error?j(Zc(x.error)):j(null,Zc(x.data)))}else{const j=new Set,A=x.hasCallback?(O,$)=>{this.target.postMessage({id:k,type:"",sourceMapId:this.mapId,error:O?Cd(O):null,data:Cd($,j)},j)}:()=>{},L=Zc(x.data);if(this.parent[x.type])this.parent[x.type](x.sourceMapId,L,A);else if(this.parent.getWorkerSource){const O=x.type.split("."),{source:$,scope:Y}=L;this.parent.getWorkerSource(x.sourceMapId,{type:O[0],source:$,scope:Y,uid:0})[O[1]](L,A)}else A(new Error(`Could not find function ${x.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=pf,o.C=Sd,o.D=Hd,o.E=Um,o.F=Pt,o.G=2,o.H=cY,o.I=qm,o.J=adt,o.K=qy,o.L=s3,o.M=Zg,o.N=F0,o.O=Nu,o.P=Ss,o.Q=vl,o.R=_g,o.S=Vm,o.T=y5,o.U=Op,o.V=Soe,o.W=d5,o.X=Dd,o.Y=Ph,o.Z=Yu,o._=Vb,o.a=function(k){return qa.API_CDN_URL_REGEX.test(k)},o.a$=loe,o.a0=Gd,o.a1=Vx,o.a2=wg,o.a3=Ks,o.a4=n3,o.a5=class extends Soe{},o.a6=Zu,o.a7=ju,o.a8=Ws,o.a9=function(k){const x=k.value;return x?wg(x)?oFe(x,!0)?[]:[new Soe(k.key,x,`invalid url "${x}"`)]:[new Soe(k.key,x,`string expected, "${Zg(x)}" found`)]:[]},o.aA=Lct,o.aB=function(k){let x=1/0,j=1/0,A=-1/0,L=-1/0;for(const O of k)x=Math.min(x,O.x),j=Math.min(j,O.y),A=Math.max(A,O.x),L=Math.max(L,O.y);return{min:new Ss(x,j),max:new Ss(A,L)}},o.aC=gt,o.aD=b,o.aE=Je,o.aF=Xt,o.aG=Y0,o.aH=Un,o.aI=na,o.aJ=function(k,x){const j={};for(let A=0;A=0?x.slice(j+1):""}catch{return""}},o.aN=class{constructor(k){this.entries={},this.scheduler=k}request(k,x,j,A){const L=this.entries[k]=this.entries[k]||{callbacks:[]};if(L.result){const[O,$]=L.result;return this.scheduler?this.scheduler.add(()=>{A(O,$)},x):A(O,$),()=>{}}return L.callbacks.push(A),L.cancel||(L.cancel=j((O,$)=>{L.result=[O,$];for(const Y of L.callbacks)this.scheduler?this.scheduler.add(()=>{Y(O,$)},x):Y(O,$);setTimeout(()=>delete this.entries[k],3e3)})),()=>{L.result||(L.callbacks=L.callbacks.filter(O=>O!==A),L.callbacks.length||(L.cancel(),delete this.entries[k]))}}},o.aO=function(k,x,j){const A=JSON.stringify(k.request);return k.data&&(this.deduped.entries[A]={result:[null,k.data]}),this.deduped.request(A,{type:"parseTile",renderSourceType:k.renderSourceType,zoom:k.tileZoom},L=>{const O=Yg(k.request,($,Y,X)=>{$?nx($)?L(null,null):L($):Y&&L(null,{rawData:Y,vectorTile:j?void 0:new bl(new loe(Y)),responseHeaders:new Map(X.entries())})});return()=>{O.cancel(),L(null,null)}},x)},o.aP=function(k){return k?{cacheControl:k.get("cache-control"),expires:k.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(k){vo++,vo>so&&(k.getActor().send("enforceCacheSizeLimit",Ta),vo=0)},o.aR=Yy,o.aS=Bdt,o.aT=Kdt,o.aU=Ds,o.aV=zdt,o.aW=function(k,x){const j=document.createElement("video");j.muted=!0,j.onloadstart=function(){x(null,j)};for(let A=0;A{}}},o.aX=rY,o.aY=kI,o.aZ=Vt,o.a_=Ioe,o.aa=nT,o.ab=ld,o.ac=ur,o.ad=class{constructor(k){this.specification=k}possiblyEvaluate(k,x){return Hr(k.expression.evaluate(x))}interpolate(k,x,j){return{x:Pr(k.x,x.x,j),y:Pr(k.y,x.y,j),z:Pr(k.z,x.z,j),azimuthal:Pr(k.azimuthal,x.azimuthal,j),polar:Pr(k.polar,x.polar,j)}}},o.ae=Vi,o.af=Pc,o.ag=pa,o.ah=Ve,o.ai=H,o.aj=ft,o.ak=Up,o.al=d3,o.am=Pr,o.an=fr,o.ao=Ni,o.ap=Gs,o.aq=Js,o.ar=class{constructor(k){this.specification=k}possiblyEvaluate(k,x){return function([j,A]){const L=Hr([1,j,A]);return{x:L.x,y:L.y,z:L.z}}(k.expression.evaluate(x))}interpolate(k,x,j){return{x:Pr(k.x,x.x,j),y:Pr(k.y,x.y,j),z:Pr(k.z,x.z,j)}}},o.as=function(k,x,j=0,A=!0){const L=new Ss(j,j),O=k.sub(L),$=x.add(L),Y=[O,new Ss($.x,O.y),$,new Ss(O.x,$.y)];return A&&Y.push(O.clone()),Y},o.at=function(k,x){const j=[];for(let A=0;Athis.buckets[je].layers.some(Ce=>$.has(Ce.fqid))),X=Object.keys(this.buckets).some(je=>this.buckets[je].layers.some(Ce=>Ce.hasTransition&&Ce.hasTransition())),le=this._firstPrepareComplete&&O!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(x));const xe=this._lastUpdatedBrightness!==A;this._lastAvailableImagesCount=O,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||A||this._hasAppearances||Y||X||le)&&(!(this._hasAppearances||Y||X||le)&&this._lastUpdatedBrightness&&A&&Math.abs(this._lastUpdatedBrightness-A)<.001||(this.updateBuckets(x,xe,void 0,le||Y||X,$,L),this._lastUpdatedBrightness=A))}evaluateQueryRenderedFeaturePadding(){let k=0;for(const x in this.buckets){const j=this.buckets[x];j.evaluateQueryRenderedFeaturePadding&&(k=Math.max(k,j.evaluateQueryRenderedFeaturePadding()))}return k}queryRenderedFeatures(k,x,j,A,L,O,$){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const Y=this.evaluateQueryRenderedFeaturePadding(),X=function(le,xe){const je=M([],[.5*le.width,.5*-le.height,1]);return w(je,je,[1,-1,0]),b(je,je,le.calculateProjMatrix(xe.toUnwrapped())),Float32Array.from(je)}(L,this.tileID);return this.latestFeatureIndex.query(k,{tilespaceGeometry:x,pixelPosMatrix:X,transform:A,availableImages:j,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:Y,scope:$})}querySourceFeatures(k,x){const j=this.latestFeatureIndex;if(!j||!j.rawTileData)return;const A=j.loadVTLayers(),L=x?x.sourceLayer:"",O=A._geojsonTileLayer||A[L];if(!O)return;const $=iT(x&&x.filter),{z:Y,x:X,y:le}=this.tileID.canonical,xe={z:Y,x:X,y:le};for(let je=0;jej)A=!1;else if(x)if(this.expirationTimej.appearances&&j.appearances.length>0))return!0;return!1}updateBuckets(k,x,j,A,L,O){if(!this.latestFeatureIndex||!k.style)return;const $=O||k.style.listImages(),Y=k.style.getBrightness(),X=L||new Set;for(const le in this.buckets){if(!k.style.hasLayer(le))continue;const xe=this.buckets[le],je=xe.layers[0],Ce=je.sourceLayer||"_geojsonTileLayer",Ie=k.style.getLayerSourceCache(je),Fe=xe.layers.some(Rt=>X.has(Rt.fqid)),Ke=(A||Fe)&&xe instanceof pk?k.style.getOwnLayer(le):void 0;let et=j&&j[Ce]||{};Ie&&!j&&(et=Ie._state.getState(Ce,void 0));const at=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},vt=Object.keys(et).length>0&&!x;xe.hasAppearances=xe.layers.some(Rt=>Rt.appearances&&Rt.appearances.length>0);const pt=vt?xe.stateDependentLayers:xe.layers;if(vt&&xe.stateDependentLayers.length!==0||x||Fe||A){const Rt=this.latestFeatureIndex.loadVTLayers()[Ce];if(xe.update(et,Rt,$,at,pt,x,Y,this.tileID.canonical),(A||Fe)&&!x&&xe instanceof pk&&Ke&&Ke.type==="symbol"){const Bt=xe;Bt.text&&Bt.text.uboBinder&&Bt.text.uboBinder.updateDynamicExpressions(Ke,Rt,this.tileID.canonical,$,et,Y),Bt.icon&&Bt.icon.uboBinder&&Bt.icon.uboBinder.updateDynamicExpressions(Ke,Rt,this.tileID.canonical,$,et,Y)}if(xe instanceof pk){const Bt=xe,Ns=k.context;Bt.text&&Bt.text.uboBinder&&Bt.text.uboBinder.upload(Ns),Bt.icon&&Bt.icon.uboBinder&&Bt.icon.uboBinder.upload(Ns)}}if(vt&&xe.stateDependentLayers.length!==0||x||xe.hasAppearances){const Rt={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},Bt=xe.updateAppearances(this.tileID.canonical,et,$,Rt,k.imageManager,vt&&xe.stateDependentLayers.length!==0);if(Bt&&Bt.hasUboChanges){const Ns=k.context;xe instanceof pk&&xe.text&&xe.text.uboBinder&&xe.text.uboBinder.upload(Ns),xe instanceof pk&&xe.icon&&xe.icon.uboBinder&&xe.icon.uboBinder.upload(Ns)}}(xe instanceof ooe||xe instanceof Uie)&&k._terrain&&k._terrain.enabled&&Ie&&xe.uploadPending()&&k._terrain._clearRenderCacheForTile(Ie.id,this.tileID);const At=k&&k.style&&k.style.getOwnLayer(le);At&&(this.queryPadding=Math.max(this.queryPadding,At.queryRadius(xe)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Ke--){const et=4*Ke,at=vT[et+0],vt=vT[et+1],pt=vT[et+2],At=vT[et+3],Rt=at+pt>>1,Bt=vt+At>>1,Ns=Rt+Bt-vt,us=Bt+at-Rt,ws=vt*v5+at,ys=At*v5+pt,vs=Bt*v5+Rt,vn=Math.hypot((b5[2*ws+0]+b5[2*ys+0])/2-b5[2*vs+0],(b5[2*ws+1]+b5[2*ys+1])/2-b5[2*vs+1])>=16;bT[vs]=bT[vs]||(vn?1:0),Ke<1022&&(bT[vs]=bT[vs]||bT[(vt+us>>1)*v5+(at+Ns>>1)]||bT[(At+us>>1)*v5+(pt+Ns>>1)])}const xe=new bo,je=new Qu;let Ce=0;function Ie(Ke,et){const at=et*v5+Ke;return Aoe[at]===0&&(xe.emplaceBack(b5[2*at+0],b5[2*at+1],Ke*fr/p2,et*fr/p2),Aoe[at]=++Ce),Aoe[at]-1}function Fe(Ke,et,at,vt,pt,At){const Rt=Ke+at>>1,Bt=et+vt>>1;if(Math.abs(Ke-pt)+Math.abs(et-At)>1&&bT[Bt*v5+Rt])Fe(pt,At,Ke,et,Rt,Bt),Fe(at,vt,pt,At,Rt,Bt);else{const Ns=Ie(Ke,et),us=Ie(at,vt),ws=Ie(pt,At);je.emplaceBack(Ns,us,ws)}}return Fe(0,0,p2,p2,p2,0),Fe(p2,p2,0,0,0,p2),{vertices:xe,indices:je}}(this.tileID.canonical,x);A=O.vertices,L=O.indices}else{A=new bo,L=new Qu;for(const{x:$,y:Y}of j)A.emplaceBack($,Y,0,0);const O=Wz(A.int16.subarray(0,4*A.length),void 0,4);for(let $=0;$0&&($=y(new Float64Array(16),x.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,A,x,L,$,O),this._makeGlobeTileDebugTextBuffer(k,A,x,L,$,O)}_globePoint(k,x,j,A,L,O,$){let Y=$K(k,x,j);if(O){const X=1<.5?Ce=-1:je<-.5&&(Ce=1);let Ie=(k/fr+j.x)/X+Ce,Fe=(x/fr+j.y)/X;Ie=(Ie-le)*A._pixelsPerMercatorPixel+le,Fe=(Fe-xe)*A._pixelsPerMercatorPixel+xe;const Ke=[Ie*A.worldSize,Fe*A.worldSize,0];Ve(Ke,Ke,O),Y=c3(Y,Ke,$)}return Ve(Y,Y,L)}_makeGlobeTileDebugBorderBuffer(k,x,j,A,L,O){const $=new ao,Y=new i3,X=new xl,le=(je,Ce,Ie,Fe,Ke)=>{const et=(Ie-je)/(Ke-1),at=(Fe-Ce)/(Ke-1),vt=$.length;for(let pt=0;ptle*je+Ce;for(let je=0;je1)return!1;const j=x.getSource().maxzoom,A=1<1)return x;const L=A.getSource().maxzoom,O=1<{const Y=this.getAtTileOffset(k,L,O,$),X=A.upVector(k.canonical,L.x,L.y);return ce(X,X,Y*A.upVectorScale(k.canonical,x,j).metersToTile),X}}getForTilePoints(k,x,j,A){if(this.isUsingMockSource())return!1;const L=iB.create(this,k,A);return!!L&&(x.forEach(O=>{O[2]=this.exaggeration()*L.getElevationAt(O[0],O[1],j)}),!0)}getMinMaxForTile(k){if(this.isUsingMockSource())return null;const x=this.findDEMTileFor(k);if(!x||!x.dem)return null;const j=x.dem.tree,A=x.tileID,L=1<0&&(A+=(k[L]-0)*(k[L]-0)),x[L]<0&&(A+=(0-x[L])*(0-x[L]));return A},o.cL=function(k){return k*k*k*k*k},o.cM=pn,o.cN=45,o.cO=Vz,o.cP=function(k,x,j){const A=Math.sqrt(k*k+x*x+j*j),L=A>0?Math.acos(j/A)*Pn:0;let O=k!==0||x!==0?Math.atan2(-x,-k)*Pn+90:0;return O<0&&(O+=360),[A,O,L]},o.cQ=K,o.cR=Hr,o.cS=Kn,o.cT=oe,o.cU=Kl,o.cV=re,o.cW=function(k){return[Math.pow(k[0],1/2.2),Math.pow(k[1],1/2.2),Math.pow(k[2],1/2.2)]},o.cX=xct,o.cY=ERe,o.cZ=_ct,o.c_=oFe,o.ca=2,o.cb=7,o.cc=6,o.cd=ke,o.ce=G,o.cf=V,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=Gz,o.cl=$v,o.cm=yct,o.cn=fI,o.co=Wot,o.cp=function(k,x,j,A,L,O,$,Y,X){if(X.name==="globe")return Wot(k,x,new fI(j,A,L),!1);const le=wI({z:j,x:A,y:L},X);return new Kl([(O+le.x/le.scale)*x,x*(le.y/le.scale),$],[(O+le.x2/le.scale)*x,x*(le.y2/le.scale),Y])},o.cq=function(k,x,j){return k[0]=Math.min(x[0],j[0]),k[1]=Math.min(x[1],j[1]),k[2]=Math.min(x[2],j[2]),k[3]=Math.min(x[3],j[3]),k},o.cr=function(k,x,j){return k[0]=Math.max(x[0],j[0]),k[1]=Math.max(x[1],j[1]),k[2]=Math.max(x[2],j[2]),k[3]=Math.max(x[3],j[3]),k},o.cs=function(k){const x=Math.round((k+45+360)%360/90)%4;return tr[x]},o.ct=In,o.cu=Xe,o.cv=6,o.cw=function(k){const x=v(new Float64Array(16));b(x,k.pixelMatrix,k.globeMatrix);const j=[0,ds,0],A=[0,Cs,0];return Ve(j,j,x),Ve(A,A,x),[j[0]>0&&j[0]<=k.width&&j[1]>0&&j[1]<=k.height&&!ZDe(k,new Ds(k.center.lat,90)),A[0]>0&&A[0]<=k.width&&A[1]>0&&A[1]<=k.height&&!ZDe(k,new Ds(k.center.lat,-90))]},o.cx=function(k,x){const{scale:j}=k.tileTransform,A=j*fr/(k.tileSize*Math.pow(2,x.zoom-k.tileID.overscaledZ+k.tileID.canonical.z));return function(L,O,$){var Y=O[1],X=O[2],le=O[3],xe=$[0],je=$[1];return L[0]=O[0]*xe,L[1]=Y*xe,L[2]=X*je,L[3]=le*je,L}(new Float32Array(4),x.inverseAdjustmentMatrix,[A,A])},o.cy=toe,o.cz=q,o.d=function(k){return qa.API_TILEJSON_REGEX.test(k)},o.d$=ycs,o.d0=Pu,o.d1=class{static calculate(k,x,j){const A=new Set,L=new Map,O=new Set,$=new Set;for(const X of Object.values(k))for(const[le,xe]of Object.entries(X.floors)){O.add(le),xe.isDefault&&$.add(le),xe.conflicts&&L.set(le,xe.conflicts);const je=le===x,Ce=xe.connections&&x&&xe.connections.has(x);(je||Ce)&&A.add(le)}const Y=X=>{const le=L.get(X)||new Set;for(const xe of A)if((L.get(xe)||new Set).has(X)||le.has(xe))return!0;return!1};if(j)for(const X of j)O.has(X)&&(Y(X)||A.add(X));for(const X of $)A.has(X)||Y(X)||A.add(X);return A}},o.d2=hoe,o.d3=KRe,o.d4=Pi,o.d5=function(){return{API_URL:qa.API_URL,DRACO_URL:qa.DRACO_URL,MESHOPT_URL:qa.MESHOPT_URL,MESHOPT_SIMD_URL:qa.MESHOPT_SIMD_URL,BUILDING_GEN_URL:qa.BUILDING_GEN_URL}},o.d6=a5,o.d7=Ma,o.d8=mc,o.d9=Zn,o.dA=Lie,o.dB=ao,o.dC=Qu,o.dD=function(k,x){return[Math.pow(k[0],2.2)*x,Math.pow(k[1],2.2)*x,Math.pow(k[2],2.2)*x]},o.dE=h,o.dF=function(k,x){var j=Math.sin(x),A=Math.cos(x);return k[0]=A,k[1]=j,k[2]=0,k[3]=-j,k[4]=A,k[5]=0,k[6]=0,k[7]=0,k[8]=1,k},o.dG=_e,o.dH=Yot,o.dI=Ua,o.dJ=Eo,o.dK=aFe,o.dL=function(k,x){const j=[0,0,0];return Ve(j,j,UK(f5(x.canonical))),Ve(j,j,k),j},o.dM=k=>({u_matrix:new N(k),u_texsize:new e_(k),u_pixels_to_tile_units:new W(k),u_device_pixel_ratio:new Hm(k),u_width_scale:new Hm(k),u_floor_width_scale:new Hm(k),u_image:new mI(k),u_units_to_pixels:new e_(k),u_tile_units_to_pixels:new Hm(k),u_alpha_discard_threshold:new Hm(k),u_trim_offset:new e_(k),u_trim_fade_range:new e_(k),u_trim_gradient_mix_range:new e_(k),u_trim_color:new Vz(k),u_zbias_factor:new Hm(k),u_tile_to_meter:new Hm(k),u_ground_shadow_factor:new pI(k),u_pattern_transition:new Hm(k)}),o.dN=k=>({u_matrix:new N(k),u_pixels_to_tile_units:new W(k),u_device_pixel_ratio:new Hm(k),u_width_scale:new Hm(k),u_floor_width_scale:new Hm(k),u_units_to_pixels:new e_(k),u_dash_image:new mI(k),u_gradient_image:new mI(k),u_image_height:new Hm(k),u_texsize:new e_(k),u_tile_units_to_pixels:new Hm(k),u_alpha_discard_threshold:new Hm(k),u_trim_offset:new e_(k),u_trim_fade_range:new e_(k),u_trim_gradient_mix_range:new e_(k),u_trim_color:new Vz(k),u_zbias_factor:new Hm(k),u_tile_to_meter:new Hm(k),u_ground_shadow_factor:new pI(k)}),o.dO=k=>({u_camera_to_center_distance:new Hm(k),u_extrude_scale:new W(k),u_device_pixel_ratio:new Hm(k),u_matrix:new N(k),u_inv_rot_matrix:new N(k),u_merc_center:new e_(k),u_tile_id:new pI(k),u_zoom_transition:new Hm(k),u_up_dir:new pI(k),u_emissive_strength:new Hm(k)}),o.dP=EK,o.dQ=gus,o.dR=class{constructor(k,x,j,A){this.context=k,this.format=A,this.size=j,this.texture=k.gl.createTexture();const[L,O,$]=this.size,{gl:Y}=k;Y.bindTexture(Y.TEXTURE_3D,this.texture),k.pixelStoreUnpackFlipY.set(!1),k.pixelStoreUnpack.set(1),k.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in x&&x.data&&Y.texImage3D(Y.TEXTURE_3D,0,this.format,L,O,$,0,wRe(this.format),jRe(this.format),x.data)}bind(k,x){const{context:j}=this,{gl:A}=j;A.bindTexture(A.TEXTURE_3D,this.texture),k!==this.minFilter&&(A.texParameteri(A.TEXTURE_3D,A.TEXTURE_MAG_FILTER,k),A.texParameteri(A.TEXTURE_3D,A.TEXTURE_MIN_FILTER,k),this.minFilter=k),x!==this.wrapS&&(A.texParameteri(A.TEXTURE_3D,A.TEXTURE_WRAP_S,x),A.texParameteri(A.TEXTURE_3D,A.TEXTURE_WRAP_T,x),this.wrapS=x)}destroy(){const{gl:k}=this.context;k.deleteTexture(this.texture),this.texture=null}},o.dS=Jot,o.dT=(k,x,j,A,L,O)=>{const $=k.transform,Y=$.projection.name==="globe";let X;if(O.paint.get("circle-pitch-alignment")==="map")if(Y){const xe=Yot($.zoom,x.canonical)*$._pixelsPerMercatorPixel;X=Float32Array.from([xe,0,0,xe])}else X=$.calculatePixelsToTileUnitsMatrix(j);else X=new Float32Array([$.pixelsToGLUnits[0],0,0,$.pixelsToGLUnits[1]]);const le={u_camera_to_center_distance:k.transform.getCameraToCenterDistance($.projection),u_matrix:k.translatePosMatrix(x.projMatrix,j,O.paint.get("circle-translate"),O.paint.get("circle-translate-anchor")),u_device_pixel_ratio:wu.devicePixelRatio,u_extrude_scale:X,u_inv_rot_matrix:Ncs,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:O.paint.get("circle-emissive-strength")};if(Y){le.u_inv_rot_matrix=A,le.u_merc_center=L,le.u_tile_id=[x.canonical.x,x.canonical.y,1<{const xe=k.transform,je=xe.pitch<15?Ict(.07,.7,gt((14-xe.zoom)/5,0,1)):.07,Ce=j.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:Rct(k,x,j,A),u_texsize:x.imageAtlasTexture?x.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:xe.calculatePixelsToTileUnitsMatrix(x),u_device_pixel_ratio:L,u_width_scale:O,u_floor_width_scale:$,u_image:0,u_tile_units_to_pixels:Dct(x,xe),u_units_to_pixels:[1/xe.pixelsToGLUnits[0],1/xe.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:Y,u_trim_fade_range:j.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:j.paint.get("line-trim-color").toPremultipliedRenderColor(Ce?null:j.lut).toArray01(),u_zbias_factor:je,u_tile_to_meter:Kn(x.tileID.canonical,0),u_ground_shadow_factor:X,u_pattern_transition:le}},o.dX=(k,x,j,A,L,O,$,Y,X,le)=>{const xe=k.transform,je=xe.calculatePixelsToTileUnitsMatrix(x),Ce=j.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Ie=xe.pitch<15?Ict(.07,.7,gt((14-xe.zoom)/5,0,1)):.07;return{u_matrix:Rct(k,x,j,A),u_pixels_to_tile_units:je,u_device_pixel_ratio:O,u_width_scale:$,u_floor_width_scale:Y,u_units_to_pixels:[1/xe.pixelsToGLUnits[0],1/xe.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:L,u_texsize:Oct(j)&&x.lineAtlasTexture?x.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:Dct(x,k.transform),u_alpha_discard_threshold:0,u_trim_offset:X,u_trim_fade_range:j.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:j.paint.get("line-trim-color").toPremultipliedRenderColor(Ce?null:j.lut).toArray01(),u_zbias_factor:Ie,u_tile_to_meter:Kn(x.tileID.canonical,0),u_ground_shadow_factor:le}},o.dY=gs,o.dZ=qK,o.d_=jn,o.da=function(k){const x=k.indexOf(dt);return x>=0?k.slice(0,x):k},o.db=function(k){return k.indexOf(dt)>=0},o.dc=function(k){const x=k.lastIndexOf(dt);return x>=0?k.slice(x+1):""},o.dd=function(k){const x=[],j=k.id;return j===void 0&&x.push({message:`layers.${j}: missing required property "id"`}),k.render===void 0&&x.push({message:`layers.${j}: missing required method "render"`}),k.renderingMode&&k.renderingMode!=="2d"&&k.renderingMode!=="3d"&&x.push({message:`layers.${j}: property "renderingMode" must be either "2d" or "3d"`}),x},o.de=function(k,x,j,A){return k.type==="custom"?new dhs(k,x):new fhs[k.type](k,x,j,A)},o.df=Zs,o.dg=iT,o.dh=Hs,o.di=class extends NI{constructor(k,x){super(k._vectorTileFeature,k._z,k._x,k._y,k.id),k.state&&(this.state=Object.assign({},k.state)),this.target=x.target,this.namespace=x.namespace,x.properties&&(this.properties=x.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=k.source,this.sourceLayer=k.sourceLayer,this.layer=k.layer)}toJSON(){const k=super.toJSON();return k.target=this.target,k.namespace=this.namespace,k}},o.dj=i5,o.dk=function(k){return k({pluginStatus:Mu,pluginURL:mx}),i5.on("pluginStateChange",k),k},o.dl=HDe,o.dm=class extends Jb{constructor(k){super(k),this.current=T}set(k,x,j){if(this.fetchUniformLocation(k,x)){for(let A=0;A<9;A++)if(j[A]!==this.current[A]){this.current=j,this.gl.uniformMatrix3fv(this.location,!1,j);break}}}},o.dn=Lr,o.dp=function(k,x,j){const A=d3(j.zoom),L=k.style.map._antialias,O=k.terrain&&k.terrain.exaggeration()>0;return A===0&&!L&&!O},o.dq=function(k){const x=k.pixelsPerMeter,j=x/nn(1,k.center.lat),A=v(new Float64Array(16));return w(A,A,[k.point.x,k.point.y,0]),S(A,A,[j,j,x]),Float32Array.from(A)},o.dr=Iie,o.ds=function(k){const x=80.051129;k=gt(k,-80.051129,x)/x*90;const j=Math.pow(Math.abs(Math.sin(Gs(k))),3);return Math.round(j*(Ts.length-1))},o.dt=function(k,x,j,A){const L=x.getNorth(),O=x.getSouth(),$=x.getWest(),Y=x.getEast(),X=1<0){const Fe=180/A;p(Ie,Ie,[Fe/le+1,0,0,0,Fe/xe+1,0,-.5*Fe/je,.5*Fe/Ce,1])}return Ie[2]=X,Ie[5]=k.x,Ie[8]=k.y,Ie},o.du=UK,o.dv=f5,o.dw=function(k,x,j){const A=v(new Float64Array(16)),L=(x/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(k,x=!1){const j=Llt(new Ss(0,0),new Ss(fr,fr),k),A=[];if(x&&!uRe(j,this._globalClipBounds))return A;for(const L of this._activeRegions){if(L.hiddenByOverlap||!uRe(j,L))continue;const O=ids(L.min,L.max,k);A.push({min:O.min,max:O.max,sourceId:this._sourceIds[L.priority],footprint:L.footprint,footprintTileId:L.tileId,order:L.order,clipMask:L.clipMask,clipScope:L.clipScope})}return A}setSources(k){this._setSources(k.map(x=>({getSourceId:()=>x.cache.id,getFootprints:()=>{const j=[];for(const A of x.cache.getVisibleCoordinates()){const L=x.cache.getTile(A).buckets[x.layer];L&&L.updateFootprints(A.toUnwrapped(),j)}return j},getOrder:()=>x.order,getClipMask:()=>x.clipMask,getClipScope:()=>x.clipScope})))}_addSource(k){const x=k.getFootprints();if(x.length===0)return;const j=k.getOrder(),A=k.getClipMask(),L=k.getClipScope();for(const O of x){if(!O.footprint)continue;const $=Llt(O.footprint.min,O.footprint.max,O.id);this._activeRegions.push({min:$.min,max:$.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:O.id,footprint:O.footprint,order:j,clipMask:A,clipScope:L})}this._sourceIds.push(k.getSourceId())}_computeReplacement(){this._activeRegions.sort((x,j)=>x.priority-j.priority||Vie(x.min,j.min)||Vie(x.max,j.max)||x.order-j.order||x.clipMask-j.clipMask||function(A,L){const O=($,Y)=>$+Y;return A.length-L.length||A.reduce(O,"").localeCompare(L.reduce(O,""))}(x.clipScope,j.clipScope));let k=this._activeRegions.length!==this._prevRegions.length;if(!k){let x=0;for(;!k&&x!==this._activeRegions.length;){const j=this._activeRegions[x],A=this._prevRegions[x];k=j.priority!==A.priority||!Plt(j,A)||j.order!==A.order||j.clipMask!==A.clipMask||!pr(j.clipScope,A.clipScope),this._activeRegions[x].hiddenByOverlap=A.hiddenByOverlap,++x}}if(k){++this._updateTime;for(const j of this._activeRegions)j.order!==XK&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,j.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,j.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,j.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,j.max.y));const x=j=>{const A=this._activeRegions;if(j>=A.length)return j;const L=A[j].priority;for(;j1){let j=0,A=x(j);for(;j!==A;){let L=j;const O=j;for(;L!==A;){const $=this._activeRegions[L];$.hiddenByOverlap=!1;for(let Y=0;Y=0;x--)this._addSource(k[x]);this._computeReplacement()}},o.eH=bo,o.eI=joe,o.eJ=i3,o.eK=XK,o.eL=class{constructor(k){this._createGrid(k),this._createPoles(k)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const k of this._poleSegments)k.destroy();for(const k of this._gridSegments)k.withSkirts.destroy(),k.withoutSkirts.destroy()}_fillGridMeshWithLods(k,x){const j=new ao,A=new Qu,L=[],O=k+1+2,$=x[0]+1,Y=x[0]+1+(1+x.length),X=(le,xe,je)=>{let Ce=le===O-1?le-2:le===0?le:le-1;return Ce+=je?24575:0,[Ce,xe]};for(let le=0;le>>=0,k=Math.imul(2747636419^k,2654435769)>>>0,k=Math.imul(k^k>>>16,2654435769)>>>0,(k=Math.imul(k^k>>>16,2654435769)>>>0)/4294967296},o.ec=Hot,o.ed=KDe,o.ee=Xb,o.ef=E,o.eg=function(k,x){return k[0]=x[0],k[1]=x[1],k[2]=x[2],k[3]=x[4],k[4]=x[5],k[5]=x[6],k[6]=x[8],k[7]=x[9],k[8]=x[10],k},o.eh=r3,o.ei=lI,o.ej=function(k,x,j,A,L){return gt((k-x)/(j-x)*(L-A)+A,A,L)},o.ek=zt,o.el=function(k,x){var j=x[0],A=x[1],L=x[2],O=x[3],$=x[4],Y=x[5],X=x[6],le=x[7],xe=x[8],je=xe*$-Y*le,Ce=-xe*O+Y*X,Ie=le*O-$*X,Fe=j*je+A*Ce+L*Ie;return Fe?(k[0]=je*(Fe=1/Fe),k[1]=(-xe*A+L*le)*Fe,k[2]=(Y*A-L*$)*Fe,k[3]=Ce*Fe,k[4]=(xe*j-L*X)*Fe,k[5]=(-Y*j+L*O)*Fe,k[6]=Ie*Fe,k[7]=(-le*j+A*X)*Fe,k[8]=($*j-A*O)*Fe,k):null},o.em=_a,o.en=2,o.eo=Ee,o.ep=ut,o.eq=D,o.er=function(k,x){var j=new d(3);D(j,x);var A=1/j[0],L=1/j[1],O=1/j[2],$=x[0]*A,Y=x[1]*L,X=x[2]*O,le=x[4]*A,xe=x[5]*L,je=x[6]*O,Ce=x[8]*A,Ie=x[9]*L,Fe=x[10]*O,Ke=$+xe+Fe,et=0;return Ke>0?(et=2*Math.sqrt(Ke+1),k[3]=.25*et,k[0]=(je-Ie)/et,k[1]=(Ce-X)/et,k[2]=(Y-le)/et):$>xe&&$>Fe?(et=2*Math.sqrt(1+$-xe-Fe),k[3]=(je-Ie)/et,k[0]=.25*et,k[1]=(Y+le)/et,k[2]=(Ce+X)/et):xe>Fe?(et=2*Math.sqrt(1+xe-$-Fe),k[3]=(Ce-X)/et,k[0]=(Y+le)/et,k[1]=.25*et,k[2]=(je+Ie)/et):(et=2*Math.sqrt(1+Fe-$-xe),k[3]=(Y-le)/et,k[0]=(Ce+X)/et,k[1]=(je+Ie)/et,k[2]=.25*et),k},o.es=function(k,x){var j=2*Math.acos(x[3]),A=Math.sin(j/2);return A>c?(k[0]=x[0]/A,k[1]=x[1]/A,k[2]=x[2]/A):(k[0]=1,k[1]=0,k[2]=0),j},o.et=dFe,o.eu=roe,o.ev=noe,o.ew=[1,1,1],o.ex=iB,o.ey=function(k,x,j,A){var L=x[0],O=x[1],$=x[2],Y=x[3];return k[0]=L+A*(j[0]-L),k[1]=O+A*(j[1]-O),k[2]=$+A*(j[2]-$),k[3]=Y+A*(j[3]-Y),k},o.ez=Qz,o.f=gl,o.f0=Xot,o.f1=function(k){const x=[0,0,0],j=v(new Float64Array(16));return b(j,k.pixelMatrix,k.globeMatrix),Ve(x,x,j),new Ss(x[0],x[1])},o.f2=G0,o.f3=function(k,x,j=!1){if(Mu===Lh.deferred||Mu===Lh.loading||Mu===Lh.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");mx=wu.resolveURL(k),Mu=Lh.deferred,gp=x,ok(),j||o5()},o.f4=zo,o.f5=ui,o.f6=ar,o.f7=function(k){const x=$m();if(!x)return;const j=x.delete(to);k&&j.then(()=>k()).catch(k)},o.f8=kr,o.f9=mT,o.fA=Si,o.fB=function(k){let x=0;if(new Uint32Array(k,0,1)[0]!==uct){const j=new Uint32Array(k,0,7),[,,A,L,O,$]=j;x=j.byteLength+L+O+$+O,(A!==k.byteLength||x>=k.byteLength)&&aa("Invalid b3dm header information.")}return fct(k,x)},o.fC=function(k,x){const j=ERe(k);for(const A of j){for(const L of A.meshes)Fds(L);A.lights&&(A.lightMeshIndex=A.meshes.length,A.meshes.push(Ods(A.lights,x)))}return j},o.fD=Coe,o.fE=Ba,o.fF=ey,o.fG=Lh,o.fH=function(k){al(),pi!=null&&pi.then(x=>{x.keys().then(j=>{for(let A=0;Aaa(L.message))}).catch(j=>aa(j.message))}).catch(x=>aa(x.message))},o.fa=2,o.fb=Vy,o.fc=wI,o.fd=DK,o.fe=tut,o.ff=sut,o.fg=Tct,o.fh=Xi,o.fi="hd_road_elevation",o.fj=Xc,o.fk=Vs,o.fl=Uie,o.fm=u3,o.fn=GRe,o.fo=1,o.fp=pk,o.fq=function(k,x,j,A,L,O,$,Y=1,X,le,xe,je){k.createArrays(),k.tilePixelRatio=fr/(512*k.overscaling),k.compareText={},k.iconsNeedLinear=!1;const Ce=k.layers[0].layout,Ie=k.layers[0]._unevaluatedLayout._values,Fe={};Fe.scaleFactor=Y,Fe.textSizeScaleRange=Ce.get("text-size-scale-range"),Fe.iconSizeScaleRange=Ce.get("icon-size-scale-range");const[Ke,et]=Fe.textSizeScaleRange,[at,vt]=Fe.iconSizeScaleRange;Fe.textScaleFactor=gt(Fe.scaleFactor,Ke,et),Fe.iconScaleFactor=gt(Fe.scaleFactor,at,vt);const pt=Ie["text-size"],At=Ie["icon-size"];if(k.textSizeData.kind==="composite"){const{minZoom:ys,maxZoom:vs}=k.textSizeData;Fe.compositeTextSizes=[pt.possiblyEvaluate(new Vi(ys,{worldview:xe}),O),pt.possiblyEvaluate(new Vi(vs,{worldview:xe}),O)]}if(k.iconSizeData.kind==="composite"){const{minZoom:ys,maxZoom:vs}=k.iconSizeData;Fe.compositeIconSizes=[At.possiblyEvaluate(new Vi(ys,{worldview:xe}),O,je),At.possiblyEvaluate(new Vi(vs,{worldview:xe}),O,je)]}Fe.layoutTextSize=pt.possiblyEvaluate(new Vi($+1,{worldview:xe}),O),Fe.layoutIconSize=At.possiblyEvaluate(new Vi($+1,{worldview:xe}),O,je),Fe.textMaxSize=pt.possiblyEvaluate(new Vi(18,{worldview:xe}),O);const Rt=Ce.get("symbol-placement"),Bt=Ce.get("text-rotation-alignment")==="map"&&Rt!=="point",Ns=Ce.get("text-size");let us=!1;const ws=[];for(const ys of k.features){const vs=Ce.get("text-font").evaluate(ys,{},O).join(","),vn=Ns.evaluate(ys,{},O)*Fe.textScaleFactor,Nn=Fe.layoutTextSize.evaluate(ys,{},O)*Fe.textScaleFactor,Rn=Fe.layoutIconSize.evaluate(ys,{},O,je)*Fe.iconScaleFactor,$n={horizontal:{},vertical:void 0},Fn=ys.text;let sr,gn=[0,0];if(Fn){const lo=Fn.toString(),Lu=Ce.get("text-letter-spacing").evaluate(ys,{},O)*Vp,Dl=Ce.get("text-line-height").evaluate(ys,{},O)*Vp,hl=QC(lo)?Lu:0,qc=Ce.get("text-anchor").evaluate(ys,{},O),ku=Ce.get("text-variable-anchor");if(!ku){const eh=Ce.get("text-radial-offset").evaluate(ys,{},O);if(eh)gn=fdt(qc,[eh*Vp,ZRe]);else{const Zx=Ce.get("text-offset").evaluate(ys,{},O);gn=[Zx[0]*Vp,Zx[1]*Vp]}}let Hp=Bt?"center":Ce.get("text-justify").evaluate(ys,{},O);const Su=Rt==="point",Ju=Su?Ce.get("text-max-width").evaluate(ys,{},O)*Vp:1/0,sm=eh=>{k.allowVerticalPlacement&&hx(lo)&&($n.vertical=zRe(Fn,x,j,L,vs,Ju,Dl,qc,eh,hl,gn,V1.vertical,!0,Nn,vn,X,Fe.textScaleFactor))};if(!Bt&&ku){const eh=Hp==="auto"?ku.map(Gp=>XRe(Gp)):[Hp];let Zx=!1;for(let Gp=0;Gp=0||!hx(lo)){const eh=zRe(Fn,x,j,L,vs,Ju,Dl,qc,Hp,hl,gn,V1.horizontal,!1,Nn,vn,X,Fe.textScaleFactor);eh&&($n.horizontal[Hp]=eh)}sm(Su?"left":Hp)}}let Bn,Vn,nr,yr,ra,Er,Cr=!1;const vr=Ce.get("icon-text-fit").evaluate(ys,{},O);if(ys.icon&&ys.icon.hasPrimary()){const lo=hY(ys.icon,k.iconSizeData,Ie["icon-size"],O,k.zoom,ys,X,Fe.iconScaleFactor,xe,je);Bn=lo.iconPrimary,nr=lo.iconSecondary;const Lu=Bn.toString();if(Vn=A.get(Lu),Vn&&(ra=Ce.get("icon-offset").evaluate(ys,{},O),Er=Ce.get("icon-anchor").evaluate(ys,{},O),sr=doe(L.get(Lu),nr?L.get(nr.toString()):void 0,ra,Er),Cr=Vn.sdf,k.sdfIcons===void 0?k.sdfIcons=Vn.sdf:k.sdfIcons!==Vn.sdf&&aa("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Vn.pixelRatio!==k.pixelRatio||Ce.get("icon-rotate").constantOr(1)!==0)&&(k.iconsNeedLinear=!0)),nr){const Dl=nr.toString();yr=A.get(Dl)}}us=us||!(!ys.icon||!ys.icon.hasSecondary());const ta=goe($n.horizontal)||$n.vertical;k.iconsInText||(k.iconsInText=!!ta&&ta.iconsInText);const fa=Nn*Fe.textScaleFactor/Vp,{defaultShapedIcon:ei,verticallyShapedIcon:Aa}=Kus(k,sr,Ce,ys,O,$n,fa,ra,vr);vr!=="none"&&sr&&(Xct(sr)||Qct(sr))&&(xoe(0,Vn,Bn,sr,ei,vr,le,A,L),xoe(0,yr,nr,sr,ei,vr,le,A,L),Aa&&(xoe(0,Vn,Bn,sr,Aa,vr,le,A,L),xoe(0,yr,nr,sr,Aa,vr,le,A,L))),sr=ei;const{iconBBox:zi,iconVerticalBBox:Xo,textBBox:Bi,textVerticalBBox:sl}=qus(k,sr,Aa,Ce,ys,O,Rn,ra,Fe,L,Er,$n,Nn,gn,je);ws.push({feature:ys,shapedTextOrientations:$n,shapedText:ta,shapedIcon:sr,iconPrimary:Bn,iconSecondary:nr,iconOffset:ra,iconAnchor:Er,verticallyShapedIcon:Aa,layoutTextSize:Nn,layoutIconSize:Rn,textOffset:gn,isSDFIcon:Cr,iconTextFit:vr,iconCollisionBounds:zi,iconVerticalCollisionBounds:Xo,textCollisionBounds:Bi,textVerticalCollisionBounds:sl})}return{featureData:ws,sizes:Fe,hasAnySecondaryIcon:us,textAlongLine:Bt,symbolPlacement:Rt}},o.fr=WRe,o.fs=HRe,o.ft=odt,o.fu=ldt,o.fv=function(k,x,j,A,L,O,$,Y,X,le){k.iconAtlasPositions=le.iconPositions;const{featureData:xe,hasAnySecondaryIcon:je,sizes:Ce,textAlongLine:Ie,symbolPlacement:Fe}=x;for(const Ke of xe){const{shapedIcon:et,verticallyShapedIcon:at,feature:vt,shapedTextOrientations:pt,shapedText:At,layoutTextSize:Rt,textOffset:Bt,isSDFIcon:Ns,iconPrimary:us,iconSecondary:ws,iconTextFit:ys,iconOffset:vs,iconCollisionBounds:vn,iconVerticalCollisionBounds:Nn,textCollisionBounds:Rn}=Ke;vdt(et,le.iconPositions,us,ws),vdt(at,le.iconPositions,us,ws),Wus(pt,le.iconPositions),Gus(us,ws,le.iconPositions),(At||et)&&Yus(k,vt,pt,et,at,X,Ce,Rt,0,Bt,Ns,A,L,$,Y,je,ys,vs,Ie,Fe,vn,Nn,Rn)}j&&k.generateCollisionDebugBuffers(O,k.collisionBoxArray,Ce.textScaleFactor)},o.fw=ooe,o.fx=bl,o.fy=function(k){return k<=1?1:Math.pow(2,Math.floor(Math.log2(k)))},o.fz=Loe,o.g=qa,o.h=function(k,x){return vm(Object.assign(k,{method:"GET"}),x)},o.i=function(k){return qa.API_STYLE_REGEX.test(k)&&!tl(k)},o.j=function(k){return btoa(encodeURIComponent(k).replace(/%([0-9A-F]{2})/g,(x,j)=>String.fromCharCode(+("0x"+j))))},o.k=$x,o.l=function(k){return decodeURIComponent(atob(k).split("").map(x=>"%"+("00"+x.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(k,x){return vm(Object.assign(k,{type:"json"}),x)},o.n=fd,o.o=wu,o.p=function(k,x){return vm(Object.assign(k,{method:"POST"}),x)},o.q=Cg,o.r=ks,o.s=function(k){try{const x=self[k];return x.setItem("_mapbox_test_",1),x.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Mt,o.u=function(){return function k(x){return x?(x^Math.random()*(16>>x/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,k)}()},o.v=function(k){return!!k&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(k)},o.w=aa,o.x=class{constructor(k){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(k&&k.maxTextureMemoryMB?k.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(x=>{this.cache.delete(x),this.clearExpiredTextures()})}calculateTextureMemory(k){return k.image?Math.ceil(k.image.width*k.image.height*4*(k.patternPositions.size>0?1.33:1)):0}evictTexture(k){const x=this.textures.get(k);if(x){const j=this.calculateTextureMemory(k);x.destroy(),this.textures.delete(k),this.textureAccessTimes.delete(k),this.textureMemoryUsed-=j}}evictTexturesIfNeeded(k){for(;this.textureMemoryUsed+k>this.maxTextureMemory&&this.textures.size>0;){let x=null,j=1/0;for(const[A]of this.textures.entries()){const L=this.textureAccessTimes.get(A)||0;Lthis._layers[Zn.id]),ks=Qt[0];if(ks.visibility==="none")continue;const gs=ks.source||"";let Vt=this.familiesBySource[gs];Vt||(Vt=this.familiesBySource[gs]=Object.create(null));const Vs=ks.sourceLayer||"_geojsonTileLayer";let Zs=Vt[Vs];Zs||(Zs=Vt[Vs]=[]),Zs.push(Qt)}}}const f=1*c.fa;class g{constructor(it){const gt={},ft=[];for(const ks in it){const gs=it[ks],Vt=gt[ks]={};for(const Vs in gs.glyphs){const Zs=gs.glyphs[+Vs];if(!Zs||Zs.bitmap.width===0||Zs.bitmap.height===0)continue;const Zn=Zs.metrics.localGlyph?f:1,Or={x:0,y:0,w:Zs.bitmap.width+2*Zn,h:Zs.bitmap.height+2*Zn};ft.push(Or),Vt[Vs]=Or}}const{w:Lt,h:Mt}=c.J(ft),Qt=new c.f9({width:Lt||1,height:Mt||1});for(const ks in it){const gs=it[ks];for(const Vt in gs.glyphs){const Vs=gs.glyphs[+Vt];if(!Vs||Vs.bitmap.width===0||Vs.bitmap.height===0)continue;const Zs=gt[ks][Vt],Zn=Vs.metrics.localGlyph?f:1;c.f9.copy(Vs.bitmap,Qt,{x:0,y:0},{x:Zs.x+Zn,y:Zs.y+Zn},Vs.bitmap)}}this.image=Qt,this.positions=gt}}function v(Yt,it,gt){Yt[it]?gt&&(Yt[it].center=gt):Yt[it]={floorIds:new Set,center:gt||[0,0],floors:{}}}function y(Yt,it,gt,ft){for(const Lt of it)v(Yt,Lt),Yt[Lt].floors[gt]=ft,Yt[Lt].floorIds.add(gt)}function b(Yt){return{id:Yt.properties.id.toString(),center:[Yt.properties.center_lon||0,Yt.properties.center_lat||0]}}function w(Yt,it){const gt=Yt.properties.id.toString(),ft=!!Yt.properties.is_default&&Yt.properties.is_default,Lt=Yt.properties.connected_floor_ids?new Set(Yt.properties.connected_floor_ids.toString().split(";")):new Set,Mt=Yt.properties.conflicted_floor_ids?new Set(Yt.properties.conflicted_floor_ids.toString().split(";")):new Set,Qt=Yt.properties.structure_ids?new Set(Yt.properties.structure_ids.toString().split(";")):new Set,ks=Yt.properties.name.toString(),gs=Yt.properties.z_index,Vt=function(Vs,Zs){const Zn=Vs.loadGeometry();if(!Zn||Zn.length===0)return;const Or=Zn.map(oa=>oa.map(aa=>c.fb(aa,Zs,Vs.extent)));return Or.length===0?void 0:{type:"Polygon",coordinates:[Or[0]]}}(Yt,it);return{id:gt,isDefault:ft,connections:Lt,conflicts:Mt,buildings:Qt,name:ks,zIndex:gs,geometry:Vt}}function S(Yt,it){return it.every(gt=>Yt.properties&&Yt.properties[gt]!=null)}function C(Yt){return S(Yt,["type","id","name"])&&Yt.properties.type==="structure"}function E(Yt){return S(Yt,["type","id","name","z_index"])&&Yt.properties.type==="floor"}c.f8(g,"GlyphAtlas");class P{constructor(it){this.tileID=new c.aR(it.tileID.overscaledZ,it.tileID.wrap,it.tileID.canonical.z,it.tileID.canonical.x,it.tileID.canonical.y),this.tileZoom=it.tileZoom,this.uid=it.uid,this.zoom=it.zoom,this.lut=it.lut,this.canonical=it.tileID.canonical,this.pixelRatio=it.pixelRatio,this.tileSize=it.tileSize,this.source=it.source,this.scope=it.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=it.showCollisionBoxes,this.collectResourceTiming=!!it.request&&it.request.collectResourceTiming,this.promoteId=it.promoteId,this.renderSourceType=it.renderSourceType,this.tileTransform=c.fc(it.tileID.canonical,it.projection),this.projection=it.projection,this.worldview=it.worldview,this.localizableLayerIds=it.localizableLayerIds,this.brightness=it.brightness,this.extraShadowCaster=!!it.extraShadowCaster,this.tessellationStep=it.tessellationStep,this.scaleFactor=it.scaleFactor,this.worldview=it.worldview,this.indoor=it.indoor}parse(it,gt,ft,Lt,Mt,Qt){this.status="parsing",this.data=it,this.collisionBoxArray=new c.fd;const ks=new c.fe(Object.keys(it.layers).sort()),gs=new c.ff(this.tileID,this.promoteId);gs.bucketLayerIDs=[];const Vt={},Vs=new c.fg(256,256),Zs={featureIndex:gs,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Vs,availableImages:ft,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Zs.activeFloors=function(aa,Kr,Tr,Hr){const Ba=Kr.indoorState.activeFloorsVisible;if(!Kr.sourceLayers)return Ba?Kr.indoorState.activeFloors:void 0;const Ja=function(Oa,Ao){if(!Oa)return c.w("No source layers defined in indoor specification"),Ao;if(Oa.size===0)return Ao;const uo=Oa.difference(Ao);for(const Ua of uo)c.w(`Missing source layer required in indoor specification: ${Ua}`);return Ao.intersection(Ao)}(Kr.sourceLayers,new Set(Object.keys(aa.layers))),Ro=Kr.indoorState,ji=function(Oa,Ao,uo,Ua,Eo){const Ji={};for(const qa of Ao){const ar=Oa.layers[qa];if(ar)for(let ui=0;ui=Ua.maxzoom||Ua.visibility==="none")continue;M(uo,this.zoom,Zs.brightness,ft,this.worldview,Zs.activeFloors);const Eo=Vt[Ua.id]=Ua.createBucket({index:gs.bucketLayerIDs.length,layers:uo,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Ro,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Lt,worldview:this.worldview,localizable:Oa,availableImages:ft,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});gs.bucketLayerIDs.push(uo.map(qa=>c.F(qa.id,qa.scope)));let Ji=Eo.prepare?Eo.prepare():null;Ji!=null?(Ji=Ji.then(()=>Eo.populate(ji,Zs,this.tileID.canonical,this.tileTransform)),Zn.push(Ji)):Eo.populate(ji,Zs,this.tileID.canonical,this.tileTransform)}}const oa=()=>{Vs.trim();const aa=!(!Zs.elevationFeatures||!Zs.elevationFeatures.some(Ua=>Ua.heightRange.min<0));let Kr,Tr,Hr,Ba,Ja,Ro,ji;const Oa={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Ao=()=>{if(Kr)return this.status="done",Qt(Kr);if(this.extraShadowCaster)this.status="done",Qt(null,{buckets:Object.values(Vt).filter(Ua=>!Ua.isEmpty()),featureIndex:gs,collisionBoxArray:null,hasTunnelGeometry:aa,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Zs.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Tr&&Hr&&Ba&&ji){const Eo=new g(Tr),Ji=new Map;for(const[ui,zo]of Hr.entries()){const{imagePosition:gl}=c.fn(ui,zo,c.fo);Ji.set(ui,gl)}const qa={};for(const ui in Vt){const zo=Vt[ui];zo instanceof c.fp&&(M(zo.layers,this.zoom,Zs.brightness,ft,this.worldview,Zs.activeFloors),qa[ui]=c.fq(zo,Tr,Eo.positions,Hr,Ji,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Ja,this.worldview,ft))}const ar={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Mt,Hr,Ja,()=>{ar.iconsPending=!1,uo(qa,Eo,ar,void 0,ji)}),this.rasterizeIfNeeded(Mt,Ba,Ro,()=>{ar.patternsPending=!1,uo(qa,Eo,ar,void 0,ji)})}},uo=(Ua,Eo,Ji,qa,ar)=>{if(Ji.iconsPending||Ji.patternsPending)return;const ui=Hr.size>0||Ba.size>0,zo=Object.keys(Ua).length>0;if(!ui&&!zo)return this.status="done",void Qt(null,{buckets:Object.values(Vt).filter(tl=>!tl.isEmpty()),featureIndex:gs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:aa,glyphAtlasImage:Eo.image,lineAtlas:Vs,imageAtlas:null,brightness:Zs.brightness});const gl=(tl,Ll)=>{for(const Ku in Vt){const uh=Vt[Ku];if(Ku in Ua)c.fv(uh,Ua[Ku],this.showCollisionBoxes,ft,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Hr,Ll);else if(uh.hasPattern&&(uh instanceof c.fw||uh instanceof c.fl||uh instanceof c.e0)){M(uh.layers,this.zoom,Zs.brightness,ft,this.worldview,Zs.activeFloors);const ym=Object.fromEntries(Ll.patternPositions);uh.addFeatures(Zs,this.tileID.canonical,ym,ft,this.tileTransform,this.brightness)}}this.status="done",Qt(null,{buckets:Object.values(Vt).filter(Ku=>!Ku.isEmpty()),featureIndex:gs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:aa,glyphAtlasImage:Eo.image,lineAtlas:Vs,imageAtlas:tl,brightness:Zs.brightness})};if(ui){const tl=new Map,Ll=c.fr(Hr,tl),Ku=c.fr(Ba,tl),uh=new c.fs(Ll,Ku,ar,this.lut,tl);Mt.send("checkAtlasCache",{descriptor:uh,scope:this.scope},(ym,Ld)=>{let Bm,Sl;if(ym&&c.w(`[Worker] Error checking atlas cache: ${ym.message}`),Ld)Bm=new c.ft(Ld.sourceHash),Sl=Ld;else{const wu=new c.fu(Hr,Ba,this.lut,ar);Bm=wu,Sl=wu}gl(Bm,Sl)})}else gl(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Ua=c.fk(Zs.glyphDependencies,qa=>Object.keys(qa).map(Number));Object.keys(Ua).length?Mt.send("getGlyphs",{uid:this.uid,stacks:Ua},(qa,ar)=>{Kr||(Kr=qa,Tr=ar,Ao())},void 0,!1,Oa):Tr={},ji=new Map;const Eo=Array.from(Zs.iconDependencies.keys()).map(qa=>c.I.parse(qa));Eo.length?Mt.send("getImages",{images:Eo,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(qa,ar)=>{if(!Kr){Kr=qa,Hr=new Map,Ja=this.updateImageMapAndGetImageTaskQueue(Hr,ar.images,Zs.iconDependencies);for(const[ui,zo]of ar.versions.entries())ji.set(ui,zo);Ao()}},void 0,!1,Oa):(Hr=new Map,Ja=new Map);const Ji=Array.from(Zs.patternDependencies.keys()).map(qa=>c.I.parse(qa));Ji.length?Mt.send("getImages",{images:Ji,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(qa,ar)=>{if(!Kr){Kr=qa,Ba=new Map,Ro=this.updateImageMapAndGetImageTaskQueue(Ba,ar.images,Zs.patternDependencies);for(const[ui,zo]of ar.versions.entries())ji.set(ui,zo);Ao()}},void 0,!1,Oa):(Ba=new Map,Ro=new Map)}if(Zs.elevationFeatures&&Zs.elevationFeatures.length>0){const Ua=[];for(const Ji of Object.values(Vt))if(Ji instanceof c.fl){const qa=Ji.getUnevaluatedPortalGraph();qa&&Ua.push(qa)}const Eo=c.fm.evaluate(Ua);for(const Ji of Object.values(Vt))if(Ji instanceof c.fl){const qa=it.layers[ks.decode(Ji.sourceLayerIndex)];Ji.setEvaluatedPortalGraph(Eo,qa,this.tileID.canonical,Zs.availableImages,Zs.brightness)}}Ao()};Zn.length>0?Promise.allSettled(Zn).then(oa).catch(Qt):oa()}updateParameters(it){this.scaleFactor=it.scaleFactor,this.showCollisionBoxes=it.showCollisionBoxes,this.projection=it.projection,this.brightness=it.brightness,this.tileTransform=c.fc(it.tileID.canonical,it.projection),this.extraShadowCaster=it.extraShadowCaster,this.lut=it.lut,this.worldview=it.worldview,this.indoor=it.indoor}rasterizeIfNeeded(it,gt,ft,Lt){Array.from(gt.values()).some(Mt=>Mt.usvg)?this.rasterize(it,gt,ft,Lt):Lt()}updateImageMapAndGetImageTaskQueue(it,gt,ft){const Lt=new Map;for(const Mt of gt.keys()){const Qt=ft.get(Mt)||[];for(const ks of Qt){const gs=ks.toString(),Vt=gt.get(ks.id.toString());Vt.usvg?Lt.has(gs)||(Lt.set(gs,ks),it.set(gs,Object.assign({},Vt))):it.set(gs,Vt)}}return Lt}rasterize(it,gt,ft,Lt){this.rasterizeTask=it.send("rasterizeImages",{scope:this.scope,tasks:ft},(Mt,Qt)=>{if(!Mt)for(const[ks,gs]of Qt.entries()){const Vt=Object.assign(gt.get(ks),{data:gs});gt.set(ks,Vt)}Lt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(Yt,it,gt,ft,Lt,Mt){const Qt=new c.ae(it,{brightness:gt,worldview:Lt,activeFloors:Mt});for(const ks of Yt)ks.recalculate(Qt,ft)}class I extends c.E{constructor({actor:it,layerIndex:gt,availableImages:ft,availableModels:Lt,isSpriteLoaded:Mt,tileProvider:Qt,brightness:ks,maxUniformBufferBindings:gs,maxUniformBlockSizeDwords:Vt,disableSymbolUBO:Vs}){super(),this.actor=it,this.layerIndex=gt,this.availableImages=ft,this.availableModels=Lt,this.loadVectorData=c.aO,this.tileProvider=Qt,this.loading={},this.loaded={},this.deduped=new c.aN(it.scheduler),this.isSpriteLoaded=Mt,this.scheduler=it.scheduler,this.brightness=ks,this.maxUniformBufferBindings=gs,this.maxUniformBlockSizeDwords=Vt,this.disableSymbolUBO=Vs}loadTileData(it,gt){if(!this.tileProvider)return this.loadVectorData(it,gt);const ft=new AbortController,{z:Lt,x:Mt,y:Qt}=it.tileID.canonical;return this.tileProvider.loadTile({z:Lt,x:Mt,y:Qt},{request:it.request,signal:ft.signal}).then(ks=>{if(ft.signal.aborted)return;if(ks==null){const Vt=new Error("Tile not found");return Vt.status=404,gt(Vt)}if(ks.data===null)return gt(null,null);const gs=new Map;ks.expires&&gs.set("expires",ks.expires),ks.cacheControl&&gs.set("cache-control",ks.cacheControl),gt(null,{rawData:ks.data,responseHeaders:gs})}).catch(ks=>{ft.signal.aborted||gt(ks instanceof Error?ks:new Error(String(ks)))}),()=>ft.abort()}loadTile(it,gt){const ft=it.uid,Lt=it&&it.request,Mt=Lt&&Lt.collectResourceTiming,Qt=this.loading[ft]=new P(it);Qt.maxUniformBufferBindings=this.maxUniformBufferBindings,Qt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,Qt.disableSymbolUBO=this.disableSymbolUBO,Qt.abort=this.loadTileData(it,(ks,gs)=>{const Vt=!this.loading[ft];if(delete this.loading[ft],Qt.cancelRasterize(),Vt||ks||!gs)return Qt.status="done",Vt||(this.loaded[ft]=Qt),gt(ks);const Vs=gs.rawData,Zs={},Zn=c.aP(gs.responseHeaders);Zn&&Zn.expires&&(Zs.expires=Zn.expires),Zn&&Zn.cacheControl&&(Zs.cacheControl=Zn.cacheControl),Qt.vectorTile=gs.vectorTile||new c.fx(new c.a$(Vs));const Or=()=>{Qt.parse(Qt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(oa,aa)=>{if(oa||!aa)return gt(oa);const Kr={};if(Mt){const Tr=d(Lt);Tr.length>0&&(Kr.resourceTiming=JSON.parse(JSON.stringify(Tr)))}gt(null,Object.assign({rawTileData:Vs.slice(0),responseHeaders:gs.responseHeaders},aa,Zs,Kr))})};this.isSpriteLoaded?Or():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Or,{type:"parseTile",renderSourceType:it.renderSourceType,zoom:it.tileZoom}):Or()}),this.loaded=this.loaded||{},this.loaded[ft]=Qt})}reloadTile(it,gt){const ft=this.loaded,Lt=it.uid;if(ft&&ft[Lt]){const Mt=ft[Lt];Mt.updateParameters(it);const Qt=(ks,gs)=>{const Vt=Mt.reloadCallback;Vt&&(delete Mt.reloadCallback,Mt.parse(Mt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Vt)),gt(ks,gs)};Mt.status==="parsing"?Mt.reloadCallback=Qt:Mt.status==="done"&&(Mt.vectorTile?Mt.parse(Mt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Qt):Qt())}else gt(null,void 0)}abortTile(it,gt){const ft=it.uid,Lt=this.loading[ft];Lt&&(Lt.abort&&Lt.abort(),delete this.loading[ft]),gt()}removeTile(it,gt){const ft=this.loaded,Lt=it.uid;ft&&ft[Lt]&&delete ft[Lt],gt()}}class D{constructor(it){this.loading={}}loadTile(it,gt){const ft=it.uid,{cancel:Lt}=c.b1(it.request,(Mt,Qt,ks)=>{const gs=!this.loading[ft];if(delete this.loading[ft],gs||Mt||!Qt)return gt(Mt);this.decodeTile(ft,Qt,it.encoding).then(Vt=>{const{expires:Vs,cacheControl:Zs}=c.aP(ks);gt(null,Object.assign(Vt,{expires:Vs,cacheControl:Zs}))}).catch(Vt=>gt(Vt))});this.loading[ft]={cancel:Lt}}async decodeTile(it,gt,ft){const Lt=await createImageBitmap(new Blob([new Uint8Array(gt)],{type:"image/png"})),Mt=1-(Lt.width-c.fy(Lt.width))/2,Qt=Mt<1,ks=this.getImageData(Lt,Mt);return Lt.close(),{dem:new c.fz(it,ks,ft,Qt),borderReady:Qt}}reloadTile(it,gt){gt(null,null)}abortTile(it,gt){const ft=it.uid,Lt=this.loading[ft];Lt&&(Lt.cancel(),delete this.loading[ft]),gt()}removeTile(it,gt){gt()}getImageData(it,gt){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(it.width,it.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=it.width,this.offscreenCanvas.height=it.height,this.offscreenCanvasContext.drawImage(it,0,0,it.width,it.height);const ft=this.offscreenCanvasContext.getImageData(-gt,-gt,it.width+2*gt,it.height+2*gt);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),ft}}c.a_.setPbf(c.a$);class F{constructor(it){this._mrt=new c.a_(it.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=it.uid,this.tileID=it.tileID,this.source=it.source}parse(it,gt){const ft=this._mrt;this.status="parsing",this._entireBuffer=it;try{ft.parseHeader(it),this._isHeaderLoaded=!0;const Lt=[];for(const Mt in ft.layers){const Qt=ft.getLayer(Mt),ks=Qt.getDataRange(Qt.getBandList()),gs=ft.createDecodingTask(ks),Vt=it.slice(ks.firstByte,ks.lastByte+1),Vs=c.a_.performDecoding(Vt,gs).then(Zs=>gs.complete(null,Zs)).catch(Zs=>gs.complete(Zs,null));Lt.push(Vs)}Promise.allSettled(Lt).then(()=>gt(null,ft)).catch(Mt=>gt(Mt))}catch(Lt){gt(Lt)}}}class q{constructor({actor:it}){this.actor=it,this.loading={},this.loaded={}}loadTile(it,gt){const ft=it.uid,Lt=it.request,Mt=this.loading[ft]=new F(it),{cancel:Qt}=c.b1(Lt,(ks,gs,Vt)=>{const Vs=!this.loading[ft];if(delete this.loading[ft],Vs||ks||!gs)return Mt.status="done",Vs||(this.loaded[ft]=Mt),gt(ks);Mt.parse(gs,(Zs,Zn)=>{if(Zs||!Zn)return gt(Zs);gt(null,Zn,Vt)}),this.loaded[ft]=Mt});Mt.abort=Qt}reloadTile(it,gt){gt(null,void 0)}abortTile(it,gt){const ft=it.uid,Lt=this.loading[ft];Lt&&(Lt.abort&&Lt.abort(),delete this.loading[ft]),gt()}removeTile(it,gt){const ft=it.uid;this.loaded[ft]&&delete this.loaded[ft],gt()}decodeRasterArray(it,gt){c.a_.performDecoding(it.buffer,it.task).then(ft=>gt(null,ft)).catch(ft=>gt(ft))}}const G=c.fA.prototype.toGeoJSON;class V{constructor(it){this._feature=it,this.extent=c.an,this.type=it.type,this.properties=it.tags,"id"in it&&!isNaN(it.id)&&(this.id=parseInt(it.id,10))}loadGeometry(){if(this._feature.type===1){const it=[];for(const gt of this._feature.geometry)it.push([new c.P(gt[0],gt[1])]);return it}{const it=[];for(const gt of this._feature.geometry){const ft=[];for(const Lt of gt)ft.push(new c.P(Lt[0],Lt[1]));it.push(ft)}return it}}toGeoJSON(it,gt,ft){return G.call(this,it,gt,ft)}}class H{constructor(it,gt){this.name=it,this.extent=c.an,this.length=gt.length,this._jsonFeatures=gt}feature(it){return new V(this._jsonFeatures[it])}}class K{constructor(it){this.layers={},this.extent=c.an;for(const gt of Object.keys(it))this.layers[gt]=new H(gt,it[gt])}}const Z=64/4096;class oe{constructor(){this.features=new Map}clear(){this.features.clear()}load(it=[],gt){for(const ft of it){const Lt=ft.id;if(Lt==null)continue;let Mt=this.features.get(Lt);Mt&&this.updateCache(Mt,gt),ft.geometry?(Mt=ae(ft),this.updateCache(Mt,gt),this.features.set(Lt,Mt)):this.features.delete(Lt),this.updateCache(Mt,gt)}}updateCache(it,gt){for(const{canonical:ft,uid:Lt}of Object.values(gt)){const{z:Mt,x:Qt,y:ks}=ft;re(it,Math.pow(2,Mt),Qt,ks)&&delete gt[Lt]}}getTile(it,gt,ft){const Lt=Math.pow(2,it),Mt=[];for(const Qt of this.features.values())re(Qt,Lt,gt,ft)&&Mt.push(ve(Qt,Lt,gt,ft));return{features:Mt}}getFeatures(){return[...this.features.values()]}}function re({minX:Yt,minY:it,maxX:gt,maxY:ft},Lt,Mt,Qt){return Yt<(Mt+1+Z)/Lt&&it<(Qt+1+Z)/Lt&>>(Mt-Z)/Lt&&ft>(Qt-Z)/Lt}function ae(Yt){const{id:it,geometry:gt,properties:ft}=Yt;if(!gt)return;if(gt.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Lt,coordinates:Mt}=gt,Qt={id:it,type:1,geometry:[],tags:ft,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},ks=Qt.geometry;if(Lt==="Point")J(Mt,ks,Qt);else if(Lt==="MultiPoint")for(const gs of Mt)J(gs,ks,Qt);else if(Lt==="LineString")Qt.type=2,te(Mt,ks,Qt);else if(Lt==="MultiLineString")Qt.type=2,ce(Mt,ks,Qt);else if(Lt==="Polygon")Qt.type=3,ce(Mt,ks,Qt,!0);else{if(Lt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Qt.type=3;for(const gs of Mt)ce(gs,ks,Qt,!0)}return Qt}function J([Yt,it],gt,ft){const Lt=c.aH(Yt);let Mt=c.aL(it);Mt=Mt<0?0:Mt>1?1:Mt,gt.push(Lt,Mt),ft.minX=Math.min(ft.minX,Lt),ft.minY=Math.min(ft.minY,Mt),ft.maxX=Math.max(ft.maxX,Lt),ft.maxY=Math.max(ft.maxY,Mt)}function te(Yt,it,gt,ft=!1,Lt=!1){const Mt=[];for(const Qt of Yt)J(Qt,Mt,gt);it.push(Mt),ft&&function(Qt,ks){let gs=0;for(let Vt=0,Vs=Qt.length,Zs=Vs-2;Vt0===ks)for(let Vt=0,Vs=Qt.length;Vt=Qt&&Zs>=Qt||(Vt>=Qt?(Vs+=Math.round(oa*((Qt-Vt)/Or)),Vt=Qt):Zs>=Qt&&(Zn=Vs+Math.round(oa*((Qt-Vt)/Or)),Zs=Qt),Vs>=Qt&&Zn>=Qt||(Vs>=Qt?(Vt+=Math.round(Or*((Qt-Vs)/oa)),Vs=Qt):Zn>=Qt&&(Zs=Vt+Math.round(Or*((Qt-Vs)/oa)),Zn=Qt),ks&&Vt===ks[ks.length-1][0]&&Vs===ks[ks.length-1][1]||(ks=[[Vt,Vs]],Lt.push(ks)),ks.push([Zs,Zn])))))}}function he(Yt,it,gt,ft,Lt){const Mt=(gt-Z)/it,Qt=(ft-Z)/it,ks=(gt+1+Z)/it,gs=(ft+1+Z)/it;function Vt(Zn,Or){let oa=0;return Znks&&(oa|=2),Orgs&&(oa|=8),oa}let Vs=[];for(let Zn=1;Zn<=8;Zn*=2){let Or=Yt[Yt.length-2],oa=Yt[Yt.length-1],aa=!(Vt(Or,oa)&Zn);for(let Kr=0;Kr>31}function ke(Yt,it){const{geometry:gt,type:ft}=Yt;let Lt=0,Mt=0;if(ft===1){it.writeVarint(Pe(1,gt.length));for(const Qt of gt){const ks=Qt[0]-Lt,gs=Qt[1]-Mt;it.writeVarint(Oe(ks)),it.writeVarint(Oe(gs)),Lt+=ks,Mt+=gs}}else for(const Qt of gt){if(Qt.length===0)continue;it.writeVarint(Pe(1,1));const ks=Qt.length-(ft===3?1:0);for(let gs=0;gsYt},Ae=Math.fround||(Se=new Float32Array(1),Yt=>(Se[0]=+Yt,Se[0]));var Se;class We{constructor(it){this.options=Object.assign(Object.create(_e),it),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(it){const{log:gt,minZoom:ft,maxZoom:Lt}=this.options;gt&&console.time("total time");const Mt=`prepare ${it.length} points`;gt&&console.time(Mt),this.points=it;const Qt=[];for(let gs=0;gs=ft;gs--){const Vt=+Date.now();ks=this.trees[gs]=this._createTree(this._cluster(ks,gs)),gt&&console.log("z%d: %d clusters in %dms",gs,ks.numItems,+Date.now()-Vt)}return gt&&console.timeEnd("total time"),this}getClusters(it,gt){let ft=((it[0]+180)%360+360)%360-180;const Lt=Math.max(-90,Math.min(90,it[1]));let Mt=it[2]===180?180:((it[2]+180)%360+360)%360-180;const Qt=Math.max(-90,Math.min(90,it[3]));if(it[2]-it[0]>=360)ft=-180,Mt=180;else if(ft>Mt){const Zs=this.getClusters([ft,Lt,180,Qt],gt),Zn=this.getClusters([-180,Lt,Mt,Qt],gt);return Zs.concat(Zn)}const ks=this.trees[this._limitZoom(gt)],gs=ks.range(Ze(ft),$e(Qt),Ze(Mt),$e(Lt)),Vt=ks.data,Vs=[];for(const Zs of gs){const Zn=this.stride*Zs;Vs.push(Vt[Zn+5]>1?qe(Vt,Zn,this.clusterProps):this.points[Vt[Zn+3]])}return Vs}getChildren(it){const gt=this._getOriginId(it),ft=this._getOriginZoom(it),Lt="No cluster with the specified id.",Mt=this.trees[ft];if(!Mt)throw new Error(Lt);const Qt=Mt.data;if(gt*this.stride>=Qt.length)throw new Error(Lt);const ks=this.options.radius/(this.options.extent*Math.pow(2,ft-1)),gs=Mt.within(Qt[gt*this.stride],Qt[gt*this.stride+1],ks),Vt=[];for(const Vs of gs){const Zs=Vs*this.stride;Qt[Zs+4]===it&&Vt.push(Qt[Zs+5]>1?qe(Qt,Zs,this.clusterProps):this.points[Qt[Zs+3]])}if(Vt.length===0)throw new Error(Lt);return Vt}getLeaves(it,gt,ft){const Lt=[];return this._appendLeaves(Lt,it,gt=gt||10,ft=ft||0,0),Lt}getTile(it,gt,ft){const Lt=this.trees[this._limitZoom(it)],Mt=Math.pow(2,it),{extent:Qt,radius:ks}=this.options,gs=ks/Qt,Vt=(ft-gs)/Mt,Vs=(ft+1+gs)/Mt,Zs={features:[]};return this._addTileFeatures(Lt.range((gt-gs)/Mt,Vt,(gt+1+gs)/Mt,Vs),Lt.data,gt,ft,Mt,Zs),gt===0&&this._addTileFeatures(Lt.range(1-gs/Mt,Vt,1,Vs),Lt.data,Mt,ft,Mt,Zs),gt===Mt-1&&this._addTileFeatures(Lt.range(0,Vt,gs/Mt,Vs),Lt.data,-1,ft,Mt,Zs),Zs.features.length?Zs:null}getClusterExpansionZoom(it){let gt=this._getOriginZoom(it)-1;for(;gt<=this.options.maxZoom;){const ft=this.getChildren(it);if(gt++,ft.length!==1)break;it=ft[0].properties.cluster_id}return gt}_appendLeaves(it,gt,ft,Lt,Mt){const Qt=this.getChildren(gt);for(const ks of Qt){const gs=ks.properties;if(gs&&gs.cluster?Mt+gs.point_count<=Lt?Mt+=gs.point_count:Mt=this._appendLeaves(it,gs.cluster_id,ft,Lt,Mt):Mt1;let Vs,Zs,Zn;if(Vt)Vs=Be(gt,gs,this.clusterProps),Zs=gt[gs],Zn=gt[gs+1];else{const aa=this.points[gt[gs+3]];Vs=aa.properties;const[Kr,Tr]=aa.geometry.coordinates;Zs=Ze(Kr),Zn=$e(Tr)}const Or={type:1,geometry:[[Math.round(this.options.extent*(Zs*Mt-ft)),Math.round(this.options.extent*(Zn*Mt-Lt))]],tags:Vs};let oa;oa=Vt||this.options.generateId?gt[gs+3]:this.points[gt[gs+3]].id,oa!==void 0&&(Or.id=oa),Qt.features.push(Or)}}_limitZoom(it){return Math.max(this.options.minZoom,Math.min(Math.floor(+it),this.options.maxZoom+1))}_cluster(it,gt){const{radius:ft,extent:Lt,reduce:Mt,minPoints:Qt}=this.options,ks=ft/(Lt*Math.pow(2,gt)),gs=it.data,Vt=[],Vs=this.stride;for(let Zs=0;Zsgt&&(Kr+=gs[Hr+5])}if(Kr>aa&&Kr>=Qt){let Tr,Hr=Zn*aa,Ba=Or*aa,Ja=-1;const Ro=(Zs/Vs<<5)+(gt+1)+this.points.length;for(const ji of oa){const Oa=ji*Vs;if(gs[Oa+2]<=gt)continue;gs[Oa+2]=gt;const Ao=gs[Oa+5];Hr+=gs[Oa]*Ao,Ba+=gs[Oa+1]*Ao,gs[Oa+4]=Ro,Mt&&(Tr||(Tr=this._map(gs,Zs,!0),Ja=this.clusterProps.length,this.clusterProps.push(Tr)),Mt(Tr,this._map(gs,Oa)))}gs[Zs+4]=Ro,Vt.push(Hr/Kr,Ba/Kr,1/0,Ro,-1,Kr),Mt&&Vt.push(Ja)}else{for(let Tr=0;Tr1)for(const Tr of oa){const Hr=Tr*Vs;if(!(gs[Hr+2]<=gt)){gs[Hr+2]=gt;for(let Ba=0;Ba>5}_getOriginZoom(it){return(it-this.points.length)%32}_map(it,gt,ft){if(it[gt+5]>1){const Qt=this.clusterProps[it[gt+6]];return ft?Object.assign({},Qt):Qt}const Lt=this.points[it[gt+3]].properties,Mt=this.options.map(Lt);return ft&&Mt===Lt?Object.assign({},Mt):Mt}}function qe(Yt,it,gt){return{type:"Feature",id:Yt[it+3],properties:Be(Yt,it,gt),geometry:{type:"Point",coordinates:[(ft=Yt[it],360*(ft-.5)),Xe(Yt[it+1])]}};var ft}function Be(Yt,it,gt){const ft=Yt[it+5],Lt=ft>=1e4?`${Math.round(ft/1e3)}k`:ft>=1e3?Math.round(ft/100)/10+"k":ft,Mt=Yt[it+6],Qt=Mt===-1?{}:Object.assign({},gt[Mt]);return Object.assign(Qt,{cluster:!0,cluster_id:Yt[it+3],point_count:ft,point_count_abbreviated:Lt})}function Ze(Yt){return Yt/360+.5}function $e(Yt){const it=Math.sin(Yt*Math.PI/180),gt=.5-.25*Math.log((1+it)/(1-it))/Math.PI;return gt<0?0:gt>1?1:gt}function Xe(Yt){const it=(180-360*Yt)*Math.PI/180;return 360*Math.atan(Math.exp(it))/Math.PI-90}function nt(Yt,it,gt,ft){let Lt=ft;const Mt=it+(gt-it>>1);let Qt,ks=gt-it;const gs=Yt[it],Vt=Yt[it+1],Vs=Yt[gt],Zs=Yt[gt+1];for(let Zn=it+3;ZnLt)Qt=Zn,Lt=Or;else if(Or===Lt){const oa=Math.abs(Zn-Mt);oaft&&(Qt-it>3&&nt(Yt,it,Qt,ft),Yt[Qt+2]=Lt,gt-Qt>3&&nt(Yt,Qt,gt,ft))}function Ge(Yt,it,gt,ft,Lt,Mt){let Qt=Lt-gt,ks=Mt-ft;if(Qt!==0||ks!==0){const gs=((Yt-gt)*Qt+(it-ft)*ks)/(Qt*Qt+ks*ks);gs>1?(gt=Lt,ft=Mt):gs>0&&(gt+=Qt*gs,ft+=ks*gs)}return Qt=Yt-gt,ks=it-ft,Qt*Qt+ks*ks}function Je(Yt,it,gt,ft){const Lt={id:Yt??null,type:it,geometry:gt,tags:ft,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(it==="Point"||it==="MultiPoint"||it==="LineString")ut(Lt,gt);else if(it==="Polygon")ut(Lt,gt[0]);else if(it==="MultiLineString")for(const Mt of gt)ut(Lt,Mt);else if(it==="MultiPolygon")for(const Mt of gt)ut(Lt,Mt[0]);return Lt}function ut(Yt,it){for(let gt=0;gt0&&(Qt+=ft?(Lt*Vs-Vt*Mt)/2:Math.sqrt(Math.pow(Vt-Lt,2)+Math.pow(Vs-Mt,2))),Lt=Vt,Mt=Vs}const ks=it.length-3;it[2]=1,nt(it,0,ks,gt),it[ks+2]=1,it.size=Math.abs(Qt),it.start=0,it.end=it.size}function Zt(Yt,it,gt,ft){for(let Lt=0;Lt1?1:gt}function It(Yt,it,gt,ft,Lt,Mt,Qt,ks){if(ft/=it,Mt>=(gt/=it)&&Qt=ft)return null;const gs=[];for(const Vt of Yt){const Vs=Vt.geometry;let Zs=Vt.type;const Zn=Lt===0?Vt.minX:Vt.minY,Or=Lt===0?Vt.maxX:Vt.maxY;if(Zn>=gt&&Or=ft)continue;let oa=[];if(Zs==="Point"||Zs==="MultiPoint")qs(Vs,oa,gt,ft,Lt);else if(Zs==="LineString")wt(Vs,oa,gt,ft,Lt,!1,ks.lineMetrics);else if(Zs==="MultiLineString")Es(Vs,oa,gt,ft,Lt,!1);else if(Zs==="Polygon")Es(Vs,oa,gt,ft,Lt,!0);else if(Zs==="MultiPolygon")for(const aa of Vs){const Kr=[];Es(aa,Kr,gt,ft,Lt,!0),Kr.length&&oa.push(Kr)}if(oa.length){if(ks.lineMetrics&&Zs==="LineString"){for(const aa of oa)gs.push(Je(Vt.id,Zs,aa,Vt.tags));continue}Zs!=="LineString"&&Zs!=="MultiLineString"||(oa.length===1?(Zs="LineString",oa=oa[0]):Zs="MultiLineString"),Zs!=="Point"&&Zs!=="MultiPoint"||(Zs=oa.length===3?"Point":"MultiPoint"),gs.push(Je(Vt.id,Zs,oa,Vt.tags))}}return gs.length?gs:null}function qs(Yt,it,gt,ft,Lt){for(let Mt=0;Mt=gt&&Qt<=ft&&kn(it,Yt[Mt],Yt[Mt+1],Yt[Mt+2])}}function wt(Yt,it,gt,ft,Lt,Mt,Qt){let ks=Us(Yt);const gs=Lt===0?Sn:bn;let Vt,Vs,Zs=Yt.start;for(let Kr=0;Krgt&&(Vs=gs(ks,Tr,Hr,Ja,Ro,gt),Qt&&(ks.start=Zs+Vt*Vs)):ji>ft?Oa=gt&&(Vs=gs(ks,Tr,Hr,Ja,Ro,gt),Ao=!0),Oa>ft&&ji<=ft&&(Vs=gs(ks,Tr,Hr,Ja,Ro,ft),Ao=!0),!Mt&&Ao&&(Qt&&(ks.end=Zs+Vt*Vs),it.push(ks),ks=Us(Yt)),Qt&&(Zs+=Vt)}let Zn=Yt.length-3;const Or=Yt[Zn],oa=Yt[Zn+1],aa=Lt===0?Or:oa;aa>=gt&&aa<=ft&&kn(ks,Or,oa,Yt[Zn+2]),Zn=ks.length-3,Mt&&Zn>=3&&(ks[Zn]!==ks[0]||ks[Zn+1]!==ks[1])&&kn(ks,ks[0],ks[1],ks[2]),ks.length&&it.push(ks)}function Us(Yt){const it=[];return it.size=Yt.size,it.start=Yt.start,it.end=Yt.end,it}function Es(Yt,it,gt,ft,Lt,Mt){for(const Qt of Yt)wt(Qt,it,gt,ft,Lt,Mt,!1)}function kn(Yt,it,gt,ft){Yt.push(it,gt,ft)}function Sn(Yt,it,gt,ft,Lt,Mt){const Qt=(Mt-it)/(ft-it);return kn(Yt,Mt,gt+(Lt-gt)*Qt,1),Qt}function bn(Yt,it,gt,ft,Lt,Mt){const Qt=(Mt-gt)/(Lt-gt);return kn(Yt,it+(ft-it)*Qt,Mt,1),Qt}function cr(Yt,it){const gt=[];for(let ft=0;ft0&&it.size<(Lt?Qt:ft))return void(gt.numPoints+=it.length/3);const ks=[];for(let gs=0;gsQt)&&(gt.numSimplified++,ks.push(it[gs],it[gs+1])),gt.numPoints++;Lt&&function(gs,Vt){let Vs=0;for(let Zs=0,Zn=gs.length,Or=Zn-2;Zs0===Vt)for(let Zs=0,Zn=gs.length;Zs24)throw new Error("maxZoom should be in the 0-24 range");if(gt.promoteId&>.generateId)throw new Error("promoteId and generateId cannot be used together.");let Lt=function(Mt,Qt){const ks=[];if(Mt.type==="FeatureCollection")for(let gs=0;gs1&&console.time("creation"),Or=this.tiles[Zn]=Tn(it,gt,ft,Lt,Vt),this.tileCoords.push({z:gt,x:ft,y:Lt}),Vs)){Vs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",gt,ft,Lt,Or.numFeatures,Or.numPoints,Or.numSimplified),console.timeEnd("creation"));const Ao=`z${gt}`;this.stats[Ao]=(this.stats[Ao]||0)+1,this.total++}if(Or.source=it,Mt==null){if(gt===Vt.indexMaxZoom||Or.numPoints<=Vt.indexMaxPoints)continue}else{if(gt===Vt.maxZoom||gt===Mt)continue;if(Mt!=null){const Ao=Mt-gt;if(ft!==Qt>>Ao||Lt!==ks>>Ao)continue}}if(Or.source=null,it.length===0)continue;Vs>1&&console.time("clipping");const oa=.5*Vt.buffer/Vt.extent,aa=.5-oa,Kr=.5+oa,Tr=1+oa;let Hr=null,Ba=null,Ja=null,Ro=null,ji=It(it,Zs,ft-oa,ft+Kr,0,Or.minX,Or.maxX,Vt),Oa=It(it,Zs,ft+aa,ft+Tr,0,Or.minX,Or.maxX,Vt);it=null,ji&&(Hr=It(ji,Zs,Lt-oa,Lt+Kr,1,Or.minY,Or.maxY,Vt),Ba=It(ji,Zs,Lt+aa,Lt+Tr,1,Or.minY,Or.maxY,Vt),ji=null),Oa&&(Ja=It(Oa,Zs,Lt-oa,Lt+Kr,1,Or.minY,Or.maxY,Vt),Ro=It(Oa,Zs,Lt+aa,Lt+Tr,1,Or.minY,Or.maxY,Vt),Oa=null),Vs>1&&console.timeEnd("clipping"),gs.push(Hr||[],gt+1,2*ft,2*Lt),gs.push(Ba||[],gt+1,2*ft,2*Lt+1),gs.push(Ja||[],gt+1,2*ft+1,2*Lt),gs.push(Ro||[],gt+1,2*ft+1,2*Lt+1)}}getTile(it,gt,ft){it=+it,gt=+gt,ft=+ft;const Lt=this.options,{extent:Mt,debug:Qt}=Lt;if(it<0||it>24)return null;const ks=1<1&&console.log("drilling down to z%d-%d-%d",it,gt,ft);let Vt,Vs=it,Zs=gt,Zn=ft;for(;!Vt&&Vs>0;)Vs--,Zs>>=1,Zn>>=1,Vt=this.tiles[Ss(Vs,Zs,Zn)];return Vt&&Vt.source?(Qt>1&&(console.log("found parent tile z%d-%d-%d",Vs,Zs,Zn),console.time("drilling down")),this.splitTile(Vt.source,Vs,Zs,Zn,it,gt,ft),Qt>1&&console.timeEnd("drilling down"),this.tiles[gs]?cn(this.tiles[gs],Mt):null):null}}function Ss(Yt,it,gt){return 32*((1<Vt.tags&&"3d_elevation_id"in Vt.tags&&"source"in Vt.tags&&Vt.tags.source==="elevation",Mt=ft.features.filter(Vt=>Lt(Vt));let Qt={_geojsonTileLayer:ft.features};Mt.length>0&&(Qt={_geojsonTileLayer:ft.features.filter(Vt=>!Lt(Vt)),hd_road_elevation:Mt});const ks=new K(Qt),gs=function(Vt){const Vs=new c.a$;for(const Zs of Object.keys(Vt))Vs.writeMessage(3,ge,{name:Zs,features:Vt[Zs]});return Vs.finish()}(Qt).buffer;it(null,{vectorTile:ks,rawData:gs})}class hn extends I{constructor(it){super(it),this.loadVectorData=pr,this._dynamicIndex=new oe}loadData(it,gt){const ft=it&&it.request,Lt=ft&&ft.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(it,(Mt,Qt)=>{if(Mt||!Qt)return gt(Mt);if(typeof Qt!="object")return gt(new Error(`Input data given to '${it.source}' is not a valid GeoJSON object.`));{try{if(it.filter){const gs=c.X(it.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(gs.result==="error")throw new Error(gs.value.map(Vt=>`${Vt.key}: ${Vt.message}`).join(", "));Qt.features=Qt.features.filter(Vt=>gs.value.evaluate({zoom:0},Vt))}it.dynamic?(Qt.type==="Feature"&&(Qt={type:"FeatureCollection",features:[Qt]}),it.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(Qt.features,this.loaded),it.cluster&&(Qt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=it.cluster?new We(function({superclusterOptions:gs,clusterProperties:Vt}){if(!Vt||!gs)return gs;const Vs={},Zs={},Zn={accumulated:null,zoom:0},Or={properties:null},oa=Object.keys(Vt);for(const aa of oa){const[Kr,Tr]=Vt[aa],Hr=c.X(Tr),Ba=c.X(typeof Kr=="string"?[Kr,["accumulated"],["get",aa]]:Kr);Vs[aa]=Hr.value,Zs[aa]=Ba.value}return gs.map=aa=>{Or.properties=aa;const Kr={};for(const Tr of oa)Kr[Tr]=Vs[Tr].evaluate(Zn,Or);return Kr},gs.reduce=(aa,Kr)=>{Or.properties=Kr;for(const Tr of oa)Zn.accumulated=aa[Tr],aa[Tr]=Zs[Tr].evaluate(Zn,Or)},gs}(it)).load(Qt.features):it.dynamic?this._dynamicIndex:function(gs,Vt){return new As(gs,Vt)}(Qt,it.geojsonVtOptions)}catch(gs){return gt(gs)}const ks={};if(Lt){const gs=d(ft);gs&&(ks.resourceTiming={},ks.resourceTiming[it.source]=JSON.parse(JSON.stringify(gs)))}gt(null,ks)}})}reloadTile(it,gt){const ft=this.loaded;return ft&&ft[it.uid]?it.partial?gt(null,void 0):super.reloadTile(it,gt):this.loadTile(it,gt)}loadGeoJSON(it,gt){if(it.request)c.m(it.request,gt);else{if(typeof it.data!="string")return gt(new Error(`Input data given to '${it.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return gt(null,JSON.parse(it.data))}catch{return gt(new Error(`Input data given to '${it.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(it,gt){try{gt(null,this._geoJSONIndex.getClusterExpansionZoom(it.clusterId))}catch(ft){gt(ft)}}getClusterChildren(it,gt){try{gt(null,this._geoJSONIndex.getChildren(it.clusterId))}catch(ft){gt(ft)}}getClusterLeaves(it,gt){try{gt(null,this._geoJSONIndex.getLeaves(it.clusterId,it.limit,it.offset))}catch(ft){gt(ft)}}}class Pn{constructor(it,gt,ft){this.tileID=new c.aR(it.tileID.overscaledZ,it.tileID.wrap,it.tileID.canonical.z,it.tileID.canonical.x,it.tileID.canonical.y),this.tileZoom=it.tileZoom,this.uid=it.uid,this.zoom=it.zoom,this.canonical=it.tileID.canonical,this.pixelRatio=it.pixelRatio,this.tileSize=it.tileSize,this.source=it.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=it.projection,this.brightness=gt,this.worldview=ft}parse(it,gt,ft,Lt){this.status="parsing";const Mt=new c.aR(ft.tileID.overscaledZ,ft.tileID.wrap,ft.tileID.canonical.z,ft.tileID.canonical.x,ft.tileID.canonical.y),Qt=[],ks=gt.familiesBySource[ft.source],gs=new c.ff(Mt,ft.promoteId);gs.bucketLayerIDs=[],gs.is3DTile=!0,c.fB(it).then(Vt=>{const Vs=Vt.json.extensionsUsed&&Vt.json.extensionsUsed.includes("MAPBOX_mesh_features")||Vt.json.asset.extras&&Vt.json.asset.extras.MAPBOX_mesh_features,Zs=Vt.json.extensionsUsed&&Vt.json.extensionsUsed.includes("EXT_meshopt_compression"),Zn=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Or in ks)for(const oa of ks[Or]){const aa=oa[0];gs.bucketLayerIDs.push(oa.map(Hr=>c.F(Hr.id,Hr.scope))),aa.recalculate(Zn,[]);const Kr=c.fC(Vt,1/c.cS(ft.tileID.canonical)),Tr=new c.fD(oa,Kr,Mt,Vs,Zs,this.brightness,gs,this.worldview);Vs||(Tr.needsUpload=!0),Qt.push(Tr),Tr.evaluate(aa)}this.status="done",Lt(null,{buckets:Qt,featureIndex:gs,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Vt=>Lt(new Error(Vt.message)))}}class Gs{constructor({actor:it,layerIndex:gt,availableImages:ft,availableModels:Lt,brightness:Mt,worldview:Qt}){this.actor=it,this.layerIndex=gt,this.availableImages=ft,this.availableModels=Lt,this.brightness=Mt,this.loading={},this.loaded={},this.worldview=Qt}loadTile(it,gt){const ft=it.uid,Lt=this.loading[ft]=new Pn(it,this.brightness,this.worldview);c.b1(it.request,(Mt,Qt)=>{const ks=!this.loading[ft];return delete this.loading[ft],ks||Mt?(Lt.status="done",ks||(this.loaded[ft]=Lt),gt(Mt)):Qt&&Qt.byteLength!==0?void Lt.parse(Qt,this.layerIndex,it,(gs,Vt)=>{Lt.status="done",this.loaded=this.loaded||{},this.loaded[ft]=Lt,gs||!Vt?gt(gs):gt(null,Vt)}):(Lt.status="done",this.loaded[ft]=Lt,gt())})}reloadTile(it,gt){const ft=this.loaded,Lt=it.uid;if(ft&&ft[Lt]){const Mt=ft[Lt];Mt.projection=it.projection,Mt.brightness=it.brightness;const Qt=(ks,gs)=>{Mt.reloadCallback&&(delete Mt.reloadCallback,this.loadTile(it,gt)),gt(ks,gs)};Mt.status==="parsing"?Mt.reloadCallback=Qt:Mt.status==="done"&&this.loadTile(it,gt)}}abortTile(it,gt){const ft=it.uid;this.loading[ft]&&delete this.loading[ft],gt()}removeTile(it,gt){const ft=this.loaded,Lt=it.uid;ft&&ft[Lt]&&delete ft[Lt],gt()}}const an=new Map,tr=new Map;class Lr{constructor(it){this.self=it,this.actor=new c.A(it,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:I,geojson:hn,"raster-dem":D,"raster-array":q,"batched-model":Gs},this.workerSources={},this.self.registerWorkerSource=(gt,ft)=>{if(this.workerSourceTypes[gt])throw new Error(`Worker source with name "${gt}" already registered.`);this.workerSourceTypes[gt]=ft},this.self.registerRTLTextPlugin=gt=>{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=gt.applyArabicShaping,c.fF.processBidirectionalText=gt.processBidirectionalText,c.fF.processStyledBidirectionalText=gt.processStyledBidirectionalText;for(const ft of this.rtlPluginParsingListeners)ft(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(it,gt,ft){delete this.layerIndexes[it],delete this.availableImages[it],delete this.availableModels[it],delete this.workerSources[it],ft()}checkIfReady(it,gt,ft){ft()}setReferrer(it,gt){this.referrer=gt}spriteLoaded(it,gt){this.isSpriteLoaded[it]||(this.isSpriteLoaded[it]={});const{scope:ft,isLoaded:Lt}=gt;if(this.isSpriteLoaded[it][ft]=Lt,this.workerSources[it]&&this.workerSources[it][ft])for(const Mt in this.workerSources[it][ft]){const Qt=this.workerSources[it][ft][Mt];for(const ks in Qt){const gs=Qt[ks];gs instanceof I&&(gs.isSpriteLoaded=Lt,gs.fire(new c.C("isSpriteLoaded")))}}}setImages(it,gt,ft){this.availableImages[it]||(this.availableImages[it]={});const{scope:Lt,images:Mt}=gt;if(this.availableImages[it][Lt]=Mt,this.workerSources[it]&&this.workerSources[it][Lt]){for(const Qt in this.workerSources[it][Lt]){const ks=this.workerSources[it][Lt][Qt];for(const gs in ks)ks[gs].availableImages=Mt}ft()}else ft()}setModels(it,{scope:gt,models:ft},Lt){if(this.availableModels[it]||(this.availableModels[it]={}),this.availableModels[it][gt]=ft,this.workerSources[it]&&this.workerSources[it][gt]){for(const Mt in this.workerSources[it][gt]){const Qt=this.workerSources[it][gt][Mt];for(const ks in Qt)Qt[ks].availableModels=ft}Lt()}else Lt()}setProjection(it,gt){this.projections[it]=c.c0(gt)}setBrightness(it,gt,ft){this.brightness=gt,ft()}setContextParams(it,gt,ft){this.maxUniformBufferBindings=gt.maxBindingPoints,this.maxUniformBlockSizeDwords=gt.maxUniformBlockSizeDwords,this.disableSymbolUBO=gt.disableSymbolUBO,ft()}setWorldview(it,gt,ft){this.worldview=gt,ft()}setLayers(it,gt,ft){this.getLayerIndex(it,gt.scope).replace(gt.layers,gt.options),ft()}updateLayers(it,gt,ft){this.getLayerIndex(it,gt.scope).update(gt.layers,gt.removedIds,gt.options),ft()}loadTile(it,gt,ft){gt.projection=this.projections[it]||this.defaultProjection,this.getWorkerSource(it,gt).loadTile(gt,ft)}decodeRasterArray(it,gt,ft){this.getWorkerSource(it,gt).decodeRasterArray(gt,ft)}reloadTile(it,gt,ft){gt.projection=this.projections[it]||this.defaultProjection,this.getWorkerSource(it,gt).reloadTile(gt,ft)}abortTile(it,gt,ft){this.getWorkerSource(it,gt).abortTile(gt,ft)}removeTile(it,gt,ft){this.getWorkerSource(it,gt).removeTile(gt,ft)}removeSource(it,gt,ft){if(!(this.workerSources[it]&&this.workerSources[it][gt.scope]&&this.workerSources[it][gt.scope][gt.type]&&this.workerSources[it][gt.scope][gt.type][gt.source]))return;const Lt=this.workerSources[it][gt.scope][gt.type][gt.source];delete this.workerSources[it][gt.scope][gt.type][gt.source],Lt.removeSource!==void 0?Lt.removeSource(gt,ft):ft()}loadTileProvider(it,gt,ft){(async function(Lt,Mt){const Qt=tr.get(Lt);if(Qt)return Qt;const ks=an.get(Lt);if(ks!==void 0)return ks;const gs=import(Mt).then(Vt=>{const Vs=Vt.default;if(typeof Vs!="function")throw new Error(`TileProvider "${Lt}" module must default-export a class`);if(typeof Vs.prototype.loadTile!="function")throw new Error(`TileProvider "${Lt}" class must have a loadTile method`);return tr.set(Lt,Vs),Vs}).finally(()=>{an.delete(Lt)});return an.set(Lt,gs),gs})(gt.name,gt.url).then(Lt=>{const Mt=new Lt(gt.options);return this.getWorkerSource(it,{type:gt.type,source:gt.source,scope:gt.scope},Mt),Mt.load&>.request?Mt.load({request:gt.request}):null}).then(Lt=>ft(null,Lt)).catch(Lt=>ft(Lt instanceof Error?Lt:new Error(typeof Lt=="string"?Lt:"Unknown error")))}loadWorkerSource(it,gt,ft){try{this.self.importScripts(gt.url),ft()}catch(Lt){ft(Lt)}}syncRTLPluginState(it,gt,ft){if(c.fF.isParsed())ft(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(ft);else try{c.fF.setState(gt);const Lt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||Lt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(Lt),c.fF.isParsed()?ft(null,!0):this.rtlPluginParsingListeners.push(ft))}catch(Lt){ft(Lt)}}setConfig(it,gt){Object.assign(c.g,gt)}getAvailableImages(it,gt){this.availableImages[it]||(this.availableImages[it]={});let ft=this.availableImages[it][gt];return ft||(ft=[]),ft}getAvailableModels(it,gt){this.availableModels[it]||(this.availableModels[it]={});let ft=this.availableModels[it][gt];return ft||(ft={}),ft}getLayerIndex(it,gt){this.layerIndexes[it]||(this.layerIndexes[it]={});let ft=this.layerIndexes[it][gt];return ft||(ft=this.layerIndexes[it][gt]=new p,ft.scope=gt),ft}getWorkerSource(it,gt,ft){const{type:Lt,source:Mt,scope:Qt}=gt,ks=this.workerSources;if(ks[it]||(ks[it]={}),ks[it][Qt]||(ks[it][Qt]={}),ks[it][Qt][Lt]||(ks[it][Qt][Lt]={}),this.isSpriteLoaded[it]||(this.isSpriteLoaded[it]={}),!ks[it][Qt][Lt][Mt]){const gs={send:(Vs,Zs,Zn,Or,oa,aa)=>this.actor.send(Vs,Zs,Zn,it,oa,aa),scheduler:this.actor.scheduler},Vt=this.workerSourceTypes[Lt];if(!Vt)throw new Error(`Unknown worker source type "${Lt}".`);ks[it][Qt][Lt][Mt]=new Vt({actor:gs,layerIndex:this.getLayerIndex(it,Qt),availableImages:this.getAvailableImages(it,Qt),availableModels:this.getAvailableModels(it,Qt),isSpriteLoaded:this.isSpriteLoaded[it][Qt],tileProvider:ft,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return ks[it][Qt][Lt][Mt]}rasterizeImagesWorker(it,gt,ft){const Lt=new Map;for(const[Mt,{image:Qt,imageVariant:ks}]of gt.tasks.entries()){const gs=this.imageRasterizer.rasterize(ks,Qt,gt.scope,it);Lt.set(Mt,gs)}ft(void 0,Lt)}removeRasterizedImages(it,gt,ft){this.imageRasterizer.removeImagesFromCacheByIds(gt.imageIds,gt.scope,it),ft()}enforceCacheSizeLimit(it,gt){c.fH(gt)}getWorkerPerformanceMetrics(it,gt,ft){ft(void 0,void 0)}}return c.fE(self)&&(self.worker=new Lr(self)),Lr}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(R){performance.mark(R)},measure(R,N,T){performance.measure(R,N,T)}};function h(R){const N=R.name.split("?")[0];return o.a(N)&&N.includes("mapbox-gl.js")?"javascript":o.a(N)&&N.includes("mapbox-gl.css")?"css":o.b(N)?"fontRange":o.c(N)?"sprite":o.i(N)?"style":o.d(N)?"tilejson":"other"}var m,p={},f=function(){if(m)return p;function R(B){return!N(B)}function N(B){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var Q,se,ue=new Blob([""],{type:"text/javascript"}),we=URL.createObjectURL(ue);try{se=new Worker(we),Q=!0}catch{Q=!1}return se&&se.terminate(),URL.revokeObjectURL(we),Q}()?function(){var Q=document.createElement("canvas");Q.width=Q.height=1;var se=Q.getContext("2d");if(!se)return!1;var ue=se.getImageData(0,0,1,1);return ue&&ue.width===Q.width}()?(T[W=B&&B.failIfMajorPerformanceCaveat]===void 0&&(T[W]=function(Q){var se,ue=function(we){var Te=document.createElement("canvas"),De=Object.create(R.webGLContextAttributes);return De.failIfMajorPerformanceCaveat=we,Te.getContext("webgl2",De)}(Q);if(!ue)return!1;try{se=ue.createShader(ue.VERTEX_SHADER)}catch{return!1}return!(!se||ue.isContextLost())&&(ue.shaderSource(se,"void main() {}"),ue.compileShader(se),ue.getShaderParameter(se,ue.COMPILE_STATUS)===!0)}(W)),T[W]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var W}m=1,p.supported=R,p.notSupportedReason=N;var T={};return R.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},p}();function g(R,N,T){const B=document.createElement(R);return N!=null&&(B.className=N),T&&T.appendChild(B),B}function v(R,N,T){const B=document.createElementNS("http://www.w3.org/2000/svg",R);for(const W of Object.keys(N))B.setAttributeNS(null,W,String(N[W]));return T&&T.appendChild(B),B}const y=typeof document<"u"?document.documentElement&&document.documentElement.style:null,b=y&&y.userSelect!==void 0?"userSelect":"WebkitUserSelect";let w;function S(){y&&b&&(w=y[b],y[b]="none")}function C(){y&&b&&(y[b]=w)}function E(R){R.preventDefault(),R.stopPropagation(),window.removeEventListener("click",E,!0)}function P(){window.addEventListener("click",E,!0),window.setTimeout(()=>{window.removeEventListener("click",E,!0)},0)}function M(R,N){const T=R.getBoundingClientRect();return F(R,T,N)}function I(R,N){const T=R.getBoundingClientRect(),B=[];for(let W=0;Wthis._skuTokenExpiresAt}transformRequest(N,T){return this._transformRequestFn&&this._transformRequestFn(N,T)||{url:N}}normalizeStyleURL(N,T){if(!o.e(N))return N;const B=K(N);return B.params.push(`sdk=js-${c}`),B.path=`/styles/v1${B.path}`,this._makeAPIURL(B,this._customAccessToken||T)}normalizeGlyphsURL(N,T){if(!o.e(N))return N;const B=K(N);return B.path=`/fonts/v1${B.path}`,this._makeAPIURL(B,this._customAccessToken||T)}normalizeModelURL(N,T){if(!o.e(N))return N;const B=K(N);return B.path=`/models/v1${B.path}`,this._makeAPIURL(B,this._customAccessToken||T)}normalizeSourceURL(N,T,B,W){if(!o.e(N))return N;const Q=K(N);return Q.path=`/v4/${Q.authority}.json`,Q.params.push("secure"),B&&Q.params.push(`language=${B}`),W&&Q.params.push(`worldview=${W}`),this._makeAPIURL(Q,this._customAccessToken||T)}normalizeIconsetURL(N,T){const B=K(N);return o.e(N)?(B.path=`/styles/v1${B.path}/iconset.pbf`,this._makeAPIURL(B,this._customAccessToken||T)):Z(B)}normalizeSpriteURL(N,T,B,W){const Q=K(N);return o.e(N)?(Q.path=`/styles/v1${Q.path}/sprite${T}${B}`,this._makeAPIURL(Q,this._customAccessToken||W)):(Q.path+=`${T}${B}`,Z(Q))}normalizeTileURL(N,T,B){if(this._isSkuTokenExpired()&&this._createSkuToken(),N&&!o.e(N))return N;const W=K(N);W.path=W.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${T||B&&W.authority!=="raster"&&B===512?"@2x":""}${o.k.supported?".webp":"$1"}`),W.authority==="raster"?W.path=`/${o.g.RASTER_URL_PREFIX}${W.path}`:W.authority==="rasterarrays"?W.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${W.path}`:W.authority==="3dtiles"?W.path=`/${o.g.TILES3D_URL_PREFIX}${W.path}`:(W.path=W.path.replace(/^.+\/v4\//,"/"),W.path=`/${o.g.TILE_URL_VERSION}${W.path}`);const Q=this._customAccessToken||function(se){for(const ue of se){const we=ue.match(/^access_token=(.*)$/);if(we)return we[1]}return null}(W.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&Q&&this._skuToken&&W.params.push(`sku=${this._skuToken}`),this._makeAPIURL(W,Q)}canonicalizeTileURL(N,T){const B=K(N);if(!B.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!B.path.match(/\.[\w]+$/))return N;let W="mapbox://";B.path.match(/^\/raster\/v1\//)?W+=`raster/${B.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:B.path.match(/^\/rasterarrays\/v1\//)?W+=`rasterarrays/${B.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:W+=`tiles/${B.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let Q=B.params;return T&&(Q=Q.filter(se=>!se.match(/^access_token=/))),Q.length&&(W+=`?${Q.join("&")}`),W}canonicalizeTileset(N,T){const B=!!T&&o.e(T),W=[];for(const Q of N.tiles||[])o.f(Q)?W.push(this.canonicalizeTileURL(Q,B)):W.push(Q);return W}_makeAPIURL(N,T){const B="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",W=K(o.g.API_URL);if(N.protocol=W.protocol,N.authority=W.authority,N.protocol==="http"){const Q=N.params.indexOf("secure");Q>=0&&N.params.splice(Q,1)}if(W.path!=="/"&&(N.path=`${W.path}${N.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return Z(N);if(T=T||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!T)throw new Error(`An API access token is required to use Mapbox GL. ${B}`);if(T[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${B}`)}return N.params=N.params.filter(Q=>Q.indexOf("access_token")===-1),N.params.push(`access_token=${T||""}`),Z(N)}}const H=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function K(R){const N=R.match(H);if(!N)throw new Error("Unable to parse URL object");return{protocol:N[1],authority:N[2],path:N[3]||"/",params:N[4]?N[4].split("&"):[]}}function Z(R){const N=R.params.length?`?${R.params.join("&")}`:"";return`${R.protocol}://${R.authority}${R.path}${N}`}const oe="mapbox.eventData";function re(R){if(!R)return null;const N=R.split(".");if(!N||N.length!==3)return null;try{return JSON.parse(o.l(N[1]))}catch{return null}}function ae(R){return!(!o.g.EVENTS_URL||!R&&!o.g.ACCESS_TOKEN)}class J{constructor(N){this.type=N,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(N){const T=re(o.g.ACCESS_TOKEN);let B="";return B=T&&T.u?o.j(T.u):o.g.ACCESS_TOKEN||"",N?`${oe}.${N}:${B}`:`${oe}:${B}`}fetchEventData(){const N=o.s("localStorage"),T=this.getStorageKey(),B=this.getStorageKey("uuid"),W=this.getStorageKey("uuidTimestamp");if(N)try{const Q=localStorage.getItem(T);Q&&(this.eventData=JSON.parse(Q));const se=localStorage.getItem(B);se&&(this.anonId=se);const ue=localStorage.getItem(W);ue&&(this.anonIdTimestamp=Number(ue));const we=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(T,JSON.stringify(this.eventData)),se&&localStorage.setItem(W,se.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(N){}postEvent(N,T,B,W){if(!o.g.EVENTS_URL)return;const Q=K(o.g.EVENTS_URL);Q.params.push(`access_token=${W||o.g.ACCESS_TOKEN||""}`);const se={event:this.type,created:new Date(N).toISOString()},ue=T?Object.assign(se,T):se,we={url:Z(Q),headers:{"Content-Type":"text/plain"},body:JSON.stringify([ue])};this.pendingRequest=o.p(we,Te=>{this.pendingRequest=null,B(Te),this.saveEventData(),this.processRequests(W)})}queueRequest(N,T){this.queue.push(N),this.processRequests(T)}}class te extends J{constructor(N){super("metrics"),N&&(this.data=N)}postMetricsEvent(N){if(!ae(N))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const T=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:T},N)}processRequests(N){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:T,payload:B}=this.queue.shift();this.postEvent(T,B,()=>{},N)}}const ce=new class extends J{constructor(R){super("appUserTurnstile"),this._customAccessToken=R}postTurnstileEvent(R,N){ae(N)&&Array.isArray(R)&&R.some(T=>o.e(T)||o.f(T))&&this.queueRequest(Date.now(),N)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const N=re(o.g.ACCESS_TOKEN),T=N?N.u:o.g.ACCESS_TOKEN;let B=T!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),B=!0);const W=this.queue.shift();if(this.eventData.lastSuccess){const Q=new Date(this.eventData.lastSuccess),se=new Date(W),ue=(W-this.eventData.lastSuccess)/864e5;B=B||ue>=1||ue<-1||Q.getDate()!==se.getDate()}else B=!0;B?this.postEvent(W,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:q,"enabled.telemetry":!1,userId:this.anonId},Q=>{Q||(this.eventData.lastSuccess=W,this.eventData.tokenU=T)},R):this.processRequests()}},ve=ce.postTurnstileEvent.bind(ce),me=new class extends J{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(R,N,T,B){this.skuToken=N,this.errorCb=B,o.g.EVENTS_URL&&(T||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},T):this.errorCb(new Error(G)))}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{id:N,timestamp:T}=this.queue.shift();N&&this.success[N]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(T,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:q,skuToken:this.skuToken,userId:this.anonId},B=>{B?this.errorCb(B):N&&(this.success[N]=!0)},R))}remove(){this.errorCb=null}},he=me.postMapLoadEvent.bind(me),ge=new class extends J{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(R){let N=this.mapInstanceIdMap.get(R);return N||(N=o.u(),this.mapInstanceIdMap.set(R,N)),N}getEventId(R){const N=this.eventIdPerMapInstanceMap.get(R)||0;return this.eventIdPerMapInstanceMap.set(R,N+1),N}postStyleLoadEvent(R,N){const{map:T,style:B,importedStyles:W}=N;if(!ae(R))return;const Q=this.getMapInstanceId(T),se={mapInstanceId:Q,eventId:this.getEventId(Q),style:B};W.length&&(se.importedStyles=W),this.queueRequest({timestamp:Date.now(),payload:se},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,payload:T}=this.queue.shift();this.postEvent(N,T,()=>{},R)}},Ee=ge.postStyleLoadEvent.bind(ge),Ne=new te({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Pe=Ne.postMetricsEvent.bind(Ne),Oe=new te({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),ke=Oe.postMetricsEvent.bind(Oe),Ve=new class extends J{constructor(){super("gljs.performance")}postPerformanceEvent(R,N){ae(R)&&this.queueRequest({timestamp:Date.now(),performanceData:N},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,performanceData:T}=this.queue.shift(),B=function(W){const Q=performance.getEntriesByType("resource"),se=performance.getEntriesByType("mark"),ue=function(tt){const ht={};if(tt){for(const ct in tt)if(ct!=="other")for(const St of tt[ct]){const kt=`${ct}ResolveRangeMin`,Ut=`${ct}ResolveRangeMax`,Xt=`${ct}RequestCount`,Et=`${ct}RequestCachedCount`;ht[kt]=Math.min(ht[kt]||1/0,St.startTime),ht[Ut]=Math.max(ht[Ut]||-1/0,St.responseEnd);const Ts=ds=>{ht[ds]===void 0&&(ht[ds]=0),++ht[ds]};St.transferSize!==void 0&&St.transferSize===0&&Ts(Et),Ts(Xt)}}return ht}(function(tt,ht){const ct={};if(tt)for(const St of tt){const kt=ht(St);ct[kt]===void 0&&(ct[kt]=[]),ct[kt].push(St)}return ct}(Q,h)),we=window.devicePixelRatio,Te=navigator.connection||navigator.mozConnection||navigator.webkitConnection,De=Te?Te.effectiveType:void 0,Qe={counters:[],metadata:[],attributes:[]},Ye=(tt,ht,ct)=>{ct!=null&&tt.push({name:ht,value:ct.toString()})};for(const tt in ue)Ye(Qe.counters,tt,ue[tt]);if(W.interactionRange[0]!==1/0&&W.interactionRange[1]!==-1/0&&(Ye(Qe.counters,"interactionRangeMin",W.interactionRange[0]),Ye(Qe.counters,"interactionRangeMax",W.interactionRange[1])),se)for(const tt of Object.values(d)){const ht=se.find(ct=>ct.name===tt);ht&&Ye(Qe.counters,tt,ht.startTime)}return Ye(Qe.counters,"visibilityHidden",W.visibilityHidden),Ye(Qe.attributes,"style",function(tt){if(tt)for(const ht of tt){const ct=ht.name.split("?")[0];if(o.i(ct)){const St=ct.split("/").slice(-2);if(St.length===2)return`mapbox://styles/${St[0]}/${St[1]}`}}}(Q)),Ye(Qe.attributes,"terrainEnabled",W.terrainEnabled?"true":"false"),Ye(Qe.attributes,"fogEnabled",W.fogEnabled?"true":"false"),Ye(Qe.attributes,"projection",W.projection),Ye(Qe.attributes,"zoom",W.zoom),Ye(Qe.metadata,"devicePixelRatio",we),Ye(Qe.metadata,"connectionEffectiveType",De),Ye(Qe.metadata,"navigatorUserAgent",navigator.userAgent),Ye(Qe.metadata,"screenWidth",window.screen.width),Ye(Qe.metadata,"screenHeight",window.screen.height),Ye(Qe.metadata,"windowWidth",window.innerWidth),Ye(Qe.metadata,"windowHeight",window.innerHeight),Ye(Qe.metadata,"mapWidth",W.width/we),Ye(Qe.metadata,"mapHeight",W.height/we),Ye(Qe.metadata,"webglRenderer",W.renderer),Ye(Qe.metadata,"webglVendor",W.vendor),Ye(Qe.metadata,"sdkVersion",c),Ye(Qe.metadata,"sdkIdentifier","mapbox-gl-js"),Qe}(T);for(const W of B.metadata);for(const W of B.counters);for(const W of B.attributes);this.postEvent(N,B,()=>{},R)}},_e=Ve.postPerformanceEvent.bind(Ve),Ae=new class extends J{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(R,N,T,B){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const W=K(o.g.API_URL+o.g.SESSION_PATH);W.params.push(`sku=${N||""}`),W.params.push(`access_token=${B||o.g.ACCESS_TOKEN||""}`);const Q={url:Z(W),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(Q,se=>{this.pendingRequest=null,T(se),this.saveEventData(),this.processRequests(B)})}getSessionAPI(R,N,T,B){this.skuToken=N,this.errorCb=B,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(T||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},T):this.errorCb(new Error(G)))}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{id:N,timestamp:T}=this.queue.shift();N&&this.success[N]||this.getSession(T,this.skuToken,B=>{B?this.errorCb(B):N&&(this.success[N]=!0)},R)}remove(){this.errorCb=null}},Se=Ae.getSessionAPI.bind(Ae),We=new Set;function qe(R,N){N?We.add(R):We.delete(R)}class Be{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(N,T){this._updatedSourceCaches[N]=T,this.setDirty()}discardSourceCacheUpdate(N){delete this._updatedSourceCaches[N]}updateLayer(N){const T=N.scope;this._updatedLayers[T]=this._updatedLayers[T]||new Set,this._updatedLayers[T].add(N.id),this.setDirty()}removeLayer(N){const T=N.scope;this._removedLayers[T]=this._removedLayers[T]||{},this._updatedLayers[T]=this._updatedLayers[T]||new Set,this._removedLayers[T][N.id]=N,this._updatedLayers[T].delete(N.id),this._updatedPaintProps.delete(N.fqid),this.setDirty()}getRemovedLayer(N){return this._removedLayers[N.scope]?this._removedLayers[N.scope][N.id]:null}discardLayerRemoval(N){this._removedLayers[N.scope]&&delete this._removedLayers[N.scope][N.id]}getLayerUpdatesByScope(){const N={};for(const T in this._updatedLayers)N[T]=N[T]||{},N[T].updatedIds=Array.from(this._updatedLayers[T].values());for(const T in this._removedLayers)N[T]=N[T]||{},N[T].removedIds=Object.keys(this._removedLayers[T]);return N}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(N){this._updatedPaintProps.add(N.fqid),this.setDirty()}getUpdatedImages(N){return this._updatedImages[N]?Array.from(this._updatedImages[N].values()):[]}updateImage(N,T){this._updatedImages[T]=this._updatedImages[T]||new Set,this._updatedImages[T].add(o.I.toString(N)),this.setDirty()}resetUpdatedImages(N){this._updatedImages[N]&&this._updatedImages[N].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Ze(R){const{userImage:N}=R;return!!(N&&N.render&&N.render())&&(R.data.replace(new Uint8Array(N.data.buffer)),!0)}const $e={workerUrl:"",workerClass:null,workerParams:void 0};function Xe(R){return $e.workerClass!=null?new $e.workerClass:new self.Worker($e.workerUrl,Object.assign({name:R},$e.workerParams))}const nt="mapboxgl_preloaded_worker_pool";class Ge{constructor(N){this.active={},this.name=N}acquire(N,T=Ge.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{T.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[nt]}numActive(){return Object.keys(this.active).length}}Ge.workerCount=2;class Je{constructor(N,T,B="Worker",W=Ge.workerCount){this.workerPool=N,this.actors=[],this.currentActor=0,this.id=o.r();const Q=this.workerPool.acquire(this.id,W);for(let se=0;se{this.ready=!0})}broadcast(N,T,B){o.t(this.actors,(W,Q)=>{W.send(N,T,Q)},B=B||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(N=>{N.remove()}),this.actors=[],this.workerPool.release(this.id)}}let ut,lt;function qt(){return ut||(ut=new Ge),ut}Je.Actor=o.A;class zt extends o.E{constructor(N){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=N,N!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new Je((lt||(lt=new Ge("ImageRasterizer")),lt),this,"Image Rasterizer Worker",1))}addScope(N){this.loaded.set(N,!1),this.imageProviders.set(N,new Map),this.images.set(N,new Map),this.updatedImages.set(N,new Set),this.callbackDispatchedThisFrame.set(N,new Set),this.imageVersions.set(N,new Map),this.patterns.set(N,new Map),this.atlasImage.set(N,new o.q({width:1,height:1}))}removeScope(N){this.loaded.delete(N),this.imageProviders.delete(N),this.images.delete(N),this.updatedImages.delete(N),this.callbackDispatchedThisFrame.delete(N),this.imageVersions.delete(N),this.patterns.delete(N),this.atlasImage.delete(N);const T=this.atlasTexture.get(N);T&&(T.destroy(),this.atlasTexture.delete(N))}addImageProvider(N,T){this.imageProviders.has(T)||this.imageProviders.set(T,new Map),this.imageProviders.get(T).set(N.id,N)}removeImageProvider(N,T){this.imageProviders.has(T)&&this.imageProviders.get(T).delete(N)}getPendingImageProviders(){const N=[];for(const T of this.imageProviders.values())for(const B of T.values())B.hasPendingRequests()&&N.push(B);return N}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const N of this.loaded.keys())if(!this.loaded.get(N))return!1;return!0}setLoaded(N,T){if(this.loaded.get(T)!==N&&(this.loaded.set(T,N),N)){for(const{ids:B,callback:W}of this.requestors)this._notify(B,T,W);this.requestors=[]}}hasImage(N,T){return!!this.getImage(N,T)}getImage(N,T){return this.images.get(T).get(N.toString())}addImage(N,T,B){if(this._validate(N,B)){this.images.get(T).set(N.toString(),B);const W=this.imageVersions.get(T),Q=W.get(N.toString())||0;W.set(N.toString(),Q+1)}}_validate(N,T){let B=!0;return this._validateStretch(T.stretchX,T.data&&T.data.width)||(this.fire(new o.B(new Error(`Image "${N.name}" has invalid "stretchX" value`))),B=!1),this._validateStretch(T.stretchY,T.data&&T.data.height)||(this.fire(new o.B(new Error(`Image "${N.name}" has invalid "stretchY" value`))),B=!1),this._validateContent(T.content,T)||(this.fire(new o.B(new Error(`Image "${N.name}" has invalid "content" value`))),B=!1),B}_validateStretch(N,T){if(!N)return!0;let B=0;for(const W of N){if(W[0]o.I.from(T))}getImageVersions(N){const T=this.imageVersions.get(N);if(T)return T}getImages(N,T,B){const W=[],Q=[],se=this.imageProviders.get(T);for(const De of N){if(!De.iconsetId){W.push(De);continue}const Qe=se.get(De.iconsetId);Qe&&(this.getImage(De,T)?Q.push(De):Qe.addPendingRequest(De))}if(W.length===0)return void this._notify(Q,T,B);let ue=!0;const we=!!this.loaded.get(T),Te=this.images.get(T);if(!we)for(const De of W)Te.has(De.toString())||(ue=!1);we||ue?this._notify(W,T,B):this.requestors.push({ids:W,scope:T,callback:B})}rasterizeImages(N,T){const B=new Map,{tasks:W,scope:Q}=N;for(const[se,ue]of W.entries()){const we=this.getImage(ue.id,Q);we&&B.set(se,{image:we,imageVariant:ue})}this._rasterizeImages(Q,B,T)}_rasterizeImages(N,T,B){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:T,scope:N},B);else{const W=new Map;for(const[Q,{image:se,imageVariant:ue}]of T.entries())W.set(Q,this.imageRasterizer.rasterize(ue,se,N,0));B(void 0,W)}}getUpdatedImages(N){return this.updatedImages.get(N)||new Set}_notify(N,T,B){const W=this.images.get(T),Q=new Map;for(const se of N){if(!W.get(se.toString())){if(se.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:se.name}))}const ue=W.get(se.toString());if(!ue){o.w(`Image "${se.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 we={data:ue.usvg?null:ue.data.clone(),pixelRatio:ue.pixelRatio,sdf:ue.sdf,usvg:ue.usvg,stretchX:ue.stretchX,stretchY:ue.stretchY,content:ue.content,hasRenderCallback:!!(ue.userImage&&ue.userImage.render)};ue.usvg&&Object.assign(we,{width:ue.icon.usvg_tree.width,height:ue.icon.usvg_tree.height}),Q.set(o.I.toString(se),we)}B(null,{images:Q,versions:this.getImageVersions(T)})}getPixelSize(N){const{width:T,height:B}=this.atlasImage.get(N);return{width:T,height:B}}getPattern(N,T,B){const W=N.toString(),Q=this.patterns.get(T),se=Q.get(W),ue=this.getImage(N,T);if(!ue)return null;if(se){if(se.position.version===ue.version)return se.position;se.position.version=ue.version}else{if(ue.usvg&&!ue.data){const we=this.getPatternInFlightId(W,T);if(this.patternsInFlight.has(we))return null;this.patternsInFlight.add(we);const Te=new o.D(N).scaleSelf(o.o.devicePixelRatio),De=new Map([[Te.toString(),{image:ue,imageVariant:Te}]]);return this._rasterizeImages(T,De,(Qe,Ye)=>this.storePatternImage(Te,T,ue,B,Ye)),null}this.storePattern(N,T,ue)}return this._updatePatternAtlas(T,B),Q.get(W).position}getPatternInFlightId(N,T){return o.F(N,T)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(N,T,B,W,Q){const se=N.toString(),ue=Q?Q.get(se):void 0;ue&&(B.data=ue,this.storePattern(N.id,T,B),this._updatePatternAtlas(T,W),this.patternsInFlight.delete(this.getPatternInFlightId(N.id.toString(),T)))}storePattern(N,T,B){const W={w:B.data.width+2*o.G,h:B.data.height+2*o.G,x:0,y:0},Q=new o.H(W,B,o.G);this.patterns.get(T).set(N.toString(),{bin:W,position:Q})}destroyAtlasTextures(){for(const N of this.atlasTexture.values())N&&N.destroy();this.atlasTexture.clear()}bind(N,T){const B=N.gl;let W=this.atlasTexture.get(T);W?this.dirty&&(W.update(this.atlasImage.get(T)),this.dirty=!1):(W=new o.T(N,this.atlasImage.get(T),B.RGBA8),this.atlasTexture.set(T,W)),W.bind(B.LINEAR,B.CLAMP_TO_EDGE)}_updatePatternAtlas(N,T){const B=this.patterns.get(N),W=Array.from(B.values()).map(({bin:Te})=>Te),{w:Q,h:se}=o.J(W),ue=this.atlasImage.get(N);ue.resize({width:Q||1,height:se||1});const we=this.images.get(N);for(const[Te,{bin:De,position:Qe}]of B.entries()){let Ye=Qe.padding;const tt=De.x+Ye,ht=De.y+Ye,ct=we.get(Te).data,St=ct.width,kt=ct.height;Ye=Ye>1?Ye-1:Ye,o.q.copy(ct,ue,{x:0,y:0},{x:tt,y:ht},{width:St,height:kt},T),o.q.copy(ct,ue,{x:0,y:kt-Ye},{x:tt,y:ht-Ye},{width:St,height:Ye},T),o.q.copy(ct,ue,{x:0,y:0},{x:tt,y:ht+kt},{width:St,height:Ye},T),o.q.copy(ct,ue,{x:St-Ye,y:0},{x:tt-Ye,y:ht},{width:Ye,height:kt},T),o.q.copy(ct,ue,{x:0,y:0},{x:tt+St,y:ht},{width:Ye,height:kt},T),o.q.copy(ct,ue,{x:St-Ye,y:kt-Ye},{x:tt-Ye,y:ht-Ye},{width:Ye,height:Ye},T),o.q.copy(ct,ue,{x:0,y:kt-Ye},{x:tt+St,y:ht-Ye},{width:Ye,height:Ye},T),o.q.copy(ct,ue,{x:0,y:0},{x:tt+St,y:ht+kt},{width:Ye,height:Ye},T),o.q.copy(ct,ue,{x:St-Ye,y:0},{x:tt-Ye,y:ht+kt},{width:Ye,height:Ye},T)}this.dirty=!0}beginFrame(){for(const N of this.images.keys())this.callbackDispatchedThisFrame.set(N,new Set)}dispatchRenderCallbacks(N,T){const B=this.images.get(T);for(const W of N){if(this.callbackDispatchedThisFrame.get(T).has(W.toString()))continue;this.callbackDispatchedThisFrame.get(T).add(W.toString());const Q=B.get(W.toString());Ze(Q)&&this.updateImage(W,T,Q)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Zt(R){const N=R.value,T=R.valueSpec,B=R.style,W=R.styleSpec,Q=R.key,se=R.arrayElementValidator||hn;if(!Array.isArray(N))return[new o.V(Q,N,`array expected, ${o.M(N)} found`)];if(T.length&&N.length!==T.length)return[new o.V(Q,N,`array length ${T.length} expected, length ${N.length} found`)];if(T["min-length"]&&N.lengthW)return[new o.V(N,T,`${T} is greater than the maximum value ${W}`)]}return[]}function Dt(R){const N=R.key,T=R.value;if(!o.K(T))return[new o.V(N,T,`object expected, ${o.M(T)} found`)];const B=R.valueSpec,W=o.L(T.type);let Q,se,ue,we={};const Te=W!=="categorical"&&T.property===void 0,De=!Te,Qe=function(ct){const St=ct.stops;return Array.isArray(St)&&Array.isArray(St[0])&&o.K(St[0][0])}(T),Ye=Pn({key:R.key,value:R.value,valueSpec:R.styleSpec.function,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{stops:function(ct){if(W==="identity")return[new o.V(ct.key,ct.value,'identity function may not have a "stops" property')];let St=[];const kt=ct.value;return St=St.concat(Zt({key:ct.key,value:kt,valueSpec:ct.valueSpec,style:ct.style,styleSpec:ct.styleSpec,arrayElementValidator:tt})),Array.isArray(kt)&&kt.length===0&&St.push(new o.V(ct.key,kt,"array must have at least one stop")),St},default:function(ct){return hn({key:ct.key,value:ct.value,valueSpec:B,style:ct.style,styleSpec:ct.styleSpec})}}});return W==="identity"&&Te&&Ye.push(new o.V(R.key,R.value,'missing required property "property"')),W==="identity"||T.stops||Ye.push(new o.V(R.key,R.value,'missing required property "stops"')),W==="exponential"&&B.expression&&!o.O(B)&&Ye.push(new o.V(R.key,R.value,"exponential functions not supported")),R.styleSpec.$version>=8&&(De&&!o.Q(B)?Ye.push(new o.V(R.key,R.value,"property functions not supported")):Te&&!o.S(B)&&Ye.push(new o.V(R.key,R.value,"zoom functions not supported"))),W!=="categorical"&&!Qe||T.property!==void 0||Ye.push(new o.V(R.key,R.value,'"property" property is required')),Ye;function tt(ct){let St=[];const kt=ct.value,Ut=ct.key;if(!Array.isArray(kt))return[new o.V(Ut,kt,`array expected, ${o.M(kt)} found`)];if(kt.length!==2)return[new o.V(Ut,kt,`array length 2 expected, length ${kt.length} found`)];if(Qe){if(!o.K(kt[0]))return[new o.V(Ut,kt,`object expected, ${o.M(kt[0])} found`)];const Xt=kt[0];if(Xt.zoom===void 0)return[new o.V(Ut,kt,"object stop key must have zoom")];if(Xt.value===void 0)return[new o.V(Ut,kt,"object stop key must have value")];const Et=o.L(Xt.zoom);if(typeof Et!="number")return[new o.V(Ut,Xt.zoom,"stop zoom values must be numbers")];if(ue&&ue>Et)return[new o.V(Ut,Xt.zoom,"stop zoom values must appear in ascending order")];Et!==ue&&(ue=Et,se=void 0,we={}),St=St.concat(Pn({key:`${Ut}[0]`,value:kt[0],valueSpec:{zoom:{}},style:ct.style,styleSpec:ct.styleSpec,objectElementValidators:{zoom:ms,value:ht}}))}else St=St.concat(ht({key:`${Ut}[0]`,value:kt[0],style:ct.style,styleSpec:ct.styleSpec},kt));return o.U(o.W(kt[1]))?St.concat([new o.V(`${Ut}[1]`,kt[1],"expressions are not allowed in function stops.")]):St.concat(hn({key:`${Ut}[1]`,value:kt[1],valueSpec:B,style:ct.style,styleSpec:ct.styleSpec}))}function ht(ct,St){const kt=o.M(ct.value),Ut=o.L(ct.value),Xt=ct.value!==null?ct.value:St;if(Q){if(kt!==Q)return[new o.V(ct.key,Xt,`${kt} stop domain type must match previous stop domain type ${Q}`)]}else Q=kt;if(kt!=="number"&&kt!=="string"&&kt!=="boolean"&&typeof Ut!="number"&&typeof Ut!="string"&&typeof Ut!="boolean")return[new o.V(ct.key,Xt,"stop domain value must be a number, string, or boolean")];if(kt!=="number"&&W!=="categorical"){let Et=`number expected, ${kt} found`;return o.Q(B)&&W===void 0&&(Et+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(ct.key,Xt,Et)]}return W!=="categorical"||kt!=="number"||typeof Ut=="number"&&isFinite(Ut)&&Math.floor(Ut)===Ut?W!=="categorical"&&kt==="number"&&typeof Ut=="number"&&typeof se=="number"&&se!==void 0&&Utnew o.V(`${R.key}${B.key}`,R.value,B.message));const T=N.value.expression||N.value._styleExpression.expression;if(R.expressionContext==="property"&&R.propertyKey==="text-font"&&!T.outputDefined())return[new o.V(R.key,R.value,`Invalid data expression for "${R.propertyKey}". Output values must be contained as literals within the expression.`)];if(R.expressionContext==="property"&&R.propertyType==="layout"&&!o.$(T))return[new o.V(R.key,R.value,'"feature-state" data expressions are not supported with layout properties.')];if(R.expressionContext==="filter")return qs(T,R);if(R.expressionContext==="appearance")return wt(T,R);if(R.expressionContext&&R.expressionContext.indexOf("cluster")===0){if(!o.Z(T,["zoom","feature-state"]))return[new o.V(R.key,R.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(R.expressionContext==="cluster-initial"&&!o._(T))return[new o.V(R.key,R.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function qs(R,N){const T=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(N.valueSpec&&N.valueSpec.expression)for(const W of N.valueSpec.expression.parameters)T.delete(W);if(T.size===0)return[];const B=[];return R instanceof o.a0&&T.has(R.name)?[new o.V(N.key,N.value,`["${R.name}"] expression is not supported in a filter for a ${N.object.type} layer with id: ${N.object.id}`)]:(R.eachChild(W=>{B.push(...qs(W,N))}),B)}function wt(R,N){const T=new Set;if(N.valueSpec&&N.valueSpec.expression)for(const W of N.valueSpec.expression.parameters)T.add(W);if(T.size===0)return[];const B=[];return R instanceof o.a0&&!T.has(R.name)?[new o.V(N.key,N.value,`["${R.name}"] is not an allowed parameter`)]:(R.eachChild(W=>{B.push(...wt(W,N))}),B)}function Us(R){const N=R.key,T=R.value,B=R.valueSpec,W=[];return Array.isArray(B.values)?B.values.indexOf(o.L(T))===-1&&W.push(new o.V(N,T,`expected one of [${B.values.join(", ")}], ${JSON.stringify(T)} found`)):Object.keys(B.values).indexOf(o.L(T))===-1&&W.push(new o.V(N,T,`expected one of [${Object.keys(B.values).join(", ")}], ${JSON.stringify(T)} found`)),W}function Es(R){return o.a4(o.W(R.value))?It(Object.assign({},R,{expressionContext:"filter",valueSpec:R.styleSpec[`filter_${R.layerType||"fill"}`]})):kn(R)}function kn(R){const N=R.value,T=R.key;if(!Array.isArray(N))return[new o.V(T,N,`array expected, ${o.M(N)} found`)];if(N.length<1)return[new o.V(T,N,"filter array must have at least 1 element")];const B=R.styleSpec;let W=Us({key:`${T}[0]`,value:N[0],valueSpec:B.filter_operator});const Q=()=>{N.length>=2&&(o.a2(N[1])||W.push(new o.V(`${T}[1]`,N[1],`string expected, ${o.M(N[1])} found`)));for(let se=2;se":case">=":N.length>=2&&o.L(N[1])==="$type"&&W.push(new o.V(T,N,`"$type" cannot be use with operator "${N[0]}"`)),N.length!==3&&W.push(new o.V(T,N,`filter array for operator "${N[0]}" must have 3 elements`)),Q();break;case"==":case"!=":N.length!==3&&W.push(new o.V(T,N,`filter array for operator "${N[0]}" must have 3 elements`)),Q();break;case"in":case"!in":Q();break;case"any":case"all":case"none":for(let se=1;se{Te in T&&N.push(new o.V(B,T[Te],`"${Te}" is prohibited for ref layers`))}),W.layers.forEach(Te=>{o.L(Te.id)===ue&&(we=Te)}),we?we.ref?N.push(new o.V(B,T.ref,"ref cannot reference another ref layer")):se=o.L(we.type):typeof ue=="string"&&N.push(new o.V(B,T.ref,`ref layer "${ue}" not found`))}else if(se!=="background"&&se!=="sky"&&se!=="slot")if(T.source)if(o.a2(T.source)){const we=W.sources&&W.sources[T.source],Te=we&&o.L(we.type);we?Te==="vector"&&se==="raster"?N.push(new o.V(B,T.source,`layer "${T.id}" requires a raster source`)):Te==="raster"&&se!=="raster"?N.push(new o.V(B,T.source,`layer "${T.id}" requires a vector source`)):Te!=="vector"||T["source-layer"]?Te==="raster-dem"&&se!=="hillshade"?N.push(new o.V(B,T.source,"raster-dem source can only be used with layer type 'hillshade'.")):Te!=="raster-array"||["raster","raster-particle"].includes(se)?se==="line"&&T.paint&&(T.paint["line-gradient"]||T.paint["line-trim-offset"])&&Te==="geojson"&&!we.lineMetrics?N.push(new o.V(B,T,`layer "${T.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):se==="raster-particle"&&Te!=="raster-array"&&N.push(new o.V(B,T.source,`layer "${T.id}" requires a 'raster-array' source.`)):N.push(new o.V(B,T.source,"raster-array source can only be used with layer type 'raster'.")):N.push(new o.V(B,T,`layer "${T.id}" must specify a "source-layer"`)):N.push(new o.V(B,T.source,`source "${T.source}" not found`))}else N.push(new o.V(`${B}.source`,T.source,'"source" must be a string'));else N.push(new o.V(B,T,'missing required property "source"'));return N=N.concat(Pn({key:B,value:T,valueSpec:Q.layer,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{"*":()=>[],type:()=>hn({key:`${B}.type`,value:T.type,valueSpec:Q.layer.type,style:R.style,styleSpec:R.styleSpec,object:T,objectKey:"type"}),filter:we=>Es(Object.assign({layerType:se},we)),layout:we=>Pn({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Te=>cr(Object.assign({layerType:se},Te))}}),paint:we=>Pn({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Te=>bn(Object.assign({layerType:se,layer:T},Te))}}),appearances(we){const Te=Zt({key:we.key,value:we.value,valueSpec:we.valueSpec,style:we.style,styleSpec:we.styleSpec,arrayElementValidator:Ye=>function(tt){const{key:ht,layer:ct,layerType:St}=tt,kt=o.L(tt.value),Ut=o.L(kt.name),Xt=o.L(kt.condition),Et=Pn({key:ht,value:kt,valueSpec:tt.styleSpec.appearance,style:tt.style,styleSpec:tt.styleSpec,objectElementValidators:{condition:Ts=>function(ds){const Cs=[];return Cs.push(...It({key:ds.key,value:ds.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Cs}(Object.assign({layer:ct,layerType:St},Ts)),properties:Ts=>function(ds){const Cs=[],{styleSpec:es,layer:is,layerType:_s}=ds,Xs=es[`paint_${_s}`],Ds=es[`layout_${_s}`],_n=ds.object[ds.objectKey];for(const pn in _n){const Un=pn in Xs?"paint":pn in Ds?"layout":void 0;if(!Un){Cs.push(new o.V(ds.key,pn,`unknown property "${pn}" for layer type "${_s}"`));continue}const Xn=Object.assign({},ds,{key:`${ds.key}.${pn}`,object:_n,objectKey:pn,layer:is,layerType:_s,value:_n[pn],valueSpec:Un==="paint"?Xs[pn]:Ds[pn]});Cs.push(...Sn(Xn,Un))}return Cs}(Object.assign({layer:ct,layerType:St},Ts))}});return Ut!=="hidden"&&Xt===void 0&&Et.push(new o.V(tt.key,"name",'Appearance with name different than "hidden" must have a condition')),Et}(Object.assign({layerType:se,layer:T},Ye))}),De=Array.isArray(we.value)?we.value:[],Qe=new Set;return De.forEach((Ye,tt)=>{const ht=o.L(Ye.name);if(ht)if(Qe.has(ht)){const ct=o.L(T.id);Te.push(new o.V(we.key,ht,`Duplicated appearance name "${ht}" for layer "${ct}"`))}else Qe.add(ht)}),Te}}})),N}function cn({key:R,value:N}){return o.a2(N)?[]:[new o.V(R,N,`string expected, ${o.M(N)} found`)]}const lr={promoteId:function R({key:N,value:T}){if(o.a2(T))return cn({key:N,value:T});if(Array.isArray(T)){const W=[],Q=o.W(T),se=o.X(Q);return se.result==="error"?(se.value.forEach(ue=>{W.push(new o.V(`${N}${ue.key}`,null,`${ue.message}`))}),W):(o.Z(se.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||W.push(new o.V(`${N}`,null,"promoteId expression should be only feature dependent")),W)}if(!o.K(T))return[new o.V(N,T,`string, expression or object expected, "${o.M(T)}" found`)];const B=[];for(const W in T)B.push(...R({key:`${N}.${W}`,value:T[W]}));return B}};function Tn(R){const N=R.value,T=R.key,B=R.styleSpec,W=R.style;if(!o.K(N))return[new o.V(T,N,`object expected, ${o.M(N)} found`)];if(!("type"in N))return[new o.V(T,N,'"type" is required')];const Q=o.L(N.type);let se=[];switch(["vector","raster","raster-dem","raster-array"].includes(Q)&&("url"in N||"tiles"in N||se.push(new o.a5(T,N,'Either "url" or "tiles" is required.'))),Q){case"vector":case"raster":case"raster-dem":case"raster-array":return se=se.concat(Pn({key:T,value:N,valueSpec:B[`source_${Q.replace("-","_")}`],style:R.style,styleSpec:B,objectElementValidators:lr})),se;case"geojson":if(se=Pn({key:T,value:N,valueSpec:B.source_geojson,style:W,styleSpec:B,objectElementValidators:lr}),"cluster"in N&&"clusterProperties"in N){if(!o.K(N.clusterProperties))return[new o.V(`${T}.clusterProperties`,N,`object expected, ${o.M(N)} found`)];for(const ue in N.clusterProperties){const we=N.clusterProperties[ue];if(!Array.isArray(we))return[new o.V(`${T}.clusterProperties.${ue}`,we,"array expected")];const[Te,De]=we,Qe=typeof Te=="string"?[Te,["accumulated"],["get",ue]]:Te;se.push(...It({key:`${T}.${ue}.map`,value:De,expressionContext:"cluster-map"})),se.push(...It({key:`${T}.${ue}.reduce`,value:Qe,expressionContext:"cluster-reduce"}))}}return se;case"video":return Pn({key:T,value:N,valueSpec:B.source_video,style:W,styleSpec:B});case"image":return Pn({key:T,value:N,valueSpec:B.source_image,style:W,styleSpec:B});case"canvas":return[new o.V(T,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Us({key:`${T}.type`,value:N.type,valueSpec:{values:Yn(B)}})}}function Yn(R){return R.source.reduce((N,T)=>{const B=R[T];return B.type.type==="enum"&&(N=N.concat(Object.keys(B.type.values||{}))),N},[])}function fs(R){const N=R.value,T=R.styleSpec,B=T.light,W=R.style;if(N===void 0)return[];if(!o.K(N))return[new o.V("light",N,`object expected, ${o.M(N)} found`)];let Q=[];for(const se in N){const ue=se.match(/^(.*)-transition$/),we=se.match(/^(.*)-use-theme$/);Q=Q.concat(we&&B[we[1]]?hn({key:se,value:N[se],valueSpec:{type:"string"},style:W,styleSpec:T}):ue&&B[ue[1]]&&B[ue[1]].transition?hn({key:se,value:N[se],valueSpec:T.transition,style:W,styleSpec:T}):B[se]?hn({key:se,value:N[se],valueSpec:B[se],style:W,styleSpec:T}):[new o.V(se,N[se],`unknown property "${se}"`)])}return Q}function wn(R){const N=R.value;if(!N)return[];const T=R.key;if(!o.K(N))return[new o.V(T,N,`object expected, ${o.M(N)} found`)];let B=[];const W=R.styleSpec,Q=W["light-3d"],se=R.style,ue=R.style.lights;for(const De of["type","id"])if(!(De in N))return B=B.concat([new o.V(T,N,`missing property "${De}"`)]),B;if(!o.a2(N.type))return B=B.concat([new o.V(`${T}.type`,N.type,"string expected")]),B;if(ue)for(let De=0;De[],array:Zt,boolean:function(R){const N=R.value,T=R.key;return o.a1(N)?[]:[new o.V(T,N,`boolean expected, ${o.M(N)} found`)]},number:ms,color:function({key:R,value:N}){return o.a2(N)?o.a3.parseCSSColor(N)===null?[new o.V(R,N,`color expected, "${N}" found`)]:[]:[new o.V(R,N,`color expected, ${o.M(N)} found`)]},enum:Us,filter:Es,function:Dt,layer:Fs,object:Pn,source:Tn,model:o.a9,light:fs,"light-3d":wn,terrain:As,fog:Ss,string:cn,formatted:function(R){return cn(R).length===0?[]:It(R)},resolvedImage:function(R){return cn(R).length===0?[]:It(R)},projection:function(R){const N=R.value,T=R.styleSpec,B=T.projection,W=R.style;if(o.K(N)){let Q=[];for(const se in N)Q=Q.concat(hn({key:se,value:N[se],valueSpec:B[se],style:W,styleSpec:T}));return Q}return o.a2(N)?[]:[new o.V("projection",N,`object or string expected, ${o.M(N)} found`)]},import:function(R){const N=R.key,{value:T,styleSpec:B}=R;if(!o.K(T))return[new o.V(N,T,"import must be an object")];const{data:W,...Q}=T;Object.defineProperty(Q,"__line__",{value:T.__line__,enumerable:!1});let se=Pn(Object.assign({},R,{value:Q,valueSpec:B.import}));return o.L(Q.id)===""&&se.push(new o.V(`${R.key}.id`,Q,"import id can't be an empty string")),W&&(se=se.concat(an(W,B,{key:`${R.key}.data`}))),se},iconset:function(R){const N=R.value,T=R.key,B=R.styleSpec,W=R.style;if(!o.K(N))return[new o.V(T,N,"object expected")];if(!N.type)return[new o.V(T,N,'"type" is required')];const Q=o.L(N.type);let se=[];if(se=se.concat(Pn({key:T,value:N,valueSpec:B[`iconset_${Q}`],style:W,styleSpec:B})),function(ue,we){return!(ue!=="source"||!we.source)}(Q,N)){const ue=W.sources&&W.sources[N.source],we=ue&&o.L(ue.type);ue?we!=="raster-array"&&se.push(new o.V(T,N.source,`iconset cannot be used with a source of type ${String(we)}, it only be used with a "raster-array" source type`)):se.push(new o.V(T,N.source,`source "${N.source}" not found`))}return se}};function hn(R,N=!1){const T=R.value,B=R.valueSpec,W=R.styleSpec;if(B.expression){if(o.a6(o.L(T)))return Dt(R);if(o.U(o.W(T)))return It(R)}if(B.type&&pr[B.type]){const Q=pr[B.type](R);return N===!0&&Q.length>0&&Array.isArray(R.value)?It(R):Q}return Pn(Object.assign({},R,{valueSpec:B.type?W[B.type]:B}))}function Pn(R){const N=R.key,T=R.value,B=R.valueSpec||{},W=R.objectElementValidators||{},Q=R.style,se=R.styleSpec;if(!o.K(T))return[new o.V(N,T,`object expected, ${o.M(T)} found`)];let ue=[];for(const we in T){const Te=we.split(".")[0];let De;W[Te]?De=W[Te]:B[Te]?De=hn:W["*"]?De=W["*"]:B["*"]&&(De=hn),De?ue=ue.concat(De({key:(N&&`${N}.`)+we,value:T[we],valueSpec:B[Te]||B["*"],style:Q,styleSpec:se,object:T,objectKey:we},T)):ue.push(new o.a5(N,T[we],`unknown property "${we}"`))}for(const we in B){if(W[we])continue;const Te=B[we];Te.required&&Te.default===void 0&&T[we]===void 0&&ue.push(new o.V(N,T,`missing required property "${we}"`))}return ue}function Gs({key:R,value:N}){const T=cn({key:R,value:N});if(T.length)return T;const B=N;return B.indexOf("{fontstack}")===-1&&T.push(new o.V(R,N,'"glyphs" url must include a "{fontstack}" token')),B.indexOf("{range}")===-1&&T.push(new o.V(R,N,'"glyphs" url must include a "{range}" token')),T}function an(R,N=o.a8,T={}){return Pn({key:T.key||"",value:R,valueSpec:Object.assign(N.$root,{"*":{type:"*"}}),styleSpec:N,style:R,objectElementValidators:{glyphs:Gs}})}function tr(R,N=o.a8){return Zs(an(R,N))}const Lr=R=>Zs(Tn(R)),Yt=R=>Zs(fs(R)),it=R=>Zs(wn(R)),gt=R=>Zs(As(R)),ft=R=>Zs(Ss(R)),Lt=R=>Zs(function(N){const T=N.value,B=N.style,W=N.styleSpec,Q=W.snow;if(T===void 0)return[];if(!o.K(T))return[new o.V("snow",T,`object expected, ${o.M(T)} found`)];let se=[];for(const ue in T){const we=ue.match(/^(.*)-transition$/);se=se.concat(we&&Q[we[1]]&&Q[we[1]].transition?hn({key:ue,value:T[ue],valueSpec:W.transition,style:B,styleSpec:W}):Q[ue]?hn({key:ue,value:T[ue],valueSpec:Q[ue],style:B,styleSpec:W}):[new o.a5(ue,T[ue],`unknown property "${ue}"`)])}return se}(R)),Mt=R=>Zs(function(N){const T=N.value,B=N.style,W=N.styleSpec,Q=W.rain;if(T===void 0)return[];if(!o.K(T))return[new o.V("rain",T,`object expected, ${o.M(T)} found`)];let se=[];for(const ue in T){const we=ue.match(/^(.*)-transition$/);se=se.concat(we&&Q[we[1]]&&Q[we[1]].transition?hn({key:ue,value:T[ue],valueSpec:W.transition,style:B,styleSpec:W}):Q[ue]?hn({key:ue,value:T[ue],valueSpec:Q[ue],style:B,styleSpec:W}):[new o.a5(ue,T[ue],`unknown property "${ue}"`)])}return se}(R)),Qt=R=>Zs(Fs(R)),ks=R=>Zs(Es(R)),gs=R=>Zs(bn(R)),Vt=R=>Zs(cr(R)),Vs=R=>Zs(o.a9(R));function Zs(R){return R.slice().sort((N,T)=>N.line&&T.line?N.line-T.line:0)}function Zn(R,N){let T=!1;if(N&&N.length)for(const B of N)B instanceof o.a5?o.w(B.message):(R.fire(new o.B(new Error(B.message))),T=!0);return T}const Or=o.a8.light;let oa;class aa extends o.E{constructor(N,T="flat"){super(),this._transitionable=new o.aa(oa||(oa=new o.ab({anchor:new o.ac(Or.anchor),position:new o.ad(Or.position),color:new o.ac(Or.color),intensity:new o.ac(Or.intensity)}))),this.setLight(N,T),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(N,T,B={}){this._validate(Yt,N,B)||(this._transitionable.setTransitionOrValue(N),this.id=T)}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}_validate(N,T,B){return(!B||B.validate!==!1)&&Zn(this,N.call(tr,Object.assign({value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const Kr=o.a8.terrain;let Tr=class extends o.E{constructor(R,N,T,B,W){super(),this.scope=T,this._transitionable=new o.aa(new o.ab({source:new o.ac(Kr.source),exaggeration:new o.ac(Kr.exaggeration)}),T,B),this._transitionable.setTransitionOrValue(R,B),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=N,this.worldview=W}get(){return this._transitionable.serialize()}set(R,N){this._transitionable.setTransitionOrValue(R,N)}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}getExaggeration(R){return this._transitioning.possiblyEvaluate(new o.ae(R,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const R=this._transitionable._values.exaggeration;if(!R)return null;const N=R.value.expression;if(!N)return null;let T=-1,B=-1,W=1;for(const Q of N.zoomStops)W=N.evaluate(new o.ae(Q,{worldview:this.worldview})),W>.01?(T=Q,B=-1):B=Q;return W<.01&&T>0&&B>T?[T,B]:null}isZoomDependent(){const R=this._transitionable._values.exaggeration;return R!=null&&R.value!=null&&R.value.expression!=null&&R.value.expression instanceof o.af}};const Hr=.05;function Ba(R,N,T,B){const W=o.aj(45,65,T),[Q,se]=Ja(R,B);let ue=1-Math.min(1,Math.exp((N-Q)/(se-Q)*-6));return ue*=ue*ue,ue=Math.min(1,1.00747*ue),ue*W*R.alpha}function Ja(R,N){const T=.5/Math.tan(.5*N);return[R.range[0]+T,R.range[1]+T]}function Ro(R,N,T,B,W){const Q=o.ah([],[N,T,B],W.mercatorFogMatrix);return Ba(R,o.ai(Q),W.pitch,W._fov)}function ji(R,N,T,B,W,Q,se){const ue=[[T,B,0],[W,B,0],[W,Q,0],[T,Q,0]];let we=Number.MAX_VALUE,Te=-Number.MAX_VALUE;for(const De of ue){const Qe=o.ah([],De,N),Ye=o.ai(Qe);we=Math.min(we,Ye),Te=Math.max(Te,Ye)}return[Ba(R,we,se.pitch,se._fov),Ba(R,Te,se.pitch,se._fov)]}const Oa=o.a8.fog;class Ao extends o.E{constructor(N,T,B,W){super();const Q=new o.ab({range:new o.ac(Oa.range),color:new o.ac(Oa.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Oa["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Oa["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Oa["horizon-blend"]),"star-intensity":new o.ac(Oa["star-intensity"]),"vertical-range":new o.ac(Oa["vertical-range"])});this._transitionable=new o.aa(Q,B,new Map(W)),this.set(N,W),this._transitioning=this._transitionable.untransitioned(),this._transform=T,this.properties=new o.ak(Q),this.scope=B}get state(){const N=this._transform,T=N.projection.name==="globe",B=o.al(N.zoom),W=this.properties.get("range"),Q=[.5,3];return{range:T?[o.am(Q[0],W[0],B),o.am(Q[1],W[1],B)]:W,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(N,T,B={}){if(this._validate(ft,N,B))return;const W=Object.assign({},N);for(const Q of Object.keys(Oa))W[Q]===void 0&&(W[Q]=Oa[Q].default);this._options=W,this._transitionable.setTransitionOrValue(this._options,T)}getOpacity(N){if(!this._transform.projection.supportsFog)return 0;const T=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,N))*T.a}getOpacityAtLatLng(N,T){return this._transform.projection.supportsFog?function(B,W,Q){const se=o.ag.fromLngLat(W),ue=Q.elevation?Q.elevation.getAtPointOrZero(se):0;return Ro(B,se.x,se.y,ue,Q)}(this.state,N,T):0}getOpacityForTile(N){if(!this._transform.projection.supportsFog)return[1,1];const T=this._transform.calculateFogTileMatrix(N.toUnwrapped());return ji(this.state,T,0,0,o.an,o.an,this._transform)}getOpacityForBounds(N,T,B,W,Q){return this._transform.projection.supportsFog?ji(this.state,N,T,B,W,Q,this._transform):[1,1]}getFovAdjustedRange(N){return this._transform.projection.supportsFog?Ja(this.state,N):[0,1]}isVisibleOnFrustum(N){if(!this._transform.projection.supportsFog)return!1;const T=[4,5,6,7];for(const B of T){const W=N.points[B];let Q;if(W[2]>=0)Q=W;else{const se=N.points[B-4];Q=o.ao(se,W,se[2]/(se[2]-W[2]))}if(Ro(this.state,Q[0],Q[1],0,this._transform)>=Hr)return!0}return!1}updateConfig(N){this._transitionable.setTransitionOrValue(this._options,new Map(N))}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}_validate(N,T,B){return(!B||B.validate!==!1)&&Zn(this,N.call(tr,Object.assign({value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let uo,Ua,Eo,Ji=class extends o.E{constructor(R,N,T,B){super();const W=uo||(uo=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(W,T,new Map(B)),this.set(R,B),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(W),this.scope=T}get state(){const R=this.properties.get("opacity"),N=this.properties.get("color"),T=this.properties.get("direction"),B=o.ap(T[0]),W=-Math.max(o.ap(T[1]),.01),Q=[Math.cos(B)*Math.cos(W),Math.sin(B)*Math.cos(W),Math.sin(W)],se=this.properties.get("vignette"),ue=this.properties.get("vignette-color");return ue.a=se,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(N.r,N.g,N.b,N.a*R),direction:Q,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:ue}}get(){return this._transitionable.serialize()}set(R,N,T={}){if(this._validate(Lt,R,T))return;const B=Object.assign({},R),W=o.a8.snow;for(const Q of Object.keys(W))B[Q]===void 0&&(B[Q]=W[Q].default);this._options=B,this._transitionable.setTransitionOrValue(this._options,N)}updateConfig(R){this._transitionable.setTransitionOrValue(this._options,new Map(R))}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}_validate(R,N,T){return(!T||T.validate!==!1)&&Zn(this,R.call(tr,Object.assign({value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},qa=class extends o.E{constructor(R,N,T,B){super();const W=Ua||(Ua=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(W,T,new Map(B)),this.set(R,B),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(W),this.scope=T}get state(){const R=this.properties.get("opacity"),N=this.properties.get("color"),T=this.properties.get("direction"),B=o.ap(T[0]),W=-Math.max(o.ap(T[1]),.01),Q=[Math.cos(B)*Math.cos(W),Math.sin(B)*Math.cos(W),Math.sin(W)],se=this.properties.get("vignette-color");return se.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(N.r,N.g,N.b,N.a*R),direction:Q,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:se}}get(){return this._transitionable.serialize()}set(R,N,T={}){if(this._validate(Mt,R,T))return;const B=Object.assign({},R),W=o.a8.rain;for(const Q of Object.keys(W))B[Q]===void 0&&(B[Q]=W[Q].default);this._options=B,this._transitionable.setTransitionOrValue(this._options,N)}updateConfig(R){this._transitionable.setTransitionOrValue(this._options,new Map(R))}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}_validate(R,N,T){return(!T||T.validate!==!1)&&Zn(this,R.call(tr,Object.assign({value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class ar extends o.E{constructor(N,T,B,W){super(),this.scope=B,this._options=N,this.properties=new o.ak(T),this._transitionable=new o.aa(T,B,new Map(W)),this._transitionable.setTransitionOrValue(N.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(N){this._transitionable.setTransitionOrValue(this._options.properties,new Map(N))}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(N,T){this._options=N,this._transitionable.setTransitionOrValue(N.properties,T)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const ui=()=>Eo||(Eo=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 zo;const gl=()=>zo||(zo=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 tl{constructor(N,T,B){this.screenBounds=N,this.cameraPoint=B.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=T,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,B)}static createFromScreenPoints(N,T){let B,W;if(N instanceof o.P||typeof N[0]=="number"){const Q=o.P.convert(N);B=[Q],W=T.isPointAboveHorizon(Q)}else{const Q=o.P.convert(N[0]),se=o.P.convert(N[1]),ue=Q.add(se)._div(2);B=[Q,se],W=o.as(Q,se).every(we=>T.isPointAboveHorizon(we))&&T.isPointAboveHorizon(ue)}return new tl(B,W,T)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(N){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],N)}bufferedCameraGeometry(N){const T=this.screenBounds[0],B=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],W=o.as(T,B,0,!1);return this.cameraPoint.y>B.y&&(this.cameraPoint.x>T.x&&this.cameraPoint.x=B.x?W[2]=this.cameraPoint:this.cameraPoint.x<=T.x&&(W[3]=this.cameraPoint)),o.at(W,N)}bufferedCameraGeometryGlobe(N){const T=this.screenBounds[0],B=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],W=o.as(T,B,N),Q=this.cameraPoint.clone(),se=+(Q.x>T.x)+ +(Q.x>B.x);switch(3*(+(Q.y>T.y)+ +(Q.y>B.y))+se){case 0:W[0]=Q,W[4]=Q.clone();break;case 1:W.splice(1,0,Q);break;case 2:W[1]=Q;break;case 3:W.splice(4,0,Q);break;case 5:W.splice(2,0,Q);break;case 6:W[3]=Q;break;case 7:W.splice(3,0,Q);break;case 8:W[2]=Q}return W}containsTile(N,T,B,W=0){const Q=Math.max(N.queryPadding,N.evaluateQueryRenderedFeaturePadding())/T._pixelsPerMercatorPixel+1,se=B?this._bufferedCameraMercator(Q,T):this._bufferedScreenMercator(Q,T);let ue=N.tileID.wrap+(se.unwrapped?W:0);const we=se.polygon.map(St=>o.au(N.tileTransform,St,ue));if(!o.av(we,0,0,o.an,o.an))return;ue=N.tileID.wrap+(this.screenGeometryMercator.unwrapped?W:0);const Te=this.screenGeometryMercator.polygon.map(St=>o.aw(N.tileTransform,St,ue)),De=Te.map(St=>new o.P(St[0],St[1])),Qe=T.getFreeCameraOptions().position||new o.ag(0,0,0),Ye=o.aw(N.tileTransform,Qe,ue),tt=Te.map(St=>{const kt=o.ax(St,St,Ye);return o.ay(kt,kt),new o.az(Ye,kt)}),ht=o.aA(N,1,T.zoom)*T._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:De,tilespaceRays:tt,bufferedTilespaceGeometry:we,bufferedTilespaceBounds:(ct=o.aB(we),ct.min.x=o.aC(ct.min.x,0,o.an),ct.min.y=o.aC(ct.min.y,0,o.an),ct.max.x=o.aC(ct.max.x,0,o.an),ct.max.y=o.aC(ct.max.y,0,o.an),ct),tile:N,tileID:N.tileID,pixelToTileUnitsFactor:ht};var ct}_bufferedScreenMercator(N,T){const B=uh(N);if(this._screenRaycastCache[B])return this._screenRaycastCache[B];{let W;return W=T.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(N),T):{polygon:this.bufferedScreenGeometry(N).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._screenRaycastCache[B]=W,W}}_bufferedCameraMercator(N,T){const B=uh(N);if(this._cameraRaycastCache[B])return this._cameraRaycastCache[B];{let W;return W=T.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(N),T):{polygon:this.bufferedCameraGeometry(N).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._cameraRaycastCache[B]=W,W}}_projectAndResample(N,T){const B=function(Q,se){const ue=o.aD([],se.pixelMatrix,se.globeMatrix),we=[0,-o.aF,0,1],Te=[0,o.aF,0,1],De=[0,0,0,1];o.aE(we,we,ue),o.aE(Te,Te,ue),o.aE(De,De,ue);const Qe=new o.P(we[0]/we[3],we[1]/we[3]),Ye=new o.P(Te[0]/Te[3],Te[1]/Te[3]),tt=o.aG(Q,Qe)&&we[3]1?Ll(Q.slice(0,St),se):[],Xt=Stnew o.P(Ku(Cs.x),Cs.y)),Xt=Xt.map(Cs=>new o.P(Ku(Cs.x),Cs.y));const Et=[...Ut];Et.length===0&&Et.push(Xt[Xt.length-1]);const Ts=o.am(Et[Et.length-1].y,(Xt.length===0?Ut[0]:Xt[0]).y,kt);let ds;return ds=tt?[new o.P(0,Ts),new o.P(0,0),new o.P(1,0),new o.P(1,Ts)]:[new o.P(1,Ts),new o.P(1,1),new o.P(0,1),new o.P(0,Ts)],Et.push(...ds),Xt.length===0?Et.push(Ut[0]):Et.push(...Xt),{polygon:Et.map(Cs=>new o.ag(Cs.x,Cs.y)),unwrapped:!1}}(N,T);if(B)return B;const W=function(Q,se){let ue=!1,we=-1/0,Te=0;for(let Qe=0;Qewe&&(we=Q[Qe].x,Te=Qe);for(let Qe=0;Qe.5&&(tt.x{Qe.x-=1}),{polygon:Q,unwrapped:ue}}(Ll(N,T).map(Q=>new o.P(Ku(Q.x),Q.y)),T);return{polygon:W.polygon.map(Q=>new o.ag(Q.x,Q.y)),unwrapped:W.unwrapped}}}function Ll(R,N){return o.aI(R,T=>{const B=N.pointCoordinate3D(T);T.x=B.x,T.y=B.y},1/256)}function Ku(R){return R<0?1+R%1:R%1}function uh(R){return 100*R|0}function ym(R,N,T){try{N=function(W){if(!W.variants)return W;if(!Array.isArray(W.variants))throw new Error("variants must be an array");for(const Q of W.variants){if(Q==null||typeof Q!="object"||Q.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Q.capabilities))throw new Error("capabilities must be an array");if(Q.capabilities.length===1&&Q.capabilities[0]==="meshopt")return Object.assign(W,Q)}return W}(N)}catch(W){return new Error("Failed to process TileJSON variants",{cause:W})}const B=o.aJ(Object.assign({},N,R),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return R.url&&N.tiles&&R.tiles&&(B.tiles=N.tiles),B.tiles=T.canonicalizeTileset(B,R.url),B}function Ld(R,N,T,B,W){const Q=function(ue,we){if(ue)return W(ue);if(we){R.url&&we.tiles&&R.tiles&&delete R.tiles;const Te=ym(R,we,N);if(Te instanceof Error)return W(Te);W(null,Te)}},se=function(ue,we,Te){if(!ue)return null;if(!we&&!Te)return ue;Te=Te||ue.worldview_default;const De=Object.values(ue.language||{});if(De.length===0)return null;const Qe=Object.values(ue.worldview||{});if(Qe.length===0)return null;const Ye=De.every(ht=>ht===we),tt=Qe.every(ht=>ht===Te);return Ye&&tt?ue:we in(ue.language_options||{})||Te in(ue.worldview_options||{})?null:ue.language_options&&ue.worldview_options?ue:null}(R.data,T,B);return se?o.o.frame(()=>Q(null,se)):R.url?o.m(N.transformRequest(N.normalizeSourceURL(R.url,null,T,B),o.R.Source),Q):o.o.frame(()=>{const{data:ue,...we}=R;Q(null,we)})}function Bm(R,N){const T=Math.pow(2,N.z),B=Math.floor(o.aH(R.getWest())*T),W=Math.floor(o.aL(R.getNorth())*T),Q=Math.ceil(o.aH(R.getEast())*T),se=Math.ceil(o.aL(R.getSouth())*T);return N.x>=B&&N.x=W&&N.ythis.maxzoom||N.z{this._tileJSONRequest=null,this._loaded=!0,se?(T&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${T}`),B&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${B}`),this.fire(new o.B(se))):ue&&(this._setTileJSON(ue),ve(ue.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"}))),N&&N(se)};this.provider=this._options.provider;const Q=function(se){if("provider"in se&&!se.provider)return null;let ue=se.provider;if(!ue&&"url"in se&&se.url&&(ue=o.aM(se.url)),!ue)return null;const we=o.g.TILE_PROVIDER_URLS[ue];if(!we)return null;let Te;try{Te=new URL(we,o.g.API_URL).href}catch{return o.w(`TileProvider "${ue}" has an invalid URL: "${we}"`),null}return{name:ue,url:Te}}(this._options);if(this.provider&&!Q)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(N&&N());this._tileJSONRequest=Q?this._loadWithProvider(Q,W):Ld(this._options,this.map._requestManager,T,B,W)}_loadWithProvider(N,T){this.provider=N.name;const B=new AbortController,W=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,Q=W?Object.assign({},this._options,{url:W.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:N.name,url:N.url,source:this.id,scope:this.scope,type:this.type,options:Q,request:W},(se,ue)=>{if(B.signal.aborted)return;if(se)return void T(se);const we=ue?ue.find(Te=>Te!=null):null;if(we){const Te=ym(this._options,we,this.map._requestManager);Te instanceof Error?T(Te):T(null,Te)}else T(null,{tiles:this._options.tiles})}),{cancel:()=>{B.abort()}}}_setTileJSON(N){if(Object.assign(this,N),this.hasWorldviews=!!N.worldview_options,N.worldview_default&&(this.worldviewDefault=N.worldview_default),N.vector_layers){this.vectorLayers=N.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const T of N.vector_layers)this.vectorLayerIds.push(T.id),N.worldview&&N.worldview[T.source]&&this.localizableLayerIds.add(T.id)}this.tileBounds=Sl.fromTileJSON(N)}loaded(){return this._loaded}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}onAdd(N){this.map=N,this.load()}reload(){this.cancelTileJSONRequest();const N=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(N))}setTiles(N){return this._options.tiles=N,this.reload(),this}setUrl(N){return this.url=N,this._options.url=N,this.reload(),this}onRemove(N){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(N,T){const B=N.tileID.canonical.url(this.tiles,this.scheme),W=this.map._requestManager.normalizeTileURL(B),Q=this.map._requestManager.transformRequest(W,o.R.Tile),se=this.map.style?this.map.style.getLut(this.scope):null,ue=se?{image:se.image.clone()}:null,we={request:Q,data:void 0,uid:N.uid,tileID:N.tileID,tileZoom:N.tileZoom,zoom:N.tileID.overscaledZ,maxZoom:this.maxzoom,lut:ue,tileSize:this.tileSize*N.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:N.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:N.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.e(B)&&(we.localizableLayerIds=this.localizableLayerIds),we.request.collectResourceTiming=this._collectResourceTiming,N.actor&&N.state!=="expired")N.state==="loading"?N.reloadCallback=T:N.request=N.actor.send("reloadTile",we,Te.bind(this));else if(N.actor=this._tileWorkers[W]=this._tileWorkers[W]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)N.request=N.actor.send("loadTile",we,Te.bind(this),void 0,!0);else{const De=o.aO.call({deduped:this._deduped},we,(Qe,Ye)=>{if(Qe||!Ye)Te.call(this,Qe);else{const tt=o.aP(Ye.responseHeaders);we.data={rawData:Ye.rawData.slice(0),expires:tt.expires,cacheControl:tt.cacheControl},N.actor&&N.actor.send("loadTile",we,Te.bind(this),void 0,!0)}},!0);N.request={cancel:De}}function Te(De,Qe){return delete N.request,N.aborted?T(null):De?T(De):(Qe&&Qe.resourceTiming&&(N.resourceTiming=Qe.resourceTiming),this.map._refreshExpiredTiles&&Qe&&N.setExpiryData(Qe),N.loadVectorData(Qe,this.map.painter),o.aQ(this.dispatcher),T(null,Qe),void(N.reloadCallback&&(this.loadTile(N,N.reloadCallback),N.reloadCallback=null)))}}abortTile(N){N.request&&(N.request.cancel(),delete N.request),N.actor&&N.actor.send("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(N,T){N.actor&&N.actor.send("removeTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope}),N.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class js extends o.E{constructor(N,T,B,W){super(),this.id=N,this.dispatcher=B,this.setEventedParent(W),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},T),Object.assign(this,o.aJ(T,["url","scheme","tileSize"]))}load(N){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const T=this.map.getWorldview();this._tileJSONRequest=Ld(this._options,this.map._requestManager,null,T,(B,W)=>{this._tileJSONRequest=null,this._loaded=!0,B?this.fire(new o.B(B)):W&&(Object.assign(this,W),W.raster_layers&&(this.rasterLayers=W.raster_layers,this.rasterLayerIds=this.rasterLayers.map(Q=>Q.id)),this.tileBounds=Sl.fromTileJSON(W),ve(W.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),N&&N(B)})}loaded(){return this._loaded}onAdd(N){this.map=N,this.load()}reload(){this.cancelTileJSONRequest();const N=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(N))}setTiles(N){return this._options.tiles=N,this.reload(),this}setUrl(N){return this.url=N,this._options.url=N,this.reload(),this}onRemove(N){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}loadTile(N,T){const B=o.o.devicePixelRatio>=2,W=this.map._requestManager.normalizeTileURL(N.tileID.canonical.url(this.tiles,this.scheme),B,this.tileSize);N.request=o.n(this.map._requestManager.transformRequest(W,o.R.Tile),(Q,se,ue)=>{if(delete N.request,N.aborted)return N.state="unloaded",T(null);if(Q)return N.state="errored",T(Q);if(!se)return T(null);const we=o.aP(ue);this.map._refreshExpiredTiles&&N.setExpiryData(we),N.setTexture(se,this.map.painter),N.state="loaded",o.aQ(this.dispatcher),T(null)})}abortTile(N,T){N.request&&(N.request.cancel(),delete N.request),T&&T()}unloadTile(N,T){N.texture&&N.texture instanceof o.T?(N.destroy(!1),N.texture&&N.texture instanceof o.T&&this.map.painter.saveTileTexture(N.texture)):N.destroy(),T&&T()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Ma([R,N],T,B,{scaled:W=!0}={}){const{tileSize:Q,buffer:se}=B,{x:ue,y:we,z:Te}=T;if(!isFinite(ue)||!isFinite(we)||!isFinite(Te))throw new Error("Invalid MRT header");const De=2**Te,Qe=De*o.aH(R),Ye=De*o.aL(N);return function([tt,ht],ct,{scaled:St=!0}={}){if(!ct)throw new Error("bandView is undefined");const{data:kt,tileSize:Ut,buffer:Xt,offset:Et,scale:Ts,dimension:ds}=ct;if(tt<-Xt||tt>Ut+Xt||ht<-Xt||ht>Ut+Xt)throw new Error(`Point (${tt}, ${ht}) out of bounds for tileSize=${Ut}, buffer=${Xt}`);const Cs=(ht+Xt)*(Ut+2*Xt)+(tt+Xt);if(new Uint32Array(kt.buffer)[Cs]===4294967295)return null;let es=[];es=St?[]:new ct.data.constructor(ds);for(let is=0;is{if(delete N.request,N.aborted)return N.state="unloaded",T(null);if(ue)return ue.name==="AbortError"?void 0:(N.state="errored",T(ue));if(this.map._refreshExpiredTiles&&we){const De=o.aP(Te);N.setExpiryData(De)}if(this.partial&&N.state!=="expired")N.state="empty";else if(!this.partial){if(!we)return T(null);N.state="loaded",N._isHeaderLoaded=!0,N._mrt=we}T(null)};N.request=this.partial?N.fetchHeader(void 0,se.bind(this)):N.actor.send("loadTile",Q,se.bind(this),void 0,!0)}abortTile(N){N.request&&(N.request.cancel(),delete N.request),N.actor&&N.actor.send("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(N,T){const B=N.texturePerLayer;if(N.flushAllQueues(),B.size){N.destroy(!1);for(const W of B.values())this.map.painter.saveTileTexture(W)}else N.destroy()}prepareTile(N,T,B,W){N._isHeaderLoaded&&(N.state!=="empty"&&(N.state="reloading"),N.fetchBandForRender(T,B,W,(Q,se)=>{Q?(N.state="errored",this.fire(new o.B(Q))):se&&(N._isHeaderLoaded=!0,N.setTexturePerLayer(B,se,this.map.painter),N.state="loaded"),this.triggerRepaint(N)}))}getInitialBand(N){if(!this.rasterLayers)return 0;const T=this.rasterLayers.find(({id:Q})=>Q===N),B=T&&T.fields,W=B&&B.bands&&B.bands;return W?W[0]:0}getTextureDescriptor(N,T,B){if(!N)return;const W=T.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!W)return;let Q=null;T instanceof o.aS?Q=T.paint.get("raster-array-band"):T instanceof o.aT&&(Q=T.paint.get("raster-particle-array-band"));const se=Q||this.getInitialBand(W);if(se==null)return;if(!N.textureDescriptorPerLayer.get(T.id))return void this.prepareTile(N,W,T.id,se);if(N.updateNeeded(T.id,se)&&!B)return;const ue=N.textureDescriptorPerLayer.get(T.id);return Object.assign({},ue,{texture:N.texturePerLayer.get(T.id)})}getImages(N,T){const B=new Map;for(const W of N)for(const Q of T){const[se,ue]=Q.split("/"),we=W.getLayer(se);if(!we||!we.hasBand(ue)||!we.hasDataForBand(ue))continue;const{bytes:Te,tileSize:De,buffer:Qe}=we.getBandView(ue),Ye=De+2*Qe,tt={data:new o.q({width:Ye,height:Ye},Te),pixelRatio:2,sdf:!1,usvg:!1,version:0};B.set(Q,tt)}return B}queryRasterArrayValueByBandId(N,T,B){const W=T._mrt;return new Promise(Q=>{const se={},ue=new Set;for(const[we,Te]of Object.entries(W.layers)){if(B.layerName&&we!==B.layerName)continue;const De={};se[we]=De;for(const{bands:Qe}of Te.dataIndex)for(const Ye of Qe)B.bands&&!B.bands.includes(Ye)||(ue.add(o.F(we,Ye)),T.fetchBand(we,null,Ye,tt=>{o.o.frame(()=>{De[Ye]=tt?null:Ma([N.lng,N.lat],W,Te.getBandView(Ye)),ue.delete(o.F(we,Ye)),ue.size===0&&Q(se)})},!1))}ue.size===0&&Q(se)})}_loadTileForQuery(N,T){if(this._loadTileLoaded[N.uid])return void T(null,N._mrt);if(this._loadTilePending[N.uid])return void this._loadTilePending[N.uid].push(T);this._loadTilePending[N.uid]=[T];const B=this.map._requestManager.normalizeTileURL(N.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),W=this.map._requestManager.transformRequest(B,o.R.Tile);N.actor.send("loadTile",{request:W,uid:N.uid,tileID:N.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(Q,se,ue)=>{if(Q)return this._loadTilePending[N.uid].forEach(we=>we(Q,null)),void delete this._loadTilePending[N.uid];if(!se)return this._loadTilePending[N.uid].forEach(we=>we(null,null)),void delete this._loadTilePending[N.uid];if(this.map._refreshExpiredTiles&&se){const we=o.aP(ue);N.setExpiryData(we)}N._mrt=se,N._isHeaderLoaded=!0,N.state="loaded",this._loadTilePending[N.uid].forEach(we=>we(null,se)),this._loadTileLoaded[N.uid]=!0,delete this._loadTilePending[N.uid]},void 0,!0)}queryRasterArrayValueByAllBands(N,T,B){return new Promise((W,Q)=>{this._loadTileForQuery(T,(se,ue)=>{se?Q(se):W(ue?this.queryRasterArrayValueByBandId(N,T,B):null)})})}queryRasterArrayValue(N,T){const B=o.aU.convert(N),W=this.findLoadedParent(B);return W&&W._mrt?T.bands||!this.partial?this.queryRasterArrayValueByBandId(B,W,T):this.queryRasterArrayValueByAllBands(B,W,T):Promise.resolve(null)}findLoadedParent(N){const T=o.ag.fromLngLat(N,this.map.transform.tileSize),B=this.maxzoom+1,W=1<0&&(ue[new o.aR(R.overscaledZ,W,N.z,B,N.y-1).key]={backfilled:!1},ue[new o.aR(R.overscaledZ,R.wrap,N.z,N.x,N.y-1).key]={backfilled:!1},ue[new o.aR(R.overscaledZ,se,N.z,Q,N.y-1).key]={backfilled:!1}),N.y+1{if(this._loaded=!0,this._pendingLoad=null,B)this.fire(new o.B(B));else{const Q={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&W&&W.resourceTiming&&W.resourceTiming[this.id]&&(Q.resourceTiming=W.resourceTiming[this.id]),R&&(this._partialReload=!0),this.fire(new o.C("data",Q)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(R),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const R=o.F(this.id,this.scope);this.map.style.clearSource(R),this._updateWorkerData()}loadTile(R,N){const T=R.actor?"reloadTile":"loadTile";R.actor=this.actor;const B=this.map.style?this.map.style.getLut(this.scope):null,W=B?{image:B.image.clone()}:null,Q=this._partialReload,se={type:this.type,uid:R.uid,tileID:R.tileID,tileZoom:R.tileZoom,zoom:R.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:W,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:R.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:Q,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};R.request=this.actor.send(T,se,(ue,we)=>Q&&!we?(R.state="loaded",N(null)):(delete R.request,R.destroy(!1),R.aborted?N(null):ue?N(ue):(R.loadVectorData(we,this.map.painter,T==="reloadTile"),N(null))),void 0,T==="loadTile")}abortTile(R){R.request&&(R.request.cancel(),delete R.request),R.aborted=!0}unloadTile(R,N){this.actor.send("removeTile",{uid:R.uid,type:this.type,source:this.id,scope:this.scope}),R.destroy()}onRemove(R){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(R,N,T,B){super(R,N,T,B),this.roundZoom=!0,this.type="video",this.options=N}load(){this._loaded=!1;const R=this.options;this.urls=[];for(const N of R.urls)this.urls.push(this.map._requestManager.transformRequest(N,o.R.Source).url);o.aW(this.urls,(N,T)=>{this._loaded=!0,N?this.fire(new o.B(N)):T&&(this.video=T,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(R){if(this.video){const N=this.video.seekable;RN.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${N.start(0)} and ${N.end(0)}-second mark.`))):this.video.currentTime=R}}getVideo(){return this.video}onAdd(R){this.map||(this.map=R,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 R=this.map.painter.context,N=R.gl;this.texture?this.video.paused||(this.texture.bind(N.LINEAR,N.CLAMP_TO_EDGE),N.texSubImage2D(N.TEXTURE_2D,0,0,0,N.RGBA,N.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(R,this.video,N.RGBA8),this.texture.bind(N.LINEAR,N.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(R)}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(R,N,T,B){super(),this.type="batched-model",this.id=R,this.tileSize=512,this._options=N,this.tiles=this._options.tiles,this.maxzoom=N.maxzoom||19,this.minzoom=N.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=T,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(B)}onAdd(R){this.map=R,this.load()}reload(){this.cancelTileJSONRequest();const R=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(R))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(R){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const N=Array.isArray(this.map._language)?this.map._language.join():this.map._language,T=this.map.getWorldview();this._tileJSONRequest=Ld(this._options,this.map._requestManager,N,T,(B,W)=>{this._tileJSONRequest=null,this._loaded=!0,B?(N&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${N}`),T&&T.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${T}`),this.fire(new o.B(B))):W&&(Object.assign(this,W),W.bounds&&(this.tileBounds=new Sl(W.bounds,this.minzoom,this.maxzoom)),ve(W.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"}))),R&&R(B)})}hasTransition(){return!1}hasTile(R){return!this.tileBounds||this.tileBounds.contains(R.canonical)}loaded(){return this._loaded}loadTile(R,N){const T=this.map._requestManager.normalizeTileURL(R.tileID.canonical.url(this.tiles,this.scheme)),B={request:this.map._requestManager.transformRequest(T,o.R.Tile),data:void 0,uid:R.uid,tileID:R.tileID,tileZoom:R.tileZoom,zoom:R.tileID.overscaledZ,tileSize:this.tileSize*R.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:R.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(R.actor&&R.state!=="expired")if(R.state==="loading")R.reloadCallback=N;else{if(R.buckets){const Q=Object.values(R.buckets);for(const se of Q)se.dirty=!0;return void(R.state="loaded")}R.request=R.actor.send("reloadTile",B,W.bind(this))}else R.actor=this.dispatcher.getActor(),R.request=R.actor.send("loadTile",B,W.bind(this),void 0,!0);function W(Q,se){return R.aborted?N(null):Q&&Q.status!==404?N(Q):(this.map._refreshExpiredTiles&&se&&R.setExpiryData(se),R.loadModelData(se,this.map.painter),R.state="loaded",void N(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(R,N,T,B){super(R,N,T,B),N.coordinates?Array.isArray(N.coordinates)&&N.coordinates.length===4&&!N.coordinates.some(W=>!Array.isArray(W)||W.length!==2||W.some(Q=>typeof Q!="number"))||this.fire(new o.B(new o.V(`sources.${R}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${R}`,null,'missing required property "coordinates"'))),N.animate&&typeof N.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${R}`,null,'optional "animate" property must be a boolean value'))),N.canvas?typeof N.canvas=="string"||N.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${R}`,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.${R}`,null,'missing required property "canvas"'))),this.options=N,this.animate=N.animate===void 0||N.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(R){this.map=R,this.load(),this.canvas&&this.animate&&this.play()}onRemove(R){this.pause()}prepare(){let R=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,R=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,R=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const N=this.map.painter.context;this.texture?!R&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(N,this.canvas,N.gl.RGBA8,{premultiply:!0}),this._prepareData(N)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const R of[this.canvas.width,this.canvas.height])if(isNaN(R)||R<=0)return!0;return!1}},custom:class extends o.E{constructor(R,N,T,B){super(),this.id=R,this.type="custom",this._dataType="raster",this._dispatcher=T,this._implementation=N,this.setEventedParent(B),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 Sl(this._implementation.bounds,this.minzoom,this.maxzoom));const W=N;W.update=this._update.bind(this),W.clearTiles=this._clearTiles.bind(this),W.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(N,["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(R){this.map=R,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(R),this.load()}onRemove(R){this._implementation.onRemove&&this._implementation.onRemove(R)}hasTile(R){if(this._implementation.hasTile){const{x:N,y:T,z:B}=R.canonical;return this._implementation.hasTile({x:N,y:T,z:B})}return!this.tileBounds||this.tileBounds.contains(R.canonical)}loadTile(R,N){const{x:T,y:B,z:W}=R.tileID.canonical,Q=new AbortController,se=Promise.resolve(this._implementation.loadTile({x:T,y:B,z:W},{signal:Q.signal})).then((function(ue){return delete R.request,R.aborted?(R.state="unloaded",N(null)):ue===void 0?(R.state="errored",N(null)):ue===null?(this.loadTileData(R,{width:this.tileSize,height:this.tileSize,data:null}),R.state="loaded",N(null)):function(we){return we instanceof ImageData||we instanceof HTMLCanvasElement||we instanceof ImageBitmap||we instanceof HTMLImageElement}(ue)?(this.loadTileData(R,ue),R.state="loaded",void N(null)):(R.state="errored",N(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(ue=>{ue.name!=="AbortError"&&(R.state="errored",N(ue))});se.cancel=()=>Q.abort(),R.request=se}loadTileData(R,N){R.setTexture(N,this.map.painter)}unloadTile(R,N){if(R.texture&&R.texture instanceof o.T?(R.destroy(!1),R.texture&&R.texture instanceof o.T&&this.map.painter.saveTileTexture(R.texture)):R.destroy(),this._implementation.unloadTile){const{x:T,y:B,z:W}=R.tileID.canonical;this._implementation.unloadTile({x:T,y:B,z:W})}N&&N()}abortTile(R,N){R.request&&R.request.cancel&&(R.request.cancel(),delete R.request),N&&N()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(R=>({x:R.canonical.x,y:R.canonical.y,z:R.canonical.z}))}_clearTiles(){const R=o.F(this.id,this.scope);this.map.style.clearSource(R)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},so=function(R,N,T,B){const W=new Ta[N.type](R,N,T,B);if(W.id!==R)throw new Error(`Expected Source id to be ${R} instead of ${W.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],W),W};function ho(R,N,T=""){return`${T}:${N.id||""}:${N.layer.id}:${function(B){if("layerId"in B)return`layer:${B.layerId}`;{const{featuresetId:W,importId:Q}=B;return`featureset:${W}${Q?`:import:${Q}`:""}`}}(R.target)}`}function pi(R,N,T,B=""){if(R.uniqueFeatureID){const W=ho(R,N,B);if(T.has(W))return!0;T.add(W)}return!1}function $m(R,N,T,B,W=!1,Q=void 0){const se=N.sourceCache.transform,ue=N.sourceCache.tilesIn(R,N.has3DLayers,W);ue.sort($x);const we=[];for(const Te of ue){const De=Te.tile.queryRenderedFeatures(N,Te,T,B,se,W,Q);Object.keys(De).length&&we.push({wrappedTileID:Te.tile.tileID.wrapped().key,queryResults:De})}for(const Te in N.layers){const De=N.layers[Te];if(De.styleLayer){const Qe=De.styleLayer.queryRenderedFeatures(R,N.sourceCache,B);Object.keys(Qe).length&&we.push({wrappedTileID:0,queryResults:Qe})}}return we.length===0?{}:function(Te){const De={},Qe={};for(const Ye of Te){const tt=Ye.queryResults,ht=Ye.wrappedTileID,ct=Qe[ht]=Qe[ht]||{};for(const St in tt){const kt=tt[St],Ut=ct[St]=ct[St]||{},Xt=De[St]=De[St]||[];for(const Et of kt)Ut[Et.featureIndex]||(Ut[Et.featureIndex]=!0,Xt.push(Et))}}return De}(we)}function al(R,N,T,B,W,Q){const se={},ue=B.queryRenderedSymbols(R),we=[];for(const Te of Object.keys(ue).map(Number))we.push(W[Te]);we.sort($x);for(const Te of we){const De=Te.featureIndex.lookupSymbolFeatures(ue[Te.bucketInstanceId],Te.bucketIndex,Te.sourceLayerIndex,N,T,Q);for(const Qe in De){const Ye=se[Qe]=se[Qe]||[],tt=De[Qe];tt.sort((ht,ct)=>{const St=Te.featureSortOrder;if(St){const kt=St.indexOf(ht.featureIndex);return St.indexOf(ct.featureIndex)-kt}return ct.featureIndex-ht.featureIndex});for(const ht of tt)Ye.push(ht)}}return se}function vo(R,N){const T=R.getRenderableIds().map(Q=>R.getTileByID(Q)),B=[],W={};for(let Q=0;Q{if(Q)T(Q);else try{const we=B.getHeaderLength(se);if(we>N)return void(this.request=this.fetchHeader(we,T));B.parseHeader(se),this._isHeaderLoaded=!0;let Te=0;for(const De of Object.values(B.layers))Te=Math.max(Te,De.dataIndex[De.dataIndex.length-1].lastByte);se.byteLength>=Te&&(this.entireBuffer=se),T(null,this.entireBuffer||se,ue)}catch(we){T(we)}}),this.request}fetchBandForRender(N,T,B,W){this.fetchBand(N,T,B,Q=>{if(Q)return void W(Q);this.updateTextureDescriptor(N,T,B);const se=this.textureDescriptorPerLayer.get(T);W(null,se?se.img:null)})}fetchBand(N,T,B,W,Q=!0){const se=this._mrt;if(!this._isHeaderLoaded||!se)return void W(new Error("Tile header is not ready"));const ue=this.actor;if(!ue)return void W(new Error("Can't fetch tile band without an actor"));let we;const Te=o.F(String(B),o.F(this.tileID.key,N));let De=this._taskQueue.get(Te);De?De.add(W):(De=new Set,De.add(W),this._taskQueue.set(Te,De));const Qe=(ct,St)=>{we.complete(ct,St),ct?W(ct):(De.forEach(kt=>kt(null,St)),this._taskQueue.delete(Te))},Ye=(ct,St)=>{if(ct)return W(ct);const kt=ue.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:St,task:we},Qe,void 0,!0);if(T!==null){const Ut=this._workQueuePerLayer.get(T)||[];Ut.push(()=>{kt&&kt.cancel(),we.cancel()}),this._workQueuePerLayer.has(T)||this._workQueuePerLayer.set(T,Ut)}};let tt;try{tt=se.getLayer(N)}catch(ct){if(this.state==="reloading")return;throw ct}if(!tt)return void W(new Error(`Unknown sourceLayer "${N}"`));if(tt.hasDataForBand(B))return De.forEach(ct=>ct(null,null)),void this._taskQueue.delete(Te);const ht=tt.getDataRange([B]);if(we=se.createDecodingTask(ht),!we||we.tasks.length)if(T!==null&&this.flushQueues(T),this.entireBuffer)Ye(null,this.entireBuffer.slice(ht.firstByte,ht.lastByte+1));else{const ct=Object.assign({},this.requestParams,{headers:{Range:`bytes=${ht.firstByte}-${ht.lastByte}`}}),St=o.b1(ct,Ye);if(T!==null){const kt=this._fetchQueuePerLayer.get(T)||[];kt.push(()=>{St.cancel(),we.cancel()}),this._fetchQueuePerLayer.has(T)||this._fetchQueuePerLayer.set(T,kt)}}}updateNeeded(N,T){return(!this.textureDescriptorPerLayer.get(N)||this.textureDescriptorPerLayer.get(N).band!==T||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(N,T,B){if(!this._mrt)return;const W=this._mrt.getLayer(N);if(!W||!W.hasBand(B)||!W.hasDataForBand(B))return;const{bytes:Q,tileSize:se,buffer:ue,offset:we,scale:Te}=W.getBandView(B),De=se+2*ue,Qe=new o.q({width:De,height:De},Q),Ye=this.texturePerLayer.get(T);Ye&&Ye instanceof o.T&&Ye.update(Qe,{premultiply:!1}),this.textureDescriptorPerLayer.set(T,{layer:N,band:B,img:Qe,buffer:ue,offset:we,tileSize:se,format:W.pixelFormat,mix:[Te,256*Te,65536*Te,16777216*Te]})}destroy(N=!1){if(super.destroy(N),delete this._mrt,!N)for(const T of this.texturePerLayer.values())T&&T instanceof o.T&&T.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 yl{constructor(N,T){this.max=N,this.onRemove=T,this.reset()}reset(){for(const N in this.data)for(const T of this.data[N])T.timeout&&clearTimeout(T.timeout),this.onRemove(T.value);return this.data={},this.order=[],this}add(N,T,B){const W=N.wrapped().key;this.data[W]===void 0&&(this.data[W]=[]);const Q={value:T,timeout:void 0};if(B!==void 0&&(Q.timeout=setTimeout(()=>{this.remove(N,Q)},B)),this.data[W].push(Q),this.order.push(W),this.order.length>this.max){const se=this._getAndRemoveByKey(this.order[0]);se&&this.onRemove(se)}return this}has(N){return N.wrapped().key in this.data}getAndRemove(N){return this.has(N)?this._getAndRemoveByKey(N.wrapped().key):null}_getAndRemoveByKey(N){const T=this.data[N].shift();return T.timeout&&clearTimeout(T.timeout),this.data[N].length===0&&delete this.data[N],this.order.splice(this.order.indexOf(N),1),T.value}getByKey(N){const T=this.data[N];return T?T[0].value:null}get(N){return this.has(N)?this.data[N.wrapped().key][0].value:null}remove(N,T){if(!this.has(N))return this;const B=N.wrapped().key,W=T===void 0?0:this.data[B].indexOf(T),Q=this.data[B][W];return this.data[B].splice(W,1),Q.timeout&&clearTimeout(Q.timeout),this.data[B].length===0&&delete this.data[B],this.onRemove(Q.value),this.order.splice(this.order.indexOf(B),1),this}setMaxSize(N){for(this.max=N;this.order.length>this.max;){const T=this._getAndRemoveByKey(this.order[0]);T&&this.onRemove(T)}return this}filter(N){const T=[];for(const B in this.data)for(const W of this.data[B])N(W.value)||T.push(W);for(const B of T)this.remove(B.value.tileID,B)}}class E1{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(N,T,B){const W=String(T);if(this.stateChanges[N]=this.stateChanges[N]||{},this.stateChanges[N][W]=this.stateChanges[N][W]||{},Object.assign(this.stateChanges[N][W],B),this.deletedStates[N]===null){this.deletedStates[N]={};for(const Q in this.state[N])Q!==W&&(this.deletedStates[N][Q]=null)}else if(this.deletedStates[N]&&this.deletedStates[N][W]===null){this.deletedStates[N][W]={};for(const Q in this.state[N][W])B[Q]||(this.deletedStates[N][W][Q]=null)}else for(const Q in B)this.deletedStates[N]&&this.deletedStates[N][W]&&this.deletedStates[N][W][Q]===null&&delete this.deletedStates[N][W][Q]}removeFeatureState(N,T,B){if(this.deletedStates[N]===null)return;const W=String(T);if(this.deletedStates[N]=this.deletedStates[N]||{},B&&T!==void 0)this.deletedStates[N][W]!==null&&(this.deletedStates[N][W]=this.deletedStates[N][W]||{},this.deletedStates[N][W][B]=null);else if(T!==void 0)if(this.stateChanges[N]&&this.stateChanges[N][W])for(B in this.deletedStates[N][W]={},this.stateChanges[N][W])this.deletedStates[N][W][B]=null;else this.deletedStates[N][W]=null;else this.deletedStates[N]=null}getState(N,T){const B=this.state[N]||{},W=this.stateChanges[N]||{},Q=this.deletedStates[N];if(Q===null)return{};if(T!==void 0){const ue=String(T),we=Object.assign({},B[ue],W[ue]);if(Q){const Te=Q[T];if(Te===null)return{};for(const De in Te)delete we[De]}return we}const se=Object.assign({},B,W);if(Q)for(const ue in Q)delete se[ue];return se}initializeTileState(N,T){N.refreshFeatureState(T)}coalesceChanges(N,T){const B={};for(const W in this.stateChanges){this.state[W]=this.state[W]||{};const Q={};for(const se in this.stateChanges[W])this.state[W][se]||(this.state[W][se]={}),Object.assign(this.state[W][se],this.stateChanges[W][se]),Q[se]=this.state[W][se];B[W]=Q}for(const W in this.deletedStates){this.state[W]=this.state[W]||{};const Q={};if(this.deletedStates[W]===null)for(const se in this.state[W])Q[se]={},this.state[W][se]={};else for(const se in this.deletedStates[W]){if(this.deletedStates[W][se]===null)this.state[W][se]={};else if(this.state[W][se])for(const ue of Object.keys(this.deletedStates[W][se]))delete this.state[W][se][ue];Q[se]=this.state[W][se]}B[W]=B[W]||{},Object.assign(B[W],Q)}if(this.stateChanges={},this.deletedStates={},Object.keys(B).length!==0)for(const W in N)N[W].refreshFeatureState(T,B)}}class zc extends o.E{constructor(N,T,B){super(),this.id=N,this._renderSourceType=B,this._maxzoomOverride=null,T.on("data",W=>{W.dataType==="source"&&W.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&W.dataType==="source"&&W.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),T.on("error",()=>{this._sourceErrored=!0}),this._source=T,this._tiles={},this._cache=new yl(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=T.minTileCacheSize,this._maxTileCacheSize=T.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new E1,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&"_dataType"in this._source&&this._source._dataType==="raster",this._supportsFading=this._source.type==="raster"||this._source.type==="raster-array"||this._source.type==="image"||this._source.type==="video"||this._source.type==="custom",this._isRasterElevatedOverTerrain=!1}onAdd(N){this.map=N,this._minTileCacheSize=this._minTileCacheSize===void 0&&N?N._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&N?N._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const N in this._tiles)if(!this._tiles[N].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const N=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,N&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(N){this._maxzoomOverride=N}_loadTile(N,T){return N.renderSourceType=this._renderSourceType,N.isExtraShadowCaster=this._shadowCasterTiles[N.tileID.key],this._source.loadTile(N,T)}_unloadTile(N){if(this._source.unloadTile)return this._source.unloadTile(N)}_abortTile(N){if(this._source.abortTile)return this._source.abortTile(N)}serialize(){return this._source.serialize()}prepare(N){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const T in this._tiles){const B=this._tiles[T];B.upload(N,this.map?this.map.painter:void 0),B.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(N=>N.tileID).sort(Dp).map(N=>N.key)}getRenderableIds(N,T){const B=[];for(const W in this._tiles)this._isIdRenderable(+W,N,T)&&B.push(this._tiles[W]);return N?B.sort((W,Q)=>{const se=W.tileID,ue=Q.tileID,we=new o.P(se.canonical.x,se.canonical.y)._rotate(this.transform.angle),Te=new o.P(ue.canonical.x,ue.canonical.y)._rotate(this.transform.angle);return se.overscaledZ-ue.overscaledZ||Te.y-we.y||Te.x-we.x}).map(W=>W.tileID.key):B.map(W=>W.tileID).sort(Dp).map(W=>W.key)}hasRenderableParent(N){const T=this.findLoadedParent(N,0);return!!T&&this._isIdRenderable(T.tileID.key)}_isIdRenderable(N,T,B){return this._tiles[N]&&this._tiles[N].hasData()&&!this._coveredTiles[N]&&(T||!this._tiles[N].holdingForFade())&&(B||!this._shadowCasterTiles[N])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const N in this._tiles)this._tiles[N].state!=="errored"&&this._reloadTile(+N,"reloading")}}_reloadTile(N,T){const B=this._tiles[N];B&&(B.state!=="loading"&&(B.state=T),this._loadTile(B,this._tileLoaded.bind(this,B,N,T)))}_tileLoaded(N,T,B,W,Q){if(W){if(N.state="errored",o.b2(W)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:N})),!(N.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const ue=this.map.painter.terrain;this.update(this.transform,ue.getScaledDemTileSize(),!0),ue.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(W,{tile:N}));return}N.timeAdded=o.o.now(),B==="expired"&&(N.refreshedUponExpiration=!0),this._setTileReloadTimer(T,N),this._source.type==="raster-dem"&&N.dem&&this._backfillDEM(N),this._state.initializeTileState(N,this.map?this.map.painter:null);let se=new Map;Q&&Q.responseHeaders&&(se=Q.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:N,coord:N.tileID,sourceCacheId:this.id,responseHeaders:se}))}_hasTunnelGeometry(){for(const N in this._tiles){const T=this._tiles[N];if(T&&T.hasTunnelGeometry)return!0}return!1}_backfillDEM(N){const T=this.getRenderableIds();for(let W=0;W1||(Math.abs(se)>1&&(Math.abs(se+we)===1?se+=we:Math.abs(se-we)===1&&(se-=we)),Q.dem&&W.dem&&(W.dem.backfillBorder(Q.dem,se,ue),W.neighboringTiles&&W.neighboringTiles[Te]&&(W.neighboringTiles[Te].backfilled=!0)))}}getTile(N){return this.getTileByID(N.key)}getTileByID(N){return this._tiles[N]}_retainLoadedChildren(N,T,B,W){for(const Q in this._tiles){let se=this._tiles[Q];if(W[Q]||!se.hasData()||se.tileID.overscaledZ<=T||se.tileID.overscaledZ>B)continue;let ue=se.tileID;for(;se&&se.tileID.overscaledZ>T+1;){const Te=se.tileID.scaledTo(se.tileID.overscaledZ-1);se=this._tiles[Te.key],se&&se.hasData()&&(ue=Te)}let we=ue;for(;we.overscaledZ>T;)if(we=we.scaledTo(we.overscaledZ-1),N[we.key]){W[ue.key]=ue;break}}}findLoadedParent(N,T){if(N.key in this._loadedParentTiles){const B=this._loadedParentTiles[N.key];return B&&B.tileID.overscaledZ>=T?B:null}for(let B=N.overscaledZ-1;B>=T;B--){const W=N.scaledTo(B),Q=this._getLoadedTile(W);if(Q)return Q}}_getLoadedTile(N){const T=this._tiles[N.key];return T&&T.hasData()?T:this._cache.getByKey(this._source.reparseOverscaled?N.wrapped().key:N.canonical.key)}updateCacheSize(N,T){T=T||this._source.tileSize;const B=Math.ceil(N.width/T)+1,W=Math.ceil(N.height/T)+1,Q=Math.floor(B*W*5),se=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Q):Q,ue=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,se):se;this._cache.setMaxSize(ue)}handleWrapJump(N){const T=Math.round((N-(this._prevLng===void 0?N:this._prevLng))/360);if(this._prevLng=N,T){const B={};for(const W in this._tiles){const Q=this._tiles[W];Q.tileID=Q.tileID.unwrapTo(Q.tileID.wrap+T),B[Q.tileID.key]=Q}this._tiles=B;for(const W in this._timers)clearTimeout(this._timers[W]),delete this._timers[W];for(const W in this._tiles)this._setTileReloadTimer(+W,this._tiles[W])}}update(N,T,B,W,Q){if(this.transform=N,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!B)return;this.updateCacheSize(N,T),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const se=this._source.type==="batched-model";let ue,we=this._source.maxzoom;this._maxzoomOverride!==null&&(we=Math.min(we,this._maxzoomOverride));const Te=this.map&&this.map.painter?this.map.painter._terrain:null;if(Te&&Te.sourceCache===this&&Te.attenuationRange()){const tt=Te.attenuationRange()[0],ht=Math.floor(tt)-Math.log2(Te.getDemUpscale());we>ht&&(we=ht)}const De=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)ue=N.getVisibleUnwrappedCoordinates(this._source.tileID).map(tt=>new o.aR(tt.canonical.z,tt.wrap,tt.canonical.z,tt.canonical.x,tt.canonical.y));else if(this.tileCoverLift!==0){const tt=N.clone();tt.tileCoverLift=this.tileCoverLift,ue=tt.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:De,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:se}),this._source.minzoom<=1&&N.projection.name==="globe"&&(ue.push(new o.aR(1,0,1,0,0)),ue.push(new o.aR(1,0,1,1,0)),ue.push(new o.aR(1,0,1,0,1)),ue.push(new o.aR(1,0,1,1,1)))}else if(ue=N.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:De,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:se}),this._source.hasTile){const tt=this._source.hasTile.bind(this._source);ue=ue.filter(ht=>tt(ht))}}else ue=[];if(ue.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const tt=N.coveringZoomLevel({tileSize:T||this._source.tileSize,roundZoom:this._source.roundZoom&&!B}),ht=Math.min(tt,we);if(se){const ct=N.extendTileCover(ue,ht);for(const St of ct)ue.push(St)}else if(Q){const ct=this.transform.getFrustum(ht),St=N.extendTileCoverToNearPlane(ue,ct,ht);for(const kt of St)ue.push(kt);if(ht>=18&&this._hasTunnelGeometry()){const kt=N.extendTileCoverForTunnels(ue,ct,ht,20);for(const Ut of kt)ue.push(Ut)}}else if(this.castsShadows&&W){const ct=N.extendTileCover(ue,ht,W,16);for(const St of ct)this._shadowCasterTiles[St.key]=!0,ue.push(St)}}const Qe=this._updateRetainedTiles(ue);if(this._supportsFading&&ue.length!==0){const tt={},ht={},ct=o.o.now(),St=Object.keys(Qe);for(const Ut of St){const Xt=Qe[Ut],Et=this._tiles[Ut];if(!Et||Et.fadeEndTime!==void 0&&Et.fadeEndTime<=ct)continue;const Ts=this.findLoadedParent(Xt,Math.max(Xt.overscaledZ-zc.maxOverzooming,this._source.minzoom));Ts&&(this._addTile(Ts.tileID),tt[Ts.tileID.key]=Ts.tileID),ht[Ut]=Xt}const kt=ue[ue.length-1].overscaledZ;for(const Ut in this._tiles){const Xt=this._tiles[Ut];if(Qe[Ut]||!Xt.hasData())continue;let Et=Xt.tileID;for(;Et.overscaledZ>kt;){Et=Et.scaledTo(Et.overscaledZ-1);const Ts=this._tiles[Et.key];if(Ts&&Ts.hasData()&&ht[Et.key]){Qe[Ut]=Xt.tileID;break}}}for(const Ut in tt)Qe[Ut]||(this._coveredTiles[Ut]=!0,Qe[Ut]=tt[Ut])}for(const tt in Qe)this._tiles[tt].clearFadeHold();const Ye=o.b3(this._tiles,Qe);for(const tt of Ye){const ht=this._tiles[tt];ht.hasSymbolBuckets&&!ht.holdingForFade()?ht.setHoldDuration(this.map._fadeDuration):ht.hasSymbolBuckets&&!ht.symbolFadeFinished()||this._removeTile(+tt)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const N in this._tiles)this._tiles[N].holdingForFade()&&this._removeTile(+N)}_updateRetainedTiles(N){const T={};if(N.length===0)return T;const B={},W=N.reduce((Te,De)=>Math.min(Te,De.overscaledZ),1/0),Q=N[0].overscaledZ,se=Math.max(Q-zc.maxOverzooming,this._source.minzoom),ue=Math.max(Q+zc.maxUnderzooming,this._source.minzoom),we={};for(const Te of N){const De=this._addTile(Te);T[Te.key]=Te,De.hasData()||W=this._source.maxzoom){const Ye=Te.children(this._source.maxzoom)[0],tt=this.getTile(Ye);if(tt&&tt.hasData()){T[Ye.key]=Ye;continue}}else{const Ye=Te.children(this._source.maxzoom);if(T[Ye[0].key]&&T[Ye[1].key]&&T[Ye[2].key]&&T[Ye[3].key])continue}let Qe=De.wasRequested();for(let Ye=Te.overscaledZ-1;Ye>=se;--Ye){const tt=Te.scaledTo(Ye);if(B[tt.key]||(B[tt.key]=!0,De=this.getTile(tt),!De&&Qe&&(De=this._addTile(tt)),De&&(T[tt.key]=tt,Qe=De.wasRequested(),De.hasData())))break}}return T}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const N in this._tiles){const T=[];let B,W=this._tiles[N].tileID;for(;W.overscaledZ>0;){if(W.key in this._loadedParentTiles){B=this._loadedParentTiles[W.key];break}T.push(W.key);const Q=W.scaledTo(W.overscaledZ-1);if(B=this._getLoadedTile(Q),B)break;W=Q}for(const Q of T)this._loadedParentTiles[Q]=B}}_addTile(N){let T=this._tiles[N.key];if(T)return T.isExtraShadowCaster!==!0||this._shadowCasterTiles[N.key]||this._reloadTile(N.key,"reloading"),T;T=this._cache.getAndRemove(N),T&&(this._setTileReloadTimer(N.key,T),T.tileID=N,this._state.initializeTileState(T,this.map?this.map.painter:null),this._cacheTimers[N.key]&&(clearTimeout(this._cacheTimers[N.key]),delete this._cacheTimers[N.key],this._setTileReloadTimer(N.key,T)));const B=!!T;if(!B){const W=this.map?this.map.painter:null,Q=this._source.tileSize*N.overscaleFactor();T=this._source.type==="raster-array"?new il(N,Q,this.transform.tileZoom,W,this._isRaster):new o.b0(N,Q,this.transform.tileZoom,W,this._isRaster,this._source.worldview),this._loadTile(T,this._tileLoaded.bind(this,T,N.key,T.state))}return T.uses++,this._tiles[N.key]=T,B||this._source.fire(new o.C("dataloading",{tile:T,coord:T.tileID,dataType:"source"})),T}_setTileReloadTimer(N,T){N in this._timers&&(clearTimeout(this._timers[N]),delete this._timers[N]);const B=T.getExpiryTimeout();B&&(this._timers[N]=setTimeout(()=>{this._reloadTile(N,"expired"),delete this._timers[N]},B))}_removeTile(N){const T=this._tiles[N];T&&(T.uses--,delete this._tiles[N],this._timers[N]&&(clearTimeout(this._timers[N]),delete this._timers[N]),T.uses>0||(T.hasData()&&T.state!=="reloading"||T.state==="empty"?this._cache.add(T.tileID,T,T.getExpiryTimeout()):(T.aborted=!0,this._abortTile(T),this._unloadTile(T))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const N in this._tiles)this._removeTile(+N);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(N,T,B){const W=[],Q=this.transform;if(!Q)return W;const se=Q.projection.name==="globe",ue=o.aH(Q.center.lng);for(const we in this._tiles){const Te=this._tiles[we];if(B&&Te.clearQueryDebugViz(),Te.holdingForFade())continue;let De;if(se){const Qe=Te.tileID.canonical;if(Qe.z===0){const Ye=[Math.abs(o.aC(ue,...hp(Qe,-1))-ue),Math.abs(o.aC(ue,...hp(Qe,1))-ue)];De=[0,2*Ye.indexOf(Math.min(...Ye))-1]}else{const Ye=[Math.abs(o.aC(ue,...hp(Qe,-1))-ue),Math.abs(o.aC(ue,...hp(Qe,0))-ue),Math.abs(o.aC(ue,...hp(Qe,1))-ue)];De=[Ye.indexOf(Math.min(...Ye))-1]}}else De=[0];for(const Qe of De){const Ye=N.containsTile(Te,Q,T,Qe);Ye&&W.push(Ye)}}return W}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(N){return this._getRenderableCoordinates(N)}_getRenderableCoordinates(N,T){const B=this.getRenderableIds(N,T).map(Q=>this._tiles[Q].tileID),W=this.transform.projection.name==="globe";for(const Q of B)Q.projMatrix=this.transform.calculateProjMatrix(Q.toUnwrapped()),Q.expandedProjMatrix=W?this.transform.calculateProjMatrix(Q.toUnwrapped(),!1,!0):Q.projMatrix;return B}sortCoordinatesByDistance(N){const T=N.slice(),B=this.transform._camera.position,W=this.transform._camera.forward(),Q={};for(const se of T){const ue=1/(1<Q[se.key]-Q[ue.key]),T}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const N=o.o.now();for(const T in this._tiles){const B=this._tiles[T];if(B.fadeEndTime!==void 0&&B.fadeEndTime>=N)return!0}}return!1}setFeatureState(N,T,B){this._state.updateState(N=N||"_geojsonTileLayer",T,B)}removeFeatureState(N,T,B){this._state.removeFeatureState(N=N||"_geojsonTileLayer",T,B)}getFeatureState(N,T){return this._state.getState(N=N||"_geojsonTileLayer",T)}setDependencies(N,T,B){const W=this._tiles[N];W&&W.setDependencies(T,B)}reloadTilesForDependencies(N,T){for(const B in this._tiles)this._tiles[B].hasDependency(N,T)&&this._reloadTile(+B,"reloading");this._cache.filter(B=>!B.hasDependency(N,T))}_preloadTiles(N,T){if(!this._sourceLoaded){const we=()=>{this._sourceLoaded&&(this._source.off("data",we),this._preloadTiles(N,T))};return void this._source.on("data",we)}const B=new Map,W=Array.isArray(N)?N:[N],Q=this.map.painter.terrain,se=this.usedForTerrain&&Q?Q.getScaledDemTileSize():this._source.tileSize;for(const we of W){const Te=we.coveringTiles({tileSize:se,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const De of Te)B.set(De.key,De);this.usedForTerrain&&we.updateElevation(!1)}const ue=Array.from(B.values());o.t(ue,(we,Te)=>{const De=new o.b0(we,this._source.tileSize*we.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(De,Qe=>{this._source.type==="raster-dem"&&De.dem&&this._backfillDEM(De),Te(Qe,De)})},T)}}function Dp(R,N){const T=Math.abs(2*R.wrap)-+(R.wrap<0),B=Math.abs(2*N.wrap)-+(N.wrap<0);return R.overscaledZ-N.overscaledZ||B-T||N.canonical.y-R.canonical.y||N.canonical.x-R.canonical.x}function hp(R,N){const T=1<0:B.type==="building"?W=!B.isHidden(N)&&B.paint.get("building-opacity")>0:B.type==="model"&&(W=!B.isHidden(N)&&B.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!W&&T.visible,T.visible=W}}updateZOffset(N,T){this.currentBuildingBuckets=[];for(const W of this.layers){const Q=W.layer,se=this.style.getLayerSourceCache(Q);let ue=1;Q.type==="fill-extrusion"?ue=W.visible?Q.paint.get("fill-extrusion-vertical-scale"):0:Q.type==="building"&&(ue=W.visible?Q.paint.get("building-vertical-scale"):0);let we=se?se.getTile(T):null;if(!we&&se)for(const Te in se._tiles){const De=se._tiles[Te];if(T.canonical.isChildOf(De.tileID.canonical)){we=De;break}}this.currentBuildingBuckets.push({bucket:we?we.getBucket(Q):null,tileID:we?we.tileID:T,verticalScale:ue})}N.hasAnyZOffset=!1;let B=!1;for(let W=0;W{B in N&&(T[B]=N[B])}),T}function nx(R){R=R.slice();const N=Object.create(null);for(const T of R)N[T.id]=T;for(let T=0;T0?(W-se)/ue:0;return this.points[Q].mult(1-we).add(this.points[T].mult(we))}}class rx{constructor(N,T,B){const W=this.boxCells=[],Q=this.circleCells=[];this.xCellCount=Math.ceil(N/B),this.yCellCount=Math.ceil(T/B);for(let se=0;sethis.width||W<0||T>this.height)return!Q&&[];const ue=[];if(N<=0&&T<=0&&this.width<=B&&this.height<=W){if(Q)return!0;for(let we=0;we0:ue}_queryCircle(N,T,B,W,Q){const se=N-B,ue=N+B,we=T-B,Te=T+B;if(ue<0||se>this.width||Te<0||we>this.height)return!W&&[];const De=[];return this._forEachCell(se,we,ue,Te,this._queryCellCircle,De,{hitTest:W,circle:{x:N,y:T,radius:B},seenUids:{box:{},circle:{}}},Q),W?De.length>0:De}query(N,T,B,W,Q){return this._query(N,T,B,W,!1,Q)}hitTest(N,T,B,W,Q){return this._query(N,T,B,W,!0,Q)}hitTestCircle(N,T,B,W){return this._queryCircle(N,T,B,!0,W)}_queryCell(N,T,B,W,Q,se,ue,we){const Te=ue.seenUids,De=this.boxCells[Q];if(De!==null){const Ye=this.bboxes;for(const tt of De)if(!Te.box[tt]){Te.box[tt]=!0;const ht=4*tt;if(N<=Ye[ht+2]&&T<=Ye[ht+3]&&B>=Ye[ht+0]&&W>=Ye[ht+1]&&(!we||we(this.boxKeys[tt]))){if(ue.hitTest)return se.push(!0),!0;se.push({key:this.boxKeys[tt],x1:Ye[ht],y1:Ye[ht+1],x2:Ye[ht+2],y2:Ye[ht+3]})}}}const Qe=this.circleCells[Q];if(Qe!==null){const Ye=this.circles;for(const tt of Qe)if(!Te.circle[tt]){Te.circle[tt]=!0;const ht=3*tt;if(this._circleAndRectCollide(Ye[ht],Ye[ht+1],Ye[ht+2],N,T,B,W)&&(!we||we(this.circleKeys[tt]))){if(ue.hitTest)return se.push(!0),!0;{const ct=Ye[ht],St=Ye[ht+1],kt=Ye[ht+2];se.push({key:this.circleKeys[tt],x1:ct-kt,y1:St-kt,x2:ct+kt,y2:St+kt})}}}}}_queryCellCircle(N,T,B,W,Q,se,ue,we){const Te=ue.circle,De=ue.seenUids,Qe=this.boxCells[Q];if(Qe!==null){const tt=this.bboxes;for(const ht of Qe)if(!De.box[ht]){De.box[ht]=!0;const ct=4*ht;if(this._circleAndRectCollide(Te.x,Te.y,Te.radius,tt[ct+0],tt[ct+1],tt[ct+2],tt[ct+3])&&(!we||we(this.boxKeys[ht])))return se.push(!0),!0}}const Ye=this.circleCells[Q];if(Ye!==null){const tt=this.circles;for(const ht of Ye)if(!De.circle[ht]){De.circle[ht]=!0;const ct=3*ht;if(this._circlesCollide(tt[ct],tt[ct+1],tt[ct+2],Te.x,Te.y,Te.radius)&&(!we||we(this.circleKeys[ht])))return se.push(!0),!0}}}_forEachCell(N,T,B,W,Q,se,ue,we){const Te=this._convertToXCellCoord(N),De=this._convertToYCellCoord(T),Qe=this._convertToXCellCoord(B),Ye=this._convertToYCellCoord(W);for(let tt=Te;tt<=Qe;tt++)for(let ht=De;ht<=Ye;ht++)if(Q.call(this,N,T,B,W,this.xCellCount*ht+tt,se,ue,we))return}_convertToXCellCoord(N){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(N*this.xScale)))}_convertToYCellCoord(N){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(N*this.yScale)))}_circlesCollide(N,T,B,W,Q,se){const ue=W-N,we=Q-T,Te=B+se;return Te*Te>ue*ue+we*we}_circleAndRectCollide(N,T,B,W,Q,se,ue){const we=(se-W)/2,Te=Math.abs(N-(W+we));if(Te>we+B)return!1;const De=(ue-Q)/2,Qe=Math.abs(T-(Q+De));if(Qe>De+B)return!1;if(Te<=we||Qe<=De)return!0;const Ye=Te-we,tt=Qe-De;return Ye*Ye+tt*tt<=B*B}}const R0=Math.tan(85*Math.PI/180);function mc(R,N,T,B,W,Q,se){const ue=o.bb();if(T)if(Q.name==="globe"){const we=o.bc(W,N);o.aD(ue,ue,we)}else{const we=o.bd([],se);ue[0]=we[0],ue[1]=we[1],ue[4]=we[2],ue[5]=we[3],B||o.ba(ue,ue,W.angle)}else o.aD(ue,W.labelPlaneMatrix,R);return ue}function Sd(R,N,T,B,W,Q,se){const ue=mc(R,N,T,B,W,Q,se);return Q.name==="globe"&&T||(ue[2]=ue[6]=ue[10]=ue[14]=0),ue}function pf(R,N,T,B,W,Q,se){if(T){if(Q.name==="globe"){const ue=mc(R,N,T,B,W,Q,se);return o.b7(ue,ue),o.aD(ue,R,ue),ue}{const ue=o.b8(R),we=o.b9([]);return we[0]=se[0],we[1]=se[1],we[4]=se[2],we[5]=se[3],o.aD(ue,ue,we),B||o.ba(ue,ue,-W.angle),ue}}return W.glCoordMatrix}function lu(R,N,T,B){const W=[R,N,T,1];T?o.aE(W,W,B):Pr(W,W,B);const Q=W[3];return W[0]/=Q,W[1]/=Q,W[2]/=Q,W}function mp(R,N){return Math.min(.5+R/N*.5,1.5)}function Um(R,N){const T=R[0]/R[3],B=R[1]/R[3];return T>=-N[0]&&T<=N[0]&&B>=-N[1]&&B<=N[1]}function qm(R,N,T,B,W,Q,se,ue,we,Te,De=1){const Qe=T.transform,Ye=B?R.textSizeData:R.iconSizeData,tt=o.bj(Ye,T.transform.zoom,De),ht=Qe.projection.name==="globe",ct=[256/T.width*2+1,256/T.height*2+1],St=B?R.text.dynamicLayoutVertexArray:R.icon.dynamicLayoutVertexArray;St.clear();let kt=null;ht&&(kt=B?R.text.globeExtVertexArray:R.icon.globeExtVertexArray);const Ut=R.lineVertexArray,Xt=B?R.text.placedSymbolArray:R.icon.placedSymbolArray,Et=T.transform.width/T.transform.height;let Ts,ds=!1;for(let Cs=0;CsMath.abs(T)?{useVertical:!0}:R===o.bk.vertical?B>0?{needsFlipping:!0}:null:N!==0&&function(W,Q){return W===0||Math.abs(Q/W)>R0}(T,B)?N===1?{needsFlipping:!0}:null:T<0?{needsFlipping:!0}:null}function Ks(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut,Xt){const Et=N/24,Ts=R.lineOffsetX*Et,ds=R.lineOffsetY*Et,{lineStartIndex:Cs,glyphStartIndex:es,numGlyphs:is,segment:_s,writingMode:Xs,flipState:Ds}=R,_n=Cs+R.lineLength,pn=Un=>{if(De){const[yn,jn,In]=Un.up,Sr=Te.length;o.bm(De,Sr+0,yn,jn,In),o.bm(De,Sr+1,yn,jn,In),o.bm(De,Sr+2,yn,jn,In),o.bm(De,Sr+3,yn,jn,In)}const[Xn,nn,Bs]=Un.point;o.bn(Te,Xn,nn,Bs,Un.angle)};if(is>1){const Un=ot(Et,ue,Ts,ds,T,Qe,Ye,R,we,Q,tt,ct,!1,St,kt,Ut,Xt);if(!Un)return{notEnoughRoom:!0};if(B&&!T){let[Xn,nn,Bs]=Un.first.point,[yn,jn,In]=Un.last.point;[Xn,nn]=lu(Xn,nn,Bs,se),[yn,jn]=lu(yn,jn,In,se);const Sr=ts(Xs,Ds,(yn-Xn)*ht,jn-nn);if(R.flipState=Sr&&Sr.needsFlipping?1:2,Sr)return Sr}pn(Un.first);for(let Xn=es+1;Xn0?yn:Mn(Ye,Bs,Xn,1,W,void 0,St,kt.canonical),In=ts(Xs,Ds,(jn[0]-Xn[0])*ht,jn[1]-Xn[1]);if(R.flipState=In&&In.needsFlipping?1:2,In)return In}const Un=Ur(Et*ue.getoffsetX(es),Ts,ds,T,Qe,Ye,_s,Cs,_n,we,Q,tt,ct,!1,!1,St,kt,Ut,Xt);if(!Un)return{notEnoughRoom:!0};pn(Un)}return{}}function Js(R,N,T,B,W){const{x:Q,y:se,z:ue}=B.projectTilePoint(R.x,R.y,N);if(!W)return lu(Q,se,ue,T);const[we,Te,De]=W.getElevation(R,W.elevation,W.elevationFeature);return lu(Q+we,se+Te,ue+De,T)}function Mn(R,N,T,B,W,Q,se,ue){const we=Js(R.sub(N)._unit()._add(R),ue,W,se,Q);return o.ax(we,T,we),o.ay(we,we),o.bg(we,T,we,B)}function Ur(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut){const Xt=B?R-N:R+N;let Et=Xt>0?1:-1,Ts=0;B&&(Et*=-1,Ts=Math.PI),Et<0&&(Ts+=Math.PI);let ds=ue+se+(Et>0?0:1)|0,Cs=W,es=W,is=0,_s=0;const Xs=Math.abs(Xt),Ds=[],_n=[];let pn=Q,Un=pn,Xn=o.be([]);const nn=()=>Mn(Un,pn,es,Xs-is+1,De,Ye,ct,St.canonical);for(;is+_s<=Xs;){if(ds+=Et,ds=we)return null;if(es=Cs,Un=pn,Ds.push(es),tt&&_n.push(Un),pn=new o.P(Te.getx(ds),Te.gety(ds)),Cs=Qe[ds],!Cs){const Ea=Js(pn,St.canonical,De,ct,Ye);Cs=Ea[3]>0?Qe[ds]=Ea:nn()}is+=_s;const Kn=o.ax([],Cs,es),pa=o.bf(es,Cs);if(T&&pa>0&&_s>0&&o.bi(Xn,Kn)/(_s*pa)0,Xt),Cs=Te*ds.perspectiveRatio,es=(B.x1*T+ue.x-B.padding)*Cs+ds.point.x,is=(B.y1*T+ue.y-B.padding)*Cs+ds.point.y,_s=(B.x2*T+ue.x+B.padding)*Cs+ds.point.x,Xs=(B.y2*T+ue.y+B.padding)*Cs+ds.point.y,Ds=ds.perspectiveRatio<=.55||ds.occluded;return!this.isInsideGrid(es,is,_s,Xs)||!we&&this.grid.hitTest(es,is,_s,Xs,Qe)||Ds?{box:[],offscreen:!1,occluded:ds.occluded}:{box:[es,is,_s,Xs],offscreen:this.isOffscreen(es,is,_s,Xs),occluded:!1}}placeCollisionCircles(N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St){const kt=[],Ut=this.transform.elevation,Xt=N.getProjection(),Et=N.elevationType==="road",Ts=!!Ut||Et,ds=o.bu.getAtTileOffsetFunc(St,this.transform.center.lat,this.transform.worldSize,Xt),Cs=new o.P(B.tileAnchorX,B.tileAnchorY),es=new o.P(B.tileAnchorX,B.tileAnchorY);let{x:is,y:_s,z:Xs}=Xt.projectTilePoint(es.x,es.y,St.canonical),Ds=null;if(Ts){const pa=Et?N.getElevationFeatureForText(W):null;Ds={getElevation:ds,elevation:Ut,elevationFeature:pa};const[Ea,na,ma]=ds(Cs,Ut,pa);is+=Ea,_s+=na,Xs+=ma}const _n=Xt.name==="globe",pn=this.projectAndGetPerspectiveRatio(we,is,_s,Xs,St,_n||!!Ut||this.transform.pitch>0,Xt),{perspectiveRatio:Un}=pn,Xn=(Ye?ue/Un:ue*Un)/o.by,nn=lu(is,_s,Xs,Te),Bs=B.lineOffsetX*Xn,yn=B.lineOffsetY*Xn,jn=o.ap(N.layers[0].layout.get("text-max-angle")),In=Math.cos(jn),Sr=pn.signedDistanceFromCamera>0?ot(Xn,se,Bs,yn,Et&&B.flipState===1,nn,es,B,Q,Te,{},Ts&&!Ye?Ds:null,Ye&&Ts,Xt,St,Ye,In):null;let xr=!1,gr=!1,Kn=!0;if(Sr&&!pn.occluded){const pa=.5*ht*Un+ct,Ea=new o.P(-100,-100),na=new o.P(this.screenRightBoundary,this.screenBottomBoundary),ma=new Uu,{first:hi,last:Ei}=Sr,ki=hi.path.length;let io=[];for(let Si=ki-1;Si>=1;Si--)io.push(hi.path[Si]);for(let Si=1;Si(Ts&&!_n&&(_c=ds(YdSi[3]<=0)&&(io=[]));let oo=[];if(io.length>0){let Si=1/0,ol=-1/0,_c=1/0,Yd=-1/0;for(const $c of io)Si=Math.min(Si,$c[0]),_c=Math.min(_c,$c[1]),ol=Math.max(ol,$c[0]),Yd=Math.max(Yd,$c[1]);ol>=Ea.x&&Si<=na.x&&Yd>=Ea.y&&_c<=na.y&&(oo=[io.map($c=>new o.P($c[0],$c[1]))],(Sina.x||_cna.y)&&(oo=o.bv(oo,Ea.x,Ea.y,na.x,na.y)))}for(const Si of oo){ma.reset(Si,.25*pa);let ol=0;ol=ma.length<=.5*pa?1:Math.ceil(ma.paddedLength/ti)+1;for(let _c=0;_c0?(o.aE(we,we,N),this.fogState&&Q&&ue.name!=="globe"&&(Te=function(Ye,tt,ht,ct,St,kt){const Ut=kt.calculateFogTileMatrix(St),Xt=[tt,ht,ct];return o.ah(Xt,Xt,Ut),Ba(Ye,o.ai(Xt),kt.pitch,kt._fov)}(this.fogState,T,B,W,Q.toUnwrapped(),this.transform)>.9)):Pr(we,we,N);const De=we[3];return{point:new o.P((we[0]/De+1)/2*this.transform.width+Ni,(-we[1]/De+1)/2*this.transform.height+Ni),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(ue)/De*.5,1.5),signedDistanceFromCamera:De,occluded:se&&we[2]>De||Te}}isOffscreen(N,T,B,W){return B=this.screenRightBoundary||Wthis.screenBottomBoundary}isInsideGrid(N,T,B,W){return B>=0&&N=0&&TB.collisionGroupID===T}}return this.collisionGroups[N]}}function rc(R,N,T,B,W){const{horizontalAlign:Q,verticalAlign:se}=o.bF(R),ue=-(Q-.5)*N,we=-(se-.5)*T,Te=o.bG(R,B);return new o.P(ue+Te[0]*W,we+Te[1]*W)}function Yc(R,N,T,B,W){const Q=new o.P(R,N);return T&&Q._rotate(B?W:-W),Q}class mo{constructor(N,T,B,W,Q,se){this.transform=N.clone(),this.projection=N.projection.name,this.collisionIndex=new Lo(this.transform,Q),this.buildingIndex=se,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=T,this.retainedQueryData={},this.collisionGroups=new Ai(B),this.collisionCircleArrays={},this.prevPlacement=W,W&&(W.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(N,T,B,W,Q=1){const se=B.getBucket(T),ue=B.latestFeatureIndex;if(!se||!ue||T.fqid!==se.layerIds[0])return;const we=se.layers[0].layout,Te=se.layers[0].paint,De=B.collisionBoxArray,Qe=Math.pow(2,this.transform.zoom-B.tileID.overscaledZ),Ye=B.tileSize/o.an,tt=B.tileID.toUnwrapped();this.transform.setProjection(se.projection);const ht=(ct=B.tileID,St=se.getProjection(),kt=this.transform,St.name===this.projection?kt.calculateProjMatrix(ct.toUnwrapped()):Ah(kt,St,ct));var ct,St,kt;const Ut=we.get("text-pitch-alignment")==="map",Xt=we.get("text-rotation-alignment")==="map";T.compileFilter(T.options);const Et=T.dynamicFilter(),Ts=T.dynamicFilterNeedsFeature(),ds=T.dynamicFilterNeedsGeometry(),Cs=this.transform.calculatePixelsToTileUnitsMatrix(B),es=Sd(ht,B.tileID.canonical,Ut,Xt,this.transform,se.getProjection(),Cs);let is=null;const _s=se.getProjection().createInversionMatrix(this.transform,B.tileID.canonical);if(Ut){const yn=pf(ht,B.tileID.canonical,Ut,Xt,this.transform,se.getProjection(),Cs);is=o.aD([],this.transform.labelPlaneMatrix,yn)}let Xs=null;Et&&B.latestFeatureIndex&&(Xs={unwrappedTileID:tt,dynamicFilter:Et,dynamicFilterNeedsFeature:Ts,needGeometry:ds}),this.retainedQueryData[se.bucketInstanceId]=new gi(se.bucketInstanceId,ue,se.sourceLayerIndex,se.index,B.tileID);const[Ds,_n]=se.layers[0].layout.get("text-size-scale-range"),pn=o.aC(Q,Ds,_n),[Un,Xn]=we.get("icon-size-scale-range"),nn=o.aC(Q,Un,Xn),Bs={bucket:se,layout:we,paint:Te,posMatrix:ht,invMatrix:_s,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:es,labelToScreenMatrix:is,clippingData:Xs,scale:Qe,textPixelRatio:Ye,holdingForFade:B.holdingForFade(),collisionBoxArray:De,partiallyEvaluatedTextSize:o.bj(se.textSizeData,this.transform.zoom,pn),partiallyEvaluatedIconSize:o.bj(se.iconSizeData,this.transform.zoom,nn),collisionGroup:this.collisionGroups.get(se.sourceID),latestFeatureIndex:B.latestFeatureIndex};if(W)for(const yn of se.sortKeyRanges){const{sortKey:jn,symbolInstanceStart:In,symbolInstanceEnd:Sr}=yn;N.push({sortKey:jn,symbolInstanceStart:In,symbolInstanceEnd:Sr,parameters:Bs})}else N.push({symbolInstanceStart:0,symbolInstanceEnd:se.symbolInstances.length,parameters:Bs})}attemptAnchorPlacement(N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut,Xt,Et,Ts){const{textOffset0:ds,textOffset1:Cs,crossTileID:es}=ct,is=[ds,Cs],_s=rc(N,se,ue,is,we),Xs=this.collisionIndex.placeCollisionBox(kt,we,T,B,W,Q,Yc(_s.x,_s.y,Te,De,this.transform.angle),ht,Qe,Ye,tt.predicate);if(Xt){const Ds=kt.getSymbolInstanceIconSize(Ts,this.transform.zoom,ct.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(kt,Ds,Xt,B,W,Q,Yc(_s.x,_s.y,Te,De,this.transform.angle),ht,Qe,Ye,tt.predicate).box.length===0)return}if(Xs.box.length>0){let Ds;return this.prevPlacement&&this.prevPlacement.variableOffsets[es]&&this.prevPlacement.placements[es]&&this.prevPlacement.placements[es].text&&(Ds=this.prevPlacement.variableOffsets[es].anchor),this.variableOffsets[es]={textOffset:is,width:se,height:ue,anchor:N,textScale:we,prevAnchor:Ds},this.markUsedJustification(kt,N,ct,Ut),kt.allowVerticalPlacement&&(this.markUsedOrientation(kt,Ut,ct),this.placedOrientations[es]=Ut),{shift:_s,placedGlyphBoxes:Xs}}}placeLayerBucketPart(N,T,B,W,Q=1){const{bucket:se,layout:ue,paint:we,posMatrix:Te,textLabelPlaneMatrix:De,labelToScreenMatrix:Qe,clippingData:Ye,textPixelRatio:tt,mercatorCenter:ht,invMatrix:ct,holdingForFade:St,collisionBoxArray:kt,partiallyEvaluatedTextSize:Ut,partiallyEvaluatedIconSize:Xt,collisionGroup:Et,latestFeatureIndex:Ts}=N.parameters,ds=ue.get("text-optional"),Cs=ue.get("icon-optional"),es=ue.get("text-allow-overlap"),is=ue.get("icon-allow-overlap"),_s=ue.get("text-rotation-alignment")==="map",Xs=ue.get("icon-rotation-alignment")==="map",Ds=ue.get("text-pitch-alignment")==="map",_n=we.get("symbol-z-offset"),pn=ue.get("symbol-elevation-reference")==="sea",Un=ue.get("symbol-placement"),[Xn,nn]=ue.get("text-size-scale-range"),[Bs,yn]=ue.get("icon-size-scale-range"),jn=o.aC(Q,Xn,nn),In=o.aC(Q,Bs,yn),Sr=ue.get("text-variable-anchor"),xr=_s&&Un!=="point",gr=Xs&&Un!=="point",Kn=Sr&&se.hasTextData(),pa=se.hasIconTextFit()&&Kn&&se.hasIconData();this.transform.setProjection(se.projection);const Ea=Kn||xr,na=gr||pa;let ma=es&&(is||!se.hasIconData()||Cs),hi=is&&(es||!se.hasTextData()||ds);const Ei=!_n.isConstant();!se.collisionArrays&&kt&&se.deserializeCollisionBoxes(kt),B&&W&&se.updateCollisionDebugBuffers(this.transform.zoom,kt,jn,In);const ki=(ti,oo,Si)=>{const{crossTileID:ol,numVerticalGlyphVertices:_c}=ti;let Yd=null;if(Ye&&Ye.dynamicFilterNeedsFeature||Ei){const Xc=this.retainedQueryData[se.bucketInstanceId],cd=Ts.loadFeature({featureIndex:ti.featureIndex,bucketIndex:Xc.bucketIndex,sourceLayerIndex:Xc.sourceLayerIndex,layoutVertexArrayOffset:0}),lc=cd.properties?cd.properties.worldview:null;if(se.localizable&&se.worldview&&typeof lc=="string")if(lc==="all")cd.properties.$localized=!0;else{if(!lc.split(",").includes(se.worldview))return;cd.properties.$localized=!0,cd.properties.worldview=se.worldview}Yd=Ye&&Ye.needGeometry?o.bD(cd,!0):cd}if(Ye&&!(0,Ye.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:se.worldview},Yd,this.retainedQueryData[se.bucketInstanceId].tileID.canonical,new o.P(ti.tileAnchorX,ti.tileAnchorY),this.transform.calculateDistanceTileData(Ye.unwrappedTileID)))return this.placements[ol]=new xd(!1,!1,!1,!0),void T.add(ol);const $c=_n.evaluate(Yd,{});if((ti.zOffset||0)+($c||0)>0&&this.frontCutoffStart>0){const Xc=2*this.frontCutoffStart-1,cd=[ti.tileAnchorX,ti.tileAnchorY,0,1],lc=o.aE(o.bE(),cd,Te);if(lc[1]/lc[3]{Xc.tileID=this.retainedQueryData[se.bucketInstanceId].tileID;const cd=this.transform.elevation;Xc.elevation=pn?$c:$c+o.bu.getAtTileOffset(Xc.tileID,new o.P(Xc.tileAnchorX,Xc.tileAnchorY),cd,Gm),Xc.elevation+=ti.zOffset},$v=Si.textBox;if($v){bf($v);const Xc=lc=>{let vh=o.bk.horizontal;if(se.allowVerticalPlacement&&!lc&&this.prevPlacement){const Sg=this.prevPlacement.placedOrientations[ol];Sg&&(this.placedOrientations[ol]=Sg,vh=Sg,this.markUsedOrientation(se,vh,ti))}return vh},cd=(lc,vh)=>{if(se.allowVerticalPlacement&&_c>0&&Si.verticalTextBox){for(const Sg of se.writingModes)if(Sg===o.bk.vertical?(Fi=vh(),Rd=Fi):Fi=lc(),Fi&&Fi.box&&Fi.box.length)break}else Fi=lc()};if(Sr){let lc=Sr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[ol]){const Pu=this.prevPlacement.variableOffsets[ol];lc.indexOf(Pu.anchor)>0&&(lc=lc.filter(Uv=>Uv!==Pu.anchor),lc.unshift(Pu.anchor))}const vh=(Pu,Uv,u5)=>{const o3=se.getSymbolInstanceTextSize(Ut,ti,this.transform.zoom,oo),l3=(Pu.x2-Pu.x1)*o3+2*Pu.padding,dT=(Pu.y2-Pu.y1)*o3+2*Pu.padding,uk=ti.hasIconTextFit&&!is?Uv:null;uk&&bf(uk);let m2={box:[],offscreen:!1,occluded:!1};const uT=es?2*lc.length:lc.length;for(let Y0=0;Y0=lc.length,ti,oo,se,u5,uk,Ut,Xt);if(h5&&(m2=h5.placedGlyphBoxes,m2&&m2.box&&m2.box.length)){bl=!0,_l=h5.shift;break}}return m2};cd(()=>vh($v,Si.iconBox,o.bk.horizontal),()=>{const Pu=Si.verticalTextBox;return Pu&&bf(Pu),se.allowVerticalPlacement&&!(Fi&&Fi.box&&Fi.box.length)&&_c>0&&Pu?vh(Pu,Si.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),Fi&&(bl=Fi.box,Xi=Fi.offscreen,Uc=Fi.occluded);const Sg=Xc(!(!Fi||!Fi.box));if(!bl&&this.prevPlacement){const Pu=this.prevPlacement.variableOffsets[ol];Pu&&(this.variableOffsets[ol]=Pu,this.markUsedJustification(se,Pu.anchor,ti,Sg))}}else{const lc=(vh,Sg)=>{const Pu=se.getSymbolInstanceTextSize(Ut,ti,this.transform.zoom,oo),Uv=this.collisionIndex.placeCollisionBox(se,Pu,vh,ht,ct,Ea,new o.P(0,0),es,tt,Te,Et.predicate);return Uv&&Uv.box&&Uv.box.length&&(this.markUsedOrientation(se,Sg,ti),this.placedOrientations[ol]=Sg),Uv};cd(()=>lc($v,o.bk.horizontal),()=>{const vh=Si.verticalTextBox;return se.allowVerticalPlacement&&_c>0&&vh?(bf(vh),lc(vh,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Xc(!!(Fi&&Fi.box&&Fi.box.length))}}if(wc=Fi,bl=wc&&wc.box&&wc.box.length>0,Xi=wc&&wc.offscreen,Uc=wc&&wc.occluded,ti.useRuntimeCollisionCircles){const Xc=ti.centerJustifiedTextSymbolIndex>=0?ti.centerJustifiedTextSymbolIndex:ti.verticalPlacedTextSymbolIndex,cd=se.text.placedSymbolArray.get(Xc),lc=o.bl(se.textSizeData,Ut,cd),vh=ue.get("text-padding");Dh=this.collisionIndex.placeCollisionCircles(se,es,cd,Xc,se.lineVertexArray,se.glyphOffsetArray,lc,Te,De,Qe,B,Ds,Et.predicate,ti.collisionCircleDiameter*lc/o.by,vh,this.retainedQueryData[se.bucketInstanceId].tileID),bl=es||Dh.circles.length>0&&!Dh.collisionDetected,Xi=Xi&&Dh.offscreen,Uc=Dh.occluded}if(Si.iconFeatureIndex&&(Yx=Si.iconFeatureIndex),Si.iconBox){const Xc=cd=>{bf(cd);const lc=ti.hasIconTextFit&&_l?Yc(_l.x,_l.y,_s,Ds,this.transform.angle):new o.P(0,0),vh=se.getSymbolInstanceIconSize(Xt,this.transform.zoom,ti.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(se,vh,cd,ht,ct,na,lc,is,tt,Te,Et.predicate)};Rd&&Rd.box&&Rd.box.length&&Si.verticalIconBox?(jo=Xc(Si.verticalIconBox),Zi=jo.box.length>0):(jo=Xc(Si.iconBox),Zi=jo.box.length>0),Xi=Xi&&jo.offscreen,uu=jo.occluded}const Kl=ds||ti.numHorizontalGlyphVertices===0&&_c===0,B1=Cs||ti.numIconVertices===0;if(Kl||B1?B1?Kl||(Zi=Zi&&bl):bl=Zi&&bl:Zi=bl=Zi&&bl,bl&&wc&&wc.box&&this.collisionIndex.insertCollisionBox(wc.box,ue.get("text-ignore-placement"),se.bucketInstanceId,Rd&&Rd.box&&km?km:Lc,Et.ID),Zi&&jo&&this.collisionIndex.insertCollisionBox(jo.box,ue.get("icon-ignore-placement"),se.bucketInstanceId,Yx,Et.ID),Dh&&(bl&&this.collisionIndex.insertCollisionCircles(Dh.circles,ue.get("text-ignore-placement"),se.bucketInstanceId,Lc,Et.ID),B)){const Xc=se.bucketInstanceId;let cd=this.collisionCircleArrays[Xc];cd===void 0&&(cd=this.collisionCircleArrays[Xc]=new Vr);for(let lc=0;lc=0;--oo){const Si=ti[oo];ki(se.symbolInstances.get(Si),Si,se.collisionArrays[Si])}se.hasAnyZOffset&&o.w(`${se.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(se.hasAnyZOffset){const ti=se.getSortedIndexesByZOffset();for(let oo=0;oo=0&&(N.text.placedSymbolArray.get(Q).crossTileID=Qe>=0&&Q!==Qe?0:Te),se>=0&&(N.text.placedSymbolArray.get(se).crossTileID=Qe>=0&&se!==Qe?0:Te),ue>=0&&(N.text.placedSymbolArray.get(ue).crossTileID=Qe>=0&&ue!==Qe?0:Te),we>=0&&(N.text.placedSymbolArray.get(we).crossTileID=Qe>=0&&we!==Qe?0:Te)}markUsedOrientation(N,T,B){const W=T===o.bk.horizontal||T===o.bk.horizontalOnly?T:0,Q=T===o.bk.vertical?T:0,{leftJustifiedTextSymbolIndex:se,centerJustifiedTextSymbolIndex:ue,rightJustifiedTextSymbolIndex:we,verticalPlacedTextSymbolIndex:Te}=B,De=N.text.placedSymbolArray;se>=0&&(De.get(se).placedOrientation=W),ue>=0&&(De.get(ue).placedOrientation=W),we>=0&&(De.get(we).placedOrientation=W),Te>=0&&(De.get(Te).placedOrientation=Q)}commit(N){this.commitTime=N,this.zoomAtLastRecencyCheck=this.transform.zoom;const T=this.prevPlacement;let B=!1;this.prevZoomAdjustment=T?T.zoomAdjustment(this.transform.zoom):0;const W=T?T.symbolFadeChange(N):1,Q=T?T.opacities:{},se=T?T.variableOffsets:{},ue=T?T.placedOrientations:{};for(const we in this.placements){const Te=this.placements[we],De=Q[we];De?(this.opacities[we]=new Wl(De,W,Te.text,Te.icon,null,Te.clipped),B=B||Te.text!==De.text.placed||Te.icon!==De.icon.placed):(this.opacities[we]=new Wl(null,W,Te.text,Te.icon,Te.skipFade,Te.clipped),B=B||Te.text||Te.icon)}for(const we in Q){const Te=Q[we];if(!this.opacities[we]){const De=new Wl(Te,W,!1,!1);De.isHidden()||(this.opacities[we]=De,B=B||Te.text.placed||Te.icon.placed)}}for(const we in se)this.variableOffsets[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.variableOffsets[we]=se[we]);for(const we in ue)this.placedOrientations[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.placedOrientations[we]=ue[we]);B?this.lastPlacementChangeTime=N:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=T?T.lastPlacementChangeTime:N)}updateLayerOpacities(N,T,B,W){W&&(this.lastReplacementSourceUpdateTime=W.updateTime);const Q=new Set;for(const se of T){const ue=se.getBucket(N);ue&&se.latestFeatureIndex&&N.fqid===ue.layerIds[0]&&(this.updateBucketOpacities(ue,Q,se,se.collisionBoxArray,B,W,se.tileID,N.scope),ue.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(ue,se.tileID),ue.elevationType==="road"&&ue.updateRoadElevation(se.tileID.canonical),ue.updateZOffset())}}updateBucketOpacities(N,T,B,W,Q,se,ue,we){N.hasTextData()&&N.text.opacityVertexArray.clear(),N.hasIconData()&&N.icon.opacityVertexArray.clear(),N.hasIconCollisionBoxData()&&N.iconCollisionBox.collisionVertexArray.clear(),N.hasTextCollisionBoxData()&&N.textCollisionBox.collisionVertexArray.clear();const Te=N.layers[0].layout,De=N.layers[0].paint,Qe=!!N.layers[0].dynamicFilter(),Ye=new Wl(null,0,!1,!1,!0),tt=Te.get("text-allow-overlap"),ht=Te.get("icon-allow-overlap"),ct=Te.get("text-variable-anchor"),St=Te.get("text-rotation-alignment")==="map",kt=Te.get("text-pitch-alignment")==="map",Ut=De.get("symbol-z-offset"),Xt=Te.get("symbol-elevation-reference")==="sea",Et=!Ut.isConstant(),Ts=new Wl(null,0,tt&&(ht||!N.hasIconData()||Te.get("icon-optional")),ht&&(tt||!N.hasTextData()||Te.get("text-optional")),!0);!N.collisionArrays&&W&&(N.hasIconCollisionBoxData()||N.hasTextCollisionBoxData())&&N.deserializeCollisionBoxes(W);const ds=(es,is,_s)=>{for(let Xs=0;Xs0||Xs>0,Sr=_n>0,xr=this.placedOrientations[Ds],gr=xr===o.bk.vertical,Kn=xr===o.bk.horizontal||xr===o.bk.horizontalOnly;!In&&!Sr||jn.isHidden()||Cs++;let pa=!1;if((In||Sr)&&se)for(const Ea of N.activeReplacements){if(o.bz(Ea,Q,o.bA.Symbol,we)||Ea.min.x>pn||pn>Ea.max.x||Ea.min.y>Un||Un>Ea.max.y)continue;const na=o.bB(pn,Un,ue.canonical,Ea.footprintTileId.canonical);if(pa=o.bC(na,Ea.footprint),pa)break}if(pa&&this.collisionIndex.markSymbolAsClipped(N.bucketInstanceId,is.featureIndex),In){const Ea=pa?rd:wi(jn.text);ds(N.text,_s,gr?rd:Ea),ds(N.text,Xs,Kn?rd:Ea);const na=jn.text.isHidden(),{leftJustifiedTextSymbolIndex:ma,centerJustifiedTextSymbolIndex:hi,rightJustifiedTextSymbolIndex:Ei,verticalPlacedTextSymbolIndex:ki}=is,io=N.text.placedSymbolArray,ti=na||gr?1:0;ma>=0&&(io.get(ma).hidden=ti),hi>=0&&(io.get(hi).hidden=ti),Ei>=0&&(io.get(Ei).hidden=ti),ki>=0&&(io.get(ki).hidden=na||Kn?1:0);const oo=this.variableOffsets[Ds];oo&&this.markUsedJustification(N,oo.anchor,is,xr);const Si=this.placedOrientations[Ds];Si&&(this.markUsedJustification(N,"left",is,Si),this.markUsedOrientation(N,Si,is))}if(Sr){const Ea=pa?rd:wi(jn.icon),{placedIconSymbolIndex:na,verticalPlacedIconSymbolIndex:ma}=is,hi=N.icon.placedSymbolArray,Ei=jn.icon.isHidden()?1:0;na>=0&&(ds(N.icon,_n,gr?rd:Ea),hi.get(na).hidden=Ei),ma>=0&&(ds(N.icon,is.numVerticalIconVertices,Kn?rd:Ea),hi.get(ma).hidden=Ei)}if(N.hasIconCollisionBoxData()||N.hasTextCollisionBoxData()){const Ea=N.collisionArrays[es];if(Ea){let na=new o.P(0,0),ma=!0;if(Ea.textBox||Ea.verticalTextBox){if(ct){const Ei=this.variableOffsets[Ds];Ei?(na=rc(Ei.anchor,Ei.width,Ei.height,Ei.textOffset,Ei.textScale),St&&na._rotate(kt?this.transform.angle:-this.transform.angle)):ma=!1}Qe&&(ma=!jn.clipped),Ea.textBox&&em(N.textCollisionBox.collisionVertexArray,jn.text.placed,!ma||gr,Bs,Xt,na.x,na.y),Ea.verticalTextBox&&em(N.textCollisionBox.collisionVertexArray,jn.text.placed,!ma||Kn,Bs,Xt,na.x,na.y)}const hi=ma&&!!(!Kn&&Ea.verticalIconBox);Ea.iconBox&&em(N.iconCollisionBox.collisionVertexArray,jn.icon.placed,hi,Bs,Xt,is.hasIconTextFit?na.x:0,is.hasIconTextFit?na.y:0),Ea.verticalIconBox&&em(N.iconCollisionBox.collisionVertexArray,jn.icon.placed,!hi,Bs,Xt,is.hasIconTextFit?na.x:0,is.hasIconTextFit?na.y:0)}}}if(N.fullyClipped=Cs===0,N.sortFeatures(this.transform.angle),this.retainedQueryData[N.bucketInstanceId]&&(this.retainedQueryData[N.bucketInstanceId].featureSortOrder=N.featureSortOrder),N.hasTextData()&&N.text.opacityVertexBuffer&&N.text.opacityVertexBuffer.updateData(N.text.opacityVertexArray),N.hasIconData()&&N.icon.opacityVertexBuffer&&N.icon.opacityVertexBuffer.updateData(N.icon.opacityVertexArray),N.hasIconCollisionBoxData()&&N.iconCollisionBox.collisionVertexBuffer&&N.iconCollisionBox.collisionVertexBuffer.updateData(N.iconCollisionBox.collisionVertexArray),N.hasTextCollisionBoxData()&&N.textCollisionBox.collisionVertexBuffer&&N.textCollisionBox.collisionVertexBuffer.updateData(N.textCollisionBox.collisionVertexArray),N.bucketInstanceId in this.collisionCircleArrays){const es=this.collisionCircleArrays[N.bucketInstanceId];N.placementInvProjMatrix=es.invProjMatrix,N.placementViewportMatrix=es.viewportMatrix,N.collisionCircleArray=es.circles,delete this.collisionCircleArrays[N.bucketInstanceId]}}symbolFadeChange(N){return this.fadeDuration===0?1:(N-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(N){return Math.max(0,(this.transform.zoom-N)/1.5)}hasTransitions(N){return N-this.lastPlacementChangeTimeN}isStale(){return this.stale}setStale(){this.stale=!0}}function em(R,N,T,B,W,Q,se){R.emplaceBack(N?1:0,T?1:0,Q||0,se||0,B,W?1:0),R.emplaceBack(N?1:0,T?1:0,Q||0,se||0,B,W?1:0),R.emplaceBack(N?1:0,T?1:0,Q||0,se||0,B,W?1:0),R.emplaceBack(N?1:0,T?1:0,Q||0,se||0,B,W?1:0)}const Gt=Math.pow(2,25),An=Math.pow(2,24),qn=Math.pow(2,17),qr=Math.pow(2,16),Pa=Math.pow(2,9),vi=Math.pow(2,8),Li=Math.pow(2,1);function wi(R){if(R.opacity===0&&!R.placed)return 0;if(R.opacity===1&&R.placed)return 4294967295;const N=R.placed?1:0,T=Math.floor(127*R.opacity);return T*Gt+N*An+T*qn+N*qr+T*Pa+N*vi+T*Li+N}const rd=0;class Au{constructor(N){this._sortAcrossTiles=N.layout.get("symbol-z-order")!=="viewport-y"&&N.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(N,T,B,W,Q,se){const ue=this._bucketParts;for(;this._currentTileIndexwe.sortKey-Te.sortKey));this._currentPartIndex{const we=o.o.now()-se;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&we>2};for(;this._currentPlacementIndex>=0;){const we=T[N[this._currentPlacementIndex]],Te=this.placement.collisionIndex.transform.zoom;if(we.type==="symbol"&&we.visibility!=="none"&&(!we.minzoom||we.minzoom<=Te)&&(!we.maxzoom||we.maxzoom>Te)){const De=we,Qe=De.layout.get("symbol-z-elevate"),Ye=De.layout.get("symbol-sort-key").constantOr(1)!==void 0,tt=De.layout.get("symbol-z-order"),ht=tt==="viewport-y"||tt==="auto"&&!(tt!=="viewport-y"&&Ye),ct=De.layout.get("text-allow-overlap")||De.layout.get("icon-allow-overlap")||De.layout.get("text-ignore-placement")||De.layout.get("icon-ignore-placement"),St=ht&&ct,kt=this._inProgressLayer=this._inProgressLayer||new Au(De),Ut=o.F(we.source,we.scope);if(kt.continuePlacement(Qe||St?W[Ut]:B[Ut],this.placement,this._showCollisionBoxes,we,ue,Q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(N){return this.placement.commit(N),this.placement}}const gd=512/o.an/2;class Hd{constructor(N,T,B){this.tileID=N,this.bucketInstanceId=B,this.index=new o.bI(T.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const W=N.canonical.x*o.an,Q=N.canonical.y*o.an;for(let se=0;seSt-kt);for(const St of ct){const kt=this.crossTileIDs[St];if(this.keys[St]===De&&!B.has(kt)){B.add(kt),Te.crossTileID=kt;break}}}}}class Th{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Rp{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(N){const T=Math.round((N-this.lng)/360);if(T!==0)for(const B in this.indexes){const W=this.indexes[B],Q={};for(const se in W){const ue=W[se];ue.tileID=ue.tileID.unwrapTo(ue.tileID.wrap+T),Q[ue.tileID.key]=ue}this.indexes[B]=Q}this.lng=N}addBucket(N,T,B){if(this.indexes[N.overscaledZ]&&this.indexes[N.overscaledZ][N.key]){if(this.indexes[N.overscaledZ][N.key].bucketInstanceId===T.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(N.overscaledZ,this.indexes[N.overscaledZ][N.key])}for(let Q=0;QN.overscaledZ)for(const ue in se){const we=se[ue];we.tileID.isChildOf(N)&&we.findMatches(T.symbolInstances,N,W)}else{const ue=se[N.scaledTo(Number(Q)).key];ue&&ue.findMatches(T.symbolInstances,N,W)}}for(let Q=0;Q{T[B]=!0});for(const B in this.layerIndexes)T[B]||delete this.layerIndexes[B]}}const ac=771;class $a{constructor(N,T,B,W){this.blendFunction=N,this.blendColor=T.toNonPremultipliedRenderColor(null),this.mask=B,this.blendEquation=W}}$a.Replace=[1,0,1,0],$a.disabled=new $a($a.Replace,o.aq.transparent,[!1,!1,!1,!1]),$a.unblended=new $a($a.Replace,o.aq.transparent,[!0,!0,!0,!0]),$a.alphaBlended=new $a([1,ac,1,ac],o.aq.transparent,[!0,!0,!0,!0]),$a.alphaBlendedNonPremultiplied=new $a([770,ac,770,ac],o.aq.transparent,[!0,!0,!0,!0]),$a.multiply=new $a([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),$a.multiplyAccumulateAlpha=new $a([774,0,1,ac],o.aq.transparent,[!0,!0,!0,!0]),$a.additive=new $a([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Yr{constructor(N,T,B){this.func=N,this.mask=T,this.range=B}}Yr.ReadOnly=!1,Yr.ReadWrite=!0,Yr.disabled=new Yr(519,Yr.ReadOnly,[0,1]);const Tc=7680;class Va{constructor(N,T,B,W,Q,se){this.test=N,this.ref=T,this.mask=B,this.fail=W,this.depthFail=Q,this.pass=se}}Va.disabled=new Va({func:519,mask:0},0,0,Tc,Tc,Tc);const Fp=1029,cu=2305;class ba{constructor(N,T,B){this.enable=N,this.mode=T,this.frontFace=B}}function Zg(R,N){const T=o.bO(R,3);o.bR(R,N),o.bW(R,3,T)}function qy(R,N){const T=o.bL([]);return o.bM(T,T,-N),o.bN(T,T,-R),T}function wg(R,N){const T=[R[0],R[1],0],B=[N[0],N[1],0];if(o.ai(T)>=1e-15){const se=o.ay([],T);o.bJ(B,se,o.bi(B,se)),N[0]=B[0],N[1]=B[1]}const W=o.bh([],N,R);if(o.bK(W)<1e-15)return null;const Q=Math.atan2(-W[1],W[0]);return qy(Math.atan2(Math.sqrt(R[0]*R[0]+R[1]*R[1]),-R[2]),Q)}ba.disabled=new ba(!1,Fp,cu),ba.backCCW=new ba(!0,Fp,cu),ba.backCW=new ba(!0,Fp,2304),ba.frontCW=new ba(!0,1028,2304),ba.frontCCW=new ba(!0,1028,cu);class F0{constructor(N,T){this.position=N,this.orientation=T}get position(){return this._position}set position(N){if(N){const T=N instanceof o.ag?N:new o.ag(N[0],N[1],N[2]);this._renderWorldCopies&&(T.x=o.bs(T.x,0,1)),this._position=T}else this._position=null}lookAtPoint(N,T,B){if(this.orientation=null,!this.position)return;const W=this.position,Q=B||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(N)):0),se=o.ag.fromLngLat(N,Q),ue=[se.x-W.x,se.y-W.y,se.z-W.z];T||(T=[0,0,1]),T[2]=Math.abs(T[2]),this.orientation=wg(ue,T)}setPitchBearing(N,T){this.orientation=qy(o.ap(N),o.ap(-T))}}class Vx{constructor(N,T){this._transform=o.b9([]),this.orientation=T,this.position=N}get mercatorPosition(){const N=this.position;return new o.ag(N[0],N[1],N[2])}get position(){const N=o.bO(this._transform,3);return[N[0],N[1],N[2]]}set position(N){var T;N&&o.bW(this._transform,3,[(T=N)[0],T[1],T[2],1])}get orientation(){return this._orientation}set orientation(N){this._orientation=N||o.bL([]),N&&Zg(this._transform,this._orientation)}getPitchBearing(){const N=this.forward(),T=this.right();return{bearing:Math.atan2(-T[1],T[0]),pitch:Math.atan2(Math.sqrt(N[0]*N[0]+N[1]*N[1]),-N[2])}}setPitchBearing(N,T){this._orientation=qy(N,T),Zg(this._transform,this._orientation)}forward(){const N=o.bO(this._transform,2);return[-N[0],-N[1],-N[2]]}up(){const N=o.bO(this._transform,1);return[-N[0],-N[1],-N[2]]}right(){const N=o.bO(this._transform,0);return[N[0],N[1],N[2]]}getCameraToWorld(N,T){const B=new Float64Array(16);return o.b7(B,this.getWorldToCamera(N,T)),B}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(N,T,B){const W=this.position;o.bJ(W,W,-N);const Q=new Float64Array(16);return o.bP(Q,[B,B,B]),o.bx(Q,Q,W),Q[10]*=T,Q}getWorldToCamera(N,T){const B=new Float64Array(16),W=new Float64Array(4),Q=this.position;return o.bQ(W,this._orientation),o.bJ(Q,Q,-N),o.bR(B,W),o.bx(B,B,Q),B[1]*=-1,B[5]*=-1,B[9]*=-1,B[13]*=-1,B[8]*=T,B[9]*=T,B[10]*=T,B[11]*=T,B}getCameraToClipPerspective(N,T,B,W){const Q=new Float64Array(16);return o.bS(Q,N,T,B,W),Q}getCameraToClipOrthographic(N,T,B,W,Q,se){const ue=new Float64Array(16);return o.bT(ue,N,T,B,W,Q,se),ue}getDistanceToElevation(N,T=!1){const B=N===0?0:o.bU(N,T?o.bV(this.position[1]):this.position[1]),W=this.forward();return(B-this.position[2])/W[2]}clone(){return new Vx([...this.position],[...this.orientation])}}const Id=(R,N)=>({u_matrix:R,u_ground_shadow_factor:N});class ff{constructor(N=0,T=0,B=0,W=0){if(isNaN(N)||N<0||isNaN(T)||T<0||isNaN(B)||B<0||isNaN(W)||W<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=N,this.bottom=T,this.left=B,this.right=W}interpolate(N,T,B){return T.top!=null&&N.top!=null&&(this.top=o.am(N.top,T.top,B)),T.bottom!=null&&N.bottom!=null&&(this.bottom=o.am(N.bottom,T.bottom,B)),T.left!=null&&N.left!=null&&(this.left=o.am(N.left,T.left,B)),T.right!=null&&N.right!=null&&(this.right=o.am(N.right,T.right,B)),this}getCenter(N,T){const B=o.aC((this.left+N-this.right)/2,0,N),W=o.aC((this.top+T-this.bottom)/2,0,T);return new o.P(B,W)}equals(N){return this.top===N.top&&this.bottom===N.bottom&&this.left===N.left&&this.right===N.right}clone(){return new ff(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const bm=15;class ph{constructor(N,T,B,W,Q,se,ue){this.tileSize=512,this._renderWorldCopies=Q===void 0||Q,this._minZoom=N||0,this._maxZoom=T||22,this._minPitch=B??0,this._maxPitch=W??60,this.setProjection(se),this.setMaxBounds(ue),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 ff,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Vx,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 N=new ph(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return N._elevation=this._elevation,N._centerAltitude=this._centerAltitude,N._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,N.tileSize=this.tileSize,N.mercatorFromTransition=this.mercatorFromTransition,N.width=this.width,N.height=this.height,N.cameraElevationReference=this.cameraElevationReference,N._center=this._center,N._setZoom(this.zoom),N._seaLevelZoom=this._seaLevelZoom,N.angle=this.angle,N._fov=this._fov,N._pitch=this._pitch,N._nearZ=this._nearZ,N._farZ=this._farZ,N._nearClipOffset=this._nearClipOffset,N._averageElevation=this._averageElevation,N._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,N._unmodified=this._unmodified,N._edgeInsets=this._edgeInsets.clone(),N._camera=this._camera.clone(),N._calcMatrices(),N.freezeTileCoverage=this.freezeTileCoverage,N.frustumCorners=this.frustumCorners,N._allowWorldUnderZoom=this._allowWorldUnderZoom,N}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||N===Number.NEGATIVE_INFINITY&&(!T||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const B=this._elevation;T||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&B.exaggeration()&&this._centerAltitudeValidForExaggeration!==B.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*B.exaggeration(),this._centerAltitudeValidForExaggeration=B.exaggeration()):(this._centerAltitude=N||0,this._centerAltitudeValidForExaggeration=B.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const N=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(N)}sampleAverageElevation(){if(!this._elevation)return 0;const N=this._elevation,T=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],B=this.horizonLineFromTop();let W=0,Q=0;for(let se=0;se{const St=o.ck(Ye,Qe,tt,ht,ct);we.has(St)||(Q.push(new o.aR(Qe,Ye,tt,ht,ct)),we.add(St))};for(let Qe=0;QeYe.canonical.z)continue;const tt=Ye.canonical,ht=Ye.overscaledZ,ct=Ye.wrap,St=1<0,Xt=tt.y+10,Ts=Ye.wrap-(Ut?0:1),ds=Ye.wrap+(kt?0:1),Cs=Ut?tt.x-1:St-1,es=kt?tt.x+1:0;if(se)B[0]<0?(Te(ht,ds,tt.z,es,tt.y),B[1]<0&&Xt&&(Te(ht,ct,tt.z,tt.x,tt.y+1),Te(ht,ds,tt.z,es,tt.y+1)),B[1]>0&&Et&&(Te(ht,ct,tt.z,tt.x,tt.y-1),Te(ht,ds,tt.z,es,tt.y-1))):B[0]>0?(Te(ht,Ts,tt.z,Cs,tt.y),B[1]<0&&Xt&&(Te(ht,ct,tt.z,tt.x,tt.y+1),Te(ht,Ts,tt.z,Cs,tt.y+1)),B[1]>0&&Et&&(Te(ht,ct,tt.z,tt.x,tt.y-1),Te(ht,Ts,tt.z,Cs,tt.y-1))):B[1]<0&&Xt?Te(ht,ct,tt.z,tt.x,tt.y+1):Et&&Te(ht,ct,tt.z,tt.x,tt.y-1);else{const is=Ye.visibleQuadrants;1&is&&(Te(ht,Ts,tt.z,Cs,tt.y),Et&&(Te(ht,ct,tt.z,tt.x,tt.y-1),Te(ht,Ts,tt.z,Cs,tt.y-1))),2&is&&(Te(ht,ds,tt.z,es,tt.y),Et&&(Te(ht,ct,tt.z,tt.x,tt.y-1),Te(ht,ds,tt.z,es,tt.y-1))),4&is&&(Te(ht,Ts,tt.z,Cs,tt.y),Xt&&(Te(ht,ct,tt.z,tt.x,tt.y+1),Te(ht,Ts,tt.z,Cs,tt.y+1))),8&is&&(Te(ht,ds,tt.z,es,tt.y),Xt&&(Te(ht,ct,tt.z,tt.x,tt.y+1),Te(ht,ds,tt.z,es,tt.y+1)))}}const De=[];for(const Qe of Q)Q.some(Ye=>Qe.isChildOf(Ye))||De.push(Qe);if(Q=De.filter(Qe=>!N.some(Ye=>!!(Qe.overscaledZ{const kt=St.canonical.x+.5-tt[0],Ut=St.canonical.y+.5-tt[1];return kt*kt+Ut*Ut{const Cs=o.ck(Xt,Ut,Et,Ts,ds);Q.has(Cs)||(W.push(new o.aR(Ut,Xt,Et,Ts,ds)),Q.add(Cs))},ue=N.reduce((Ut,Xt)=>Math.max(Ut,Xt.overscaledZ),B),we=1<{const Et=Math.floor(Ut[0]),Ts=Math.floor(Ut[1]),ds=(Ut[0]-Et)*o.an,Cs=(Ut[1]-Ts)*o.an,es=Math.floor(Xt[0]),is=Math.floor(Xt[1]),_s=(Xt[0]-es)*o.an,Xs=(Xt[1]-is)*o.an;for(let Ds=-1;Ds<=1;Ds++){const _n=Et+Ds;if(!(_n<0||_n>=we)){De.x=ds-Ds*o.an,Qe.x=_s-(_n-es)*o.an;for(let pn=-1;pn<=1;pn++){const Un=Ts+pn;De.y=Cs-pn*o.an,Qe.y=Xs-(Un-is)*o.an,o.cI(De,Qe,Te)&&se(ue,0,B,_n,Un)}}}},tt=T.points,ht=tt[o.c9],ct=tt[o.ca],St=this._projectToGround(ht,tt[o.cb]),kt=this._projectToGround(ct,tt[o.cc]);return Ye(ht,St),Ye(ct,kt),W}_projectToGround(N,T){return o.cd(o.ce(),N,T,N[2]/(N[2]-T[2]))}_projectToZ(N,T,B){const W=N[2]-T[2];return Math.abs(W)<1e-6?o.cf(N):o.cd(o.ce(),N,T,(N[2]-B)/W)}extendTileCoverForTunnels(N,T,B,W){if(B<18)return[];const Q=T.points,se=Q[o.cg],ue=Q[o.ch],we=Q[o.ci],Te=Q[o.cj];if(we[2]>=0&&Te[2]>=0||se[2]<=0||ue[2]<=0)return[];const De=we[2]<0?this._projectToZ(se,we,0):we,Qe=Te[2]<0?this._projectToZ(ue,Te,0):Te,Ye=-W,tt=we[2]3&&(ct.length=3),ct}_findExtensionTilesInQuad(N,T,B,W){const Q=[],se=new Set;for(const es of N)se.add(es.key);const ue=N.reduce((es,is)=>Math.max(es,is.overscaledZ),T),we=1<{const _s=es.canonical.x+.5-ds,Xs=es.canonical.y+.5-Cs,Ds=is.canonical.x+.5-ds,_n=is.canonical.y+.5-Cs;return _s*_s+Xs*Xs-(Ds*Ds+_n*_n)||es.canonical.x-is.canonical.x||es.canonical.y-is.canonical.y}),Q}coveringTiles(N){let T=this.coveringZoomLevel(N);const B=T,W=this.elevation&&this.elevation.exaggeration(),Q=W&&!N.isTerrainDEM,se=this.projection.name==="mercator";if(N.minzoom!==void 0&&TN.maxzoom&&(T=N.maxzoom);const ue=this.locationCoordinate(this.center),we=this.center.lat,Te=1<{const jn=new o.ag(Bs.x+25e-6,Bs.y,Bs.z),In=new o.ag(Bs.x,Bs.y+25e-6,Bs.z),Sr=Bs.toLngLat(),xr=jn.toLngLat(),gr=In.toLngLat(),Kn=this.locationCoordinate(Sr),pa=this.locationCoordinate(xr),Ea=this.locationCoordinate(gr),na=Math.hypot(pa.x-Kn.x,pa.y-Kn.y),ma=Math.hypot(Ea.x-Kn.x,Ea.y-Kn.y);return Math.sqrt(na*ma)*Cs/25e-6},is=Bs=>{const yn=Ts,jn=ds;return{aabb:o.cp(this,Te,0,0,0,Bs,jn,yn,this.projection),zoom:0,x:0,y:0,minZ:jn,maxZ:yn,wrap:Bs,fullyVisible:!1}},_s=[];let Xs=[];const Ds=T,_n=N.reparseOverscaled?B:T,pn=(St-this._centerAltitude)*ct,Un=Bs=>{if(!this._elevation||!Bs.tileID||!se)return;const yn=this._elevation.getMinMaxForTile(Bs.tileID),jn=Bs.aabb;yn?(jn.min[2]=yn.min,jn.max[2]=yn.max,jn.center[2]=(jn.min[2]+jn.max[2])/2):(Bs.shouldSplit=nn(Bs),Bs.shouldSplit||(jn.min[2]=jn.max[2]=jn.center[2]=this._centerAltitude))},Xn=(Bs,yn)=>{if(.707*yn{if(Bs.zoom=.9)return!0}else if(Q&&(In=Bs.aabb.distanceZ(kt)*ct),this.projection.isReprojectedInTileSpace&&B<=5){const ma=Math.pow(2,Bs.zoom),hi=es(new o.ag((Bs.x+.5)/ma,(Bs.y+.5)/ma));Sr=hi>.85?1:hi}if(!se&&!Qe){const ma=Math.sqrt(yn*yn+jn*jn+In*In);let hi=(1<0;){const Bs=_s.pop(),yn=Bs.x,jn=Bs.y;let In=Bs.fullyVisible;const Sr=()=>this.projection.name==="globe"&&(Bs.y===0||Bs.y===(1<xr)continue;let gr=0;if(!In){let na=Ut?Bs.aabb.intersectsPrecise(tt):Bs.aabb.intersectsPreciseFlat(tt);if(na===0&&Sr()){const ma=new o.cn(Bs.zoom,yn,jn);na=o.co(this,Te,ma,!0).intersectsPrecise(tt)}if(na===0)continue;if(N.calculateQuadrantVisibility)if(tt.containsPoint(Bs.aabb.center))gr=15;else for(let ma=0;ma<4;ma++)Bs.aabb.quadrant(ma).intersects(tt)!==0&&(gr|=1<>1),pa={aabb:se?Bs.aabb.quadrant(xr):o.cp(this,Te,Bs.zoom+1,gr,Kn,Bs.wrap,Bs.minZ,Bs.maxZ,this.projection),zoom:Bs.zoom+1,x:gr,y:Kn,wrap:Bs.wrap,fullyVisible:In,tileID:void 0,shouldSplit:void 0,minZ:Bs.minZ,maxZ:Bs.maxZ};Q&&!Qe&&(pa.tileID=new o.aR(Bs.zoom+1===Ds?_n:Bs.zoom+1,Bs.wrap,Bs.zoom+1,gr,Kn),Un(pa)),_s.push(pa)}}if(this.fogCullDistSq){const Bs=this.fogCullDistSq,yn=this.horizonLineFromTop();Xs=Xs.filter(jn=>{const In=[0,0,0,1],Sr=[o.an,o.an,0,1],xr=this.calculateFogTileMatrix(jn.tileID.toUnwrapped());o.aE(In,In,xr),o.aE(Sr,Sr,xr);const gr=o.cq([],In,Sr),Kn=o.cr([],In,Sr),pa=o.cK(gr,Kn);if(pa===0)return!0;let Ea=!1;const na=this._elevation;if(na&&pa>Bs&&yn!==0){const ma=this.calculateProjMatrix(jn.tileID.toUnwrapped());let hi;N.isTerrainDEM||(hi=na.getMinMaxForTile(jn.tileID)),hi||(hi={min:ds,max:Ts});const Ei=o.cs(this.rotation),ki=[Ei[0]*o.an,Ei[1]*o.an,hi.max];o.ah(ki,ki,ma),Ea=(1-ki[1])*this.height*.5Bs.distanceSq-yn.distanceSq).map(Bs=>Bs.tileID)}resize(N,T){this.width=N,this.height=T,this.pixelsToGLUnits=[2/N,-2/T],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(N){return Math.pow(2,N)}scaleZoom(N){return Math.log2(N)}project(N){const T=o.aC(N.lat,-o.ct,o.ct),B=this.projection.project(N.lng,T);return new o.P(B.x*this.worldSize,B.y*this.worldSize)}unproject(N){return this.projection.unproject(N.x/this.worldSize,N.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(N,T){let B,W;const Q=this.centerPoint;if(this.projection.name==="globe"){const ue=this.worldSize;B=(T.x-Q.x)/ue,W=(T.y-Q.y)/ue}else{const ue=this.pointCoordinate(T),we=this.pointCoordinate(Q);B=ue.x-we.x,W=ue.y-we.y}const se=this.locationCoordinate(N);this.setLocation(new o.ag(se.x-B,se.y-W))}setLocation(N){this.center=this.coordinateLocation(N),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(N,T){return this.projection.locationPoint(this,N,T)}locationPoint3D(N,T){return this.projection.locationPoint(this,N,T,!0)}pointLocation(N){return this.coordinateLocation(this.pointCoordinate(N))}pointLocation3D(N,T){return this.coordinateLocation(this.pointCoordinate3D(N,T))}locationCoordinate(N,T){const B=T?o.bU(T,N.lat):void 0,W=this.projection.project(N.lng,N.lat);return new o.ag(W.x,W.y,B)}coordinateLocation(N){return this.projection.unproject(N.x,N.y)}pointRayIntersection(N,T){const B=T??this._centerAltitude,W=[N.x,N.y,0,1],Q=[N.x,N.y,1,1];o.aE(W,W,this.pixelMatrixInverse),o.aE(Q,Q,this.pixelMatrixInverse);const se=Q[3];o.cu(W,W,1/W[3]),o.cu(Q,Q,1/se);const ue=W[2],we=Q[2];return{p0:W,p1:Q,t:ue===we?0:(B-ue)/(we-ue)}}screenPointToMercatorRay(N){const T=[N.x,N.y,0,1],B=[N.x,N.y,1,1];return o.aE(T,T,this.pixelMatrixInverse),o.aE(B,B,this.pixelMatrixInverse),o.cu(T,T,1/T[3]),o.cu(B,B,1/B[3]),T[2]=o.bU(T[2],this._center.lat)*this.worldSize,B[2]=o.bU(B[2],this._center.lat)*this.worldSize,o.cu(T,T,1/this.worldSize),o.cu(B,B,1/this.worldSize),new o.az([T[0],T[1],T[2]],o.ay([],o.ax([],B,T)))}rayIntersectionCoordinate(N){const{p0:T,p1:B,t:W}=N,Q=o.bU(T[2],this._center.lat),se=o.bU(B[2],this._center.lat);return new o.ag(o.am(T[0],B[0],W)/this.worldSize,o.am(T[1],B[1],W)/this.worldSize,o.am(Q,se,W))}pointCoordinate(N,T=this._centerAltitude){return this.projection.pointCoordinate(this,N.x,N.y,T)}pointCoordinate3D(N,T){if(!this.elevation)return this.pointCoordinate(N,T);let B=this.projection.pointCoordinate3D(this,N.x,N.y);if(B)return new o.ag(B[0],B[1],B[2]);let W=0,Q=this.horizonLineFromTop();if(N.y>Q)return this.pointCoordinate(N,T);const se=.02*Q,ue=N.clone();for(let we=0;we<10&&Q-W>se;we++){ue.y=o.am(W,Q,.66);const Te=this.projection.pointCoordinate3D(this,ue.x,ue.y);Te?(Q=ue.y,B=Te):W=ue.y}return B?new o.ag(B[0],B[1],B[2]):this.pointCoordinate(N)}isPointAboveHorizon(N){return this.projection.isPointAboveHorizon(this,N)}isPointOnSurface(N){if(N.y<0||N.y>this.height||N.x<0||N.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(N);const T=this.pointCoordinate(N);return T.y>=0&&T.y<=1}_coordinatePoint(N,T){const B=T&&this.elevation?this.elevation.getAtPointOrZero(N,this._centerAltitude):this._centerAltitude,W=[N.x*this.worldSize,N.y*this.worldSize,B+N.toAltitude(),1];return o.aE(W,W,this.pixelMatrix),W[3]>0?new o.P(W[0]/W[3],W[1]/W[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:N,left:T}=this._edgeInsets,B=this.height-this._edgeInsets.bottom,W=this.width-this._edgeInsets.right,Q=this.pointLocation3D(new o.P(T,N)),se=this.pointLocation3D(new o.P(W,N)),ue=this.pointLocation3D(new o.P(W,B)),we=this.pointLocation3D(new o.P(T,B));let Te=Math.min(Q.lng,se.lng,ue.lng,we.lng),De=Math.max(Q.lng,se.lng,ue.lng,we.lng),Qe=Math.min(Q.lat,se.lat,ue.lat,we.lat),Ye=Math.max(Q.lat,se.lat,ue.lat,we.lat);const tt=Math.pow(2,-this.zoom)/16*270,ht=this.projection.name==="globe"?1:4,ct=(St,kt,Ut,Xt,Et)=>{const Ts=(St+Ut)/2,ds=(kt+Xt)/2,Cs=new o.P(Ts,ds),{lng:es,lat:is}=this.pointLocation3D(Cs),_s=Math.max(0,Te-es,Qe-is,es-De,is-Ye);Te=Math.min(Te,es),De=Math.max(De,es),Qe=Math.min(Qe,is),Ye=Math.max(Ye,is),(Ettt)&&(ct(St,kt,Ts,ds,Et+1),ct(Ts,ds,Ut,Xt,Et+1))};if(ct(T,N,W,N,1),ct(W,N,W,B,1),ct(W,B,T,B,1),ct(T,B,T,N,1),this.projection.name==="globe"){const[St,kt]=o.cw(this);St?(Ye=90,De=180,Te=-180):kt&&(Qe=-90,De=180,Te=-180)}return new o.aK(new o.aU(Te,Qe),new o.aU(De,Ye))}_getBoundsRectangular(N,T){const{top:B,left:W}=this._edgeInsets,Q=this.height-this._edgeInsets.bottom,se=this.width-this._edgeInsets.right,ue=new o.P(W,B),we=new o.P(se,B),Te=new o.P(se,Q),De=new o.P(W,Q);let Qe=this.pointCoordinate(ue,N),Ye=this.pointCoordinate(we,N);const tt=this.pointCoordinate(Te,T),ht=this.pointCoordinate(De,T),ct=(St,kt)=>(kt.y-St.y)/(kt.x-St.x);return Qe.y>1&&Ye.y>=0?Qe=new o.ag((1-ht.y)/ct(ht,Qe)+ht.x,1):Qe.y<0&&Ye.y<=1&&(Qe=new o.ag(-ht.y/ct(ht,Qe)+ht.x,0)),Ye.y>1&&Qe.y>=0?Ye=new o.ag((1-tt.y)/ct(tt,Ye)+tt.x,1):Ye.y<0&&Qe.y<=1&&(Ye=new o.ag(-tt.y/ct(tt,Ye)+tt.x,0)),new o.aK().extend(this.coordinateLocation(Qe)).extend(this.coordinateLocation(Ye)).extend(this.coordinateLocation(ht)).extend(this.coordinateLocation(tt))}_getBoundsRectangularTerrain(){const N=this.elevation;if(!N.visibleDemTiles.length||N.isUsingMockSource())return this._getBoundsRectangular(0,0);const T=N.visibleDemTiles.reduce((B,W)=>{if(W.dem){const Q=W.dem.tree;B.min=Math.min(B.min,Q.minimums[0]),B.max=Math.max(B.max,Q.maximums[0])}return B},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(T.min*N.exaggeration(),T.max*N.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(N=!0){const T=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,B=this.height/2-T*(1-this._horizonShift);return N?Math.max(0,B):B}getMaxBounds(){return this.maxBounds}setMaxBounds(N){this.maxBounds=N,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,N&&(this.minLat=N.getSouth(),this.maxLat=N.getNorth(),this.minLng=N.getWest(),this.maxLng=N.getEast(),this.maxLngQe&&(ue=Qe-Te),Qe-Dett&&(se=tt-we),tt-Ye{for(let nn=0;nn<16;nn++)_n[nn]=o.am(pn[nn],Un[nn],Xn)})(ue,ue,we,o.cL(this.pitch>=bm?1:this.pitch/bm))}else ue=we;const Te=o.cz([],we,se);let De=o.cz([],ue,se);if(this.projection.isReprojectedInTileSpace){const is=this.locationCoordinate(this.center),_s=o.b9([]);o.bx(_s,_s,[is.x*this.worldSize,is.y*this.worldSize,0]),o.aD(_s,_s,o.cA(this)),o.bx(_s,_s,[-is.x*this.worldSize,-is.y*this.worldSize,0]),o.aD(De,De,_s),o.aD(Te,Te,_s),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],De,[this.worldSize,this.worldSize,this.worldSize/Q,1]),this.projMatrix=De,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),T){const is=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);is[8]=2*-N.x/this.width,is[9]=2*N.y/this.height,this.expandedFarZProjMatrix=o.cz([],is,se)}else this.expandedFarZProjMatrix=this.projMatrix;const Qe=o.b7([],ue);this.frustumCorners=o.cD.fromInvProjectionMatrix(Qe,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!T);const Ye=new Float32Array(16);o.b9(Ye),o.cC(Ye,Ye,[1,-1,1]),o.cE(Ye,Ye,this._pitch),o.ba(Ye,Ye,this.angle);const tt=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(tt);const ht=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;tt[8]=2*-N.x/this.width,tt[9]=2*(N.y+ht)/this.height,this.skyboxMatrix=o.aD(Ye,tt,Ye);const ct=this.point,St=ct.x,kt=ct.y,Ut=this.width%2/2,Xt=this.height%2/2,Et=Math.cos(this.angle),Ts=Math.sin(this.angle),ds=St-Math.round(St)+Et*Ut+Ts*Xt,Cs=kt-Math.round(kt)+Et*Xt+Ts*Ut,es=new Float64Array(De);if(o.bx(es,es,[ds>.5?ds-1:ds,Cs>.5?Cs-1:Cs,0]),this.alignedProjMatrix=es,De=o.bb(),o.cC(De,De,[this.width/2,-this.height/2,1]),o.bx(De,De,[1,-1,0]),this.labelPlaneMatrix=De,De=o.bb(),o.cC(De,De,[1,-1,1]),o.bx(De,De,[-1,-1,0]),o.cC(De,De,[2/this.width,2/this.height,1]),this.glCoordMatrix=De,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,Te),this._calcFogMatrices(),this._distanceTileDataCache={},De=o.b7(new Float64Array(16),this.pixelMatrix),!De)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=De,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const is=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(is,is,se),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=De;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const N=this.cameraWorldSizeForFog,T=this.cameraPixelsPerMeter,B=this._camera.position,W=1/this.height/this._pixelsPerMercatorPixel,Q=[N,N,T];o.bJ(Q,Q,W),o.bJ(B,B,-1),o.cG(B,B,Q);const se=o.bb();o.bx(se,se,B),o.cC(se,se,Q),this.mercatorFogMatrix=se,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(N,T,W)}_computeCameraPosition(N){const T=(N=N||this.pixelsPerMeter)/this.pixelsPerMeter,B=this._camera.forward(),W=this.point,Q=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*T-N/this.worldSize*this._centerAltitude;return[W.x/this.worldSize-B[0]*Q,W.y/this.worldSize-B[1]*Q,N/this.worldSize*this._centerAltitude-B[2]*Q]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(N){const T=this._maxCameraBoundsDistance()*Math.cos(this._pitch),B=this._camera.position[2],W=N[2];let Q=1;this.projection.wrap&&(this.center=this.center.wrap()),W>0&&(Q=Math.min((T-B)/W,1)),this._camera.position=o.bg([],this._camera.position,N,Q),this._updateStateFromCamera()}_updateStateFromCamera(){const N=this._camera.position,T=this._camera.forward(),{pitch:B,bearing:W}=this._camera.getPitchBearing(),Q=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,se=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),ue=Math.max((N[2]-Q)/Math.cos(B),se),we=this._zoomFromMercatorZ(ue);o.bg(N,N,T,ue),this._pitch=o.aC(B,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(W,-Math.PI,Math.PI),this._setZoom(o.aC(we,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(N[0],N[1],N[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(N){return Math.pow(2,N)*this.tileSize}_mercatorZfromZoom(N){return this.cameraToCenterDistance/this._worldSizeFromZoom(N)}_minimumHeightOverTerrain(){const N=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(N)}_zoomFromMercatorZ(N){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,N)*this.tileSize))}zoomFromMercatorZAdjusted(N){let T=0,B=o.cv,W=0,Q=1/0;for(;B-T>1e-6&&B>T;){const se=T+.5*(B-T),ue=this.tileSize*Math.pow(2,se),we=this.getCameraToCenterDistance(this.projection,se,ue),Te=this.scaleZoom(we/(Math.max(0,N)*this.tileSize)),De=Math.abs(se-Te);DeTe||Ye.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(N,T){const B=o.ai(o.ax([],this._camera.position,N)),W=this._zoomFromMercatorZ(B)+T;return B-this._mercatorZfromZoom(W)}getCameraPoint(){if(this.projection.name==="globe"){const N=function([T,B,W],Q){const se=[T,B,W,1];o.aE(se,se,Q);const ue=se[3]=Math.max(se[3],1e-6);return se[0]/=ue,se[1]/=ue,se[2]/=ue,se}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(N[0],N[1])}{const N=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,N))}}getCameraToCenterDistance(N,T=this.zoom,B=this.worldSize){const W=o.cy(N,T,this.width,this.height,1024),Q=N.pixelSpaceConversion(this.center.lat,B,W);let se=.5/Math.tan(.5*this._fov)*this.height*Q;return this.isOrthographic&&(se=o.am(1,se,o.cL(this.pitch>=bm?1:this.pitch/bm))),se}getWorldToCameraMatrix(){const N=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(N,N,this.globeMatrix),N}getFrustum(N){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,N,this.projection.zAxisUnit==="meters")}}const Gd=(R,N)=>{if(N>0&&R.terrain&&o.w("Cutoff is currently disabled on terrain"),N<=0||R.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const T=R.transform,B=T.pitch,W=T.isLODDisabled(!1)?60:30;if(B0,uniformValues:{u_cutoff_params:[T._nearZ,T._farZ,(De-T._nearZ)/Q,(De-Ye-T._nearZ)/Q]}}},xf=2048;class T1{constructor(N,T){this.aabb=N,this.lastCascade=T}}class M1{add(N,T){const B=this.receivers[N.key];B!==void 0?(B.aabb.min[0]=Math.min(B.aabb.min[0],T.min[0]),B.aabb.min[1]=Math.min(B.aabb.min[1],T.min[1]),B.aabb.min[2]=Math.min(B.aabb.min[2],T.min[2]),B.aabb.max[0]=Math.max(B.aabb.max[0],T.max[0]),B.aabb.max[1]=Math.max(B.aabb.max[1],T.max[1]),B.aabb.max[2]=Math.max(B.aabb.max[2],T.max[2])):this.receivers[N.key]=new T1(T,null)}clear(){this.receivers={}}get(N){return this.receivers[N.key]}computeRequiredCascades(N,T,B){const W=o.cU.fromPoints(N.points);let Q=0;for(const se in this.receivers){const ue=this.receivers[se];if(!ue||!W.intersectsAabb(ue.aabb))continue;ue.aabb.min=W.closestPoint(ue.aabb.min),ue.aabb.max=W.closestPoint(ue.aabb.max);const we=ue.aabb.getCorners();for(let Te=0;Te1||Ye[1]<-1||Ye[1]>1){De=!1;break}}if(ue.lastCascade=Te,Q=Math.max(Q,Te),De)break}}return Q+1}}class yd{constructor(N){this.painter=N,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new M1,this._depthMode=new Yr(N.context.gl.LEQUAL,Yr.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 N of this._cascades)N.texture.destroy(),N.framebuffer.destroy();this._cascades=[]}updateShadowParameters(N,T){const B=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!T||!T.properties)return;const W=T.properties.get("shadow-intensity"),Q=T.properties.get("shadow-draw-before-layer");if(!T.shadowsEnabled()||W<=0)return;let se=-1,ue=0;for(const kt of B.style.order){const Ut=B.style._mergedLayers[kt];Ut.hasShadowPass()&&!Ut.isHidden(N.zoom)&&(se=ue),!Q||Q!==kt&&Q!==Ut.slot||(this._drawShadowAfterLayer=ue>0?ue-1:0),ue+=1}if(this._enabled=se>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=se);const we=B.context,Te=xf,De=xf;if(this._cascades.length===0||xf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let kt=0;kt<2;++kt){const Ut=we.gl,Xt=we.createFramebuffer(Te,De,0,"texture"),Et=new o.T(we,{width:Te,height:De,data:null},Ut.DEPTH_COMPONENT16);Xt.depthAttachment.set(Et.texture),this._cascades.push({framebuffer:Xt,texture:Et,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=O0(T);let Qe=0;if(N.elevation){const kt=N.elevation,Ut=[1e4,-1e4];kt.visibleDemTiles.filter(Xt=>Xt.dem).forEach(Xt=>{const Et=Xt.dem.tree;Ut[0]=Math.min(Ut[0],Et.minimums[0]),Ut[1]=Math.max(Ut[1],Et.maximums[0])}),Ut[0]!==1e4&&(Qe=(Ut[1]-Ut[0])*kt.exaggeration())}const Ye=1.5*N.cameraToCenterDistance,tt=3*Ye,ht=new Float64Array(16);for(let kt=0;kt=0)return{};const Q=function(we,Te,De){const Qe=De/(1<0&&(o.cT(Q[1],Q[1],[W[0]*se,0,0]),o.cT(Q[2],Q[2],[W[0]*se,0,0])),W[1]<0?(o.cT(Q[0],Q[0],[0,W[1]*se,0]),o.cT(Q[1],Q[1],[0,W[1]*se,0])):W[1]>0&&(o.cT(Q[2],Q[2],[0,W[1]*se,0]),o.cT(Q[3],Q[3],[0,W[1]*se,0]));const ue={};return ue.vertices=Q,ue.planes=[Xg(Q[1],Q[0],Q[4]),Xg(Q[2],Q[1],Q[5]),Xg(Q[3],Q[2],Q[6]),Xg(Q[0],Q[3],Q[7])],ue}addShadowReceiver(N,T,B){this._receivers.add(N,o.cU.fromTileIdAndHeight(N,T,B))}getMaxCascadeForTile(N){const T=this._receivers.get(N);return T&&T.lastCascade?T.lastCascade:0}}function Xg(R,N,T){const B=o.ax([],T,N),W=o.ax([],R,N),Q=o.bh([],B,W),se=o.ai(Q);return se===0?[0,0,1,0]:(o.bJ(Q,Q,1/se),[Q[0],Q[1],Q[2],-o.bi(Q,N)])}function O0(R){const N=R.properties.get("direction"),T=o.cP(N.x,N.y,N.z);T[2]=o.aC(T[2],0,75);const B=o.cR([T[0],T[1],T[2]]);return o.cQ(B.x,B.y,B.z)}function _m(R,N,T){const B=N.properties.get("color-use-theme")==="none",W=N.properties.get("color"),Q=N.properties.get("intensity"),se=N.properties.get("direction"),ue=[se.x,se.y,se.z],we=T.properties.get("color-use-theme")==="none",Te=T.properties.get("color"),De=T.properties.get("intensity"),Qe=Math.max(o.bi([0,0,1],ue),0),Ye=[0,0,0];o.bJ(Ye,Te.toPremultipliedRenderColor(we?null:R.getLut(N.scope)).toArray01Linear().slice(0,3),De);const tt=[0,0,0];return o.bJ(tt,W.toPremultipliedRenderColor(B?null:R.getLut(T.scope)).toArray01Linear().slice(0,3),Qe*Q),o.cW([Ye[0]>0?Ye[0]/(Ye[0]+tt[0]):0,Ye[1]>0?Ye[1]/(Ye[1]+tt[1]):0,Ye[2]>0?Ye[2]/(Ye[2]+tt[2]):0])}function Hx(R,N,T,B,W,Q){const se=R.zoom,ue=R.scale,we=R.worldSize,Te=1/we,De=R.aspect,Qe=Math.sqrt(1+De*De)*Math.tan(.5*R.fovX),Ye=Qe*Qe,tt=B-T,ht=B+T;let ct,St;Ye>tt/ht?(ct=B,St=B*Qe):(ct=.5*ht*(1+Ye),St=.5*Math.sqrt(tt*tt+2*(B*B+T*T)*Ye+ht*ht*Ye*Ye));const kt=R.projection.pixelsPerMeter(R.center.lat,we),Ut=R._camera.getCameraToWorldMercator(),Xt=[0,0,-ct*Te];o.ah(Xt,Xt,Ut);let Et=St*Te;const Ts=function(In){return In[0]/=ue,In[1]/=ue,In[2]=o.bU(In[2],R._center.lat),In},ds=R._edgeInsets;if(!(ds.left===0&&ds.top===0&&ds.right===0&&ds.bottom===0||ds.left===ds.right&&ds.top===ds.bottom)){const In=R._camera.getWorldToCamera(R.worldSize,R.projection.zAxisUnit==="meters"?kt:1),Sr=R._camera.getCameraToClipPerspective(R._fov,R.width/R.height,T,B);Sr[8]=2*-R.centerOffset.x/R.width,Sr[9]=2*R.centerOffset.y/R.height;const xr=new Float64Array(16);o.cz(xr,Sr,In);const gr=new Float64Array(16);o.b7(gr,xr);const Kn=o.cl.fromInvProjectionMatrix(gr,we,se,!0);for(const pa of Kn.points){const Ea=Ts(pa);Et=Math.max(Et,o.bK(o.cV([],Xt,Ea)))}}Et*=W/(W-1);const Cs=Math.acos(N[2]),es=Math.atan2(-N[0],-N[1]),is=new Vx;is.position=Xt,is.setPitchBearing(Cs,es);const _s=is.getWorldToCamera(we,kt),Xs=Et*we,Ds=Math.min(R._mercatorZfromZoom(17)*we*-2,-2*Xs),_n=is.getCameraToClipOrthographic(-Xs,Xs,-Xs,Xs,Ds,(Xs+Q*kt)/N[2]),pn=new Float64Array(16);o.aD(pn,_n,_s);const Un=o.cQ(Math.floor(1e6*Xt[0])/1e6*we,Math.floor(1e6*Xt[1])/1e6*we,0),Xn=.5*W,nn=[0,0,0];o.ah(nn,Un,pn),o.bJ(nn,nn,Xn);const Bs=[Math.floor(nn[0]),Math.floor(nn[1]),Math.floor(nn[2])],yn=[0,0,0];o.ax(yn,nn,Bs),o.bJ(yn,yn,-1/Xn);const jn=new Float64Array(16);return o.b9(jn),o.bx(jn,jn,yn),o.aD(pn,jn,pn),[pn,Xs]}class Fb extends o.E{constructor(N){super(),this.requestManager=N,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(N,T){return o.cX(this.requestManager.transformRequest(T,o.R.Model).url).then(B=>{const W=o.cY(B),Q=new o.cZ(N,T,void 0,void 0,W);return Q.computeBoundsAndApplyParent(),Q}).catch(B=>{if(B&&B.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${N} from ${T}: ${B.message}`)))})}load(N,T,B={forceReload:!1}){this.models[T]||(this.models[T]={});const W=Object.keys(N),Q=[],se=[];for(const ue of W){const we=N[ue];this.hasURLBeenRequested(we)&&!B.forceReload||(this.modelByURL[we]={modelId:ue,scope:T},Q.push(this.loadModel(ue,we)),se.push(ue)),this.models[T][ue]||(this.models[T][ue]={model:null,numReferences:1})}this.numModelsLoading[T]=(this.numModelsLoading[T]||0)+se.length,Promise.allSettled(Q).then(ue=>{for(let we=0;we{this.fire(new o.B(new Error(`Could not load models: ${ue.message}`)))})}isLoaded(){for(const N in this.numModelsLoading)if(this.numModelsLoading[N]>0)return!1;return!0}hasModel(N,T,B={exactIdMatch:!1}){return!!(B.exactIdMatch?this.getModel(N,T):this.getModelByURL(this.modelUris[T][N]))}getModel(N,T){return this.models[T]||(this.models[T]={}),this.models[T][N]?this.models[T][N].model:void 0}getModelByURL(N){if(!N)return null;const T=this.modelByURL[N];return T?this.models[T.scope][T.modelId].model:null}hasModelBeenAdded(N,T){return this.models[T]&&this.models[T][N]!==void 0}getModelURIs(N){return this.modelUris[N]||{}}addModel(N,T,B){this.models[B]||(this.models[B]={}),this.modelUris[B]||(this.modelUris[B]={});const W=this.requestManager.normalizeModelURL(T);if((this.hasModel(N,B,{exactIdMatch:!0})||this.hasModelBeenAdded(N,B))&&this.modelUris[B][N]===W)this.models[B][N].numReferences++;else if(this.hasURLBeenRequested(W)){const{scope:Q,modelId:se}=this.modelByURL[W];this.models[Q][se].numReferences++}else this.modelUris[B][N]=W,this.load({[N]:this.modelUris[B][N]},B)}addModelURLs(N,T){this.models[T]||(this.models[T]={}),this.modelUris[T]||(this.modelUris[T]={});const B=this.modelUris[T];for(const W in N)B[W]=this.requestManager.normalizeModelURL(N[W])}reloadModels(N){this.load(this.modelUris[N],N,{forceReload:!0})}addModelsFromBucket(N,T){this.models[T]||(this.models[T]={}),this.modelUris[T]||(this.modelUris[T]={});const B={};for(const W of N)this.hasModel(W,T,{exactIdMatch:!0})||this.hasURLBeenRequested(W)?this.models[T][W].numReferences++:this.modelUris[T][W]&&!this.hasURLBeenRequested(W)?B[W]=this.modelUris[T][W]:!this.hasURLBeenRequested(W)&&o.c_(W,!1)&&(this.modelUris[T][W]=this.requestManager.normalizeModelURL(W),B[W]=this.modelUris[T][W]);this.load(B,T)}hasURLBeenRequested(N){return this.modelByURL[N]!==void 0}removeModel(N,T,B=!1,W=!1){if(this.models[T]&&this.models[T][N]&&(this.models[T][N].numReferences--,this.models[T][N].numReferences===0||W)){const Q=this.modelUris[T][N];B||delete this.modelUris[T][N],delete this.modelByURL[Q];const se=this.models[T][N].model;if(!se)return;delete this.models[T][N],se.destroy()}}destroy(){for(const N of Object.keys(this.models))for(const T of Object.keys(this.models[N])){const B=this.models[N][T].model;delete this.models[N][T],B&&B.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(N){return this.models[N]||(this.models[N]={}),Object.keys(this.models[N])}upload(N,T){this.models[T]||(this.models[T]={});for(const B in this.models[T])this.models[T][B].model&&this.models[T][B].model.upload(N.context)}}const fh=o.a8.colorTheme,Mc=new o.ab({data:new o.ac(fh.data)});function Cl(R){if(!R.metadata||!R.metadata.content_area)return;const N=o.o.devicePixelRatio,{left:T,top:B,width:W,height:Q}=R.metadata.content_area,se=T*N,ue=B*N;return[se,ue,se+W*N,ue+Q*N]}function fl(R){if(R)return R.map(([N,T])=>[N*o.o.devicePixelRatio,T*o.o.devicePixelRatio])}class qu{constructor(N,T,B){this.id=N,this.scope=T,this.sourceCache=B,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(N){this.missingRequests.has(N.name)||this.pendingRequests.has(N.name)||this.pendingRequests.add(N.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const N=new Map;if(!this.sourceCache.loaded())return N;const T=this.sourceCache.getVisibleCoordinates();if(T.length===0)return N;const B=this.sourceCache.getSource();if(!(B instanceof to))return N;const W=T.map(se=>this.sourceCache.getTile(se)),Q=B.getImages(W,Array.from(this.pendingRequests));for(const[se,ue]of Q)N.set(o.I.from({name:se,iconsetId:this.id}),ue),this.pendingRequests.delete(se);for(const se of this.pendingRequests)this.missingRequests.add(se);return this.pendingRequests.clear(),N}}class Wd{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(N,T,B,W,Q){if(Bwe*this._hysteresisRatio&&(se=this._previousClosestBuildingId):Te&&!se&&(se=this._previousClosestBuildingId),this._previousClosestBuildingId=se,se}_calculateDistance(N,T){if(!T.center)return Number.MAX_VALUE;const B=N.lat-T.center[1],W=N.lng-T.center[0];return B*B+W*W}_isBuildingVisible(N,T,B){if(!B)return!1;for(const W of N.floorIds){const Q=N.floors[W];if(!Q.geometry)continue;const se=Q.geometry;if(se.type==="Polygon"){const ue=this._convertRingToPoints(se.coordinates[0]);if(o.bw(ue,B))return!0}else if(se.type==="MultiPolygon"){const ue=this._convertMultiPolygonToPoints(se.coordinates);if(o.d0(B,ue))return!0}}return!1}_convertRingToPoints(N){return N.map(T=>new o.P(T[0],T[1]))}_convertMultiPolygonToPoints(N){return N.map(T=>T.length===0?[]:T[0].map(B=>new o.P(B[0],B[1])))}}class Qg extends o.E{constructor(N){super(),this._style=N,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Wd,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(N){N===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=N,this._recalculateActiveFloors())}setActiveFloorsVisibility(N){this._updateActiveFloors(N),this._updateIndoorSelector()}setIndoorData(N){let T=!1;for(const[B,W]of Object.entries(N.buildings))if(this._buildings[B])for(const Q of W.floorIds)this._buildings[B].floorIds.add(Q),this._buildings[B].floors[Q]?this._mergeFloors(this._buildings[B].floors[Q],W.floors[Q]):(this._buildings[B].floors[Q]=W.floors[Q],T=!0);else this._buildings[B]=W,T=!0;T&&this._recalculateActiveFloors()}getIndoorTileOptions(N,T){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(N,T),indoorState:this._indoorState}:null}getControlState(){const N=this._buildings,T=this._closestBuildingId,B=T&&N?N[T]:void 0;if(!B)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let W=null;for(const se of B.floorIds)if(this._activeFloors&&this._activeFloors.has(se)){W=se;break}const Q=Array.from(B.floorIds).map(se=>({id:se,name:B.floors[se].name,zIndex:B.floors[se].zIndex})).sort((se,ue)=>ue.zIndex-se.zIndex).filter((se,ue,we)=>ue===0||se.zIndex!==we[ue-1].zIndex);return{selectedFloorId:W,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:Q}}_updateUI(){this._initialLoadDone=!0;const N=this._style.map.transform,T=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,N.center,N.zoom,N.getBounds(),this._makeViewportPolygon());if(T!==this._closestBuildingId){const B=this._closestBuildingId;this._closestBuildingId=T,this._onBuildingTransition(B,T),this._updateIndoorSelector()}}_onBuildingTransition(N,T){if(!this._indoorState)return;!T&&N?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!T&&!N&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(N){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:N,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const N=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(T,B){if(T===B)return!0;if(!T||!B||T.size!==B.size)return!1;for(const W of T)if(!B.has(W))return!1;return!0})(N,this._activeFloors)||(this._activeFloors=N,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(N,T){T.geometry&&(N.geometry?(N.geometry.type==="Polygon"&&(N.geometry={type:"MultiPolygon",coordinates:[N.geometry.coordinates]}),T.geometry.type==="Polygon"?N.geometry.coordinates.push(T.geometry.coordinates):T.geometry.type==="MultiPolygon"&&N.geometry.coordinates.push(...T.geometry.coordinates)):N.geometry=T.geometry)}_makeViewportPolygon(){const N=this._style.map.transform,T=N.width,B=N.height;return[N.pointLocation(new o.P(0,0)),N.pointLocation(new o.P(T,0)),N.pointLocation(new o.P(T,B)),N.pointLocation(new o.P(0,B))].map(W=>new o.P(W.lng,W.lat))}}const z0=(R,N)=>Zn(R,N&&N.filter(T=>T.identifier!=="source.canvas")),wm=o.aJ(Pi,["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"]),nw=o.aJ(Pi,["setCenter","setZoom","setBearing","setPitch"]),Zj=new Set(["background","sky","slot","custom"]),rw={version:8,layers:[],sources:{}},Jg={duration:300,delay:0};class xh extends o.E{constructor(N,T={}){if(super(),this.map=N,this.scope=T.scope||"",this.globalId=null,this.fragments=[],this.importDepth=T.importDepth||0,this.importsCache=T.importsCache||new Map,this.resolvedImports=T.resolvedImports||new Set,this.transition=Object.assign({},Jg),this._buildingIndex=new _g(this),this.crossTileSymbolIndex=new qx,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=T.styleChanges||new Be,this._hasDataDrivenEmissive=!1,this.indoorManager=new Qg(this),this.dispatcher=T.dispatcher?T.dispatcher:new Je(qt(),this),this.map.painter&&this.map.painter.context){const W=this.map.painter.context.maxUniformBufferBindings,Q=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:W,maxUniformBlockSizeDwords:Q,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}T.imageManager?this.imageManager=T.imageManager:(this.imageManager=new zt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=T.glyphManager?T.glyphManager:new o.d2(N._requestManager,T.localFontFamily?o.d3.all:T.localIdeographFontFamily?o.d3.ideographs:o.d3.none,T.localFontFamily||T.localIdeographFontFamily,T.useServerFontComposition),T.modelManager?this.modelManager=T.modelManager:(this.modelManager=new Fb(N._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=T.configOptions?T.configOptions:new Map,this._configDependentLayers=T.configDependentLayers?T.configDependentLayers:new Set,this._indoorDependentLayers=T.indoorDependentLayers?T.indoorDependentLayers:new Set,this._config=T.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:T.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=T.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const B=this;this._rtlTextPluginCallback=xh.registerForPluginStateChange(W=>{B.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:W.pluginStatus,pluginURL:W.pluginURL},(Q,se)=>{if(o.d6(Q),se&&se.every(ue=>ue))for(const ue in B._sourceCaches){const we=B._sourceCaches[ue],Te=we.getSource().type;Te!=="vector"&&Te!=="geojson"||we.reload()}})}),this.on("data",W=>{if(W.dataType!=="source"||W.sourceDataType!=="metadata")return;const Q=this.getOwnSource(W.sourceId);if(Q&&Q.vectorLayerIds)for(const se in this._layers){const ue=this._layers[se];ue.source===Q.id&&this._validateLayer(ue)}})}load(N){return N?(typeof N=="string"?this.loadURL(N):this.loadJSON(N),this):this}_getGlobalId(N){if(!N)return null;if(typeof N=="string"){if(o.e(N))return N;const T=o.d7(N);if(!T.startsWith("http"))try{return new URL(T,location.href).toString()}catch{return T}return T}return`json://${o.d8(JSON.stringify(N))}`}_diffStyle(N,T,B){this.globalId=this._getGlobalId(N);const W=(Q,se)=>{try{se(null,this.setState(Q,B))}catch(ue){se(ue,!1)}};if(typeof N=="string"){const Q=this.map._requestManager.normalizeStyleURL(N),se=this.map._requestManager.transformRequest(Q,o.R.Style);o.m(se,(ue,we)=>{ue?this.fire(new o.B(ue)):we&&W(we,T)})}else typeof N=="object"&&W(N,T)}loadURL(N,T={}){this.fire(new o.C("dataloading",{dataType:"style"}));const B=typeof T.validate=="boolean"?T.validate:!o.e(N);this.globalId=this._getGlobalId(N),N=this.map._requestManager.normalizeStyleURL(N,T.accessToken),this.resolvedImports.add(N);const W=this.importsCache.get(N);if(W)return this._load(W,B);const Q=this.map._requestManager.transformRequest(N,o.R.Style);this._request=o.m(Q,(se,ue)=>{if(this._request=null,se)this.fire(new o.B(se));else if(ue)return this.importsCache.set(N,ue),this._load(ue,B)})}loadJSON(N,T={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(N),this._request=o.o.frame(()=>{this._request=null,this._load(N,T.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(rw,!1)}_loadImports(N,T,B){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const W=[];for(const Q of N){const se=this._createFragmentStyle(Q),ue=new Promise(De=>{se.once("style.import.load",De),se.once("error",De)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(W.push(ue),this.resolvedImports.has(Q.url)){se.loadEmpty();continue}const we=Q.data||this.importsCache.get(Q.url);we?(Q.data?(se.fire(new o.C("dataloading",{dataType:"style"})),se.globalId=se._getGlobalId(we),queueMicrotask(()=>se._load(we,T))):se.loadJSON(we,{validate:T}),this._isInternalStyle(we)&&(se.globalId=null)):Q.url?se.loadURL(Q.url,{validate:T}):se.loadEmpty();const Te={style:se,id:Q.id,config:Q.config};if(B){const De=this.fragments.findIndex(({id:Qe})=>Qe===B);this.fragments=this.fragments.slice(0,De).concat(Te).concat(this.fragments.slice(De))}else this.fragments.push(Te)}return Promise.allSettled(W)}getImportGlobalIds(N=this,T=new Set){for(const B of N.fragments)B.style.globalId&&T.add(B.style.globalId),this.getImportGlobalIds(B.style,T);return[...T.values()]}_createFragmentStyle(N){const T=this.scope?o.F(N.id,this.scope):N.id;let B;const W=this._initialConfig&&this._initialConfig[T];(N.config||W)&&(B=Object.assign({},N.config,W));const Q=new xh(this.map,{scope:T,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:B,configOptions:this.options,colorThemeOverride:N["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return Q.setEventedParent(this.map,{style:Q}),Q}_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(N){return this.isRootStyle()&&(N.fragment||!!N.schema&&N.fragment!==!1)}_load(N,T){if(this._isInternalStyle(N)){const Q=Object.assign({},rw,{imports:[{id:"basemap",data:N,url:""}]},N.center?{center:N.center}:{},N.bearing?{bearing:N.bearing}:{},N.pitch?{pitch:N.pitch}:{},N.zoom?{zoom:N.zoom}:{},N.light?{light:N.light}:{});return this._importedAsBasemap=!0,void this._load(Q,T)}if(this.updateConfig(this._config,N.schema),T&&z0(this,tr(N)))return;this._loaded=!0;for(const Q in N.sources)this.addSource(Q,N.sources[Q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(N);const B=()=>{if(N.iconsets)for(const we in N.iconsets)this.addIconset(we,N.iconsets[we]);N.sprite?this._loadIconset(N.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&N.glyphs&&this.glyphManager.setURL(N.glyphs);const Q=nx(this.stylesheet.layers);if(this._order=Q.map(we=>we.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 we=this.stylesheet.lights[0];this.light=new aa(we.properties,we.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new aa(this.stylesheet.light)),this._layers={};for(const we of Q){const Te=o.de(we,this.scope,this._styleColorTheme.lut,this.options);Te.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Te.fqid),Te.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Te.fqid),this._hasAppearances=this._hasAppearances||Te.getAppearances().length!==0,Te.setEventedParent(this,{layer:{id:Te.id}}),this._layers[Te.id]=Te;const De=this.getOwnLayerSourceCache(Te),Qe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();De&&Te.canCastShadows()&&Qe&&(De.castsShadows=!0)}if(this.glyphManager.url){const we=new Set;for(const Te in this._layers){const De=this._layers[Te];if(De.type==="symbol"&&De.layout){const Qe=De.layout.get("text-font");Qe&&Qe.value&&Qe.value.kind==="constant"&&we.add(Qe.value.value.join(","))}}for(const Te of we)this.glyphManager.prefetchRange(Te,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const se=this.stylesheet.terrain;se&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(se,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 ue=this.isRootStyle();N.imports?this._loadImports(N.imports,T).then(()=>{this._reloadImports(),this.fire(new o.C(ue?"style.load":"style.import.load"))}).catch(we=>{this.fire(new o.B(new Error("Failed to load imports",we))),this.fire(new o.C(ue?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(ue?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const W=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(W){const Q=this._evaluateColorThemeData(W);this._loadColorTheme(Q).then(()=>{B()}).catch(se=>{o.w(`Couldn't load color theme from the stylesheet: ${se}`),B()})}else this._styleColorTheme.lut=null,B()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(N=>N.style.hasAppearances())}mergeAll(){let N,T,B,W,Q,se,ue,we,Te,De;const Qe={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Ye=>{if(Ye.stylesheet){if(Ye.light!=null&&(N=Ye.light),Ye.stylesheet.lights)for(const tt of Ye.stylesheet.lights)tt.type==="ambient"&&Ye.ambientLight!=null&&(T=Ye.ambientLight),tt.type==="directional"&&Ye.directionalLight!=null&&(B=Ye.directionalLight);W=this._prioritizeTerrain(W,Ye.terrain,Ye.stylesheet.terrain),Ye.stylesheet.fog&&Ye.fog!=null&&(Q=Ye.fog),Ye.stylesheet.snow&&Ye.snow!=null&&(se=Ye.snow),Ye.stylesheet.rain&&Ye.rain!=null&&(ue=Ye.rain),Ye.stylesheet.camera!=null&&(De=Ye.stylesheet.camera),Ye.stylesheet.projection!=null&&(we=Ye.stylesheet.projection),Ye.stylesheet.transition!=null&&(Te=Ye.stylesheet.transition),Qe[Ye.scope]=Ye._styleColorTheme}}),this.light=N,this.ambientLight=T,this.directionalLight=B,this.fog=Q,this.snow=se,this.rain=ue,this._styleColorThemeForScope=Qe,W===null?delete this.terrain:this.terrain=W,this.camera=De||{"camera-projection":"perspective"},this.projection=we||{name:"mercator"},this.transition=Object.assign({},Jg,Te),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(N){const T=B=>{for(const W of B.fragments)T(W.style);N(B)};T(this)}_prioritizeTerrain(N,T,B){const W=N&&N.drapeRenderMode===0;return B===null?T&&T.drapeRenderMode===0?T:W?N:null:T!=null&&(!N||W||T&&T.drapeRenderMode===1)?T:N}mergeTerrain(){let N;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(T=>{N=this._prioritizeTerrain(N,T.terrain,T.stylesheet.terrain)}),N===null?delete this.terrain:this.terrain=N}mergeProjection(){let N;this.forEachFragmentStyle(T=>{T.stylesheet.projection!=null&&(N=T.stylesheet.projection)}),this.projection=N||{name:"mercator"}}mergeSources(){const N={},T={},B={},W={};this.forEachFragmentStyle(Q=>{for(const se in Q._sourceCaches){const ue=o.F(se,Q.scope);N[ue]=Q._sourceCaches[se]}for(const se in Q._otherSourceCaches){const ue=o.F(se,Q.scope);T[ue]=Q._otherSourceCaches[se]}for(const se in Q._symbolSourceCaches){const ue=o.F(se,Q.scope);B[ue]=Q._symbolSourceCaches[se]}for(const se in Q._fillExtrusionSourceCaches){const ue=o.F(se,Q.scope);W[ue]=Q._fillExtrusionSourceCaches[se]}}),this._mergedSourceCaches=N,this._mergedOtherSourceCaches=T,this._mergedSymbolSourceCaches=B,this._mergedFillExtrusionSourceCaches=W}mergeIndoor(){this.forEachFragmentStyle(N=>{if(N.stylesheet&&N.stylesheet.indoor)for(const T of Object.values(N.stylesheet.indoor)){const B=T,W=o.F(B.sourceId,N.scope);this._mergedIndoor[W]=new Set(B.sourceLayers||[])}})}mergeLayers(){const N={},T=[],B={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(se=>{for(const ue of se._order){const we=se._layers[ue];if(we.type==="slot"){const Te=o.da(ue);if(N[Te])continue;N[Te]=[]}we.slot&&N[we.slot]?N[we.slot].push(we):T.push(we)}}),this._mergedOrder=[];let W=-1;const Q=(se=[])=>{for(const ue of se)if(ue.type==="slot"){const we=o.da(ue.id);N[we]&&Q(N[we]),this._mergedSlots.push(we)}else{const we=o.F(ue.id,ue.scope);this._mergedOrder.push(we),B[we]=ue,ue.is3D(!!this.terrain)&&(this._has3DLayers=!0,W=this._mergedOrder.length-1),ue.type==="circle"&&(this._hasCircleLayers=!0),ue.type==="symbol"&&(this._hasSymbolLayers=!0),ue.type==="clip"&&(this._clipLayerPresent=!0)}};if(Q(T),this._has3DLayers){const se={};for(let ue=0;uese[ue]-se[we])}this._mergedLayers=B,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(N){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,N),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(N){return N.data?function(T,B,W){const Q=Object.assign({},B);for(const ue of Object.keys(fh))Q[ue]===void 0&&(Q[ue]=fh[ue].default);const se=new o.aa(Mc,T,new Map(W));return se.setTransitionOrValue(Q,W),se.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,N,this.options).get("data"):null}_loadColorTheme(N){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const T=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((B,W)=>{const Q="data:image/png;base64,";if(!N||N.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void B();let se=N;se.startsWith(Q)||(se=Q+se);const ue=o.I.from("mapbox-reserved-lut"),we=new Image;we.src=se,we.onerror=()=>{this._styleColorTheme.lutLoading=!1,W(new Error("Failed to load image data"))},we.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==T)return void B();this._styleColorTheme.lutLoading=!1;const{width:Te,height:De,data:Qe}=o.o.getImageData(we);if(De>32)return void W(new Error("The height of the image must be less than or equal to 32 pixels."));if(Te!==De*De)return void W(new Error("The width of the image must be equal to the height squared."));this.getImage(ue)&&this.removeImage(ue),this.addImage(ue,{data:new o.q({width:Te,height:De},Qe),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Ye=this.imageManager.getImage(ue,this.scope);Ye?(this._styleColorTheme.lut={image:Ye.data,data:N},B()):W(new Error("Missing LUT image."))}})}getLut(N){const T=this._styleColorThemeForScope[N];return T?T.lut:null}setProjection(N){N?this.stylesheet.projection=N:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.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(N){this._spriteRequest=function(T,B,W){let Q,se,ue;const we=o.o.devicePixelRatio>1?"@2x":"";let Te=o.m(B.transformRequest(B.normalizeSpriteURL(T,we,".json"),o.R.SpriteJSON),(Ye,tt)=>{Te=null,ue||(ue=Ye,Q=tt,Qe())}),De=o.n(B.transformRequest(B.normalizeSpriteURL(T,we,".png"),o.R.SpriteImage),(Ye,tt)=>{De=null,ue||(ue=Ye,se=tt,Qe())});function Qe(){if(ue)W(ue);else if(Q&&se){const Ye=o.o.getImageData(se),tt={};for(const ht in Q){const{width:ct,height:St,x:kt,y:Ut,sdf:Xt,pixelRatio:Et,stretchX:Ts,stretchY:ds,content:Cs}=Q[ht],es=new o.q({width:ct,height:St});o.q.copy(Ye,es,{x:kt,y:Ut},{x:0,y:0},{width:ct,height:St},null),tt[ht]={data:es,pixelRatio:Et!==void 0?Et:1,sdf:Xt!==void 0&&Xt,stretchX:Ts,stretchY:ds,content:Cs,usvg:!1,version:0}}W(null,tt)}}return{cancel(){Te&&(Te.cancel(),Te=null),De&&(De.cancel(),De=null)}}}(N,this.map._requestManager,(T,B)=>{if(this._spriteRequest=null,T)this.fire(new o.B(T));else if(B){const W=new Map;for(const Q in B)W.set(o.I.from(Q),B[Q]);this.addImages(W)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(N,T){if(T.type==="sprite")return void this._loadSprite(T.url);const B=this.getOwnSourceCache(T.source);if(!B)return void this.fire(new o.B(new Error(`Source "${T.source}" as specified by iconset "${N}" does not exist and cannot be used as an iconset source`)));const W=B.getSource();if(W.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${T.source}" as specified by iconset "${N}" is not a "raster-array" source and cannot be used as an iconset source`)));W.partial=!1;const Q=new qu(N,this.scope,B);this.imageManager.addImageProvider(Q,this.scope)}removeIconset(N){this.imageManager.removeImageProvider(N,this.scope)}_loadIconset(N){if(!o.e(N)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(N);const T=this.map._spriteFormat==="auto";var B,W;this._spriteRequest=(W=(Q,se)=>{if(this._spriteRequest=null,Q)T?this._loadSprite(N):this.fire(new o.B(Q));else if(se){const ue=new Map;for(const we in se)ue.set(o.I.from(we),se[we]);this.addImages(ue)}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((B=this.map._requestManager).transformRequest(B.normalizeIconsetURL(N),o.R.Iconset),(Q,se)=>{if(Q)return void W(Q);const ue={},we=o.c$(new o.a$(se));for(const Te of we.icons){const De={version:1,pixelRatio:o.o.devicePixelRatio,content:Cl(Te),stretchX:Te.metadata?fl(Te.metadata.stretch_x_areas):void 0,stretchY:Te.metadata?fl(Te.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Te};ue[Te.name]=De}W(null,ue)}))}_validateLayer(N){const T=this.getOwnSource(N.source);if(!T)return;const B=N.sourceLayer;B&&(T.type==="geojson"||T.vectorLayerIds&&T.vectorLayerIds.indexOf(B)===-1)&&this.fire(new o.B(new Error(`Source layer "${B}" does not exist on source "${T.id}" as specified by style layer "${N.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const N in this._sourceCaches)if(!this._sourceCaches[N].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:N}of this.fragments)if(!N.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((N,T)=>{const B=this.fragments[T];return B&&B.style&&(N.data=B.style.serialize()),N})}_serializeSources(){const N={};for(const T in this._sourceCaches){const B=this._sourceCaches[T].getSource();N[B.id]||(N[B.id]=B.serialize())}return N}_serializeLayers(N){const T=[];for(const B of N){const W=this._layers[B];W&&W.type!=="custom"&&T.push(W.serialize())}return T}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const N in this._sourceCaches)if(this._sourceCaches[N].hasTransition())return!0;for(const N in this._layers)if(this._layers[N].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const N in this._mergedLayers){const T=this._mergedLayers[N];if(T._transitionablePaint&&T._transitionablePaint._values){const B=T._transitionablePaint._values["line-emissive-strength"];if(B&&B.value&&B.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(N){return N?this.order:this._mergedOrder}isLayerDraped(N){return!!this.terrain&&N.isDraped(this.getLayerSourceCache(N))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(N){const T=this.getOwnLayer(N);if(T)return T;this.fire(new o.B(new Error(`The layer '${N}' does not exist in the map's style.`)))}_checkSource(N){const T=this.getOwnSource(N);if(T)return T;this.fire(new o.B(new Error(`The source '${N}' does not exist in the map's style.`)))}precompilePrograms(N,T){const B=this.map.painter;if(B)for(let W=N.minzoom||0;W<(N.maxzoom||25.5);W++){const Q=N.getProgramIds();if(Q)for(const se of Q){const ue=N.getDefaultProgramParams(se,T.zoom,this._styleColorTheme.lut);ue&&(B.style=this,this.fog&&(B._fogVisible=!0,ue.overrideFog=!0,B.getOrCreateProgram(se,ue)),B._fogVisible=!1,ue.overrideFog=!1,B.getOrCreateProgram(se,ue),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(ue.overrideRtt=!0,B.getOrCreateProgram(se,ue)))}}}update(N){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(N),this.directionalLight&&this.directionalLight.recalculate(N);const T=this.calculateLightsBrightness();N.brightness=T||0,T!==this._brightness&&(this._brightness=T,this.dispatcher.broadcast("setBrightness",T)),N.worldview!==this._worldview&&(this._worldview=N.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const B=this._changes.isDirty();let W=!1;if(this._changes.isDirty()){const we=this._changes.getLayerUpdatesByScope();for(const Te in we){const{updatedIds:De,removedIds:Qe}=we[Te];(De||Qe)&&(this._updateWorkerLayers(Te,De,Qe),W=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(N),this.light&&this.light.updateTransitions(N),this.ambientLight&&this.ambientLight.updateTransitions(N),this.directionalLight&&this.directionalLight.updateTransitions(N),this.fog&&this.fog.updateTransitions(N),this.snow&&this.snow.updateTransitions(N),this.rain&&this.rain.updateTransitions(N),this._changes.reset()}const Q={};for(const we in this._mergedSourceCaches){const Te=this._mergedSourceCaches[we];Q[we]=Te.used,Te.used=!1,Te.tileCoverLift=0}const se={};for(const we of this._mergedOrder){const Te=this._mergedLayers[we];if((Te.visibility!=="none"||Te.hasTransition())&&Te.recalculate(N,this._availableImages),!Te.isHidden(N.zoom)){const De=this.getLayerSourceCache(Te);De&&(De.used=!0,De.tileCoverLift=Math.max(De.tileCoverLift,Te.tileCoverLift()))}if(Te.type==="fill-extrusion"){const De=o.F(Te.source,Te.scope);if(De in this._mergedFillExtrusionSourceCaches){const Qe=Te.layout&&Te.layout.get("source-max-zoom");if(Qe!=null){const Ye=se[De];se[De]=Ye==null?Qe:Math.min(Ye,Qe)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(Te,N)}):this.precompilePrograms(Te,N))}this._shouldPrecompile&&(this._precompileDone=!0);for(const we in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[we].setMaxzoomOverride(se[we]!=null?se[we]:null);this.terrain&&W&&this.mergeLayers();const ue=this.imageManager.getPendingImageProviders();for(const we of ue)we.sourceCache.used=!0;for(const we in Q){const Te=this._mergedSourceCaches[we];Q[we]!==Te.used&&Te.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:Te.getSource().id}))}this.light&&this.light.recalculate(N),this.terrain&&this.terrain.recalculate(N),this.fog&&this.fog.recalculate(N),this.snow&&this.snow.recalculate(N),this.rain&&this.rain.recalculate(N),this.z=N.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),B&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const N=this.imageManager.getPendingImageProviders();for(const T of N){const B=T.resolvePendingRequests(),W=this.getFragmentStyle(T.scope);W&&W.addImages(B)}}_updateTilesForChangedImages(){const N={};for(const T in this._mergedSourceCaches){const B=this._mergedSourceCaches[T].getSource().scope;N[B]=N[B]||this._changes.getUpdatedImages(B),N[B].length!==0&&this._mergedSourceCaches[T].reloadTilesForDependencies(["icons","patterns"],N[B])}for(const T in N)this._changes.resetUpdatedImages(T)}_updateWorkerLayers(N,T,B){const W=this.getFragmentStyle(N);W&&this.dispatcher.broadcast("updateLayers",{layers:T?W._serializeLayers(T):[],scope:N,removedIds:B||[],options:W.options})}setState(N,T){if(this._checkLoaded(),z0(this,tr(N)))return!1;(N=o.d9(N)).layers=nx(N.layers);const B=function(se,ue){if(!se)return[{command:Pi.setStyle,args:[ue]}];let we=[];try{if(!o.b6(se.version,ue.version))return[{command:Pi.setStyle,args:[ue]}];if(o.b6(se.center,ue.center)||we.push({command:Pi.setCenter,args:[ue.center]}),o.b6(se.zoom,ue.zoom)||we.push({command:Pi.setZoom,args:[ue.zoom]}),o.b6(se.bearing,ue.bearing)||we.push({command:Pi.setBearing,args:[ue.bearing]}),o.b6(se.pitch,ue.pitch)||we.push({command:Pi.setPitch,args:[ue.pitch]}),o.b6(se.sprite,ue.sprite)||we.push({command:Pi.setSprite,args:[ue.sprite]}),o.b6(se.glyphs,ue.glyphs)||we.push({command:Pi.setGlyphs,args:[ue.glyphs]}),o.b6(se.imports,ue.imports)||function(tt=[],ht=[],ct){ht=ht||[];const St=(tt=tt||[]).map(fd),kt=ht.map(fd),Ut=tt.reduce(Ux,{}),Xt=ht.reduce(Ux,{}),Et=St.slice();let Ts,ds,Cs,es;for(Ts=0,ds=0;Ts{tt.source&&Te[tt.source]?we.push({command:Pi.removeLayer,args:[tt.id]}):Qe.push(tt)});let Ye=se.terrain;Ye&&Te[Ye.source]&&(we.push({command:Pi.setTerrain,args:[void 0]}),Ye=void 0),we=we.concat(De),o.b6(Ye,ue.terrain)||we.push({command:Pi.setTerrain,args:[ue.terrain]}),function(tt,ht,ct){ht=ht||[];const St=(tt=tt||[]).map(fd),kt=ht.map(fd),Ut=tt.reduce(Ux,{}),Xt=ht.reduce(Ux,{}),Et=St.slice(),Ts=Object.create(null);let ds,Cs,es,is,_s,Xs,Ds;for(ds=0,Cs=0;ds!(se.command in nw));if(B.length===0)return!1;const W=B.filter(se=>!(se.command in wm));if(W.length>0)throw new Error(`Unimplemented: ${W.map(se=>se.command).join(", ")}.`);const Q=[];return B.forEach(se=>{Q.push(this[se.command](...se.args))}),T&&Promise.all(Q).then(T).catch(T),this.stylesheet=N,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(N){if(N.size===0)return this;for(const[T,B]of N.entries()){if(this.getImage(T))return this.fire(new o.B(new Error(`An image with the name "${T.name}" already exists.`)));this.imageManager.addImage(T,this.scope,B),this._changes.updateImage(T,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(N,T){return this.getImage(N)?this.fire(new o.B(new Error(`An image with the name "${N.name}" already exists.`))):(this.imageManager.addImage(N,this.scope,T),this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(N,T,B=!1){this.imageManager.updateImage(N,this.scope,T),B&&(this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(N){return this.imageManager.getImage(N,this.scope)}removeImage(N){return this.getImage(N)?(this.imageManager.removeImage(N,this.scope),this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.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(N){return this.modelManager.addModelURLs(N,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(N,T,B={}){return this._checkLoaded(),this._validate(Vs,`models.${N}`,T,null,B)||(this.modelManager.addModel(N,T,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(N){return this.modelManager.hasModel(N,this.getActualScope())}removeModel(N){return this.hasModel(N)?(this.modelManager.removeModel(N,this.getActualScope(),!1,!0),this.fire(new o.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(N,T,B={}){if(this._checkLoaded(),this.getOwnSource(N)!==void 0)throw new Error(`There is already a source with ID "${N}".`);if(!T.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(T).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(T.type)>=0&&this._validate(Lr,`sources.${N}`,T,null,B))return;this.map&&this.map._collectResourceTiming&&(T.collectResourceTiming=!0);const W=so(N,T,this.dispatcher,this);W.scope=this.scope,W.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(W.id),source:W.serialize(),sourceId:W.id}));const Q=se=>{const ue=(se===o.b4.Symbol?"symbol:":se===o.b4.FillExtrusion?"fill-extrusion:":"other:")+W.id,we=o.F(ue,this.scope),Te=this._sourceCaches[ue]=new zc(we,W,se);se===o.b4.Symbol?this._symbolSourceCaches[W.id]=Te:se===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[W.id]=Te:this._otherSourceCaches[W.id]=Te,Te.onAdd(this.map)};Q(o.b4.Other),T.type!=="vector"&&T.type!=="geojson"||(Q(o.b4.Symbol),T.type==="vector"&&Q(o.b4.FillExtrusion)),W.onAdd&&W.onAdd(this.map),B.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(N){this._checkLoaded();const T=this.getOwnSource(N);if(!T)throw new Error("There is no source with this ID");for(const W in this._layers)if(this._layers[W].source===N)return this.fire(new o.B(new Error(`Source "${N}" cannot be removed while layer "${W}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===N)return this.fire(new o.B(new Error(`Source "${N}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const W=Object.entries(this.stylesheet.iconsets).find(([Q,se])=>se.type==="source"&&se.source===N);if(W)return this.fire(new o.B(new Error(`Source "${N}" cannot be removed while iconset "${W[0]}" is using it.`)))}const B=this.getOwnSourceCaches(N);for(const W of B){const Q=o.da(W.id);delete this._sourceCaches[Q],this._changes.discardSourceCacheUpdate(W.id),W.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:W.getSource().id})),W.setEventedParent(null),W.clearTiles()}return delete this._otherSourceCaches[N],delete this._symbolSourceCaches[N],delete this._fillExtrusionSourceCaches[N],this.mergeSources(),T.setEventedParent(null),T.onRemove&&T.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(N,T){this._checkLoaded(),this.getOwnSource(N).setData(T),this._changes.setDirty()}getOwnSource(N){const T=this.getOwnSourceCache(N);return T&&T.getSource()}getOwnSources(){const N=[];for(const T in this._otherSourceCaches){const B=this.getOwnSourceCache(T);B&&N.push(B.getSource())}return N}areTilesLoaded(){const N=this._mergedSourceCaches;for(const T in N){const B=N[T]._tiles;for(const W in B){const Q=B[W];if(Q.state!=="loaded"&&Q.state!=="errored")return!1}}return!0}setLights(N){if(this._checkLoaded(),!N)return delete this.ambientLight,void delete this.directionalLight;const T=this._getTransitionParameters();for(const Q of N){if(this._validate(it,"lights",Q))return;switch(Q.type){case"ambient":if(this.ambientLight){const se=this.ambientLight;se.set(Q),se.updateTransitions(T)}else this.ambientLight=new ar(Q,ui(),this.scope,this.options);break;case"directional":if(this.directionalLight){const se=this.directionalLight;se.set(Q),se.updateTransitions(T)}else this.directionalLight=new ar(Q,gl(),this.scope,this.options)}}const B=Object.assign(T,{worldview:this.map.getWorldview()}),W=new o.ae(this.z||0,B);this.ambientLight&&this.ambientLight.recalculate(W),this.directionalLight&&this.directionalLight.recalculate(W),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const N=this.directionalLight,T=this.ambientLight;if(!N||!T)return;const B=Ye=>.2126*(Ye[0]<=.03928?Ye[0]/12.92:Math.pow((Ye[0]+.055)/1.055,2.4))+.7152*(Ye[1]<=.03928?Ye[1]/12.92:Math.pow((Ye[1]+.055)/1.055,2.4))+.0722*(Ye[2]<=.03928?Ye[2]/12.92:Math.pow((Ye[2]+.055)/1.055,2.4)),W=N.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Q=N.properties.get("intensity"),se=N.properties.get("direction"),ue=1-o.cP(se.x,se.y,se.z)[2]/90,we=B(W)*Q*ue,Te=T.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),De=T.properties.get("intensity"),Qe=B(Te)*De;return Number(((we+Qe)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const N=[];return this.directionalLight&&N.push(this.directionalLight.get()),this.ambientLight&&N.push(this.ambientLight.get()),N}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(N){if(N==null||N===""&&this.isRootStyle())return this;if(o.db(N)){const T=o.dc(N),B=this.fragments.find(({id:Q})=>Q===T);if(!B)return;const W=o.da(N);return B.style.getFragmentStyle(W)}{const T=this.fragments.find(({id:B})=>B===N);return T?T.style:void 0}}setFeaturesetSelectors(N){if(!N)return;const T=(B,W="")=>`${B}::${W}`;this._featuresetSelectors={};for(const B in N){const W={},Q=this._featuresetSelectors[B]=[];for(const se of N[B].selectors){if(se.featureNamespace){const we=this.getOwnLayer(se.layer);if(!we){o.w(`Layer is undefined for selector: ${se.layer}`);continue}const Te=T(we.source,we.sourceLayer);if(Te in W&&W[Te]!==se.featureNamespace){o.w(`"featureNamespace ${se.featureNamespace} of featureset ${B}'s selector is not associated to the same source, skip this selector`);continue}W[Te]=se.featureNamespace}let ue;if(se.properties)for(const we in se.properties){const Te=o.X(se.properties[we]);Te.result==="success"&&(ue=ue||{},ue[we]=Te.value)}Q.push({layerId:se.layer,namespace:se.featureNamespace,properties:ue,uniqueFeatureID:se._uniqueFeatureID})}}}getFeaturesetDescriptors(N){const T=this.getFragmentStyle(N);if(!T||!T.stylesheet.featuresets)return[];const B=[];for(const W in T.stylesheet.featuresets)B.push({featuresetId:W,importId:T.scope?T.scope:void 0});return B}getFeaturesetLayers(N,T){const B=this.getFragmentStyle(T),W=B.stylesheet.featuresets;if(!W||!W[N])return this.fire(new o.B(new Error(`The featureset '${N}' does not exist in the map's style and cannot be queried.`))),[];const Q=[];for(const se of W[N].selectors){const ue=B.getOwnLayer(se.layer);ue&&Q.push(ue)}return Q}getConfigProperty(N,T){const B=this.getFragmentStyle(N);if(!B)return null;const W=o.F(T,B.scope),Q=B.options.get(W),se=Q?Q.value||Q.default:null;return se?se.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(N,T){const B=o.F(N,T);return this._mergedIndoor[B]}setIndoorData(N,T){this.indoorManager.setIndoorData(T)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(N,T,B){const W=this.getFragmentStyle(N);if(!W)return;const Q=W.stylesheet.schema;if(!Q||!Q[T])return;const se=o.X(B);if(se.result!=="success")return void z0(this,se.value);const ue=se.value.expression,we=o.F(T,W.scope),Te=W.options.get(we);if(!Te)return;let De;const{minValue:Qe,maxValue:Ye,stepValue:tt,type:ht,values:ct}=Q[T],St=o.X(Q[T].default);St.result==="success"&&(De=St.value.expression),De?(this.options.set(we,Object.assign({},Te,{value:ue,default:De,minValue:Qe,maxValue:Ye,stepValue:tt,type:ht,values:ct})),this.updateConfigDependencies(T)):this.fire(new o.B(new Error(`No schema defined for the config option "${T}" in the "${N}" fragment.`)))}getConfig(N){const T=this.getFragmentStyle(N);if(!T)return null;const B=T.stylesheet.schema;if(!B)return null;const W={};for(const Q in B){const se=o.F(Q,T.scope),ue=T.options.get(se),we=ue?ue.value||ue.default:null;W[Q]=we?we.serialize():null}return W}setConfig(N,T){const B=this.getFragmentStyle(N);B&&(B.updateConfig(T,B.stylesheet.schema),this.updateConfigDependencies())}getSchema(N){const T=this.getFragmentStyle(N);return T?T.stylesheet.schema:null}setSchema(N,T){const B=this.getFragmentStyle(N);B&&(B.stylesheet.schema=T,B.updateConfig(B._config,T),this.updateConfigDependencies())}updateConfig(N,T){if(this._config=N,N||T)if(T)for(const B in T){let W,Q;const se=o.X(T[B].default);if(se.result==="success"&&(W=se.value.expression),N&&N[B]!==void 0){const Ye=o.X(N[B]);Ye.result==="success"&&(Q=Ye.value.expression)}const{minValue:ue,maxValue:we,stepValue:Te,type:De,values:Qe}=T[B];if(W){const Ye=o.F(B,this.scope);this.options.set(Ye,{default:W,value:Q,minValue:ue,maxValue:we,stepValue:Te,type:De,values:Qe})}else this.fire(new o.B(new Error(`No schema defined for config option "${B}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(N,T=()=>!0){for(const B of N){const W=this.getLayer(B);W&&T(W)&&(W.possiblyEvaluateVisibility(),this._updateLayer(W),this._changes.setDirty())}}updateConfigDependencies(N){this._updateLayers(this._configDependentLayers,T=>!N||T.expressionDependencies.configDependencies.has(N)),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(T=>{const B=T._styleColorTheme.colorThemeOverride?T._styleColorTheme.colorThemeOverride:T._styleColorTheme.colorTheme;if(B){const W=T._evaluateColorThemeData(B);(!T._styleColorTheme.lut&&W!==""||T._styleColorTheme.lut&&W!==T._styleColorTheme.lut.data)&&T.setColorTheme(B)}}),this._changes.setDirty()}addLayer(N,T,B={}){this._checkLoaded();const W=N.id;if(this._layers[W])return void this.fire(new o.B(new Error(`Layer with id "${W}" already exists on this map`)));let Q;if(N.type==="custom"){if(z0(this,o.dd(N)))return;Q=o.de(N,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof N.source=="object"&&(this.addSource(W,N.source),N=o.d9(N),N=Object.assign(N,{source:W})),this._validate(Qt,`layers.${W}`,N,{arrayIndex:-1},B))return;Q=o.de(N,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Q),Q.setEventedParent(this,{layer:{id:W}})}const se=o.F(Q.source,Q.scope);Q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(se),Q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(se);let ue=this._order.length;if(T){const Qe=this._order.indexOf(T);if(Qe===-1)return void this.fire(new o.B(new Error(`Layer with id "${T}" does not exist on this map.`)));Q.slot&&Q.slot!==this._layers[T].slot?o.w(`Layer with id "${T}" has a different slot. Layers can only be rearranged within the same slot.`):ue=Qe}this._order.splice(ue,0,W),this._handleLayerOrderChange(),this._layers[W]=Q;const we=this.getOwnLayerSourceCache(Q),Te=!!this.directionalLight&&this.directionalLight.shadowsEnabled();we&&Q.canCastShadows()&&Te&&(we.castsShadows=!0);const De=this._changes.getRemovedLayer(Q);if(De&&Q.source&&we&&Q.type!=="custom"){this._changes.discardLayerRemoval(Q);const Qe=o.F(Q.source,Q.scope);De.type!==Q.type?this._changes.updateSourceCache(Qe,"clear"):(this._changes.updateSourceCache(Qe,"reload"),we.pause())}this._updateLayer(Q),Q.onAdd&&Q.onAdd(this.map),Q.scope=this.scope,this.mergeLayers()}moveLayer(N,T){this._checkLoaded();const B=this._checkLayer(N);if(!B||N===T)return;const W=this._order.indexOf(N);this._order.splice(W,1);let Q=this._order.length;if(T){const se=this._order.indexOf(T);if(se===-1)return void this.fire(new o.B(new Error(`Layer with id "${T}" does not exist on this map.`)));B.slot&&B.slot!==this._layers[T].slot?o.w(`Layer with id "${T}" has a different slot. Layers can only be rearranged within the same slot.`):Q=se}this._order.splice(Q,0,N),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(N){this._checkLoaded();const T=this._checkLayer(N);if(!T)return;T.setEventedParent(null);const B=this._order.indexOf(N);this._order.splice(B,1),delete this._layers[N],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(T.fqid),this._indoorDependentLayers.delete(T.fqid),this._changes.removeLayer(T);const W=this.getOwnLayerSourceCache(T);if(W&&W.castsShadows){let Q=!1;for(const se in this._layers)if(this._layers[se].source===T.source&&this._layers[se].canCastShadows()){Q=!0;break}W.castsShadows=Q}T.onRemove&&T.onRemove(this.map),this.mergeLayers()}getOwnLayer(N){return this._layers[N]}hasLayer(N){return N in this._mergedLayers}hasLayerType(N){for(const T in this._layers)if(this._layers[T].type===N)return!0;return!1}setLayerZoomRange(N,T,B){this._checkLoaded();const W=this._checkLayer(N);W&&(W.minzoom===T&&W.maxzoom===B||(T!=null&&(W.minzoom=T),B!=null&&(W.maxzoom=B),this._updateLayer(W)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(N,T){this._checkLoaded();const B=this._checkLayer(N);B&&B.slot!==T&&(B.slot=T,this._updateLayer(B))}setFilter(N,T,B={}){this._checkLoaded();const W=this._checkLayer(N);if(W&&!o.b6(W.filter,T))return T==null?(W.filter=void 0,void this._updateLayer(W)):void(this._validate(ks,`layers.${W.id}.filter`,T,{layerType:W.type},B)||(W.filter=o.d9(T),this._updateLayer(W)))}getFilter(N){const T=this._checkLayer(N);if(T)return o.d9(T.filter)}setLayoutProperty(N,T,B,W={}){this._checkLoaded();const Q=this._checkLayer(N);if(Q&&!o.b6(Q.getLayoutProperty(T),B)){if(B!=null&&(!W||W.validate!==!1)&&z0(Q,Vt.call(tr,{key:`layers.${N}.layout.${T}`,layerType:Q.type,objectKey:T,value:B,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;Q.setLayoutProperty(T,B),Q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Q.fqid),Q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Q.fqid),this._updateLayer(Q)}}setLayerProperty(N,T,B,W={}){this._checkLoaded();const Q=this._checkLayer(N);Q&&(T==="appearances"?(Q.setAppearances(B),this._updateLayer(Q)):Q.isPaintProperty(T)?this.setPaintProperty(N,T,B,W):this.setLayoutProperty(N,T,B,W))}getLayoutProperty(N,T){const B=this._checkLayer(N);if(B)return B.getLayoutProperty(T)}setPaintProperty(N,T,B,W={}){this._checkLoaded();const Q=this._checkLayer(N);if(!Q||o.b6(Q.getPaintProperty(T),B)||B!=null&&(!W||W.validate!==!1)&&z0(Q,gs.call(tr,{key:`layers.${N}.paint.${T}`,layerType:Q.type,objectKey:T,value:B,styleSpec:o.a8})))return;const se=Q.setPaintProperty(T,B);Q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Q.fqid),Q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Q.fqid),se&&this._updateLayer(Q),this._changes.updatePaintProperties(Q)}getPaintProperty(N,T){const B=this._checkLayer(N);if(B)return B.getPaintProperty(T)}setFeatureState(N,T){if(this._checkLoaded(),"target"in N){if("featuresetId"in N.target){const{featuresetId:we,importId:Te}=N.target,De=this.getFragmentStyle(Te),Qe=De.getFeaturesetLayers(we);for(const{source:Ye,sourceLayer:tt}of Qe)De.setFeatureState({id:N.id,source:Ye,sourceLayer:tt},T)}else if("layerId"in N.target){const{layerId:we}=N.target,Te=this.getLayer(we);this.setFeatureState({id:N.id,source:Te.source,sourceLayer:Te.sourceLayer},T)}return}const B=N.source,W=N.sourceLayer,Q=this._checkSource(B);if(!Q)return;const se=Q.type;if(se==="geojson"&&W)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(se==="vector"&&!W)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));N.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const ue=this.getOwnSourceCaches(B);for(const we of ue)we.setFeatureState(W,N.id,T)}removeFeatureState(N,T){if(this._checkLoaded(),"target"in N){if("featuresetId"in N.target){const{featuresetId:we,importId:Te}=N.target,De=this.getFragmentStyle(Te),Qe=De.getFeaturesetLayers(we);for(const{source:Ye,sourceLayer:tt}of Qe)De.removeFeatureState({id:N.id,source:Ye,sourceLayer:tt},T)}else if("layerId"in N.target){const{layerId:we}=N.target,Te=this.getLayer(we);this.removeFeatureState({id:N.id,source:Te.source,sourceLayer:Te.sourceLayer},T)}return}const B=N.source,W=this._checkSource(B);if(!W)return;const Q=W.type,se=Q==="vector"?N.sourceLayer:void 0;if(Q==="vector"&&!se)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(T&&typeof N.id!="string"&&typeof N.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const ue=this.getOwnSourceCaches(B);for(const we of ue)we.removeFeatureState(se,N.id,T)}getFeatureState(N){if(this._checkLoaded(),"target"in N){let Q;if("featuresetId"in N.target){const{featuresetId:se,importId:ue}=N.target,we=this.getFragmentStyle(ue),Te=we.getFeaturesetLayers(se);for(const{source:De,sourceLayer:Qe}of Te){const Ye=we.getFeatureState({id:N.id,source:De,sourceLayer:Qe});if(Ye&&!Q)Q=Ye;else if(!o.b6(Q,Ye))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 N.target){const{layerId:se}=N.target,ue=this.getLayer(se);Q=this.getFeatureState({id:N.id,source:ue.source,sourceLayer:ue.sourceLayer})}return Q}const T=N.source,B=N.sourceLayer,W=this._checkSource(T);if(W){if(W.type!=="vector"||B)return N.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(T)[0].getFeatureState(B,N.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(N){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,N),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(N){N!==this._worldview&&(this._worldview=N,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const N=this.getTerrain(),T=N&&this.terrain&&this.terrain.scope===this.scope?N: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:T,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)},B=>B!==void 0)}_updateFilteredLayers(N){for(const T of Object.values(this._mergedLayers))N(T)&&this._updateLayer(T)}_updateLayer(N){this._changes.updateLayer(N);const T=this.getLayerSourceCache(N),B=o.F(N.source,N.scope),W=this._changes.getUpdatedSourceCaches();N.source&&!W[B]&&T&&T.getSource().type!=="raster"&&(this._changes.updateSourceCache(B,"reload"),T.pause()),N.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(N){const T=ue=>this._mergedLayers[ue].is3D(!!this.terrain),B=this.order,W={},Q=[];for(let ue=B.length-1;ue>=0;ue--){const we=B[ue];if(T(we)){W[we]=ue;for(const Te of N){const De=Te[we];if(De)for(const Qe of De)Q.push(Qe)}}}Q.sort((ue,we)=>we.intersectionZ-ue.intersectionZ);const se=[];for(let ue=B.length-1;ue>=0;ue--){const we=B[ue];if(T(we))for(let Te=Q.length-1;Te>=0;Te--){const De=Q[Te].feature;if(De.layer&&W[De.layer.id]{if(Zj.has(De.type))return;const Qe=this.getOwnLayerSourceCache(De),Ye=Q[Qe.id]=Q[Qe.id]||{sourceCache:Qe,layers:{},has3DLayers:!1};De.is3D(!!this.terrain)&&(Ye.has3DLayers=!0),Ye.layers[De.fqid]=Ye.layers[De.fqid]||{styleLayer:De,targets:[]},Ye.layers[De.fqid].targets.push({filter:W})};if(T&&T.layers){if(!Array.isArray(T.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const De of T.layers){const Qe=this._layers[De];if(!Qe)return this.fire(new o.B(new Error(`The layer '${De}' does not exist in the map's style and cannot be queried for features.`))),[];se(Qe)}}else for(const De in this._layers)se(this._layers[De]);const ue=this._queryRenderedFeatures(N,Q,B),we=this._flattenAndSortRenderedFeatures(ue),Te=[];for(const De of we)o.dh(De.layer.id)===this.scope&&Te.push(De);return Te}queryRenderedFeatureset(N,T,B){let W;T&&!Array.isArray(T)&&T.filter&&(this._validate(ks,"queryRenderedFeatures.filter",T.filter,null,T),W=o.dg(T.filter));const Q="mock",se=[];if(T&&T.target)se.push(Object.assign({},T,{targetId:Q,filter:W}));else{const De=this.getFeaturesetDescriptors();for(const Qe of De)se.push({targetId:Q,filter:W,target:Qe});for(const{style:Qe}of this.fragments){const Ye=Qe.getFeaturesetDescriptors();for(const tt of Ye)se.push({targetId:Q,filter:W,target:tt})}}const ue=this.queryRenderedTargets(N,se,B),we=[],Te=new Set;for(const De of ue)for(const Qe of De.variants[Q])pi(Qe,De,Te)||we.push(new o.di(De,Qe));return we}queryRenderedTargets(N,T,B){const W={},Q=(ue,we,Te,De)=>{const Qe=W[we.id]=W[we.id]||{sourceCache:we,layers:{},has3DLayers:!1};if(Qe.layers[ue.fqid]=Qe.layers[ue.fqid]||{styleLayer:ue,targets:[]},ue.is3D(!!this.terrain)&&(Qe.has3DLayers=!0),!De)return Te.uniqueFeatureID=!1,void Qe.layers[ue.fqid].targets.push(Te);Qe.layers[ue.fqid].targets.push(Object.assign({},Te,{namespace:De.namespace,properties:De.properties,uniqueFeatureID:De.uniqueFeatureID}))};for(const ue of T)if("featuresetId"in ue.target){const{featuresetId:we,importId:Te}=ue.target,De=this.getFragmentStyle(Te);if(!De||!De._featuresetSelectors)continue;const Qe=De._featuresetSelectors[we];if(!Qe){this.fire(new o.B(new Error(`The featureset '${we}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Ye of Qe){const tt=De.getOwnLayer(Ye.layerId);tt&&!Zj.has(tt.type)&&Q(tt,De.getOwnLayerSourceCache(tt),ue,Ye)}}else if("layerId"in ue.target){const{layerId:we}=ue.target,Te=this.getLayer(we);if(!Te||Zj.has(Te.type))continue;Q(Te,this.getLayerSourceCache(Te),ue)}const se=this._queryRenderedFeatures(N,W,B);return this._flattenAndSortRenderedFeatures(se)}_queryRenderedFeatures(N,T,B){const W=[],Q=!!this.map._showQueryGeometry,se=tl.createFromScreenPoints(N,B);for(const ue in T){const we=$m(se,T[ue],this._availableImages,B,Q,this.getActualScope());Object.keys(we).length&&W.push(we)}if(this.placement)for(const ue in T){if(T[ue].sourceCache._renderSourceType!==o.b4.Symbol)continue;const we=al(se.screenGeometry,T[ue],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(we).length&&W.push(we)}return W}querySourceFeatures(N,T){const B=T&&T.filter;B&&this._validate(ks,"querySourceFeatures.filter",B,null,T);let W=[];const Q=this.getOwnSourceCaches(N);for(const se of Q)W=W.concat(vo(se,T));return W}addSourceType(N,T,B){return xh.getSourceType(N)?B(new Error(`A source type called "${N}" already exists.`)):(xh.setSourceType(N,T),T.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:N,url:T.workerSourceURL},B):B(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(N,T,B={}){this._checkLoaded();const W=this.light.getLight();let Q=!1;for(const ue in N)if(!o.b6(N[ue],W[ue])){Q=!0;break}if(!Q)return;const se=this._getTransitionParameters();this.light.setLight(N,T,B),this.light.updateTransitions(se)}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(N,T=1){if(this._checkLoaded(),!N)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),T===0&&delete this.terrain,N===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let B=N;const W=!("source"in N)||N.source==null;if(T===1){if(this.disableElevatedTerrain)return;if("source"in B&&typeof B.source=="object"){const ue="terrain-dem-src";this.addSource(ue,B.source),B=o.d9(B),B=Object.assign(B,{source:ue})}const Q=Object.assign({},B),se={};if(this.terrain&&W){Q.source=this.terrain.get().source;const ue=this.terrain?this.getFragmentStyle(this.terrain.scope):null;ue&&(se.style=ue.serialize())}if(this._validate(gt,"terrain",Q,se))return}if(!this.terrain||this.terrain.scope!==this.scope&&!W||this.terrain&&T!==this.terrain.drapeRenderMode){if(!B)return;this._createTerrain(B,T),this.fire(new o.C("data",{dataType:"style"}))}else{const Q=this.terrain,se=Q.get();for(const ue of Object.keys(o.a8.terrain))!B.hasOwnProperty(ue)&&o.a8.terrain[ue].default&&(B[ue]=o.a8.terrain[ue].default);for(const ue in N)if(!o.b6(N[ue],se[ue])){Q.set(N,this.options),this.stylesheet.terrain=N;const we=this._getTransitionParameters({duration:0});Q.updateTransitions(we),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(N){const T=this.fog=new Ao(N,this.map.transform,this.scope,this.options);this.stylesheet.fog=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_createSnow(N){const T=this.snow=new Ji(N,this.map.transform,this.scope,this.options);this.stylesheet.snow=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_createRain(N){const T=this.rain=new qa(N,this.map.transform,this.scope,this.options);this.stylesheet.rain=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const N of this.map._markers)N._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(N){if(this._checkLoaded(),!N)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const T=this.fog;if(!o.b6(T.get(),N)){T.set(N,this.options),this.stylesheet.fog=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createFog(N);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(N){if(this._checkLoaded(),!N)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const T=this.snow;if(!o.b6(T.get(),N)){T.set(N,this.options),this.stylesheet.snow=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createSnow(N);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(N){if(this._checkLoaded(),!N)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const T=this.rain;if(!o.b6(T.get(),N)){T.set(N,this.options),this.stylesheet.rain=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createRain(N);this._markersNeedUpdate=!0}_reloadColorTheme(){const N=()=>{for(const W in this._layers)this._layers[W].lut=this._styleColorTheme.lut;for(const W in this._sourceCaches)this._sourceCaches[W].clearTiles()},T=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!T)return this._styleColorTheme.lut=null,void N();const B=this._evaluateColorThemeData(T);this._loadColorTheme(B).then(()=>{this.fire(new o.C("colorthemeset")),N()}).catch(W=>{o.w(`Couldn't set color theme: ${W}`)})}setColorTheme(N){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&o.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=N,this._reloadColorTheme()}setImportColorTheme(N,T){const B=this.getFragmentStyle(N);B&&(B._styleColorTheme.colorThemeOverride=T,B._reloadColorTheme())}_getTransitionParameters(N){return{now:o.o.now(),transition:Object.assign(this.transition,N)}}updateDrapeFirstLayers(){if(!this.terrain)return;const N=[],T=[];for(const B of this._mergedOrder)this.isLayerDraped(this._mergedLayers[B])?N.push(B):T.push(B);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...N),this._drapedFirstOrder.push(...T)}_createTerrain(N,T){const B=this.terrain=new Tr(N,T,this.scope,this.options,this.map.getWorldview());T===1&&(this.stylesheet.terrain=N),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const W=this._getTransitionParameters({duration:0});B.updateTransitions(W)}_force3DLayerUpdate(){for(const N in this._layers){const T=this._layers[N];T.type==="fill-extrusion"&&this._updateLayer(T)}}_forceSymbolLayerUpdate(){for(const N in this._layers){const T=this._layers[N];T.type==="symbol"&&this._updateLayer(T)}}_validate(N,T,B,W,Q={}){if(Q&&Q.validate===!1)return!1;const se=Object.assign({},this.serialize());return z0(this,N.call(tr,Object.assign({key:T,style:se,value:B,styleSpec:o.a8},W)))}_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 N in this._mergedLayers)this._mergedLayers[N].setEventedParent(null);for(const N in this._mergedSourceCaches)this._mergedSourceCaches[N].clearTiles(),this._mergedSourceCaches[N].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(N){const T=this.getSourceCaches(N);for(const B of T)B.clearTiles()}clearSources(){for(const N in this._mergedSourceCaches)this._mergedSourceCaches[N].clearTiles()}clearLayers(){for(const N in this._mergedLayers){const T=this._mergedLayers[N];T._clear&&T._clear()}}reloadSource(N){const T=this.getSourceCaches(N);for(const B of T)B.resume(),B.reload()}reloadSources(){for(const N of this.getSources())N.reload&&N.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(N=>{N.modelManager.reloadModels(N.scope)})}updateSources(N){let T;this.directionalLight&&(T=O0(this.directionalLight));const B=new Set,W=new Set,Q=new Set;for(const se in this._mergedLayers){const ue=this._mergedLayers[se];ue.type==="building"?B.add(ue.source):ue.type==="raster"&&ue.paint&&ue.paint.get("raster-elevation-reference")==="ground"&&Q.add(ue.source),ue.hasElevation()&&!W.has(ue.source)&&W.add(ue.source)}for(const se in this._mergedSourceCaches){const ue=this._mergedSourceCaches[se],we=W.has(ue._source.id);ue._isRasterElevatedOverTerrain=Q.has(ue._source.id),B.has(ue._source.id)&&(ue._source.reparseOverscaled=!1),ue.update(N,void 0,void 0,T,we)}}_generateCollisionBoxes(){for(const N in this._sourceCaches){const T=this._sourceCaches[N];T.resume(),T.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new pp),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(N,T,B,W,Q){this.pauseablePlacement||(this.pauseablePlacement=new pp);let se=!1,ue=!1;const we={},Te={};for(const ct of this._mergedOrder){const St=this._mergedLayers[ct];if(St.type!=="symbol")continue;const kt=o.F(St.source,St.scope);let Ut=we[kt];if(!Ut){const Et=this.getLayerSourceCache(St);if(!Et)continue;const Ts=Et.getRenderableIds(!0).map(ds=>Et.getTileByID(ds));Te[kt]=Ts.slice(),Ut=we[kt]=Ts.sort((ds,Cs)=>Cs.tileID.overscaledZ-ds.tileID.overscaledZ||(ds.tileID.isLessThan(Cs.tileID)?-1:1))}const Xt=this.crossTileSymbolIndex.addLayer(St,Ut,N.center.lng,N.projection);se=se||Xt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const De=!!(this.placement&&!N.equals(this.placement.transform)),Qe=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Q||this.placement.lastReplacementSourceUpdateTime!==Q.updateTime)),Ye=De||Qe||se,tt=(Ye||this.pauseablePlacement.isStale())&&B===0,ht=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),N.zoom)&&B!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||tt||ht)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(N,this._mergedOrder,T,B,W,this.placement,this.fog&&N.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const ct=this.map.painter.maxFrontCutoffRawStart;if(ct>0){const St=180*N.pitch/Math.PI;if(St>=15){const kt=Math.min(1,Math.max(0,(St-15)/5)),Ut=kt*kt*(3-2*kt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Ut)+ct*Ut}}}if(this.pauseablePlacement.isDone()?Ye&&B!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,we,Te,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),ue=!0),se&&this.pauseablePlacement.setStale()),ue||se){this._buildingIndex.onNewFrame(N.zoom);for(let ct=0;ctQ===N.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${N.id}' already exists in the map's style.`)));if(!T)return B.push(N),this._loadImports([N],!0);const W=B.findIndex(({id:Q})=>Q===T);return W===-1&&this.fire(new o.B(new Error(`Import with id "${T}" does not exist on this map.`))),this.stylesheet.imports=B.slice(0,W).concat(N).concat(B.slice(W)),this._loadImports([N],!0,T)}updateImport(N,T){this._checkLoaded();const B=this.stylesheet.imports||[],W=this.getImportIndex(N);return W===-1?this:typeof T=="string"?(this.setImportUrl(N,T),this):(T.url&&T.url!==B[W].url&&this.setImportUrl(N,T.url),o.b6(T.config,B[W].config)||this.setImportConfig(N,T.config,T.data.schema),o.b6(T.data,B[W].data)||this.setImportData(N,T.data),this)}moveImport(N,T){this._checkLoaded();let B=this.stylesheet.imports||[];const W=this.getImportIndex(N);if(W===-1)return this;const Q=this.getImportIndex(T);if(Q===-1)return this;const se=B[W],ue=this.fragments[W];return B=B.filter(({id:we})=>we!==N),this.fragments=this.fragments.filter(({id:we})=>we!==N),this.stylesheet.imports=B.slice(0,Q).concat(se).concat(B.slice(Q)),this.fragments=this.fragments.slice(0,Q).concat(ue).concat(this.fragments.slice(Q)),this.mergeLayers(),this}setImportUrl(N,T){this._checkLoaded();const B=this.stylesheet.imports||[],W=this.getImportIndex(N);if(W===-1)return this;B[W].url=T;const Q=this.fragments[W];return Q.style=this._createFragmentStyle(B[W]),Q.style.on("style.import.load",()=>this.mergeAll()),Q.style.loadURL(T),this}setImportData(N,T){this._checkLoaded();const B=this.getImportIndex(N),W=this.stylesheet.imports||[];return B===-1?this:T?(this.fragments[B].style.setState(T),this._reloadImports(),this):(delete W[B].data,this.setImportUrl(N,W[B].url))}setImportConfig(N,T,B){this._checkLoaded();const W=this.getImportIndex(N),Q=this.stylesheet.imports||[];if(W===-1)return this;T?Q[W].config=T:delete Q[W].config;const se=this.fragments[W];B&&se.style.stylesheet&&(se.style.stylesheet.schema=B);const ue=se.style.stylesheet&&se.style.stylesheet.schema;return se.config=T,se.style.updateConfig(T,ue),this.updateConfigDependencies(),this}removeImport(N){this._checkLoaded();const T=this.stylesheet.imports||[],B=this.getImportIndex(N);B!==-1&&(T.splice(B,1),this.fragments[B].style._remove(),this.fragments.splice(B,1),this._reloadImports())}getImportIndex(N){const T=(this.stylesheet.imports||[]).findIndex(B=>B.id===N);return T===-1&&this.fire(new o.B(new Error(`Import '${N}' does not exist in the map's style and cannot be updated.`))),T}getLayer(N){return this._mergedLayers[N]}getSources(){const N=[];for(const T in this._mergedOtherSourceCaches){const B=this._mergedOtherSourceCaches[T];B&&N.push(B.getSource())}return N}getSource(N,T){const B=this.getSourceCache(N,T);return B&&B.getSource()}getLayerSource(N){const T=this.getLayerSourceCache(N);return T&&T.getSource()}getSourceCache(N,T){const B=o.F(N,T);return this._mergedOtherSourceCaches[B]}getLayerSourceCache(N){const T=o.F(N.source,N.scope);return N.type==="symbol"?this._mergedSymbolSourceCaches[T]:N.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[T]||this._mergedOtherSourceCaches[T]}getSourceCaches(N){if(N==null)return Object.values(this._mergedSourceCaches);const T=[];return this._mergedOtherSourceCaches[N]&&T.push(this._mergedOtherSourceCaches[N]),this._mergedSymbolSourceCaches[N]&&T.push(this._mergedSymbolSourceCaches[N]),this._mergedFillExtrusionSourceCaches[N]&&T.push(this._mergedFillExtrusionSourceCaches[N]),T}updateSourceCaches(){const N=this._changes.getUpdatedSourceCaches();for(const T in N){const B=N[T];B==="reload"?this.reloadSource(T):B==="clear"&&this.clearSource(T)}}updateLayers(N){const T=this._changes.getUpdatedPaintProperties();for(const B of T){const W=this.getLayer(B);W&&W.updateTransitions(N)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(N){this.stylesheet.glyphs=N,this.glyphManager.setURL(N)}getImages(N,T,B){this.imageManager.getImages(T.images,T.scope,B),this._updateTilesForChangedImages();const W=se=>{if(se){const ue=T.images.map(we=>o.I.toString(we));se.setDependencies(T.tileID.key,T.type,ue)}},Q=o.F(T.source,T.scope);W(this._mergedOtherSourceCaches[Q]),W(this._mergedSymbolSourceCaches[Q]),T.images.some(se=>se.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(N,T,B){this.imageManager.rasterizeImages(T,B)}checkAtlasCache(N,T,B){const W=this.imageManager.imageAtlasCache.findCachedAtlas(T.descriptor);B(null,W&&W.contentDescriptor?{iconPositions:W.iconPositions,patternPositions:W.patternPositions,sourceHash:W.contentDescriptor.hash}:null)}getGlyphs(N,T,B){this.glyphManager.getGlyphs(T.stacks,B)}getOwnSourceCache(N){return this._otherSourceCaches[N]}getOwnLayerSourceCache(N){return N.type==="symbol"?this._symbolSourceCaches[N.source]:N.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[N.source]||this._otherSourceCaches[N.source]}getOwnSourceCaches(N){const T=[];return this._otherSourceCaches[N]&&T.push(this._otherSourceCaches[N]),this._symbolSourceCaches[N]&&T.push(this._symbolSourceCaches[N]),this._fillExtrusionSourceCaches[N]&&T.push(this._fillExtrusionSourceCaches[N]),T}_isSourceCacheLoaded(N){const T=this.getOwnSourceCaches(N);return T.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${N}'`))),!1):T.every(B=>B.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(N,T){if(!this._clipLayerPresent&&N.type!=="fill-extrusion"&&N.type!=="building")return!1;const B=N.type==="fill-extrusion"&&(N.sourceLayer==="building"||N.sourceLayer==="procedural_buildings"),W=N.type==="building";if(N.is3D(!!this.terrain)){if(B||W||T&&T.type==="batched-model"||N.type==="model")return!0}else if(N.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(N=>{N.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}xh.getSourceType=function(R){return Ta[R]},xh.setSourceType=function(R,N){Ta[R]=N},xh.registerForPluginStateChange=o.dk;var B0=` #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`,Xj=` #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;}`,$0=` #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`,aw="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;}",JN=` #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`,ek=`#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`,Ob=`#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`,zb=`#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`,tk=`#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;}`,iw=`#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`,gf=`#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 jm=/#include\s+"([^"]+)"/g,fr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,Bb=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,$b=new Set(["ifdef","ifndef","elif","if","defined"]),P1=new Set;Vy(B0,P1),Vy($0,P1),Vy(Xj,P1);const ax={"_prelude_fog.vertex.glsl":ek,"_prelude_terrain.vertex.glsl":JN,"_prelude_shadow.vertex.glsl":iw,"_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":Ob,"_prelude_shadow.fragment.glsl":gf,"_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":zb,"_prelude_raster_particle.glsl":tk},Rv={};Mo("",JN),Mo(Ob,ek),Mo(gf,iw),Mo(zb,""),Mo(tk,"");const U0=Mo(Xj,$0),ow=B0,L1=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",ow,U0.fragmentSource].join(` `),sk=["precision highp float;",ow,U0.vertexSource].join(` `);var Qj={background:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`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:Mo("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:Mo(`#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:Mo("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:Mo(`#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:Mo(`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:Mo("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:Mo("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:Mo("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:Mo("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:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`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:Mo(`#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:Mo("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:Mo(`#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:Mo(`#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:Mo(`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:Mo(`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:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`#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:Mo(`#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:Mo("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:Mo("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:Mo(`#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:Mo(`#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:Mo(`#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:Mo("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:Mo(`#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 }`,aw),skyboxGradient:Mo(`#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 }`,aw),skyboxCapture:Mo(` 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:Mo(`#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:Mo(`#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:Mo(`#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:Mo("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:Mo(`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:Mo("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:Mo("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:Mo("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:Mo("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 Vy(R,N){const T=R.split(` `);for(let B of T){if(B=B.trimStart(),B[0]!=="#"||!B.includes("if")||B.startsWith("#endif"))continue;const W=B.match(Bb);if(W)for(const Q of W)$b.has(Q)||N.add(Q)}}function GC(R){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(R)}function Mo(R,N){const T=new Set,B=[],W=[];R=R.replace(jm,(se,ue)=>(W.push(ue),"")),N=N.replace(jm,(se,ue)=>(B.push(ue),""));let Q=new Set(P1);Vy(R,Q),Vy(N,Q);for(const se of[...B,...W])Rv[se]||(Rv[se]=new Set,Vy(ax[se],Rv[se])),Q=new Set([...Q,...Rv[se]]);return{fragmentSource:R=R.replace(fr,(se,ue,we,Te,De)=>(T.add(De),ue==="define"?` #ifndef HAS_UNIFORM_u_${De} ${GC(Te)?"flat ":""}in ${we} ${Te} ${De}; #else uniform ${we} ${Te} u_${De}; #endif `:ue==="initialize"?` #ifdef HAS_UNIFORM_u_${De} ${we} ${Te} ${De} = u_${De}; #endif `:ue==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${De} in ${we} ${Te} ${De}; #endif `:ue==="initialize-attribute"?"":void 0)),vertexSource:N=N.replace(fr,(se,ue,we,Te,De)=>{const Qe=`MATERIAL_ATTRIBUTE_OFFSET_${De}`,Ye=Te==="float"?"vec2":Te,tt=`GET_ATTRIBUTE_${Ye}(a_${De}, materialInfo, ${Qe})`,ht=De.match(/color/)?"color":Ye;return ue==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${De} in ${we} ${Te} a_${De}; #endif `:T.has(De)?ue==="define"?` #ifndef HAS_UNIFORM_u_${De} uniform lowp float u_${De}_t; #if !defined(${Qe}) in ${we} ${Ye} a_${De}; #endif ${GC(Te)?"flat ":""}out ${we} ${Te} ${De}; #else uniform ${we} ${Te} u_${De}; #endif `:ue==="initialize"?ht==="vec4"||ht==="uvec4"?` #ifndef HAS_UNIFORM_u_${De} ${De} = a_${De}; #else ${we} ${Te} ${De} = u_${De}; #endif `:` #if !defined(HAS_UNIFORM_u_${De}) #ifdef ${Qe} ${De} = unpack_mix_${ht}(${tt}, u_${De}_t); #else ${De} = unpack_mix_${ht}(a_${De}, u_${De}_t); #endif #else ${we} ${Te} ${De} = u_${De}; #endif `:ue==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${De} in ${we} ${Te} a_${De}; out ${we} ${Te} ${De}; #endif `:ue==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${De} ${De} = a_${De}; #endif `:void 0:ue==="define"?` #ifndef HAS_UNIFORM_u_${De} uniform lowp float u_${De}_t; #if !defined(${Qe}) in ${we} ${Ye} a_${De}; #endif #else uniform ${we} ${Te} u_${De}; #endif `:ue==="define-instanced"?ht==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${De}0; in vec4 a_${De}1; in vec4 a_${De}2; in vec4 a_${De}3; #else uniform ${we} ${Te} u_${De}; #endif `:` #ifdef INSTANCED_ARRAYS in ${we} ${Ye} a_${De}; #else uniform ${we} ${Te} u_${De}; #endif `:ue==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${De} ${we} ${Te} ${De} = a_${De}; #endif `:ht==="vec4"||ht==="uvec4"?` #ifndef HAS_UNIFORM_u_${De} #ifdef ${Qe} ${we} ${Te} ${De} = ${tt}; #else ${we} ${Te} ${De} = a_${De}; #endif #else ${we} ${Te} ${De} = u_${De}; #endif `:` #ifndef HAS_UNIFORM_u_${De} #ifdef ${Qe} ${we} ${Te} ${De} = unpack_mix_${ht}(${tt}, u_${De}_t); #else ${we} ${Te} ${De} = unpack_mix_${ht}(a_${De}, u_${De}_t); #endif #else ${we} ${Te} ${De} = u_${De}; #endif `}),usedDefines:Q,vertexIncludes:B,fragmentIncludes:W}}class XS{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(N,T,B,W,Q,se,ue,we){this.context=N;let Te=this.boundPaintVertexBuffers.length!==W.length;for(let Qe=0;!Te&&Qe{const Ts=Xt.paint.get("hillshade-shadow-color"),ds=Xt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Cs=Xt.paint.get("hillshade-highlight-color"),es=Xt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",is=Xt.paint.get("hillshade-accent-color"),_s=Xt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Xs=Xt.paint.get("hillshade-emissive-strength");let Ds=o.ap(Xt.paint.get("hillshade-illumination-direction"));if(Xt.paint.get("hillshade-illumination-anchor")==="viewport")Ds-=kt.transform.angle;else if(kt.style&&kt.style.enable3dLights()&&kt.style.directionalLight){const pn=kt.style.directionalLight.properties.get("direction"),Un=o.cP(pn.x,pn.y,pn.z);Ds=o.ap(Un[1])}const _n=!kt.options.moving;return{u_matrix:Et||kt.transform.calculateProjMatrix(Ut.tileID.toUnwrapped(),_n),u_image:0,u_latrange:WC(0,Ut.tileID),u_light:[Xt.paint.get("hillshade-exaggeration"),Ds],u_shadow:Ts.toPremultipliedRenderColor(ds?null:Xt.lut),u_highlight:Cs.toPremultipliedRenderColor(es?null:Xt.lut),u_emissive_strength:Xs,u_accent:is.toPremultipliedRenderColor(_s?null:Xt.lut)}})(R,T,B,R.terrain?N.projMatrix:null);R.uploadCommonUniforms(ue,Ye,N.toUnwrapped());const{tileBoundsBuffer:ht,tileBoundsIndexBuffer:ct,tileBoundsSegments:St}=R.getTileBoundsBuffers(T);Ye.draw(R,we.TRIANGLES,W,Q,se,ba.disabled,tt,B.id,ht,ct,St)}function KC(R,N,T){if(!N.needsDEMTextureUpload)return;const B=R.context,W=B.gl;B.pixelStoreUnpackPremultiplyAlpha.set(!1),N.demTexture=N.demTexture||R.getTileTexture(T.stride);const Q=T.getPixels();N.demTexture?N.demTexture.update(Q,{premultiply:!1}):N.demTexture=new o.T(B,Q,W.R32F,{premultiply:!1}),N.needsDEMTextureUpload=!1}function tT(R,N,T){const B=R.context,W=B.gl;if(!N.dem)return;const Q=N.dem;if(B.activeTexture.set(W.TEXTURE1),KC(R,N,Q),!N.demTexture)return;N.demTexture.bind(W.NEAREST,W.CLAMP_TO_EDGE);const se=Q.dim;B.activeTexture.set(W.TEXTURE0);let ue=N.hillshadeFBO;if(!ue){const Ye=new o.T(B,{width:se,height:se,data:null},W.RGBA8);Ye.bind(W.LINEAR,W.CLAMP_TO_EDGE),ue=N.hillshadeFBO=B.createFramebuffer(se,se,1,"renderbuffer"),ue.colorAttachment0.set(Ye.texture)}B.bindFramebuffer.set(ue.framebuffer),B.viewport.set([0,0,se,se]);const{tileBoundsBuffer:we,tileBoundsIndexBuffer:Te,tileBoundsSegments:De}=R.getMercatorTileBoundsBuffers(),Qe=[];R.linearFloatFilteringSupported()&&Qe.push("TERRAIN_DEM_FLOAT_FORMAT"),R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&Qe.push("USE_MRT1"),R.getOrCreateProgram("hillshadePrepare",{defines:Qe}).draw(R,W.TRIANGLES,Yr.disabled,Va.disabled,$a.unblended,ba.disabled,((Ye,tt)=>{const ht=tt.stride,ct=o.bb();return o.bT(ct,0,o.an,-o.an,0,0,1),o.bx(ct,ct,[0,-o.an,0]),{u_matrix:ct,u_image:1,u_dimension:[ht,ht],u_zoom:Ye.overscaledZ}})(N.tileID,Q),T.id,we,Te,De),N.needsHillshadePrepare=!1}class vd{constructor(N){this.gl=N.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(N){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class lw extends vd{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(N){const T=this.current;(N.r!==T.r||N.g!==T.g||N.b!==T.b||N.a!==T.a||this.dirty)&&(this.gl.clearColor(N.r,N.g,N.b,N.a),this.current=N,this.dirty=!1)}}class YC extends vd{getDefault(){return 1}set(N){(N!==this.current||this.dirty)&&(this.gl.clearDepth(N),this.current=N,this.dirty=!1)}}class Ub extends vd{getDefault(){return 0}set(N){(N!==this.current||this.dirty)&&(this.gl.clearStencil(N),this.current=N,this.dirty=!1)}}class QL extends vd{getDefault(){return[!0,!0,!0,!0]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||N[3]!==T[3]||this.dirty)&&(this.gl.colorMask(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class Hy extends vd{getDefault(){return!0}set(N){(N!==this.current||this.dirty)&&(this.gl.depthMask(N),this.current=N,this.dirty=!1)}}class Jj extends vd{getDefault(){return 255}set(N){(N!==this.current||this.dirty)&&(this.gl.stencilMask(N),this.current=N,this.dirty=!1)}}class cw extends vd{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(N){const T=this.current;(N.func!==T.func||N.ref!==T.ref||N.mask!==T.mask||this.dirty)&&(this.gl.stencilFunc(N.func,N.ref,N.mask),this.current=N,this.dirty=!1)}}class QS extends vd{getDefault(){const N=this.gl;return[N.KEEP,N.KEEP,N.KEEP]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||this.dirty)&&(this.gl.stencilOp(N[0],N[1],N[2]),this.current=N,this.dirty=!1)}}class qb extends vd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.STENCIL_TEST):T.disable(T.STENCIL_TEST),this.current=N,this.dirty=!1}}class Vb extends vd{getDefault(){return[0,1]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||this.dirty)&&(this.gl.depthRange(N[0],N[1]),this.current=N,this.dirty=!1)}}class Gx extends vd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.DEPTH_TEST):T.disable(T.DEPTH_TEST),this.current=N,this.dirty=!1}}class Yu extends vd{getDefault(){return this.gl.LESS}set(N){(N!==this.current||this.dirty)&&(this.gl.depthFunc(N),this.current=N,this.dirty=!1)}}class Gy extends vd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.BLEND):T.disable(T.BLEND),this.current=N,this.dirty=!1}}class nk extends vd{getDefault(){const N=this.gl;return[N.ONE,N.ZERO,N.ONE,N.ZERO]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||N[3]!==T[3]||this.dirty)&&(this.gl.blendFuncSeparate(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class ZC extends vd{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(N){const T=this.current;(N.r!==T.r||N.g!==T.g||N.b!==T.b||N.a!==T.a||this.dirty)&&(this.gl.blendColor(N.r,N.g,N.b,N.a),this.current=N,this.dirty=!1)}}class jg extends vd{getDefault(){return this.gl.FUNC_ADD}set(N){(N!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(N,N),this.current=N,this.dirty=!1)}}class ix extends vd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;N?T.enable(T.CULL_FACE):T.disable(T.CULL_FACE),this.current=N,this.dirty=!1}}class rk extends vd{getDefault(){return this.gl.BACK}set(N){(N!==this.current||this.dirty)&&(this.gl.cullFace(N),this.current=N,this.dirty=!1)}}class JS extends vd{getDefault(){return this.gl.CCW}set(N){(N!==this.current||this.dirty)&&(this.gl.frontFace(N),this.current=N,this.dirty=!1)}}let e2=class extends vd{getDefault(){return null}set(R){(R!==this.current||this.dirty)&&(this.gl.useProgram(R),this.current=R,this.dirty=!1)}};class t2 extends vd{getDefault(){return this.gl.TEXTURE0}set(N){(N!==this.current||this.dirty)&&(this.gl.activeTexture(N),this.current=N,this.dirty=!1)}}class ox extends vd{getDefault(){const N=this.gl;return[0,0,N.drawingBufferWidth,N.drawingBufferHeight]}set(N){const T=this.current;(N[0]!==T[0]||N[1]!==T[1]||N[2]!==T[2]||N[3]!==T[3]||this.dirty)&&(this.gl.viewport(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class yf extends vd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindFramebuffer(T.FRAMEBUFFER,N),this.current=N,this.dirty=!1}}class XC extends vd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindRenderbuffer(T.RENDERBUFFER,N),this.current=N,this.dirty=!1}}class Fv extends vd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindTexture(T.TEXTURE_2D,N),this.current=N,this.dirty=!1}}class s2 extends vd{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.bindBuffer(T.ARRAY_BUFFER,N),this.current=N,this.dirty=!1}}class n2 extends vd{getDefault(){return null}set(N){const T=this.gl;T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,N),this.current=N,this.dirty=!1}}class e5 extends vd{getDefault(){return null}set(N){this.gl&&(N!==this.current||this.dirty)&&(this.gl.bindVertexArray(N),this.current=N,this.dirty=!1)}}class t5 extends vd{getDefault(){return 4}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_ALIGNMENT,N),this.current=N,this.dirty=!1}}class s5 extends vd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N),this.current=N,this.dirty=!1}}class r2 extends vd{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_FLIP_Y_WEBGL,N),this.current=N,this.dirty=!1}}class a2 extends vd{constructor(N,T){super(N),this.context=N,this.parent=T}getDefault(){return null}}class dw extends a2{constructor(N,T,B=0){super(N,T),this.attachmentPoint=N.gl.COLOR_ATTACHMENT0+B}setDirty(){this.dirty=!0}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachmentPoint,T.TEXTURE_2D,N,0),this.current=N,this.dirty=!1}}class ak extends a2{attachment(){return this.gl.DEPTH_ATTACHMENT}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferRenderbuffer(T.FRAMEBUFFER,this.attachment(),T.RENDERBUFFER,N),this.current=N,this.dirty=!1}}class n5 extends a2{attachment(){return this.gl.DEPTH_ATTACHMENT}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachment(),T.TEXTURE_2D,N,0),this.current=N,this.dirty=!1}}class sT extends ak{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const uw=(R,N,T,B)=>({u_matrix:R,u_image0:0,u_image1:1,u_skirt_height:N,u_ground_shadow_factor:T,u_emissive_texture_available:B}),Ov=(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St)=>({u_proj_matrix:Float32Array.from(R),u_globe_matrix:N,u_normalize_matrix:Float32Array.from(B),u_merc_matrix:T,u_zoom_transition:W,u_merc_center:Q,u_image0:0,u_image1:1,u_frustum_tl:se,u_frustum_tr:ue,u_frustum_br:we,u_frustum_bl:Te,u_globe_pos:De,u_globe_radius:Qe,u_viewport:Ye,u_grid_matrix:St?Float32Array.from(St):new Float32Array(9),u_skirt_height:tt,u_far_z_cutoff:ht,u_emissive_texture_available:ct});function i2(R,N){return R!=null&&N!=null&&!(!R.hasData()||!N.hasData())&&R.demTexture!=null&&N.demTexture!=null&&R.tileID.key!==N.tileID.key}const fp=new class{constructor(){this.operations={}}newMorphing(R,N,T,B,W){if(R in this.operations){const Q=this.operations[R];Q.to.tileID.key!==T.tileID.key&&(Q.queued=T)}else this.operations[R]={startTime:B,phase:0,duration:W,from:N,to:T,queued:null}}getMorphValuesForProxy(R){if(!(R in this.operations))return null;const N=this.operations[R];return{from:N.from,to:N.to,phase:N.phase}}update(R){for(const N in this.operations){const T=this.operations[N];for(T.phase=(R-T.startTime)/T.duration;T.phase>=1||!this._validOp(T);)if(!this._nextOp(T,R)){delete this.operations[N];break}}}_nextOp(R,N){return!!R.queued&&(R.from=R.to,R.to=R.queued,R.queued=null,R.phase=0,R.startTime=N,!0)}_validOp(R){return R.from.hasData()&&R.to.hasData()}},o2={0:null,1:"TERRAIN_VERTEX_MORPHING"};function hw(R,N,T){if(N===0)return 0;const B=N<1&&T===514?.25/N:1;return 6*Math.pow(1.5,22-R)*Math.max(N,1)*B}function Me(R,N){const T=1<({u_matrix:R});function jt(R,N,T,B,W){if(W>0){const Q=o.o.now(),se=(Q-R.timeAdded)/W,ue=N?(Q-N.timeAdded)/W:-1,we=T.getSource(),Te=B.coveringZoomLevel({tileSize:we.tileSize,roundZoom:we.roundZoom}),De=!N||Math.abs(N.tileID.overscaledZ-Te)>Math.abs(R.tileID.overscaledZ-Te),Qe=De&&R.refreshedUponExpiration?1:o.aC(De?se:1-ue,0,1);return N?{opacity:1,mix:1-Qe,isFading:se<1}:{opacity:Qe,mix:0,isFading:se<1}}return{opacity:1,mix:0,isFading:!1}}class ns extends zc{constructor(N){const T={type:"raster-dem",maxzoom:Math.ceil(N.transform.maxZoom)},B=so("mock-dem",T,N.style.dispatcher,N.style);super("mock-dem",B,null),B.setEventedParent(this),this._sourceLoaded=!0}_loadTile(N,T){N.state="loaded",T(null)}}class xs extends zc{constructor(N){const T=so("proxy",{type:"geojson",maxzoom:Math.ceil(N.transform.maxZoom)},N.style.dispatcher,N.style);super("proxy",T,null),T.setEventedParent(this),this.map=this.getSource().map=N,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(N,T,B){if(N.freezeTileCoverage)return;this.transform=N;const W=N.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((Q,se)=>{if(Q[se.key]="",!this._tiles[se.key]){const ue=new o.b0(se,this._source.tileSize*se.overscaleFactor(),N.tileZoom,void 0,void 0,this._source.worldview);ue.state="loaded",this._tiles[se.key]=ue}return Q},{});for(const Q in this._tiles)Q in W||(this.freeFBO(Q),this._tiles[Q].unloadVectorData(),delete this._tiles[Q])}freeFBO(N){const T=this.proxyCachedFBO[N];if(T!==void 0){const B=Object.values(T);this.renderCachePool.push(...B),delete this.proxyCachedFBO[N]}}deallocRenderCache(){this.renderCache.forEach(N=>N.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class bs extends o.aR{constructor(N,T,B){super(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y),this.proxyTileKey=T,this.projMatrix=B}}class Ms extends o.bu{constructor(N,T){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=N,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[B,W,Q]=function(){const we=new o.dB,Te=new o.dC,De=131;we.reserve(17161),Te.reserve(33800);const Qe=o.an/128,Ye=o.an+Qe/2,tt=Ye+Qe;for(let ct=-Qe;ctYe||ct<0||ct>Ye?24575:0,Ut=o.aC(Math.round(St),0,o.an),Xt=o.aC(Math.round(ct),0,o.an);we.emplaceBack(Ut+kt,Xt)}const ht=(ct,St)=>{const kt=St*De+ct;Te.emplaceBack(kt+1,kt,kt+De),Te.emplaceBack(kt+De,kt+De+1,kt+1)};for(let ct=1;ct<129;ct++)for(let St=1;St<129;St++)ht(St,ct);return[0,129].forEach(ct=>{for(let St=0;St<130;St++)ht(St,ct),ht(ct,St)}),[we,Te,32768]}(),se=N.context;this.gridBuffer=se.createVertexBuffer(B,o.dx.members),this.gridIndexBuffer=se.createIndexBuffer(W),this.gridSegments=o.dy.simpleSegment(0,0,B.length,W.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,B.length,Q),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new xs(T.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 ue=se.gl;this._overlapStencilMode=new Va({func:ue.GEQUAL,mask:255},0,255,ue.KEEP,ue.KEEP,ue.REPLACE),this._previousZoom=N.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=T,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new ns(T.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(N){N.on("data",this._onStyleDataEvent.bind(this)),this._style=N,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(N,T,B){if(N&&N.terrain){this._style!==N&&(this.style=N,this._evaluationZoom=void 0);const W=N.terrain.properties,Q=N.terrain.drapeRenderMode===0,se=N.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const ue=N.terrain&&N.terrain.scope,we=W.get("source"),Te=Q?this._mockSourceCache:N.getSourceCache(we,ue);if(!Te)return void o.w(`Couldn't find terrain source "${we}".`);if(this.sourceCache=Te,this._attenuationRange=N.terrain.getAttenuationRange(),this._exaggeration=se?this.calculateExaggeration(T):W.get("exaggeration"),!T.projection.requiresDraping&&se&&this._exaggeration===0)return void this._disable();this.enabled=!0;const De=()=>{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 Qe=this.getScaledDemTileSize();this.sourceCache.update(T,Qe,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,De(),this._initializing=!0),De(),T.updateElevation(!0,B),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(T),this._emptyDEMTextureDirty=!0,this._previousZoom=T.zoom}else this._disable()}calculateExaggeration(N){if(this._attenuationRange&&N.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(N.zoom);const T=this._previousCameraAltitude,B=N.getFreeCameraOptions().position.z/N.pixelsPerMeter*N.worldSize;this._previousCameraAltitude=B;const W=T!=null?B-T:Number.MAX_VALUE;if(Math.abs(W)<2)return this._exaggeration;const Q=N.zoom,se=this._style.terrain;if(!this._previousUpdateTimestamp)return se.getExaggeration(Q);let ue=Q-this._previousZoom;const we=this._previousUpdateTimestamp;let Te=Q;this._evaluationZoom!=null&&(Te=this._evaluationZoom,Math.abs(Q-Te)>.5&&(ue=.5*(Q-Te+ue)),ue*W<0&&(Te+=ue)),this._evaluationZoom=Te;const De=se.getExaggeration(Te),Qe=De===se.getExaggeration(Math.max(0,Te-.1));if(Qe&&Math.abs(De-this._exaggeration)<.01)return De;let Ye=Math.min(.1,.00375*(this._updateTimestamp-we));return(Qe||De<.1||Math.abs(ue)<1e-4)&&(Ye=Math.min(.2,4*Ye)),o.am(this._exaggeration,De,Ye)}resetTileLookupCache(N){this._findCoveringTileCache[N]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(N){N.dataType==="source"&&N.coord?this._clearRenderCacheForTile(N.sourceCacheId,N.coord):N.dataType==="style"&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const N in this._style._mergedSourceCaches)this._style._mergedSourceCaches[N].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(N=>N.fb.destroy()),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const N=2*this.proxySourceCache.getSource().tileSize;return[N,N]}set useVertexMorphing(N){this._useVertexMorphing=N}updateTileBinding(N){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const T=this.proxySourceCache,B=this.painter.transform;this._initializing&&(this._initializing=B._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(B.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const W=this.proxyCoords=T.getIds().map(we=>{const Te=T.getTileByID(we).tileID;return Te.projMatrix=B.calculateProjMatrix(Te.toUnwrapped()),Te});(function(we,Te){const De=Te.transform.pointCoordinate(Te.transform.getCameraPoint()),Qe=new o.P(De.x,De.y);we.sort((Ye,tt)=>{if(tt.overscaledZ-Ye.overscaledZ)return tt.overscaledZ-Ye.overscaledZ;const ht=new o.P(Ye.canonical.x+(1<{this.proxyToSource[we.key]={}}),this.terrainTileForTile={};const se=this._style._mergedSourceCaches;for(const we in se){const Te=se[we];if(!Te.used||(Te!==this.sourceCache&&this.resetTileLookupCache(Te.id),this._setupProxiedCoordsForOrtho(Te,N[we],Q),Te.usedForTerrain))continue;const De=N[we];(Te.getSource().reparseOverscaled||Te._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(De)}this.proxiedCoords[T.id]=W.map(we=>new bs(we,we.key,this.orthoMatrix)),this._assignTerrainTiles(W),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Q),this.renderingToTexture=!1;const ue={};this._visibleDemTiles=[];for(const we of this.proxyCoords){const Te=this.terrainTileForTile[we.key];if(!Te)continue;const De=Te.tileID.key;De in ue||(this._visibleDemTiles.push(Te),ue[De]=De)}}_assignTerrainTiles(N){this._initializing||N.forEach(T=>{if(this.terrainTileForTile[T.key])return;const B=this._findTileCoveringTileID(T,this.sourceCache);B&&(this.terrainTileForTile[T.key]=B)})}_prepareDEMTextures(){const N=this.painter.context,T=N.gl;for(const B in this.terrainTileForTile){const W=this.terrainTileForTile[B],Q=W.dem;!Q||W.demTexture&&!W.needsDEMTextureUpload||(N.activeTexture.set(T.TEXTURE1),KC(this.painter,W,Q))}}_prepareDemTileUniforms(N,T,B,W){if(!T||T.demTexture==null)return!1;const Q=N.tileID.canonical,se=Math.pow(2,T.tileID.canonical.z-Q.z),ue=W||"";return B[`u_dem_tl${ue}`]=[Q.x*se%1,Q.y*se%1],B[`u_dem_scale${ue}`]=se,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let N=0;const T=this._visibleDemTiles.reduce((B,W)=>{if(!W.dem)return B;const Q=W.dem.tree.minimums[0];return Q>0&&N++,B+Q},0);return N?T/N:0}_updateEmptyDEMTexture(){const N=this.painter.context,T=N.gl;N.activeTexture.set(T.TEXTURE2);const B=this._getLoadedAreaMinimum(),W=new o.dz({width:1,height:1},new Float32Array([B]));this._emptyDEMTextureDirty=!1;let Q=this._emptyDEMTexture;return Q?Q.update(W,{premultiply:!1}):Q=this._emptyDEMTexture=new o.T(N,W,T.R32F,{premultiply:!1}),Q}setupElevationDraw(N,T,B){const W=this.painter.context,Q=W.gl,se={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};se.u_exaggeration=this.exaggeration();let ue=null,we=null,Te=1;if(B&&B.morphing&&this._useVertexMorphing){const tt=B.morphing.srcDemTile,ht=B.morphing.dstDemTile;Te=B.morphing.phase,tt&&ht&&(this._prepareDemTileUniforms(N,tt,se,"_prev")&&(we=tt),this._prepareDemTileUniforms(N,ht,se)&&(ue=ht))}const De=tt=>tt&&tt.demTexture&&this.painter.linearFloatFilteringSupported()?Q.LINEAR:Q.NEAREST;let Qe=null;var Ye;if(this.enabled?we&&ue?(Qe=ue.demTexture,W.activeTexture.set(Q.TEXTURE4),we.demTexture.bind(De(we),Q.CLAMP_TO_EDGE),se.u_dem_lerp=Te):(ue=this.terrainTileForTile[N.tileID.key],Qe=this._prepareDemTileUniforms(N,ue,se)?ue.demTexture:this.emptyDEMTexture):Qe=this.emptyDEMTexture,W.activeTexture.set(Q.TEXTURE2),Qe&&(se.u_dem_size=(Ye=Qe).size[0]===1?1:Ye.size[0]-2,Qe.bind(De(ue),Q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(B&&B.useDepthForOcclusion,T,se),B&&B.useMeterToDem&&ue){const tt=(1<{if(kt===pn)return;const Un=[o2[pn],"PROJECTION_GLOBE_VIEW"];Xt&&Un.push("CUSTOM_ANTIALIASING");const Xn=Te.isTileAffectedByFog(_n);St=Te.getOrCreateProgram("globeRaster",{defines:Un,overrideFog:Xn}),kt=pn},Ts=Te.colorModeForRenderPass(),ds=new Yr(ct.LEQUAL,Yr.ReadWrite,Te.depthRangeFor3D);fp.update(tt);const Cs=o.dq(Ut),es=[o.aH(Ut.center.lng),o.aL(Ut.center.lat)],is=Te.globeSharedBuffers,_s=[Ut.width*o.o.devicePixelRatio,Ut.height*o.o.devicePixelRatio],Xs=Float32Array.from(Ut.globeMatrix),Ds={useDenormalizedUpVectorScale:!0};{const _n=Te.transform,pn=hw(_n.zoom,De.exaggeration(),De.sourceCache._source.tileSize);kt=-1;const Un=ct.TRIANGLES;for(const Xn of Ye){const nn=Qe.getTile(Xn),Bs=Va.disabled,yn=De.prevTerrainTileForTile[Xn.key],jn=De.terrainTileForTile[Xn.key];i2(yn,jn)&&fp.newMorphing(Xn.key,yn,jn,tt,250),Ue(Te,nn.emissiveTexture),ht.activeTexture.set(ct.TEXTURE0),nn.texture&&nn.texture.bind(ct.LINEAR,ct.CLAMP_TO_EDGE);const In=fp.getMorphValuesForProxy(Xn.key),Sr=In?1:0;In&&Object.assign(Ds,{morphing:{srcDemTile:In.from,dstDemTile:In.to,phase:o.dn(In.phase)}});const xr=o.dr(Xn.canonical),gr=o.ds(xr.getCenter().lat),Kn=o.dt(Xn.canonical,xr,gr,_n.worldSize/_n._pixelsPerMercatorPixel),pa=o.du(o.dv(Xn.canonical)),Ea=Te.emissiveMode==="mrt-fallback"?1:0,na=Ov(_n.expandedFarZProjMatrix,Xs,Cs,pa,o.al(_n.zoom),es,_n.frustumCorners.TL,_n.frustumCorners.TR,_n.frustumCorners.BR,_n.frustumCorners.BL,_n.globeCenterInViewSpace,_n.globeRadius,_s,pn,_n._farZ,Ea,Kn);if(Et(Xn,Sr),St&&(De.setupElevationDraw(nn,St,Ds),Te.uploadCommonUniforms(ht,St,Xn.toUnwrapped()),is)){const[ma,hi,Ei]=is.getGridBuffers(gr,pn!==0);St.draw(Te,Un,ds,Bs,Ts,ba.backCCW,na,"globe_raster",ma,hi,Ei)}}}if(is&&(Te.renderDefaultNorthPole||Te.renderDefaultSouthPole)){const _n=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Xt&&_n.push("CUSTOM_ANTIALIASING"),St=Te.getOrCreateProgram("globeRaster",{defines:_n});for(const pn of Ye){const{x:Un,y:Xn,z:nn}=pn.canonical,Bs=Xn===0,yn=Xn===(1<ma.draw(Te,ct.TRIANGLES,ds,Va.disabled,Ts,ba.disabled,Ov(Ut.expandedFarZProjMatrix,Kn,Kn,pa,0,es,Ut.frustumCorners.TL,Ut.frustumCorners.TR,Ut.frustumCorners.BR,Ut.frustumCorners.BL,Ut.globeCenterInViewSpace,Ut.globeRadius,_s,0,Ut._farZ,Ea),"globe_pole_raster",hi,Sr,xr);De.setupElevationDraw(gr,St,Ds),Te.uploadCommonUniforms(ht,St,pn.toUnwrapped()),Bs&&Te.renderDefaultNorthPole&&na(St,jn),yn&&Te.renderDefaultSouthPole&&(Kn=o.cC(o.bb(),Kn,[1,-1,1]),na(St,In))}}}})(W,Q,se,ue,we);else{const Te=W.context,De=Te.gl;let Qe,Ye;const tt=W.shadowRenderer,ht=Gd(W,W.longestCutoffRange),ct=Ts=>{if(Ye===Ts)return;const ds=[];ds.push(o2[Ts]),ht.shouldRenderCutoff&&ds.push("RENDER_CUTOFF"),tt&&(ds.push("RENDER_SHADOWS"),tt.useNormalOffset&&ds.push("NORMAL_OFFSET")),Qe=W.getOrCreateProgram("terrainRaster",{defines:ds}),Ye=Ts},St=W.colorModeForRenderPass(),kt=new Yr(De.LEQUAL,Yr.ReadWrite,W.depthRangeFor3D);fp.update(we);const Ut=W.transform,Xt=hw(Ut.zoom,Q.exaggeration(),Q.sourceCache._source.tileSize);let Et=[0,0,0];if(tt){const Ts=W.style.directionalLight,ds=W.style.ambientLight;Ts&&ds&&(Et=_m(W.style,Ts,ds))}{Ye=-1;const Ts=De.TRIANGLES,[ds,Cs]=[Q.gridIndexBuffer,Q.gridSegments];for(const es of ue){const is=se.getTile(es),_s=Va.disabled,Xs=Q.prevTerrainTileForTile[es.key],Ds=Q.terrainTileForTile[es.key];i2(Xs,Ds)&&fp.newMorphing(es.key,Xs,Ds,we,250),Ue(W,is.emissiveTexture),Te.activeTexture.set(De.TEXTURE0),is.texture&&is.texture.bind(De.LINEAR,De.CLAMP_TO_EDGE);const _n=fp.getMorphValuesForProxy(es.key),pn=_n?1:0;let Un;_n&&(Un={morphing:{srcDemTile:_n.from,dstDemTile:_n.to,phase:o.dn(_n.phase)}});const Xn=W.emissiveMode==="mrt-fallback"?1:0,nn=uw(es.projMatrix,Me(es.canonical,Ut.renderWorldCopies)?Xt/10:Xt,Et,Xn);if(ct(pn),!Qe)continue;Q.setupElevationDraw(is,Qe,Un);const Bs=es.toUnwrapped();tt&&tt.setupShadows(Bs,Qe),W.uploadCommonUniforms(Te,Qe,Bs,null,ht),Qe.draw(W,Ts,kt,_s,St,ba.backCCW,nn,"terrain_raster",Q.gridBuffer,ds,Cs)}}}}(T,this,this.proxySourceCache,N,this._updateTimestamp),this.renderingToTexture=!0,T.gpuTimingDeferredRenderEnd(),N.splice(0,N.length))}renderBatch(N){if(this._drapedRenderBatches.length===0)return N+1;this.renderingToTexture=!0;const T=this.painter,B=this.painter.context,W=this.proxySourceCache,Q=this.proxiedCoords[W.id],se=this._drapedRenderBatches.shift(),ue=T.style.order,we=[];this._updateFBOs(T.emissiveMode==="mrt-fallback");let Te=0;for(const De of Q){const Qe=W.getTileByID(De.proxyTileKey),Ye=W.proxyCachedFBO[De.key]?W.proxyCachedFBO[De.key][N]:void 0,tt=Ye!==void 0?W.renderCache[Ye]:this.pool[Te++],ht=Ye!==void 0;if(Qe.texture=tt.tex,Qe.emissiveTexture=tt.emissiveTex,ht&&!tt.dirty){we.push(Qe.tileID);continue}B.bindFramebuffer.set(tt.fb.framebuffer);const ct=B.gl;let St;ct.drawBuffers(T.emissiveMode==="mrt-fallback"?[ct.COLOR_ATTACHMENT0,ct.COLOR_ATTACHMENT1]:[ct.COLOR_ATTACHMENT0]),this.renderedToTile=!1,tt.dirty&&(B.clear({color:o.aq.transparent,stencil:0}),tt.dirty=!1);for(let kt=se.start;kt<=se.end;++kt){const Ut=T.style._mergedLayers[ue[kt]];if(Ut.isHidden(T.transform.zoom))continue;const Xt=T.style.getLayerSourceCache(Ut),Et=Xt?this.proxyToSource[De.key][Xt.id]:[De];if(!Et)continue;const Ts=Et;B.viewport.set([0,0,tt.fb.width,tt.fb.height]),St!==(Xt?Xt.id:null)&&(this._setupStencil(tt,Et,Ut,Xt),St=Xt?Xt.id:null),T.renderLayer(T,Xt,Ut,Ts)}if(ct.drawBuffers([ct.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const kt of this._pendingGroundEffectLayers){const Ut=T.style._mergedLayers[ue[kt]];if(Ut.isHidden(T.transform.zoom))continue;const Xt=T.style.getLayerSourceCache(Ut),Et=Xt?this.proxyToSource[De.key][Xt.id]:[De];if(!Et)continue;const Ts=Et;B.viewport.set([0,0,tt.fb.width,tt.fb.height]),St!==(Xt?Xt.id:null)&&(this._setupStencil(tt,Et,Ut,Xt),St=Xt?Xt.id:null),T.renderLayer(T,Xt,Ut,Ts)}this.renderedToTile?(tt.dirty=!0,we.push(Qe.tileID)):ht||--Te,Te===5&&(Te=0,this.renderToBackBuffer(we))}return this.renderToBackBuffer(we),this.renderingToTexture=!1,B.bindFramebuffer.set(null),B.viewport.set([0,0,T.width,T.height]),se.end+1}postRender(){}isLayerOrderingCorrect(N){const T=N.order.length;let B=-1,W=T;for(let Q=0;QB}getMinElevationBelowMSL(){let N=0;return this._visibleDemTiles.filter(T=>T.dem).forEach(T=>{N=Math.min(N,T.dem.tree.minimums[0])}),N===0?N:(N-30)*this._exaggeration}raycast(N,T,B){if(!this._visibleDemTiles)return null;const W=this._visibleDemTiles.filter(Q=>Q.dem).map(Q=>{const se=Q.tileID,ue=1<(Q.t!==null?Q.t:Number.MAX_VALUE)-(se.t!==null?se.t:Number.MAX_VALUE));for(const Q of W){if(Q.t==null)return null;const se=Q.tile.dem.tree.raycast(Q.minx,Q.miny,Q.maxx,Q.maxy,N,T,B);if(se!=null)return se}return null}_createFBO(){const N=this.painter.context,T=N.gl,B=this.drapeBufferSize;N.activeTexture.set(T.TEXTURE0);const W=new o.T(N,{width:B[0],height:B[1],data:null},T.RGBA8);W.bind(T.LINEAR,T.CLAMP_TO_EDGE);const Q=N.createFramebuffer(B[0],B[1],1,null);let se;return Q.colorAttachment0.set(W.texture),this._emissiveTexture&&(se=new o.T(N,{width:B[0],height:B[1],data:null},T.R8),se.bind(T.LINEAR,T.CLAMP_TO_EDGE),Q.createColorAttachment(N,1),Q.colorAttachment1.set(se.texture)),Q.depthAttachment=new sT(N,Q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=N.createRenderbuffer(N.gl.DEPTH_STENCIL,B[0],B[1]),this._stencilRef=0,Q.depthAttachment.set(this._sharedDepthStencil),N.clear({stencil:0})):Q.depthAttachment.set(this._sharedDepthStencil),N.extTextureFilterAnisotropic&&T.texParameterf(T.TEXTURE_2D,N.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,N.extTextureFilterAnisotropicMax),{fb:Q,tex:W,emissiveTex:se,dirty:!1}}_updateFBOs(N){if(this._emissiveTexture!==N){for(const T of this.pool)this._updateFBO(T,N);for(const T of this.proxySourceCache.renderCache)this._updateFBO(T,N);this._emissiveTexture=N}}_updateFBO(N,T){const B=N.fb,W=this.painter.context,Q=W.gl,se=this.drapeBufferSize;if(T){const ue=new o.T(W,{width:se[0],height:se[1],data:null},Q.R8);ue.bind(Q.LINEAR,Q.CLAMP_TO_EDGE),N.emissiveTex=ue,B.createColorAttachment(W,1),B.colorAttachment1.set(ue.texture)}else N.emissiveTex=void 0,B.removeColorAttachment(W,1);N.dirty=!0}_initFBOPool(){for(;this.pool.length{const T=this._style._mergedLayers[N],B=T.isHidden(this.painter.transform.zoom);return T.type==="hillshade"||T.type==="custom"?!B&&T.shouldRedrape():!B&&T.hasTransition()})}_clearLineLayersFromRenderCache(){let N=!1;for(const B of this._style.getSources())if(B instanceof wu){N=!0;break}if(!N)return;const T={};for(let B=0;Bwe>ue.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=B}_setupRenderCache(N){const T=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,T.renderCache.length>T.renderCachePool.length){const se=Object.values(T.proxyCachedFBO);T.proxyCachedFBO={};for(let ue=0;ue=0;se--){const ue=B[se];if(T.getTileByID(ue.key),T.proxyCachedFBO[ue.key]!==void 0){const we=N[ue.key],Te=this.proxyToSource[ue.key];let De=0;for(const Qe in Te){const Ye=Te[Qe],tt=we[Qe];if(!tt||tt.length!==Ye.length||Ye.some((ht,ct)=>ht!==tt[ct]||W[Qe]&&W[Qe].hasOwnProperty(ht.key))){De=-1;break}++De}for(const Qe in T.proxyCachedFBO[ue.key])T.renderCache[T.proxyCachedFBO[ue.key][Qe]].dirty=De<0||De!==Object.values(we).length}}const Q=[...this._drapedRenderBatches];Q.sort((se,ue)=>ue.end-ue.start-(se.end-se.start));for(const se of Q)for(const ue of B){if(T.proxyCachedFBO[ue.key])continue;let we=T.renderCachePool.pop();we===void 0&&T.renderCache.length<50&&(we=T.renderCache.length,T.renderCache.push(this._createFBO())),we!==void 0&&(T.proxyCachedFBO[ue.key]={},T.proxyCachedFBO[ue.key][se.start]=we,T.renderCache[we].dirty=!0)}this._tilesDirty={}}_setupStencil(N,T,B,W){if(!W||!this._sourceTilesOverlap[W.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Q=this.painter.context,se=Q.gl;if(T.length<=1)return void(this._overlapStencilType=!1);let ue;if(B.isTileClipped())ue=T.length,this._overlapStencilMode.test={func:se.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(T[0].overscaledZ>T[T.length-1].overscaledZ))return void(this._overlapStencilType=!1);ue=1,this._overlapStencilMode.test={func:se.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+ue>255&&(Q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=ue,this._overlapStencilMode.ref=this._stencilRef,B.isTileClipped()&&this._renderTileClippingMasks(T,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(N){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[N.key]),this._overlapStencilMode):Va.disabled}_renderTileClippingMasks(N,T){const B=this.painter,W=this.painter.context,Q=W.gl;B._tileClippingMaskIDs={},W.setColorMode($a.disabled),W.setDepthMode(Yr.disabled);const se=B.getOrCreateProgram("clippingMask");for(const ue of N){const we=B._tileClippingMaskIDs[ue.key]=--T;se.draw(B,Q.TRIANGLES,Yr.disabled,new Va({func:Q.ALWAYS,mask:0},we,255,Q.KEEP,Q.KEEP,Q.REPLACE),$a.disabled,ba.disabled,xt(ue.projMatrix),"$clipping",B.tileExtentBuffer,B.quadTriangleIndexBuffer,B.tileExtentSegments)}}pointCoordinate(N){const T=this.painter.transform;if(N.x<0||N.x>T.width||N.y<0||N.y>T.height)return null;const B=[N.x,N.y,1,1];o.aE(B,B,T.pixelMatrixInverse),o.cu(B,B,1/B[3]),B[0]/=T.worldSize,B[1]/=T.worldSize;const W=T._camera.position,Q=o.bU(1,T.center.lat),se=[W[0],W[1],W[2]/Q,0],ue=o.cV([],B.slice(0,3),se);o.ay(ue,ue);const we=this.raycast(se,ue,this._exaggeration);return we!==null&&we?(o.bg(se,se,ue,we),se[3]=se[2],se[2]*=Q,se):null}_setupProxiedCoordsForOrtho(N,T,B){if(N.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(N,T,B);this._findCoveringTileCache[N.id]=this._findCoveringTileCache[N.id]||{};const W=this.proxiedCoords[N.id]=[],Q=this.proxyCoords;for(let we=0;weDe.overscaledZ-Te.overscaledZ)}_setupProxiedCoordsForImageSource(N,T,B){if(!N.getSource().loaded())return;const W=this.proxiedCoords[N.id]=[],Q=this.proxyCoords,se=N.getSource(),ue=se.tileID;if(!ue)return;const we=new o.P(ue.x,ue.y)._div(1<(Qe.min.x=Math.min(Qe.min.x,Ye.x-we.x),Qe.min.y=Math.min(Qe.min.y,Ye.y-we.y),Qe.max.x=Math.max(Qe.max.x,Ye.x-we.x),Qe.max.y=Math.max(Qe.max.y,Ye.y-we.y),Qe),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),De=(Qe,Ye)=>{const tt=Qe.wrap+Qe.canonical.x/(1<St+Te.max.x||ht+ctkt+Te.max.y};for(let Qe=0;Qese.key===T.tileID.key);if(Q)return Q}if(T.tileID.key!==N.key){const Q=N.canonical.z-T.tileID.canonical.z;let se,ue,we;W=o.bb();const Te=T.tileID.wrap-N.wrap<0?(se=o.an>>Q,ue=se*((T.tileID.canonical.x<=Qe){const Ye=N.canonical.z-Qe;T.getSource().reparseOverscaled?(ue=Math.max(N.canonical.z+2,T.transform.tileZoom),se=new o.aR(ue,N.wrap,Qe,N.canonical.x>>Ye,N.canonical.y>>Ye)):Ye!==0&&(ue=Qe,se=new o.aR(ue,N.wrap,Qe,N.canonical.x>>Ye,N.canonical.y>>Ye))}se.key!==N.key&&(Te.push(se.key),B=T.getTile(se))}const De=Qe=>{Te.forEach(Ye=>{W[Ye]=Qe}),Te.length=0};for(ue-=1;ue>=we&&(!B||!B.hasData());ue--){B&&De(B.tileID.key);const Qe=se.calculateScaledKey(ue);if(B=T.getTileByID(Qe),B&&B.hasData())break;const Ye=W[Qe];if(Ye===null)break;Ye===void 0?Te.push(Qe):B=T.getTileByID(Ye)}return De(B?B.tileID.key:null),B&&B.hasData()?B:null}findDEMTileFor(N){return this.enabled?this._findTileCoveringTileID(N,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(N,T){let B=this._tilesDirty[N];B||(B=this._tilesDirty[N]={}),B[T.key]=!0}}function zs(R,N,T){const B=function(ue,we,Te){const De=o.bi(we,ue),Qe=o.bi(Te,[.2126,.7152,.0722]),Ye=(ht,ct,St)=>(1-St)*ht+St*ct,tt=Ye(1-.3*Math.min(Qe,1),1,Math.min(De+1,1));return Ye(.92,1,Math.asin(o.aC(we[2],-1,1))/Math.PI+.5)*tt}(R,[0,0,1],N),W=[0,0,0];o.bJ(W,T.slice(0,3),B);const Q=[0,0,0];o.bJ(Q,N.slice(0,3),R[2]);const se=[0,0,0];return o.cT(se,W,Q),o.cW(se)}const en=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],Dn=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Jn{static cacheKey(N,T,B,W){const Q=[T];W&&Q.push(W.cacheKey);for(const se of B)(typeof se=="string"&&se.includes(" ")||N.usedDefines.has(se))&&Q.push(se);return Q.join("/")}constructor(N,T,B,W,Q,se){const ue=N.gl;this.program=ue.createProgram(),this.configuration=W,this.name=T,this.fixedDefines=[...se];const we=`#version 300 es ${(W?W.defines():[]).concat(se.map(ct=>`#define ${ct}`)).join(` `)}`,Te=[we,L1];for(const ct of B.fragmentIncludes)Te.push(ax[ct]);Te.push(B.fragmentSource);const De=Te.join(` `),Qe=[we,sk];for(const ct of B.vertexIncludes)Qe.push(ax[ct]);this.forceManualRenderingForInstanceIDShaders=N.forceManualRenderingForInstanceIDShaders&&B.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Qe.push("uniform int u_instanceID;"),Qe.push(B.vertexSource);let Ye=Qe.join(` `);this.forceManualRenderingForInstanceIDShaders&&(Ye=Ye.replaceAll("gl_InstanceID","u_instanceID"));const tt=ue.createShader(ue.FRAGMENT_SHADER);if(ue.isContextLost())return void(this.failedToCreate=!0);ue.shaderSource(tt,De),ue.compileShader(tt),ue.attachShader(this.program,tt);const ht=ue.createShader(ue.VERTEX_SHADER);ue.isContextLost()?this.failedToCreate=!0:(ue.shaderSource(ht,Ye),ue.compileShader(ht),ue.attachShader(this.program,ht),this.attributes={},ue.linkProgram(this.program),ue.deleteShader(ht),ue.deleteShader(tt),this.fixedUniforms=Q(N),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=W?W.getUniforms(N):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(ct=>({u_instanceID:new o.bX(ct)}))(N)),(se.includes("TERRAIN")||se.includes("ELEVATED")||T.includes("symbol")||T.includes("circle"))&&(this.terrainUniforms=(ct=>({u_dem:new o.bX(ct),u_dem_prev:new o.bX(ct),u_dem_tl:new o.b_(ct),u_dem_scale:new o.bZ(ct),u_dem_tl_prev:new o.b_(ct),u_dem_scale_prev:new o.bZ(ct),u_dem_size:new o.bZ(ct),u_dem_lerp:new o.bZ(ct),u_exaggeration:new o.bZ(ct),u_depth:new o.bX(ct),u_depth_size_inv:new o.b_(ct),u_depth_range_unpack:new o.b_(ct),u_occluder_half_size:new o.bZ(ct),u_occlusion_depth_offset:new o.bZ(ct),u_meter_to_dem:new o.bZ(ct),u_label_plane_matrix_inv:new o.b$(ct)}))(N)),se.includes("GLOBE")&&(this.globeUniforms=(ct=>({u_tile_tl_up:new o.bY(ct),u_tile_tr_up:new o.bY(ct),u_tile_br_up:new o.bY(ct),u_tile_bl_up:new o.bY(ct),u_tile_up_scale:new o.bZ(ct)}))(N)),se.includes("FOG")&&(this.fogUniforms=(ct=>({u_fog_matrix:new o.b$(ct),u_fog_range:new o.b_(ct),u_fog_color:new o.cO(ct),u_fog_horizon_blend:new o.bZ(ct),u_fog_vertical_limit:new o.b_(ct),u_fog_temporal_offset:new o.bZ(ct),u_frustum_tl:new o.bY(ct),u_frustum_tr:new o.bY(ct),u_frustum_br:new o.bY(ct),u_frustum_bl:new o.bY(ct),u_globe_pos:new o.bY(ct),u_globe_radius:new o.bZ(ct),u_globe_transition:new o.bZ(ct),u_is_globe:new o.bX(ct),u_viewport:new o.b_(ct)}))(N)),se.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(ct=>({u_cutoff_params:new o.cO(ct)}))(N)),se.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(ct=>({u_lighting_ambient_color:new o.bY(ct),u_lighting_directional_dir:new o.bY(ct),u_lighting_directional_color:new o.bY(ct),u_ground_radiance:new o.bY(ct)}))(N)),se.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(ct=>({u_light_matrix_0:new o.b$(ct),u_light_matrix_1:new o.b$(ct),u_fade_range:new o.b_(ct),u_shadow_normal_offset:new o.bY(ct),u_shadow_intensity:new o.bZ(ct),u_shadow_texel_size:new o.bZ(ct),u_shadow_map_resolution:new o.bZ(ct),u_shadow_direction:new o.bY(ct),u_shadow_bias:new o.bY(ct),u_shadowmap_0:new o.bX(ct),u_shadowmap_1:new o.bX(ct)}))(N)))}getAttributeLocation(N,T){let B=this.attributes[T];return B===void 0&&(B=this.attributes[T]=N.getAttribLocation(this.program,T)),B}setTerrainUniformValues(N,T){if(!this.terrainUniforms)return;const B=this.terrainUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)B[W]&&B[W].set(this.program,W,T[W])}}setGlobeUniformValues(N,T){if(!this.globeUniforms)return;const B=this.globeUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)B[W]&&B[W].set(this.program,W,T[W])}}setFogUniformValues(N,T){if(!this.fogUniforms)return;const B=this.fogUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)B[W].set(this.program,W,T[W])}}setCutoffUniformValues(N,T){if(!this.cutoffUniforms)return;const B=this.cutoffUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)B[W].set(this.program,W,T[W])}}setLightsUniformValues(N,T){if(!this.lightsUniforms)return;const B=this.lightsUniforms;if(!this.failedToCreate){N.program.set(this.program);for(const W in T)B[W].set(this.program,W,T[W])}}setShadowUniformValues(N,T){if(this.failedToCreate||!this.shadowUniforms)return;const B=this.shadowUniforms;N.program.set(this.program);for(const W in T)B[W].set(this.program,W,T[W])}_drawDebugWireframe(N,T,B,W,Q,se,ue,we,Te,De){const Qe=N.options.wireframe;if(Qe.terrain===!1&&Qe.layers2D===!1&&Qe.layers3D===!1)return;const Ye=N.context;if(!(!(!Qe.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Qe.layers2D||N._terrain&&N._terrain.renderingToTexture||!en.includes(this.name))||!(!Qe.layers3D||!Dn.includes(this.name))))return;const tt=Ye.gl,ht=N.wireframeDebugCache.getLinesFromTrianglesBuffer(N.frameCounter,Q,Ye);if(!ht)return;const ct=[...this.fixedDefines,"DEBUG_WIREFRAME"],St=N.getOrCreateProgram(this.name,{config:this.configuration,defines:ct});Ye.program.set(St.program);const kt=(Et,Ts,ds)=>{if(Ts[Et]&&ds[Et])for(const Cs in Ts[Et])ds[Et][Cs]&&ds[Et][Cs].set(ds.program,Cs,Ts[Et][Cs].current)};Te&&Te.setUniforms(St.program,Ye,St.binderUniforms,ue,{zoom:we}),kt("fixedUniforms",this,St),kt("terrainUniforms",this,St),kt("globeUniforms",this,St),kt("fogUniforms",this,St),kt("lightsUniforms",this,St),kt("shadowUniforms",this,St),ht.bind(),Ye.setColorMode(new $a([tt.ONE,tt.ONE_MINUS_SRC_ALPHA,tt.ZERO,tt.ONE],o.aq.transparent,[!0,!0,!0,!1])),Ye.setDepthMode(new Yr(T.func===tt.LESS?tt.LEQUAL:T.func,Yr.ReadOnly,T.range)),Ye.setStencilMode(Va.disabled);const Ut=3*se.primitiveLength*2,Xt=3*se.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const Et=De||1;for(let Ts=0;Ts1?tt.drawElementsInstanced(tt.LINES,Ut,tt.UNSIGNED_SHORT,Xt,De):tt.drawElements(tt.LINES,Ut,tt.UNSIGNED_SHORT,Xt);Q.bind(),Ye.program.set(this.program),Ye.setDepthMode(T),Ye.setStencilMode(B),Ye.setColorMode(W)}checkUniforms(N,T,B){if(this.fixedDefines.includes(T)){for(const W of Object.keys(B))if(!B[W].initialized)throw new Error(`Program '${this.name}', from draw '${N}': uniform ${W} not set but required by ${T} being defined`)}}draw(N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St){const kt=N.context,Ut=kt.gl;if(this.failedToCreate)return;kt.program.set(this.program),kt.setDepthMode(B),kt.setStencilMode(W),kt.setColorMode(Q),kt.setCullFace(se);for(const[es,is]of this.fixedUniformsEntries)is.set(this.program,es,ue[es]);ht&&ht.setUniforms(this.program,kt,this.binderUniforms,Ye,{zoom:tt});const Xt={[Ut.POINTS]:1,[Ut.LINES]:2,[Ut.TRIANGLES]:3,[Ut.LINE_STRIP]:1}[T];this.checkUniforms(we,"RENDER_SHADOWS",this.shadowUniforms);const Et=ct||[],Ts=ht?ht.getPaintVertexBuffers():[],ds=T===Ut.TRIANGLES&&De,Cs=St&&St>0?1:void 0;for(const es of Qe.get()){const is=es.vaos||(es.vaos={});if((is[we]||(is[we]=new XS)).bind(kt,this,Te,Ts,De,es.vertexOffset,Et,Cs),this.forceManualRenderingForInstanceIDShaders){const _s=St||1;for(let Xs=0;Xs<_s;++Xs)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",Xs),De?Ut.drawElements(T,es.primitiveLength*Xt,Ut.UNSIGNED_SHORT,es.primitiveOffset*Xt*2):Ut.drawArrays(T,es.vertexOffset,es.vertexLength)}else St&&St>1?Ut.drawElementsInstanced(T,es.primitiveLength*Xt,Ut.UNSIGNED_SHORT,es.primitiveOffset*Xt*2,St):De?Ut.drawElements(T,es.primitiveLength*Xt,Ut.UNSIGNED_SHORT,es.primitiveOffset*Xt*2):Ut.drawArrays(T,es.vertexOffset,es.vertexLength);ds&&this._drawDebugWireframe(N,B,W,Q,De,es,Ye,tt,ht,St)}}}function tn(R,N,T=0){const B=Math.pow(2,N.tileID.overscaledZ),W=N.tileSize*Math.pow(2,R.transform.tileZoom)/B,Q=W*(N.tileID.canonical.x+N.tileID.wrap*B),se=W*N.tileID.canonical.y;return{u_image:0,u_texsize:N.imageAtlasTexture?N.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(N,1,R.transform.tileZoom),u_pixel_coord_upper:[Q>>16,se>>16],u_pixel_coord_lower:[65535&Q,65535&se],u_pattern_transition:T}}const Hn={terrain:0,flat:1},ir=o.bb(),Dr=(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut=[0,0,1])=>{const Xt=N.style.light,Et=Xt.properties.get("position"),Ts=[Et.x,Et.y,Et.z],ds=o.dE();Xt.properties.get("anchor")==="viewport"&&(o.dF(ds,-N.transform.angle),o.dG(Ts,Ts,ds));const Cs=Xt.properties.get("color").toPremultipliedRenderColor(null),es=N.transform,is={u_matrix:R,u_lightpos:Ts,u_lightintensity:Xt.properties.get("intensity"),u_lightcolor:[Cs.r,Cs.g,Cs.b],u_vertical_gradient:+T,u_opacity:B,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:ir,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:Hn[Te],u_base_type:Hn[De],u_ao:W,u_edge_radius:Q,u_width_scale:se,u_flood_light_color:ht,u_vertical_scale:ct,u_flood_light_intensity:St,u_ground_shadow_factor:kt,u_front_cutoff_params:Ut};return es.projection.name==="globe"&&(is.u_tile_id=[ue.canonical.x,ue.canonical.y,1<({u_matrix:R,u_edge_radius:N,u_width_scale:T,u_vertical_scale:B,u_height_type:Hn[W],u_base_type:Hn[Q]}),Gn=(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt)=>{const Ut=Dr(R,N,T,B,W,Q,se,ue,Te,De,Qe,Ye,tt,ht,ct,St,1,[0,0,0]),Xt={u_height_factor:-Math.pow(2,ue.overscaledZ)/we.tileSize/8};return Object.assign(Ut,tn(N,we,kt),Xt)},Gr=(R,N,T)=>({u_matrix:R,u_emissive_strength:N,u_ground_shadow_factor:T}),Ca=(R,N,T,B,W,Q=0)=>Object.assign(Gr(R,N,W),tn(T,B,Q)),_a=(R,N,T,B)=>({u_matrix:R,u_world:T,u_emissive_strength:N,u_ground_shadow_factor:B}),ro=(R,N,T,B,W,Q,se=0)=>Object.assign(Ca(R,N,T,B,Q,se),{u_world:W}),Oi=(R,N)=>({u_matrix:R,u_depth_bias:N}),Al=(R,N)=>({u_matrix:R,u_ground_shadow_factor:N}),Yi=(R,N,T,B,W)=>({u_matrix:R,u_camera_pos:[N[0],N[1],N[2]],u_depth_bias:T,u_height_scale:B,u_reset_depth:W}),bc=(R,N,T)=>({u_image:R,u_opacity:N,u_blend_mode:T}),Eu=(R,N,T,B,W,Q,se,ue,we,Te=[0,0,1])=>({u_matrix:R,u_normal_matrix:N,u_opacity:T,u_faux_facade_ao_intensity:B,u_camera_pos:W,u_tile_to_meter:Q,u_facade_emissive_chance:se,u_flood_light_color:ue,u_flood_light_intensity:we,u_front_cutoff_params:Te}),El=R=>({u_matrix:R}),eo=R=>({u_matrix:R}),fi=(R,N,T,B,W,Q,se,ue)=>{const we=o.an/Q.tileSize;return{u_matrix:R,u_inv_rot_matrix:N,u_camera_to_center_distance:T.getCameraToCenterDistance(ue),u_extrude_scale:[T.pixelsToGLUnits[0]/we,T.pixelsToGLUnits[1]/we],u_zoom_transition:B,u_tile_id:se,u_merc_center:W}},Il=(R,N,T,B)=>({u_matrix:R,u_inv_matrix:N,u_camera_to_center_distance:T.getCameraToCenterDistance(B),u_viewport_size:[T.width,T.height]}),To=(R,N,T=1)=>({u_matrix:R,u_color:N,u_overlay:0,u_overlay_scale:T}),vl=o.bb(),ju=(R,N,T,B,W,Q,se)=>{const ue=R.transform,we=ue.projection.name==="globe",Te=we?o.dH(ue.zoom,N.canonical)*ue._pixelsPerMercatorPixel:o.aA(T,1,Q),De={u_matrix:N.projMatrix,u_extrude_scale:Te,u_intensity:se,u_inv_rot_matrix:vl,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(we){De.u_inv_rot_matrix=B,De.u_merc_center=W,De.u_tile_id=[N.canonical.x,N.canonical.y,1<({u_matrix:N,u_normalize_matrix:T,u_globe_matrix:B,u_merc_matrix:W,u_grid_matrix:Q,u_tl_parent:se,u_scale_parent:De,u_fade_t:Qe.mix,u_opacity:Qe.opacity*Ye.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Ye.paint.get("raster-brightness-min"),u_brightness_high:Ye.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(Ye.paint.get("raster-saturation")),u_contrast_factor:o.dI(Ye.paint.get("raster-contrast")),u_spin_weights:lx(Ye.paint.get("raster-hue-rotate")),u_perspective_transform:tt,u_raster_elevation:ht,u_zoom_transition:ue,u_merc_center:we,u_cutoff_params:Te,u_colorization_mix:Vm(o.dK,St,Ut),u_colorization_offset:Nu(o.dK,kt,Ut),u_color_ramp:ct,u_texture_offset:[Et/(Xt+2*Et),Xt/(Xt+2*Et)],u_texture_res:[Xt+2*Et,Xt+2*Et],u_emissive_strength:Ts,u_zbias_factor:Zu(R)});function lx(R){R*=Math.PI/180;const N=Math.sin(R),T=Math.cos(R);return[(2*T+1)/3,(-Math.sqrt(3)*N-T+1)/3,(Math.sqrt(3)*N-T+1)/3]}const du=.05,ad=(R,N,T,B,W,Q,se,ue,we,Te,De,Qe)=>({u_matrix:R,u_normalize_matrix:N,u_globe_matrix:T,u_merc_matrix:B,u_grid_matrix:W,u_tl_parent:Q,u_scale_parent:Te,u_fade_t:De.mix,u_opacity:De.opacity,u_image0:0,u_image1:1,u_raster_elevation:Qe,u_zoom_transition:se,u_merc_center:ue,u_cutoff_params:we}),Kd=(R,N,T,B,W,Q,se,ue,we,Te)=>({u_particle_texture:R,u_particle_texture_side_len:N,u_tile_offset:T,u_velocity:B,u_color_ramp:Q,u_velocity_res:W,u_max_speed:se,u_uv_offset:ue,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Te,u_particle_pos_scale:1.1,u_particle_pos_offset:[du,du]}),gh=(R,N,T,B,W,Q,se,ue,we,Te)=>({u_particle_texture:R,u_particle_texture_side_len:N,u_velocity:T,u_velocity_res:B,u_max_speed:W,u_speed_factor:Q,u_reset_rate:se,u_rand_seed:Math.random(),u_uv_offset:ue,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Te,u_particle_pos_scale:1.1,u_particle_pos_offset:[du,du]}),bd=o.bb(),Mh=(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut,Xt,Et,Ts,ds,Cs)=>{const es=W.transform,is={u_is_size_zoom_constant:+(R==="constant"||R==="source"),u_is_size_feature_constant:+(R==="constant"||R==="camera"),u_size_t:N?N.uSizeT:0,u_size:N?N.uSize:0,u_camera_to_center_distance:es.getCameraToCenterDistance(Ut),u_rotate_symbol:+T,u_aspect_ratio:es.width/es.height,u_fade_change:W.options.fadeDuration?W.symbolFadeChange:1,u_matrix:Q,u_label_plane_matrix:se,u_coord_matrix:ue,u_is_text:+Te,u_elevation_from_sea:we?1:0,u_pitch_with_map:+B,u_texsize:De,u_texsize_icon:Qe,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:bd,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:bd,u_up_vector:[0,-1,0],u_color_adj_mat:Ts,u_icon_transition:ds||0,u_gamma_scale:B?W.transform.getCameraToCenterDistance(Ut)*Math.cos(W.terrain?0:W.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Cs||1,u_ground_shadow_factor:Xt,u_inv_matrix:o.b7(o.bb(),se),u_normal_scale:Et,u_lutTexture:10,u_zoom:es.zoom-Math.floor(es.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 Ut.name==="globe"&&(is.u_tile_id=[tt.canonical.x,tt.canonical.y,1<({u_matrix:R,u_emissive_strength:N,u_opacity:T,u_color:B}),Dd=(R,N,T,B,W,Q,se,ue,we)=>Object.assign(function(Te,De,Qe,Ye,tt,ht){const{width:ct,height:St}=Ye.imageManager.getPixelSize(De),kt=Math.pow(2,ht.tileID.overscaledZ),Ut=ht.tileSize*Math.pow(2,Ye.transform.tileZoom)/kt,Xt=Ut*(ht.tileID.canonical.x+ht.tileID.wrap*kt),Et=Ut*ht.tileID.canonical.y;return{u_image:0,u_pattern_tl:Qe.tl,u_pattern_br:Qe.br,u_texsize:[ct,St],u_pattern_size:Qe.displaySize,u_pattern_units_to_pixels:tt?[Ye.transform.width,-1*Ye.transform.height]:[1/o.aA(ht,1,Ye.transform.tileZoom),1/o.aA(ht,1,Ye.transform.tileZoom)],u_pixel_coord_upper:[Xt>>16,Et>>16],u_pixel_coord_lower:[65535&Xt,65535&Et]}}(0,Q,se,B,ue,we),{u_matrix:R,u_emissive_strength:N,u_opacity:T}),tm=new Float32Array(o.b9([])),Pc=(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt=[0,0,0],ht,ct,St)=>{const kt=W.style.light,Ut=kt.properties.get("position"),Xt=[-Ut.x,-Ut.y,Ut.z],Et=o.dE();kt.properties.get("anchor")==="viewport"&&(o.dF(Et,-W.transform.angle),o.dG(Xt,Xt,Et));const Ts=De.alphaMode==="MASK",ds=kt.properties.get("color").toNonPremultipliedRenderColor(null),Cs=Ye.paint.get("model-ambient-occlusion-intensity"),es=Ye.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return es.a=Ye.paint.get("model-color-mix-intensity").constantOr(0),St&&(es.r=St[0],es.g=St[1],es.b=St[2],es.a=St[3]),ct&&(es.r=ct.color.r,es.g=ct.color.g,es.b=ct.color.b,es.a=ct.colorMix,Qe=ct.emissionStrength,Q*=ct.opacity),{u_matrix:R,u_lighting_matrix:N,u_normal_matrix:T,u_node_matrix:B||tm,u_lightpos:Xt,u_lightintensity:kt.properties.get("intensity"),u_lightcolor:[ds.r,ds.g,ds.b],u_camera_pos:tt,u_opacity:Q,u_baseTextureIsAlpha:0,u_alphaMask:+Ts,u_alphaCutoff:De.alphaCutoff,u_baseColorFactor:se.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:ue.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:we,u_roughnessFactor:Te,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:es.toArray01(),u_aoIntensity:Cs,u_emissive_strength:Qe,u_occlusionTextureTransform:ht||[0,0,0,0]}},Ph=(R,N=tm,T=tm)=>({u_matrix:R,u_instance:N,u_node_matrix:T}),zp={fillExtrusion:R=>({u_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_vertical_gradient:new o.bZ(R),u_opacity:new o.bZ(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_ao:new o.b_(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_up_dir:new o.bY(R),u_height_lift:new o.bZ(R),u_flood_light_color:new o.bY(R),u_vertical_scale:new o.bZ(R),u_flood_light_intensity:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_front_cutoff_params:new o.bY(R)}),fillExtrusionDepth:R=>({u_matrix:new o.b$(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_vertical_scale:new o.bZ(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R)}),fillExtrusionPattern:R=>({u_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_vertical_gradient:new o.bZ(R),u_height_factor:new o.bZ(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_ao:new o.b_(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_up_dir:new o.bY(R),u_height_lift:new o.bZ(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_opacity:new o.bZ(R),u_pattern_transition:new o.bZ(R)}),fillExtrusionGroundEffect:R=>({u_matrix:new o.b$(R),u_opacity:new o.bZ(R),u_ao_pass:new o.bZ(R),u_meter_to_tile:new o.bZ(R),u_ao:new o.b_(R),u_flood_light_intensity:new o.bZ(R),u_flood_light_color:new o.bY(R),u_attenuation:new o.bZ(R),u_edge_radius:new o.bZ(R),u_fb:new o.bX(R),u_fb_size:new o.bZ(R),u_dynamic_offset:new o.bZ(R)}),fill:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_ground_shadow_factor:new o.bY(R)}),fillPattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_pattern_transition:new o.bZ(R)}),fillOutline:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_world:new o.b_(R),u_ground_shadow_factor:new o.bY(R)}),fillOutlinePattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_world:new o.b_(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_pattern_transition:new o.bZ(R)}),lineBlendComposite:R=>({u_image:new o.bX(R),u_opacity:new o.bZ(R),u_blend_mode:new o.bX(R)}),building:R=>({u_matrix:new o.b$(R),u_normal_matrix:new o.b$(R),u_opacity:new o.bZ(R),u_faux_facade_ao_intensity:new o.bZ(R),u_camera_pos:new o.bY(R),u_tile_to_meter:new o.bZ(R),u_facade_emissive_chance:new o.bZ(R),u_flood_light_color:new o.bY(R),u_flood_light_intensity:new o.bZ(R),u_front_cutoff_params:new o.bY(R)}),buildingBloom:R=>({u_matrix:new o.b$(R)}),buildingDepth:R=>({u_matrix:new o.b$(R)}),elevatedStructuresDepth:R=>({u_matrix:new o.b$(R),u_depth_bias:new o.bZ(R)}),elevatedStructures:R=>({u_matrix:new o.b$(R),u_ground_shadow_factor:new o.bY(R)}),elevatedStructuresDepthReconstruct:R=>({u_matrix:new o.b$(R),u_camera_pos:new o.bY(R),u_depth_bias:new o.bZ(R),u_height_scale:new o.bZ(R),u_reset_depth:new o.bZ(R)}),circle:o.dO,collisionBox:R=>({u_matrix:new o.b$(R),u_inv_rot_matrix:new o.b$(R),u_camera_to_center_distance:new o.bZ(R),u_extrude_scale:new o.b_(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_tile_id:new o.bY(R)}),collisionCircle:R=>({u_matrix:new o.b$(R),u_inv_matrix:new o.b$(R),u_camera_to_center_distance:new o.bZ(R),u_viewport_size:new o.b_(R)}),debug:R=>({u_color:new o.dl(R),u_matrix:new o.b$(R),u_overlay:new o.bX(R),u_overlay_scale:new o.bZ(R)}),clippingMask:R=>({u_matrix:new o.b$(R)}),heatmap:R=>({u_extrude_scale:new o.bZ(R),u_intensity:new o.bZ(R),u_matrix:new o.b$(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_up_dir:new o.bY(R)}),heatmapTexture:R=>({u_image:new o.bX(R),u_color_ramp:new o.bX(R),u_opacity:new o.bZ(R)}),hillshade:R=>({u_matrix:new o.b$(R),u_image:new o.bX(R),u_latrange:new o.b_(R),u_light:new o.b_(R),u_shadow:new o.dl(R),u_highlight:new o.dl(R),u_emissive_strength:new o.bZ(R),u_accent:new o.dl(R)}),hillshadePrepare:R=>({u_matrix:new o.b$(R),u_image:new o.bX(R),u_dimension:new o.b_(R),u_zoom:new o.bZ(R)}),line:o.dN,linePattern:o.dM,raster:R=>({u_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_grid_matrix:new o.dm(R),u_tl_parent:new o.b_(R),u_scale_parent:new o.bZ(R),u_fade_t:new o.bZ(R),u_opacity:new o.bZ(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_brightness_low:new o.bZ(R),u_brightness_high:new o.bZ(R),u_saturation_factor:new o.bZ(R),u_contrast_factor:new o.bZ(R),u_spin_weights:new o.bY(R),u_perspective_transform:new o.b_(R),u_raster_elevation:new o.bZ(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_cutoff_params:new o.cO(R),u_colorization_mix:new o.cO(R),u_colorization_offset:new o.bZ(R),u_color_ramp:new o.bX(R),u_texture_offset:new o.b_(R),u_texture_res:new o.b_(R),u_emissive_strength:new o.bZ(R),u_zbias_factor:new o.bZ(R)}),rasterParticle:R=>({u_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_grid_matrix:new o.dm(R),u_tl_parent:new o.b_(R),u_scale_parent:new o.bZ(R),u_fade_t:new o.bZ(R),u_opacity:new o.bZ(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_raster_elevation:new o.bZ(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_cutoff_params:new o.cO(R)}),rasterParticleTexture:R=>({u_texture:new o.bX(R),u_opacity:new o.bZ(R)}),rasterParticleDraw:R=>({u_particle_texture:new o.bX(R),u_particle_texture_side_len:new o.bZ(R),u_tile_offset:new o.b_(R),u_velocity:new o.bX(R),u_color_ramp:new o.bX(R),u_velocity_res:new o.b_(R),u_max_speed:new o.bZ(R),u_uv_offset:new o.b_(R),u_data_scale:new o.b_(R),u_data_offset:new o.bZ(R),u_particle_pos_scale:new o.bZ(R),u_particle_pos_offset:new o.b_(R)}),rasterParticleUpdate:R=>({u_particle_texture:new o.bX(R),u_particle_texture_side_len:new o.bZ(R),u_velocity:new o.bX(R),u_velocity_res:new o.b_(R),u_max_speed:new o.bZ(R),u_speed_factor:new o.bZ(R),u_reset_rate:new o.bZ(R),u_rand_seed:new o.bZ(R),u_uv_offset:new o.b_(R),u_data_scale:new o.b_(R),u_data_offset:new o.bZ(R),u_particle_pos_scale:new o.bZ(R),u_particle_pos_offset:new o.b_(R)}),symbol:R=>({u_is_size_zoom_constant:new o.bX(R),u_is_size_feature_constant:new o.bX(R),u_size_t:new o.bZ(R),u_size:new o.bZ(R),u_camera_to_center_distance:new o.bZ(R),u_rotate_symbol:new o.bX(R),u_aspect_ratio:new o.bZ(R),u_fade_change:new o.bZ(R),u_matrix:new o.b$(R),u_label_plane_matrix:new o.b$(R),u_coord_matrix:new o.b$(R),u_is_text:new o.bX(R),u_elevation_from_sea:new o.bX(R),u_pitch_with_map:new o.bX(R),u_texsize:new o.b_(R),u_texsize_icon:new o.b_(R),u_texture:new o.bX(R),u_texture_icon:new o.bX(R),u_gamma_scale:new o.bZ(R),u_device_pixel_ratio:new o.bZ(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_camera_forward:new o.bY(R),u_tile_matrix:new o.b$(R),u_up_vector:new o.bY(R),u_ecef_origin:new o.bY(R),u_is_halo:new o.bX(R),u_icon_transition:new o.bZ(R),u_color_adj_mat:new o.b$(R),u_scale_factor:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_inv_matrix:new o.b$(R),u_normal_scale:new o.bZ(R),u_lutTexture:new o.bX(R),u_zoom:new o.bZ(R),u_spp_fill_np_color:new o.cO(R),u_spp_halo_np_color:new o.cO(R),u_spp_opacity:new o.bZ(R),u_spp_halo_width:new o.bZ(R),u_spp_halo_blur:new o.bZ(R),u_spp_emissive_strength:new o.bZ(R),u_spp_occlusion_opacity:new o.bZ(R),u_spp_z_offset:new o.bZ(R),u_spp_translate_rotation:new o.b_(R)}),background:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_opacity:new o.bZ(R),u_color:new o.dl(R)}),backgroundPattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_opacity:new o.bZ(R),u_image:new o.bX(R),u_pattern_tl:new o.b_(R),u_pattern_br:new o.b_(R),u_texsize:new o.b_(R),u_pattern_size:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_pattern_units_to_pixels:new o.b_(R)}),terrainRaster:R=>({u_matrix:new o.b$(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_skirt_height:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_emissive_texture_available:new o.bZ(R)}),skybox:R=>({u_matrix:new o.b$(R),u_sun_direction:new o.bY(R),u_cubemap:new o.bX(R),u_opacity:new o.bZ(R),u_temporal_offset:new o.bZ(R)}),skyboxGradient:R=>({u_matrix:new o.b$(R),u_color_ramp:new o.bX(R),u_center_direction:new o.bY(R),u_radius:new o.bZ(R),u_opacity:new o.bZ(R),u_temporal_offset:new o.bZ(R)}),skyboxCapture:R=>({u_matrix_3f:new o.dm(R),u_sun_direction:new o.bY(R),u_sun_intensity:new o.bZ(R),u_color_tint_r:new o.cO(R),u_color_tint_m:new o.cO(R),u_luminance:new o.bZ(R)}),globeRaster:R=>({u_proj_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_grid_matrix:new o.dm(R),u_skirt_height:new o.bZ(R),u_far_z_cutoff:new o.bZ(R),u_frustum_tl:new o.bY(R),u_frustum_tr:new o.bY(R),u_frustum_br:new o.bY(R),u_frustum_bl:new o.bY(R),u_globe_pos:new o.bY(R),u_globe_radius:new o.bZ(R),u_viewport:new o.b_(R),u_emissive_texture_available:new o.bZ(R)}),globeAtmosphere:R=>({u_frustum_tl:new o.bY(R),u_frustum_tr:new o.bY(R),u_frustum_br:new o.bY(R),u_frustum_bl:new o.bY(R),u_horizon:new o.bZ(R),u_transition:new o.bZ(R),u_fadeout_range:new o.bZ(R),u_atmosphere_fog_color:new o.cO(R),u_high_color:new o.cO(R),u_space_color:new o.cO(R),u_temporal_offset:new o.bZ(R),u_horizon_angle:new o.bZ(R)}),model:R=>({u_matrix:new o.b$(R),u_lighting_matrix:new o.b$(R),u_normal_matrix:new o.b$(R),u_node_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_camera_pos:new o.bY(R),u_opacity:new o.bZ(R),u_baseColorFactor:new o.cO(R),u_emissiveFactor:new o.cO(R),u_metallicFactor:new o.bZ(R),u_roughnessFactor:new o.bZ(R),u_baseTextureIsAlpha:new o.bX(R),u_alphaMask:new o.bX(R),u_alphaCutoff:new o.bZ(R),u_baseColorTexture:new o.bX(R),u_metallicRoughnessTexture:new o.bX(R),u_normalTexture:new o.bX(R),u_occlusionTexture:new o.bX(R),u_emissionTexture:new o.bX(R),u_lutTexture:new o.bX(R),u_color_mix:new o.cO(R),u_aoIntensity:new o.bZ(R),u_emissive_strength:new o.bZ(R),u_occlusionTextureTransform:new o.cO(R)}),modelDepth:R=>({u_matrix:new o.b$(R),u_instance:new o.b$(R),u_node_matrix:new o.b$(R)}),groundShadow:R=>({u_matrix:new o.b$(R),u_ground_shadow_factor:new o.bY(R)}),stars:R=>({u_matrix:new o.b$(R),u_up:new o.bY(R),u_right:new o.bY(R),u_intensity_multiplier:new o.bZ(R)}),snowParticle:R=>({u_modelview:new o.b$(R),u_projection:new o.b$(R),u_time:new o.bZ(R),u_cam_pos:new o.bY(R),u_velocityConeAperture:new o.bZ(R),u_velocity:new o.bZ(R),u_horizontalOscillationRadius:new o.bZ(R),u_horizontalOscillationRate:new o.bZ(R),u_boxSize:new o.bZ(R),u_billboardSize:new o.bZ(R),u_simpleShapeParameters:new o.b_(R),u_screenSize:new o.b_(R),u_thinningCenterPos:new o.b_(R),u_thinningShape:new o.bY(R),u_thinningAffectedRatio:new o.bZ(R),u_thinningParticleOffset:new o.bZ(R),u_particleColor:new o.cO(R),u_direction:new o.bY(R)}),rainParticle:R=>({u_modelview:new o.b$(R),u_projection:new o.b$(R),u_time:new o.bZ(R),u_cam_pos:new o.bY(R),u_texScreen:new o.bX(R),u_velocityConeAperture:new o.bZ(R),u_velocity:new o.bZ(R),u_boxSize:new o.bZ(R),u_rainDropletSize:new o.b_(R),u_distortionStrength:new o.bZ(R),u_rainDirection:new o.bY(R),u_color:new o.cO(R),u_screenSize:new o.b_(R),u_thinningCenterPos:new o.b_(R),u_thinningShape:new o.bY(R),u_thinningAffectedRatio:new o.bZ(R),u_thinningParticleOffset:new o.bZ(R),u_shapeDirectionalPower:new o.bZ(R),u_shapeNormalPower:new o.bZ(R),u_mode:new o.bZ(R)}),vignette:R=>({u_vignetteShape:new o.bY(R),u_vignetteColor:new o.cO(R)}),occlusion:R=>({u_matrix:new o.b$(R),u_anchorPos:new o.bY(R),u_screenSizePx:new o.b_(R),u_occluderSizePx:new o.b_(R),u_color:new o.cO(R)})};class Tu{constructor(N,T,B,W){this.id=Tu.uniqueIdxCounter,Tu.uniqueIdxCounter++,this.context=N;const Q=N.gl;this.buffer=Q.createBuffer(),this.dynamicDraw=!!B,this.context.unbindVAO(),N.bindElementBuffer.set(this.buffer),Q.bufferData(Q.ELEMENT_ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?Q.DYNAMIC_DRAW:Q.STATIC_DRAW),this.dynamicDraw||W||T.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(N){this.id=Tu.uniqueIdxCounter,Tu.uniqueIdxCounter++;const T=this.context.gl;this.context.unbindVAO(),this.bind(),T.bufferSubData(T.ELEMENT_ARRAY_BUFFER,0,N.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}Tu.uniqueIdxCounter=0;const cx={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class dx{constructor(N,T,B,W,Q,se){this.length=T.length,this.attributes=B,this.itemSize=T.bytesPerElement,this.dynamicDraw=W,this.instanceCount=se,this.context=N;const ue=N.gl;this.buffer=ue.createBuffer(),N.bindVertexBuffer.set(this.buffer),ue.bufferData(ue.ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?ue.DYNAMIC_DRAW:ue.STATIC_DRAW),this.dynamicDraw||Q||T.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(N){const T=this.context.gl;this.bind(),T.bufferSubData(T.ARRAY_BUFFER,0,N.arrayBuffer)}enableAttributes(N,T){for(const B of this.attributes){const W=T.getAttributeLocation(N,B.name);W!==-1&&N.enableVertexAttribArray(W)}}setVertexAttribPointers(N,T,B){for(const W of this.attributes){const Q=T.getAttributeLocation(N,W.name);if(Q!==-1){const se=W.offset+this.itemSize*(B||0);W.type==="Float32"?N.vertexAttribPointer(Q,W.components,N.FLOAT,!1,this.itemSize,se):N.vertexAttribIPointer(Q,W.components,N[cx[W.type]],this.itemSize,se)}}}setVertexAttribDivisor(N,T,B){for(let W=0;W0&&N.vertexAttribDivisor(Q,B)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Bp{constructor(N,T,B,W,Q){this.context=N,this.width=T,this.height=B;const se=this.framebuffer=N.gl.createFramebuffer();W>0&&(this.colorAttachment0=new dw(N,se,0)),W>1&&(this.colorAttachment1=new dw(N,se,1)),Q&&(this.depthAttachmentType=Q,this.depthAttachment=Q==="renderbuffer"?new ak(N,se):new n5(N,se))}static createWithTexture(N,T,B,W,Q){const se=N.gl;if(N.activeTexture.set(se.TEXTURE1),N.viewport.set([0,0,B,W]),T&&T.width===B&&T.height===W)return se.bindTexture(se.TEXTURE_2D,T.colorAttachment0.get()),N.bindFramebuffer.set(T.framebuffer),T;T&&T.destroy();const ue=new o.T(N,{width:B,height:W,data:null},N.extRenderToTextureHalfFloat?N.gl.RGBA16F:N.gl.RGBA8);ue.bind(se.LINEAR,se.CLAMP_TO_EDGE);const we=N.createFramebuffer(B,W,1,null);if(we.colorAttachment0.set(ue.texture),Q){const Te=N.createRenderbuffer(se.DEPTH24_STENCIL8,B,W);N.bindFramebuffer.set(we.framebuffer),se.framebufferRenderbuffer(se.FRAMEBUFFER,se.DEPTH_STENCIL_ATTACHMENT,se.RENDERBUFFER,Te),we._stencilRbo=Te}return we}createColorAttachment(N,T){T===0?this.colorAttachment0=new dw(N,this.framebuffer,0):T===1&&(this.colorAttachment1=new dw(N,this.framebuffer,1))}removeColorAttachment(N,T){const B=this.context.gl;let W;T===0?(W=this.colorAttachment0.get(),this.colorAttachment0=void 0):T===1&&(W=this.colorAttachment1.get(),this.colorAttachment1=void 0),W&&B.deleteTexture(W)}destroy(){const N=this.context.gl;if(this.colorAttachment0){const T=this.colorAttachment0.get();T&&N.deleteTexture(T)}if(this.colorAttachment1){const T=this.colorAttachment1.get();T&&N.deleteTexture(T)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const T=this.depthAttachment.get();T&&N.deleteRenderbuffer(T)}else{const T=this.depthAttachment.get();T&&N.deleteTexture(T)}this._stencilRbo&&(N.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),N.deleteFramebuffer(this.framebuffer)}}class Nm{constructor(N,T){this.gl=N,this.clearColor=new lw(this),this.clearDepth=new YC(this),this.clearStencil=new Ub(this),this.colorMask=new QL(this),this.depthMask=new Hy(this),this.stencilMask=new Jj(this),this.stencilFunc=new cw(this),this.stencilOp=new QS(this),this.stencilTest=new qb(this),this.depthRange=new Vb(this),this.depthTest=new Gx(this),this.depthFunc=new Yu(this),this.blend=new Gy(this),this.blendFunc=new nk(this),this.blendColor=new ZC(this),this.blendEquation=new jg(this),this.cullFace=new ix(this),this.cullFaceSide=new rk(this),this.frontFace=new JS(this),this.program=new e2(this),this.activeTexture=new t2(this),this.viewport=new ox(this),this.bindFramebuffer=new yf(this),this.bindRenderbuffer=new XC(this),this.bindTexture=new Fv(this),this.bindVertexBuffer=new s2(this),this.bindElementBuffer=new n2(this),this.bindVertexArrayOES=new e5(this),this.pixelStoreUnpack=new t5(this),this.pixelStoreUnpackPremultiplyAlpha=new s5(this),this.pixelStoreUnpackFlipY=new r2(this),this.options=T?Object.assign({},T):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=N.getExtension("EXT_texture_filter_anisotropic")||N.getExtension("MOZ_EXT_texture_filter_anisotropic")||N.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=N.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=N.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=N.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=N.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=T&&!!T.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=T&&!!T.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=N.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=N.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=N.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=N.getParameter(N.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(N.getParameter(N.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=N.getParameter(N.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=N.getExtension("WEBGL_blend_func_extended")}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(N,T,B){return new Tu(this,N,T,B)}createVertexBuffer(N,T,B,W,Q){return new dx(this,N,T,B,W,Q)}createRenderbuffer(N,T,B){const W=this.gl,Q=W.createRenderbuffer();return this.bindRenderbuffer.set(Q),W.renderbufferStorage(W.RENDERBUFFER,N,T,B),this.bindRenderbuffer.set(null),Q}createFramebuffer(N,T,B,W){return new Bp(this,N,T,B,W)}clear({color:N,depth:T,stencil:B,colorMask:W}){const Q=this.gl;let se=0;N&&(se|=Q.COLOR_BUFFER_BIT,this.clearColor.set(N.toNonPremultipliedRenderColor(null)),this.colorMask.set(W||[!0,!0,!0,!0])),T!==void 0&&(se|=Q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(T),this.depthMask.set(!0)),B!==void 0&&(se|=Q.STENCIL_BUFFER_BIT,this.clearStencil.set(B),this.stencilMask.set(255)),Q.clear(se)}setCullFace(N){N.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(N.mode),this.frontFace.set(N.frontFace))}setDepthMode(N){N.func!==this.gl.ALWAYS||N.mask?(this.depthTest.set(!0),this.depthFunc.set(N.func),this.depthMask.set(N.mask),this.depthRange.set(N.range)):this.depthTest.set(!1)}setStencilMode(N){N.test.func!==this.gl.ALWAYS||N.mask?(this.stencilTest.set(!0),this.stencilMask.set(N.mask),this.stencilOp.set([N.fail,N.depthFail,N.pass]),this.stencilFunc.set({func:N.test.func,ref:N.ref,mask:N.test.mask})):this.stencilTest.set(!1)}setColorMode(N){o.b6(N.blendFunction,$a.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(N.blendFunction),this.blendColor.set(N.blendColor),N.blendEquation?this.blendEquation.set(N.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(N.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let id;function kr(R,N,T,B,W,Q,se){const ue=R.context,we=ue.gl,Te=R.transform,De=[o.aH(Te.center.lng),o.aL(Te.center.lat)],Qe=T.layout.get("symbol-placement"),Ye=T.layout.get("text-variable-anchor"),tt=T.layout.get("icon-rotation-alignment")==="map",ht=T.layout.get("text-rotation-alignment")==="map",ct=Qe!=="point",St=[];let kt=0,Ut=0;for(let es=0;es0){const Ea=o.bb(),na=xr;o.cz(Ea,Xs.placementInvProjMatrix,Te.glCoordMatrix),o.cz(Ea,Ea,Xs.placementViewportMatrix),St.push({circleArray:Kn,circleOffset:Ut,transform:na,invTransform:Ea,projection:Xs.getProjection()}),kt+=Kn.length/4,Ut=kt}if(!gr)continue;R.terrain&&R.terrain.setupElevationDraw(_s,Sr);const pa=jn?[is.canonical.x,is.canonical.y,1<=0&&(tt[Xt.associatedIconIndex]={x:Ds,y:_n,z:pn,angle:yn})}else ea(ds,Qe)}if(Te){Ye.clear();const Ut=R.icon.placedSymbolArray;for(let Xt=0;Xt{let Fi=[0,0,0];if(_l){const Rd=R.style.directionalLight,wc=R.style.ambientLight;Rd&&wc&&(Fi=_m(R.style,Rd,wc))}return Fi},oo=_l=>{if(R.context.disableSymbolUBO)return;_l.push("USE_PAINT_PROPERTIES_UBO");const Fi=Math.floor(R.context.maxUniformBlockSize/4),Rd=Math.floor(Fi/4);_l.push(`MAX_UBO_SIZE_VEC4 ${Rd}u`)},Si=_l=>{is.depthOcclusionForSymbolsAndCircles&&(T.hasOcclusionOpacityProperties||R.terrain)&&(_l.push("DEPTH_D24"),_l.push("DEPTH_OCCLUSION"))},ol=_l=>{T.lut&&!ds&&(T.lut.texture||(T.lut.texture=new o.dR(R.context,T.lut.image,[T.lut.image.height,T.lut.image.height,T.lut.image.height],Cs.gl.RGBA8)),Cs.activeTexture.set(Cs.gl.TEXTURE0+10),T.lut.texture&&T.lut.texture.bind(Cs.gl.LINEAR,Cs.gl.CLAMP_TO_EDGE),_l.push("APPLY_LUT_ON_GPU"))},_c=()=>{const _l=_s&&T.layout.get("symbol-placement")!=="point",Fi=[];Si(Fi),ol(Fi);const Rd=_l||Ei,wc=Kn.elevationType==="road",Dh=R.shadowRenderer,jo=wc&&Ds&&!!Dh&&Dh.enabled,Lc=ti(jo),km=wc&&Ds&&!R.terrain?nn:Xn,Yx=T.paint.get("icon-image-cross-fade");R.terrainRenderModeElevated()&&Ds&&Fi.push("PITCH_WITH_MAP_TERRAIN"),pa&&(Fi.push("PROJECTION_GLOBE_VIEW"),Rd&&Fi.push("PROJECTED_POS_ON_VIEWPORT")),Yx>0&&Kn.hasAnySecondaryIcon&&Fi.push("ICON_TRANSITION"),!Kn.icon.zOffsetVertexBuffer||wc&&R.terrain||Fi.push("Z_OFFSET"),kt===0&&Ut===0&&Xt===0&&Et===1||Fi.push("COLOR_ADJUSTMENT"),Kn.sdfIcons&&Fi.push("RENDER_SDF"),jo&&Fi.push("RENDER_SHADOWS","NORMAL_OFFSET"),wc&&Ds&&!R.terrain&&Kn.icon.orientationVertexBuffer&&Fi.push("ELEVATED_ROADS"),oo(Fi);const Gm=Cs.disableSymbolUBO?Kn.icon.programConfigurations.get(T.id):null,bf=R.getOrCreateProgram("symbol",{config:Gm,defines:Fi}),$v=gr.imageAtlasTexture?gr.imageAtlasTexture.size:[0,0],Kl=Kn.iconSizeData,B1=o.bj(Kl,is.zoom),$1=Ds||!is.isOrthographic,Xc=mc(na,gr.tileID.canonical,Ds,_s,is,Kn.getProjection(),ma),cd=pf(na,gr.tileID.canonical,Ds,_s,is,Kn.getProjection(),ma),lc=Kn.icon.uboBinder&&Kn.icon.uboBinder.cachedHeader&&256&Kn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ue,vh=R.translatePosMatrix(cd,gr,lc,Te,!0),Sg=R.translatePosMatrix(na,gr,lc,Te),Pu=Rd?$o:Xc,Uv=_s&&!Ds&&!_l;let u5=Sr;!jn&&!is.mercatorFromTransition||_s||(u5=Cd(is));const o3=pa?u5:Sr,l3=T.getColorAdjustmentMatrix(kt,Ut,Xt,Et),dT=Mh(Kl.kind,B1,Uv,Ds,R,Sg,Pu,vh,Ts,!1,$v,[0,0],0,xr,Ea,Bs,ki,o3,Kn.getProjection(),Lc,io,l3,Yx,null),uk=gr.imageAtlasTexture?gr.imageAtlasTexture:null,m2=T.layout.get("icon-size").constantOr(0)!==1||Kn.iconsNeedLinear,uT=Kn.sdfIcons||R.options.rotating||R.options.zooming||m2||$1?es.LINEAR:es.NEAREST,Y0=Kn.sdfIcons&&T.paint.get("icon-halo-width").constantOr(1)!==0,h5=R.terrain&&Ds&&_l?o.b7(o.bb(),Xc):$o;if(_l&&Kn.icon){const m5=o.bu.getAtTileOffsetFunc(xr,is.center.lat,is.worldSize,Kn.getProjection()),p5=Sd(na,gr.tileID.canonical,Ds,_s,is,Kn.getProjection(),ma),Hz=T.layout.get("icon-size-scale-range"),hT=o.aC(R.scaleFactor,Hz[0],Hz[1]);qm(Kn,na,R,!1,p5,cd,Ds,ct,m5,xr,hT)}return{program:bf,buffers:Kn.icon,uniformValues:dT,atlasTexture:uk,atlasTextureIcon:null,atlasInterpolation:uT,atlasInterpolationIcon:null,isSDF:Kn.sdfIcons,hasHalo:Y0,depthMode:km,tile:gr,renderWithShadows:jo,labelPlaneMatrixInv:h5}},Yd=()=>{const _l=Xs&&T.layout.get("symbol-placement")!=="point",Fi=[],Rd=_l||yn||Ei,wc=Kn.elevationType==="road",Dh=R.shadowRenderer,jo=wc&&_n&&!!Dh&&Dh.enabled,Lc=ti(jo),km=wc&&_n&&!R.terrain?nn:Xn;R.terrainRenderModeElevated()&&_n&&Fi.push("PITCH_WITH_MAP_TERRAIN"),pa&&(Fi.push("PROJECTION_GLOBE_VIEW"),Rd&&Fi.push("PROJECTED_POS_ON_VIEWPORT")),!Kn.text.zOffsetVertexBuffer||wc&&R.terrain||Fi.push("Z_OFFSET"),Kn.iconsInText&&Fi.push("RENDER_TEXT_AND_SYMBOL"),Fi.push("RENDER_SDF"),jo&&Fi.push("RENDER_SHADOWS","NORMAL_OFFSET"),wc&&_n&&!R.terrain&&Kn.text.orientationVertexBuffer&&Fi.push("ELEVATED_ROADS"),Si(Fi),oo(Fi);const Yx=Cs.disableSymbolUBO?Kn.text.programConfigurations.get(T.id):null,Gm=R.getOrCreateProgram("symbol",{config:Yx,defines:Fi});let bf,$v=[0,0],Kl=null;const B1=Kn.textSizeData;Kn.iconsInText&&($v=gr.imageAtlasTexture?gr.imageAtlasTexture.size:[0,0],Kl=gr.imageAtlasTexture?gr.imageAtlasTexture:null,bf=_n||!is.isOrthographic||R.options.rotating||R.options.zooming||B1.kind==="composite"||B1.kind==="camera"?es.LINEAR:es.NEAREST);const $1=gr.glyphAtlasTexture?gr.glyphAtlasTexture.size:[0,0],Xc=T.layout.get("text-size-scale-range"),cd=o.aC(R.scaleFactor,Xc[0],Xc[1]),lc=o.bj(B1,is.zoom,cd),vh=mc(na,gr.tileID.canonical,_n,Xs,is,Kn.getProjection(),ma),Sg=pf(na,gr.tileID.canonical,_n,Xs,is,Kn.getProjection(),ma),Pu=Kn.text.uboBinder&&Kn.text.uboBinder.cachedHeader&&256&Kn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:we,Uv=R.translatePosMatrix(Sg,gr,Pu,De,!0),u5=R.translatePosMatrix(na,gr,Pu,De),o3=Rd?$o:vh,l3=Xs&&!_n&&!_l;let dT=Sr;!jn&&!is.mercatorFromTransition||Xs||(dT=Cd(is));const uk=Mh(B1.kind,lc,l3,_n,R,u5,o3,Uv,Ts,!0,$1,$v,0,xr,Ea,Bs,ki,pa?dT:Sr,Kn.getProjection(),Lc,io,null,null,cd),m2=gr.glyphAtlasTexture?gr.glyphAtlasTexture:null,uT=es.LINEAR,Y0=T.paint.get("text-halo-width").constantOr(1)!==0,h5=R.terrain&&_n&&_l?o.b7(o.bb(),vh):$o;if(_l&&Kn.text){const m5=o.bu.getAtTileOffsetFunc(xr,is.center.lat,is.worldSize,Kn.getProjection()),p5=Sd(na,gr.tileID.canonical,_n,Xs,is,Kn.getProjection(),ma);qm(Kn,na,R,!0,p5,Sg,_n,St,m5,xr,cd)}return{program:Gm,buffers:Kn.text,uniformValues:uk,atlasTexture:m2,atlasTextureIcon:Kl,atlasInterpolation:uT,atlasInterpolationIcon:bf,isSDF:!0,hasHalo:Y0,depthMode:km,tile:gr,renderWithShadows:jo,labelPlaneMatrixInv:h5}},$c=Kn.icon.segments.get().length,bl=Kn.text.segments.get().length,Zi=$c&&!se.onlyText?_c():null,Xi=bl&&!se.onlyIcons?Yd():null,Uc=T.paint.get("icon-opacity").constantOr(1),uu=T.paint.get("text-opacity").constantOr(1);if(pn&&Kn.canOverlap){Un=!0;const _l=Uc&&!se.onlyText?Kn.icon.segments.get():[],Fi=uu&&!se.onlyIcons?Kn.text.segments.get():[];for(const Rd of _l)In.push({segments:new o.dy([Rd]),sortKey:Rd.sortKey,state:Zi});for(const Rd of Fi)In.push({segments:new o.dy([Rd]),sortKey:Rd.sortKey,state:Xi})}else se.onlyText||In.push({segments:Uc?Kn.icon.segments:new o.dy([]),sortKey:0,state:Zi}),se.onlyIcons||In.push({segments:uu?Kn.text.segments:new o.dy([]),sortKey:0,state:Xi})}Un&&In.sort((xr,gr)=>xr.sortKey-gr.sortKey);for(const xr of In){const gr=xr.state;if(gr)if(R.terrain?R.terrain.setupElevationDraw(gr.tile,gr.program,{useDepthForOcclusion:is.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:gr.labelPlaneMatrixInv}):R.setupDepthForOcclusion(is.depthOcclusionForSymbolsAndCircles,gr.program),Cs.activeTexture.set(es.TEXTURE0),gr.atlasTexture&&gr.atlasTexture.bind(gr.atlasInterpolation,es.CLAMP_TO_EDGE,!0),gr.atlasTextureIcon&&(Cs.activeTexture.set(es.TEXTURE1),gr.atlasTextureIcon&&gr.atlasTextureIcon.bind(gr.atlasInterpolationIcon,es.CLAMP_TO_EDGE,!0)),gr.renderWithShadows&&R.shadowRenderer.setupShadows(gr.tile.tileID.toUnwrapped(),gr.program,"vector-tile"),R.uploadCommonLightUniforms(R.context,gr.program),gr.hasHalo){const Kn=gr.uniformValues;Kn.u_is_halo=1,q0(gr.buffers,xr.segments,T,R,gr.program,gr.depthMode,W,Q,Kn,2),Kn.u_is_halo=0}else{if(gr.isSDF){const Kn=gr.uniformValues;gr.hasHalo&&(Kn.u_is_halo=1,q0(gr.buffers,xr.segments,T,R,gr.program,gr.depthMode,W,Q,Kn,1)),Kn.u_is_halo=0}q0(gr.buffers,xr.segments,T,R,gr.program,gr.depthMode,W,Q,gr.uniformValues,1)}}}function q0(R,N,T,B,W,Q,se,ue,we,Te){const De=B.context,Qe=De.gl,Ye=[R.dynamicLayoutVertexBuffer,R.opacityVertexBuffer,R.iconTransitioningVertexBuffer,R.globeExtVertexBuffer,R.zOffsetVertexBuffer,R.orientationVertexBuffer];R.featureIdBuffer&&Ye.push(R.featureIdBuffer);const tt=R.uboBinder?null:R.programConfigurations.get(T.id);if(R.uboBinder){R.uboBinder.layer=T;const St=B.transform.zoom,kt=B.style.getBrightness?B.style.getBrightness():null,Ut=R.uboBinder.getConstantUniformValues(St,kt);we.u_spp_fill_np_color=Ut.fill_np_color,we.u_spp_halo_np_color=Ut.halo_np_color,we.u_spp_opacity=Ut.opacity,we.u_spp_halo_width=Ut.halo_width,we.u_spp_halo_blur=Ut.halo_blur,we.u_spp_emissive_strength=Ut.emissive_strength,we.u_spp_occlusion_opacity=Ut.occlusion_opacity,we.u_spp_z_offset=Ut.z_offset;const Xt=T.paint.get(R.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),Et=R.uboBinder.cachedHeader&&256&R.uboBinder.cachedHeader.dataDrivenMask&&Xt==="map"?B.transform.angle:0;we.u_spp_translate_rotation=[Math.cos(Et),Math.sin(Et)]}const{batchIndices:ht,batchSegments:ct}=R.getBatchGrouping(N);for(const St of ht){const kt=ct.get(St);R.uboBinder&&R.uboBinder.bind(De,W.program,St),W.draw(B,Qe.TRIANGLES,Q,se,ue,ba.disabled,we,T.id,R.layoutVertexBuffer,R.indexBuffer,kt,T.paint,B.transform.zoom,tt,Ye,Te)}}function Xu(R,N,T,B,W,Q){const se=T.paint.get("line-width"),ue=T.paint.get("line-emissive-strength").isConstant(),we=T.paint.get("line-emissive-strength").constantOr(0),Te=T.paint.get("line-occlusion-opacity"),De=T.layout.get("line-elevation-reference"),Qe=T.layout.get("line-width-unit")==="meters",Ye=De==="sea",tt=!(!R.terrain||!R.terrain.enabled),ht=R.context,ct=ht.gl;if(T.hasElevatedBuckets&&R.transform.projection.name==="globe")return;const St=T.layout.get("line-cross-slope"),kt=St!==void 0,Ut=St<1,Xt=W||R.colorModeForDrapableLayerRenderPass(ue?we:null),Et=R.terrain&&R.terrain.renderingToTexture||Q,Ts=Et?1:o.o.devicePixelRatio,ds=T.paint.get("line-dasharray"),Cs=ds.constantOr(1),es=T.layout.get("line-cap"),is=ds.constantOr(null),_s=es.constantOr(null),Xs=T.paint.get("line-pattern"),Ds=Xs.constantOr(1),_n=T.paint.get("line-pattern-cross-fade"),pn=Xs.constantOr(null),Un=T.paint.get("line-opacity").constantOr(1);let Xn=!Ds&&Un!==1||R.depthOcclusion&&Te>0&&Te<1;const nn=T.paint.get("line-gradient"),Bs=Ds?"linePattern":"line",yn=o.dU(T);let jn;if(Et&&R.terrain&&R.terrain.clipOrMaskOverlapStencilType()&&(Xn=!1),Te!==0&&R.depthOcclusion){const Kn=T.paint._values["line-opacity"];Kn&&Kn.value&&Kn.value.kind==="constant"?jn=Kn.value:o.w(`Occlusion opacity for layer ${T.id} is supported only when line-opacity isn't data-driven.`)}se.value.kind!=="constant"&&se.value.isLineProgressConstant===!1&&yn.push("VARIABLE_LINE_WIDTH"),Et&&(R.emissiveMode!=="dual-source-blending"||ue?R.emissiveMode==="mrt-fallback"&&yn.push("USE_MRT1"):yn.push("DUAL_SOURCE_BLENDING"));const In={},Sr=(Kn,pa,Ea,na,ma,hi)=>{for(const Ei of Kn){const ki=N.getTile(Ei);if(Ds&&!ki.patternsLoaded())continue;const io=ki.getBucket(T);if(!io||io.elevationType!=="none"&&!ma||io.elevationType==="none"&&ma)continue;R.prepareDrawTile();const ti=[...pa],oo=R.shadowRenderer,Si=io.elevationType==="road"&&!!oo&&oo.enabled;let ol=[0,0,0];if(Si){const jo=R.style.directionalLight,Lc=R.style.ambientLight;jo&&Lc&&(ol=_m(R.style,jo,Lc)),ti.push("RENDER_SHADOWS","NORMAL_OFFSET")}const _c=io.programConfigurations.get(T.id);let Yd=!1;if(pn&&ki.imageAtlas){const jo=o.dV.from(pn),Lc=jo.getPrimary().scaleSelf(Ts).toString(),km=ki.imageAtlas.patternPositions.get(Lc),Yx=jo.getSecondary(),Gm=Yx?ki.imageAtlas.patternPositions.get(Yx.scaleSelf(Ts).toString()):null;Yd=!!km&&!!Gm,km&&_c.setConstantPatternPositions(km,Gm)}_n>0&&(Yd||_c.getPatternTransitionVertexBuffer("line-pattern"))&&ti.push("LINE_PATTERN_TRANSITION"),io.elevationGroundScaleVertexBuffer&&ti.push("ELEVATION_GROUND_SCALE");const $c=R.isTileAffectedByFog(Ei),bl=R.getOrCreateProgram(Bs,{config:_c,defines:ti,overrideFog:$c});if(!Ds&&is&&_s&&ki.lineAtlas){const jo=ki.lineAtlas.getDash(is,_s);jo&&_c.setConstantPatternPositions(jo)}Si&&oo.setupShadows(ki.tileID.toUnwrapped(),bl,"vector-tile");let[Zi,Xi]=T.paint.get("line-trim-offset");(_s==="round"||_s==="square")&&Zi!==Xi&&(Zi===0&&(Zi-=1),Xi===1&&(Xi+=1));const Uc=Et?Ei.projMatrix:null,uu=Qe?1/io.tileToMeter/o.aA(ki,1,R.transform.zoom):1,_l=Qe?1/io.tileToMeter/o.aA(ki,1,Math.floor(R.transform.zoom)):1,Fi=Cs?T.paint._values["line-floorwidth"]:null;let Rd;if(Fi&&Fi.value.kind==="constant"){const jo=io.zoom;jo in In||(In[jo]=Math.max(.01,T.widthExpression().evaluate({zoom:jo}))),Rd=Fi.value.value;const Lc=Math.floor(R.transform.zoom);Fi.value.value=In[jo]*Math.pow(2,Lc-ki.tileID.overscaledZ)}const wc=Ds?o.dW(R,ki,T,Uc,Ts,uu,_l,[Zi,Xi],ol,_n):o.dX(R,ki,T,Uc,io.lineClipsArray.length,Ts,uu,_l,[Zi,Xi],ol);if(nn){const jo=io.gradients[T.id];let Lc=jo.texture;if(T.gradientVersion!==jo.version){let km=256;if(T.stepInterpolant){const Yx=N.getSource().maxzoom,Gm=Ei.canonical.z===Yx?Math.ceil(1<{jn!=null&&(jn.value=Un*Te),bl.draw(R,ct.TRIANGLES,Ea,jo,Xt,ba.disabled,wc,T.id,io.layoutVertexBuffer,io.indexBuffer,io.segments,T.paint,R.transform.zoom,_c,[io.layoutVertexBuffer2,io.patternVertexBuffer,io.zOffsetVertexBuffer,io.elevationGroundScaleVertexBuffer]),jn!=null&&(jn.value=Un)};if(Xn&&!ma){const jo=R.stencilModeForClipping(Ei).ref;jo===0&&Et&&ht.clear({stencil:0});const Lc={func:ct.EQUAL,mask:255};wc.u_alpha_discard_threshold=.8,Dh(new Va(Lc,jo,255,ct.KEEP,ct.KEEP,ct.INVERT)),wc.u_alpha_discard_threshold=0,Dh(new Va(Lc,jo,255,ct.KEEP,ct.KEEP,ct.KEEP))}else wc.u_alpha_discard_threshold=Xn&&ma&&hi?.8:0,Dh(ma?na:R.stencilModeForClipping(Ei));Rd!==void 0&&(Fi.value.value=Rd)}};let xr=R.depthModeForSublayer(0,Yr.ReadOnly);const gr=new Yr(R.depthOcclusion?ct.GREATER:ct.LEQUAL,Yr.ReadOnly,R.depthRangeFor3D);if(T.hasNonElevatedBuckets){const Kn=!Et&&R.terrain;Te!==0&&Kn?o.w(`Occlusion opacity for layer ${T.id} is supported on terrain only if the layer has line-z-offset enabled.`):Kn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${T.id}.`):Sr(B,yn,xr,Va.disabled,!1,!0)}if(T.hasElevatedBuckets){De==="hd-road-markup"?tt||(xr=gr,yn.push("ELEVATED_ROADS")):(yn.push("ELEVATED"),xr=gr,kt&&yn.push(Ut?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Ye&&yn.push("ELEVATION_REFERENCE_SEA"));const Kn=Xn?R.stencilModeFor3D():Va.disabled;R.forceTerrainMode=!0,Sr(B,yn,xr,Kn,!0,!0),Xn&&Sr(B,yn,xr,Kn,!0,!1),R.forceTerrainMode=!1}Xn&&(R.resetStencilClippingMasks(),Et&&ht.clear({stencil:0})),Te===0||R.depthOcclusion||Et||R.layersWithOcclusionOpacity.push(R.currentLayer)}const vf={additive:{clearColor:new o.aq(0,0,0,0),colorMode:$a.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:$a.multiply,compositeUniformValue:0}};function I1(R,N){const T=1<=bm?1:tt.pitch/bm))),2*ht}(R.transform),Te=R.transform.getFreeCameraOptions().position,De="elevatedStructuresDepthReconstruct",Qe=R.getOrCreateProgram(De,{defines:["DEPTH_RECONSTRUCTION"]}),Ye=R.getOrCreateProgram(De);for(const tt of B){const ht=N.getTile(tt),ct=ht.getBucket(T);if(!ct)continue;const St=ct.elevatedStructures;if(!St)continue;const kt=ct.elevationBufferData.heightRange,Ut=I1(tt.toUnwrapped(),Te),Xt=R.translatePosMatrix(tt.projMatrix,ht,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));let Et,Ts,ds,Cs;if(W==="initialize"){if(!kt||kt.min>=1||St.depthSegments.segments[0].primitiveLength===0)continue;Et=Yi(Xt,Ut,we,1,0),Ts=se,ds=St.depthSegments,Cs=Qe}else if(W==="reset"){if(!kt||kt.min>=0||St.maskSegments.segments[0].primitiveLength===0)continue;Et=Yi(Xt,Ut,0,0,1),Ts=ue,ds=St.maskSegments,Cs=Qe}else if(W==="geometry"){if(St.depthSegments.segments[0].primitiveLength===0)continue;Et=Yi(Xt,Ut,we,1,0),Ts=se,ds=St.depthSegments,Cs=Ye}Cs.draw(R,Q.TRIANGLES,Ts,Va.disabled,$a.disabled,ba.disabled,Et,T.id,St.vertexBuffer,St.indexBuffer,ds,T.paint,R.transform.zoom)}}function D1(R,N,T,B){const{painter:W,sourceCache:Q,layer:se,coords:ue,colorMode:we,elevationType:Te,terrainEnabled:De,pass:Qe}=R,Ye=W.context.gl,tt=se.paint.get("fill-pattern"),ht=se.paint.get("fill-pattern-cross-fade"),ct=tt.constantOr(null);let St=Te;Te!=="road"||N&&!De||(St="none");const kt=St==="road",Ut=R.painter.shadowRenderer,Xt=kt&&!!Ut&&Ut.enabled,Et=new Yr(W.context.gl.LEQUAL,Yr.ReadOnly,W.depthRangeFor3D);let Ts=[0,0,0];if(Xt){const is=W.style.directionalLight,_s=W.style.ambientLight;is&&_s&&(Ts=_m(W.style,is,_s))}const ds=tt&&tt.constantOr(1),Cs=W.terrain&&W.terrain.renderingToTexture,es=(is,_s)=>{let Xs,Ds,_n,pn,Un;_s?(Xs=ds&&!se.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",_n=Ye.LINES):(Xs=ds?"fillPattern":"fill",_n=Ye.TRIANGLES);for(const Xn of ue){const nn=Q.getTile(Xn);if(ds&&!nn.patternsLoaded())continue;const Bs=nn.getBucket(se);if(!Bs)continue;const yn=N?Bs.elevationBufferData:Bs.bufferData;if(yn.isEmpty())continue;W.prepareDrawTile();const jn=yn.programConfigurations.get(se.id),In=W.isTileAffectedByFog(Xn),Sr=[],xr=[];kt&&(Sr.push("ELEVATED_ROADS"),xr.push(yn.elevatedLayoutVertexBuffer)),Xt&&Sr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Cs&&T&&Sr.push("USE_MRT1"),ds&&(W.context.activeTexture.set(Ye.TEXTURE0),nn.imageAtlasTexture&&nn.imageAtlasTexture.bind(Ye.LINEAR,Ye.CLAMP_TO_EDGE),jn.updatePaintBuffers());let gr=!1;if(ct&&nn.imageAtlas){const ma=nn.imageAtlas,hi=o.dV.from(ct),Ei=hi.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ki=hi.getSecondary(),io=ma.patternPositions.get(Ei),ti=ki?ma.patternPositions.get(ki.scaleSelf(o.o.devicePixelRatio).toString()):null;gr=!!io&&!!ti,io&&jn.setConstantPatternPositions(io,ti)}ht>0&&(gr||jn.getPatternTransitionVertexBuffer("fill-pattern"))&&Sr.push("FILL_PATTERN_TRANSITION");const Kn=W.getOrCreateProgram(Xs,{config:jn,overrideFog:In,defines:Sr}),pa=W.translatePosMatrix(Xn.projMatrix,nn,se.paint.get("fill-translate"),se.paint.get("fill-translate-anchor"));Xt&&Ut.setupShadows(nn.tileID.toUnwrapped(),Kn,"vector-tile");const Ea=se.paint.get("fill-emissive-strength");if(_s){pn=yn.lineIndexBuffer,Un=yn.lineSegments;const ma=W.terrain&&W.terrain.renderingToTexture?W.terrain.drapeBufferSize:[Ye.drawingBufferWidth,Ye.drawingBufferHeight];Ds=Xs==="fillOutlinePattern"&&ds?ro(pa,Ea,W,nn,ma,Ts,ht):_a(pa,Ea,ma,Ts)}else pn=yn.indexBuffer,Un=yn.triangleSegments,Ds=ds?Ca(pa,Ea,W,nn,Ts,ht):Gr(pa,Ea,Ts);W.uploadCommonUniforms(W.context,Kn,Xn.toUnwrapped());let na=is;(Te==="road"&&!De||Te==="offset")&&(na=Et),Kn.draw(W,_n,na,B||W.stencilModeForClipping(Xn),we,ba.disabled,Ds,se.id,yn.layoutVertexBuffer,pn,Un,se.paint,W.transform.zoom,jn,xr)}};W.renderPass===Qe&&es(W.depthModeForSublayer(1,W.renderPass==="opaque"?Yr.ReadWrite:Yr.ReadOnly),!1),St==="none"&&W.renderPass==="translucent"&&se.paint.get("fill-antialias")&&es(W.depthModeForSublayer(se.getPaintProperty("fill-outline-color")?2:0,Yr.ReadOnly),!0)}function $p(R,N,T,B,W,Q,se,ue){T.resetLayerRenderingStats(R);const we=R.context,Te=we.gl,De=R.transform,Qe=T.paint.get("fill-extrusion-pattern"),Ye=T.paint.get("fill-extrusion-pattern-cross-fade"),tt=Qe.constantOr(null),ht=Qe.constantOr(1),ct=T.paint.get("fill-extrusion-opacity"),St=R.style.enable3dLights(),kt=T.paint.get(St&&!ht?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Ut=[T.paint.get("fill-extrusion-ambient-occlusion-intensity"),kt],Xt=T.layout.get("fill-extrusion-edge-radius"),Et=Xt>0&&!T.paint.get("fill-extrusion-rounded-roof"),Ts=Et?0:Xt,ds=De.projection.name==="globe"?o.e1():0,Cs=De.projection.name==="globe",es=Cs?o.al(De.zoom):0,is=[o.aH(De.center.lng),o.aL(De.center.lat)],_s=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Xs=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(_s?null:T.lut).toArray01().slice(0,3),Ds=T.paint.get("fill-extrusion-flood-light-intensity"),_n=T.paint.get("fill-extrusion-vertical-scale"),pn=T.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Un=T.paint.get("fill-extrusion-height-alignment"),Xn=T.paint.get("fill-extrusion-base-alignment"),nn=Gd(R,T.paint.get("fill-extrusion-cutoff-fade-range")),Bs=T.paint.get("fill-extrusion-front-cutoff"),yn=l2(De.pitch,Bs,!!R.terrain),jn=yn[2]<1;jn&&(R.maxFrontCutoffRawStart=Math.max(R.maxFrontCutoffRawStart,Bs[0]));const In=[];let Sr;Cs&&In.push("PROJECTION_GLOBE_VIEW"),Ut[0]>0&&In.push("FAUX_AO"),Et&&In.push("ZERO_ROOF_RADIUS"),ue&&In.push("HAS_CENTROID"),Ds>0&&In.push("FLOOD_LIGHT"),nn.shouldRenderCutoff&&In.push("RENDER_CUTOFF"),jn&&In.push("RENDER_FRONT_CUTOFF"),pn&&In.push("RENDER_WALL_MODE");const xr=R.renderPass==="shadow",gr=R.shadowRenderer,Kn=xr&&!!gr,pa=xr?ba.disabled:ba.backCCW;R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0);let Ea=[0,0,0];if(gr){const hi=R.style.directionalLight,Ei=R.style.ambientLight;hi&&Ei&&(Ea=_m(R.style,hi,Ei)),xr||(In.push("RENDER_SHADOWS"),gr.useNormalOffset&&In.push("NORMAL_OFFSET")),Sr=In.concat(["SHADOWS_SINGLE_CASCADE"])}const na=Kn?"fillExtrusionDepth":ht?"fillExtrusionPattern":"fillExtrusion",ma=T.getLayerRenderingStats();for(const hi of B){const Ei=N.getTile(hi),ki=Ei.getBucket(T);if(!ki||ki.projection.name!==De.projection.name)continue;let io=!1;gr&&(io=gr.getMaxCascadeForTile(hi.toUnwrapped())===0);const ti=R.isTileAffectedByFog(hi),oo=ki.programConfigurations.get(T.id);let Si=!1;if(tt&&Ei.imageAtlas){const Xi=Ei.imageAtlas,Uc=o.dV.from(tt),uu=Uc.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),_l=Uc.getSecondary(),Fi=Xi.patternPositions.get(uu),Rd=_l?Xi.patternPositions.get(_l.scaleSelf(o.o.devicePixelRatio).toString()):null;Si=!!Fi&&!!Rd,Fi&&oo.setConstantPatternPositions(Fi,Rd)}Ye>0&&(Si||oo.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&In.push("FILL_EXTRUSION_PATTERN_TRANSITION");const ol=R.getOrCreateProgram(na,{config:oo,defines:io?Sr:In,overrideFog:ti});if(R.terrain&&R.terrain.setupElevationDraw(Ei,ol,{useMeterToDem:!0}),!ki.centroidVertexBuffer){const Xi=ol.getAttributeLocation(Te,"a_centroid_pos");Xi!==-1&&Te.vertexAttribI4ui(Xi,0,0,0,0)}!xr&&gr&&gr.setupShadows(Ei.tileID.toUnwrapped(),ol,"vector-tile"),ht&&(R.context.activeTexture.set(Te.TEXTURE0),Ei.imageAtlasTexture&&Ei.imageAtlasTexture.bind(Te.LINEAR,Te.CLAMP_TO_EDGE),oo.updatePaintBuffers());const _c=T.paint.get("fill-extrusion-vertical-gradient"),Yd=1/ki.tileToMeter;let $c;if(xr&&gr){if(Ng(Ei.tileID,ki.maxHeight,R))continue;const Xi=gr.calculateShadowPassMatrixFromTile(Ei.tileID.toUnwrapped());$c=Nr(Xi,Ts,Yd,_n,Un,Xn)}else{const Xi=R.translatePosMatrix(hi.expandedProjMatrix,Ei,T.paint.get("fill-extrusion-translate"),T.paint.get("fill-extrusion-translate-anchor")),Uc=De.projection.createInversionMatrix(De,hi.canonical);$c=ht?Gn(Xi,R,_c,ct,Ut,Ts,Yd,hi,Ei,ds,Un,Xn,es,is,Uc,Xs,_n,Ye):Dr(Xi,R,_c,ct,Ut,Ts,Yd,hi,ds,Un,Xn,es,is,Uc,Xs,_n,Ds,Ea,yn)}R.uploadCommonUniforms(we,ol,hi.toUnwrapped(),null,nn);let bl=ki.segments;if(De.projection.name==="mercator"&&!xr&&(bl=ki.getVisibleSegments(Ei.tileID,R.terrain,R.transform.getFrustum(0)),!bl.get().length))continue;if(ma)if(xr)for(const Xi of bl.get())ma.numRenderedVerticesInShadowPass+=Xi.primitiveLength;else for(const Xi of bl.get())ma.numRenderedVerticesInTransparentPass+=Xi.primitiveLength;const Zi=[];(R.terrain||ue)&&Zi.push(ki.centroidVertexBuffer),Cs&&Zi.push(ki.layoutVertexExtBuffer),pn&&Zi.push(ki.wallVertexBuffer),ol.draw(R,we.gl.TRIANGLES,W,Q,se,pa,$c,T.id,ki.layoutVertexBuffer,ki.indexBuffer,bl,T.paint,R.transform.zoom,oo,Zi)}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1)}class ux{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function l2(R,N,T){if(!(N[2]<1)||T)return[0,0,1];const B=180*R/Math.PI;if(B<15)return[-.5,N[1],N[2]];const W=Math.min(1,Math.max(0,(B-15)/5)),Q=W*W*(3-2*W);return[-.5*(1-Q)+N[0]*Q,N[1],N[2]]}function Wy(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut,Xt,Et){const Ts=N.context,ds=Ts.gl,Cs=N.transform,es=N.transform.zoom,is=[],_s=R.translate,Xs=R.translateAnchor,Ds=R.edgeRadius,_n=Gd(N,R.cutoffFadeRange);De==="clear"?(is.push("CLEAR_SUBPASS"),Xt&&(is.push("CLEAR_FROM_TEXTURE"),Ts.activeTexture.set(ds.TEXTURE0),Xt.bind(ds.LINEAR,ds.CLAMP_TO_EDGE))):De==="sdf"?is.push("SDF_SUBPASS"):De==="emissive"&&(is.push("USE_MRT1"),Ts.activeTexture.set(ds.TEXTURE0),Xt.bind(ds.LINEAR,ds.CLAMP_TO_EDGE)),kt&&is.push("HAS_CENTROID"),_n.shouldRenderCutoff&&is.push("RENDER_CUTOFF");const pn=(Un,Xn,nn,Bs,yn)=>{let jn=is;Xn.groundRadiusBuffer!=null&&(jn=is.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const In=Xn.programConfigurations.get(B.id),Sr=N.isTileAffectedByFog(Un),xr=N.getOrCreateProgram("fillExtrusionGroundEffect",{config:In,defines:jn,overrideFog:Sr}),gr=((pa,Ea,na,ma,hi,Ei,ki,io,ti,oo,Si)=>({u_matrix:Ea,u_opacity:na,u_ao_pass:ma?1:0,u_meter_to_tile:hi,u_ao:Ei,u_flood_light_intensity:ki,u_flood_light_color:io,u_attenuation:ti,u_edge_radius:oo,u_fb:0,u_fb_size:Si,u_dynamic_offset:1}))(0,Bs,Qe,Te,yn,[Ye,tt*yn],ht,ct,St,es>=17?0:Ds*yn,Xt?Xt.size[0]:0),Kn=[];kt&&Kn.push(Xn.hiddenByLandmarkVertexBuffer),Xn.groundRadiusBuffer!=null&&Kn.push(Xn.groundRadiusBuffer),N.uploadCommonUniforms(Ts,xr,Un.toUnwrapped(),null,_n),xr.draw(N,Ts.gl.TRIANGLES,Q,se,ue,we,gr,B.id,Xn.vertexBuffer,Xn.indexBuffer,nn,B.paint,es,In,Kn)};for(const Un of W){const Xn=T.getTile(Un),nn=Xn.getBucket(B);if(!nn||nn.projection.name!==Cs.projection.name||!nn.groundEffect||nn.groundEffect&&!nn.groundEffect.hasData())continue;const Bs=nn.groundEffect,yn=1/nn.tileToMeter;{const jn=N.translatePosMatrix(Un.projMatrix,Xn,_s,Xs),In=Bs.getDefaultSegment();pn(Un,Bs,In,jn,yn)}if(Ut)for(let jn=0;jn<4;jn++){const In=o.d$[jn](Un),Sr=T.getTile(In);if(!Sr)continue;const xr=Sr.getBucket(B);if(!xr||xr.projection.name!==Cs.projection.name||!xr.groundEffect||xr.groundEffect&&!xr.groundEffect.hasData())continue;const gr=xr.groundEffect;let Kn,pa;jn===0?(Kn=[-o.an,0,0],pa=1):jn===1?(Kn=[o.an,0,0],pa=0):jn===2?(Kn=[0,-o.an,0],pa=3):(Kn=[0,o.an,0],pa=2);const Ea=gr.regionSegments[pa];if(!Ea)continue;const na=new Float32Array(16);o.bx(na,Un.projMatrix,Kn),pn(Un,gr,Ea,N.translatePosMatrix(na,Xn,_s,Xs),yn)}}}function V0(R,N,T,B,W,Q,se){B.centroidVertexArray.length===0&&B.createCentroidsBuffer();const ue=Q?Q.findDEMTileFor(T):null;if(!(ue&&ue.dem||se))return;Q&&ue&&ue.dem&&B.selfDEMTileTimestamp!==ue.dem._timestamp&&(B.borderDoneWithNeighborZ=[-1,-1,-1,-1],B.selfDEMTileTimestamp=ue.dem._timestamp);const we=(kt,Ut)=>{(kt.flags|Ut.flags)&o.e3?(kt.flags|=o.e3,Ut.flags|=o.e3):(kt.flags&=~o.e3,Ut.flags&=~o.e3)},Te=kt=>new o.P(Math.ceil((kt+o.e4)*o.e5),0),De=(kt,Ut,Xt)=>{const Et=Math.ceil((kt+o.e4)*o.e5),Ts=Math.floor(Math.max(0,Math.min(o.an-1,Xt))/4);return new o.P(Et,Ts<<5|(3&Ut)<<3|7)},Qe=kt=>{const Ut=N.getSource().minzoom,Xt=Ts=>{const ds=N.getTileByID(Ts);if(ds&&ds.hasData())return ds.getBucket(W)},Et=[0,-1,1];for(const Ts of Et){if(kt.overscaledZ+Ts(Ye[0]=Math.min(kt.min.y,Ut.min.y),Ye[1]=Math.max(kt.max.y,Ut.max.y),Ye[2]=o.an-Ut.min.x>kt.max.x?Ut.min.x-o.an:kt.max.x,Ye),ht=(kt,Ut)=>(Ye[0]=Math.min(kt.min.x,Ut.min.x),Ye[1]=Math.max(kt.max.x,Ut.max.x),Ye[2]=o.an-Ut.min.y>kt.max.y?Ut.min.y-o.an:kt.max.y,Ye),ct=[(kt,Ut)=>tt(kt,Ut),(kt,Ut)=>tt(Ut,kt),(kt,Ut)=>ht(kt,Ut),(kt,Ut)=>ht(Ut,kt)],St=(kt,Ut,Xt,Et,Ts,ds,Cs)=>{if(!Q)return 0;const es=[[ds?Xt:kt,ds?kt:Xt,0],[ds?Xt:Ut,ds?Ut:Xt,0]],is=Cs<0?o.an+Cs:Cs,_s=[ds?is:(kt+Ut)/2,ds?(kt+Ut)/2:is,0];return Xt===0&&Cs<0||Xt!==0&&Cs>0?Q.getForTilePoints(Ts,[_s],!0,Et):es.push(_s),Q.getForTilePoints(T,es,!0,ue),Math.max(es[0][2],es[1][2],_s[2])/Q.exaggeration()};for(let kt=0;kt<4;kt++){const Ut=B.borderFeatureIndices[kt];if(Ut.length===0)continue;const Xt=o.d$[kt](T),Et=Qe(Xt);if(!(Et&&Et instanceof o.e0))continue;const Ts=Q?Q.findDEMTileFor(Xt):null;if(!(Ts&&Ts.dem||se)||(Q&&Ts&&Ts.dem&&B.borderDEMTileTimestamp[kt]!==Ts.dem._timestamp&&(B.borderDoneWithNeighborZ[kt]=-1,B.borderDEMTileTimestamp[kt]=Ts.dem._timestamp),B.borderDoneWithNeighborZ[kt]===Et.canonical.z))continue;Et.centroidVertexArray.length===0&&Et.createCentroidsBuffer();const ds=(kt<2?1:5)-kt,Cs=Et.borderDoneWithNeighborZ[ds]!==B.canonical.z,es=Et.borderFeatureIndices[ds];let is=0;if(B.canonical.z!==Et.canonical.z){for(const _n of Ut)B.showCentroid(B.featuresOnBorder[_n]);if(Cs)for(const _n of es)Et.showCentroid(Et.featuresOnBorder[_n]);B.borderDoneWithNeighborZ[kt]=Et.canonical.z,Et.borderDoneWithNeighborZ[ds]=B.canonical.z;continue}const _s=new Map,Xs=new Set,Ds=new Set;for(let _n=0;_n1||nn.intersectsCount()>1;{let xr=0;if(Ts&&Ts.dem&&!Sr){const gr=ct[kt](Un,Bs),Kn=kt%2?o.an-1:0;xr=St(gr[0],Math.min(o.an-1,gr[1]),Kn,Ts,Xt,kt<2,gr[2])}Un.centroidXY=De(xr,kt,In),Bs.centroidXY=De(xr,ds,In)}if(B.writeCentroidToBuffer(Un),Et.writeCentroidToBuffer(Bs),pn.buildingId!==void 0){for(const xr of B.centroidData)xr.buildingId===pn.buildingId&&xr!==Un&&(xr.centroidXY=Un.centroidXY,B.writeCentroidToBuffer(xr));for(const xr of Et.centroidData)xr.buildingId===pn.buildingId&&xr!==Bs&&(xr.centroidXY=Bs.centroidXY,Et.writeCentroidToBuffer(xr))}}for(const _n of Ut){if(Xs.has(_n))continue;const pn=B.featuresOnBorder[_n],Un=B.centroidData[pn.centroidDataIndex],Xn=pn.borders[kt];let nn;for(;isXn[0]+3||Bs[0]>Xn[0]-3)break;Et.showCentroid(nn),is++}if(nn&&isXn[1]-3||(yn++,++is===es.length))break;nn=Et.featuresOnBorder[es[is]]}for(;Bs=es.length){B.showCentroid(pn);continue}nn=Et.featuresOnBorder[es[Bs]];let jn=!1;if(yn>=1){const xr=nn.borders[ds];Math.abs(Xn[0]-xr[0])<3&&Math.abs(Xn[1]-xr[1])<3&&(yn=1,jn=!0,is=Bs+1)}else if(yn===0){B.showCentroid(pn);continue}const In=Et.centroidData[nn.centroidDataIndex];se&&jn&&we(Un,In);const Sr=pn.intersectsCount()>1||nn.intersectsCount()>1;if(yn>1)is=Bs,Un.centroidXY=In.centroidXY=new o.P(0,0);else if(Ts&&Ts.dem&&!Sr){const xr=ct[kt](Un,In),gr=kt%2?o.an-1:0,Kn=St(xr[0],Math.min(o.an-1,xr[1]),gr,Ts,Xt,kt<2,xr[2]);Un.centroidXY=In.centroidXY=Te(Kn)}else Sr?Un.centroidXY=In.centroidXY=new o.P(0,0):(Un.centroidXY=B.encodeBorderCentroid(pn),In.centroidXY=Et.encodeBorderCentroid(nn));B.writeCentroidToBuffer(Un),Et.writeCentroidToBuffer(In)}else B.showCentroid(pn)}B.borderDoneWithNeighborZ[kt]=Et.canonical.z,Et.borderDoneWithNeighborZ[ds]=B.canonical.z}(B.needsCentroidUpdate||!B.centroidVertexBuffer&&B.centroidVertexArray.length!==0)&&B.uploadCentroid(R)}const zv=[1,0,0],c2=[0,1,0],d2=[0,0,1];function Ng(R,N,T){const B=T.transform,W=T.shadowRenderer;if(!W)return!0;const Q=R.toUnwrapped(),se=B.tileSize*W._cascades[T.currentShadowCascade].scale;let ue=N;if(B.elevation){const ht=B.elevation.getMinMaxForTile(R);ht&&(ue+=ht.max)}const we=B.scaleZoom(se);ue/=o.e2(B.center.lat,we);const Te=[...W.shadowDirection];Te[2]=-Te[2];const De=W.computeSimplifiedTileShadowVolume(Q,ue,se,Te);if(!De)return!1;const Qe=[zv,c2,d2,Te,[Te[0],0,Te[2]],[0,Te[1],Te[2]]],Ye=o.cl.fromInvProjectionMatrix(B.invProjMatrix,B.worldSize,we,B.projection.name!=="globe"),tt=W.getCurrentCascadeFrustum();return Ye.intersectsPrecise(De.vertices,De.planes,Qe)===0||tt.intersectsPrecise(De.vertices,De.planes,Qe)===0}function Bv(R){const{painter:N,source:T,layer:B,coords:W}=R;let Q=R.defines;const se=N.context,ue=N.renderPass==="shadow",we=N.renderPass==="light-beam",Te=N.shadowRenderer,De=o.e2(N.transform.center.lat,N.transform.zoom),Qe=Gd(N,B.paint.get("building-cutoff-fade-range"));Qe.shouldRenderCutoff&&(Q=Q.concat("RENDER_CUTOFF"));const Ye=B.paint.get("building-front-cutoff"),tt=Ye[2]<1&&!N.terrain,ht=l2(N.transform.pitch,Ye,!!N.terrain);tt&&(Q=Q.concat("RENDER_FRONT_CUTOFF"),N.maxFrontCutoffRawStart=Math.max(N.maxFrontCutoffRawStart,Ye[0])),R.floodLightIntensity>0&&(Q=Q.concat("FLOOD_LIGHT"));for(const ct of W){const St=T.getTile(ct),kt=St.getBucket(B);if(!kt)continue;Te&&Te.getMaxCascadeForTile(ct.toUnwrapped())===0&&(Q=Q.concat("SHADOWS_SINGLE_CASCADE"));const Ut=kt.programConfigurations.get(B.id);let Xt,Et,Ts,ds=N.translatePosMatrix(ct.expandedProjMatrix,St,[0,0],"map");if(ds=o.cC(o.bb(),ds,[1,1,R.verticalScale]),ue&&Te){if(Ng(St.tileID,kt.maxHeight*De,N))continue;let es=Te.calculateShadowPassMatrixFromTile(St.tileID.toUnwrapped());es=o.cC(o.bb(),es,[1,1,R.verticalScale]),Ts=eo(es),Xt=Et=N.getOrCreateProgram("buildingDepth",{config:Ut,defines:Q,overrideFog:!1})}else if(we)Xt=Et=N.getOrCreateProgram("buildingBloom",{config:Ut,defines:Q,overrideFog:!1}),Ts=El(ds);else{const es=N.transform.calculatePosMatrix(ct.toUnwrapped(),N.transform.worldSize);o.cC(es,es,[1,1,R.verticalScale]);const is=o.bb();o.cC(is,es,[1,-1,1/De]),o.b7(is,is),o.e6(is,is);const _s=N.transform.getFreeCameraOptions().position,Xs=1<{if(we){const _s=es.entranceBloom;is.draw(N,se.gl.TRIANGLES,R.depthMode,Va.disabled,R.blendMode,ba.disabled,Ts,B.id,_s.layoutVertexBuffer,_s.indexBuffer,_s.segmentsBucket,B.paint,N.transform.zoom,Ut,[_s.layoutAttenuationBuffer,_s.layoutColorBuffer])}else{const _s=es.segmentsBucket;let Xs=[es.layoutNormalBuffer,es.layoutCentroidBuffer,es.layoutColorBuffer,es.layoutFloodLightDataBuffer];es.layoutFacadePaintBuffer&&(Xs=Xs.concat([es.layoutFacadeDataBuffer,es.layoutFacadeVerticalRangeBuffer,es.layoutFacadePaintBuffer])),is.draw(N,se.gl.TRIANGLES,R.depthMode,Va.disabled,R.blendMode,ue?ba.disabled:ba.backCW,Ts,B.id,es.layoutVertexBuffer,es.indexBuffer,_s,B.paint,N.transform.zoom,Ut,Xs)}};N.uploadCommonUniforms(se,Et,ct.toUnwrapped(),null,Qe),kt.buildingWithoutFacade&&Cs(kt.buildingWithoutFacade,Et),kt.buildingWithFacade&&(Xt!==Et&&N.uploadCommonUniforms(se,Xt,ct.toUnwrapped(),null,Qe),Cs(kt.buildingWithFacade,Xt))}}function kg(R,N,T,B,W,Q,se,ue,we,Te,De,Qe,Ye,tt){const ht=R.context.gl,ct=R.depthModeForSublayer(1,Yr.ReadOnly,ht.LEQUAL,!0),St=.1*(1-(kt=De))+3*kt;var kt;const Ut=R._showOverdrawInspector,Xt=Qe,Et=new ux;Ut||Wy(Et,R,N,T,B,ct,new Va({func:ht.ALWAYS,mask:255},255,255,ht.KEEP,ht.KEEP,ht.REPLACE),new $a([ht.ONE,ht.ONE,ht.ONE,ht.ONE],o.aq.transparent,[!1,!1,!1,!0],ht.MIN),ba.disabled,W,"sdf",Q,se,ue,we,Te,St,Xt,!1,void 0);{const Ts=Ut?Va.disabled:new Va({func:ht.EQUAL,mask:255},255,255,ht.KEEP,ht.DECR,ht.DECR),ds=Ut?R.colorModeForRenderPass():new $a([ht.ONE_MINUS_DST_ALPHA,ht.DST_ALPHA,ht.ONE,ht.ONE],o.aq.transparent,[!0,!0,!0,!0]);Wy(Et,R,N,T,B,ct,Ts,ds,ba.disabled,W,"color",Q,se,ue,we,Te,St,Xt,!1,void 0)}}function mw(R){return[R[0]*o.e7,R[1]*o.e7,R[2]*o.e7,0]}function Gb(R,N,T,B,W,Q,se,ue,we){const Te=B.getSource(),De=T.globeSharedBuffers;if(!De)return;let Qe,Ye,tt;if(N&&(Qe=B.getTile(N)),Te instanceof o.aV?(Ye=Te.texture,tt=o.dw(0,0,T.transform)):Qe&&N&&(Ye=Qe.texture,tt=o.dw(N.canonical.z,N.canonical.x,T.transform)),!Ye||!tt)return;R||(tt=o.cC(o.bb(),tt,[1,-1,1]));const ht=T.context,ct=ht.gl,St=W.paint.get("raster-resampling")==="nearest"?ct.NEAREST:ct.LINEAR,kt=T.colorModeForDrapableLayerRenderPass(Q),Ut=se.defines;Ut.push("GLOBE_POLES");const Xt=new Yr(ct.LEQUAL,Yr.ReadWrite,T.depthRangeFor3D),Et=Float32Array.from(T.transform.expandedFarZProjMatrix),Ts=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));T.terrain&&T.terrain.prepareDrawTile(),ht.activeTexture.set(ct.TEXTURE0),Ye.bind(St,ct.CLAMP_TO_EDGE),ht.activeTexture.set(ct.TEXTURE1),Ye.bind(St,ct.CLAMP_TO_EDGE),"useMipmap"in Ye&&ht.extTextureFilterAnisotropic&&T.transform.pitch>20&&ct.texParameterf(ct.TEXTURE_2D,ht.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ht.extTextureFilterAnisotropicMax);const[ds,Cs,es,is]=N?De.getPoleBuffers(N.canonical.z,!1):De.getPoleBuffers(0,!0),_s=W.paint.get("raster-elevation");let Xs;R?(Xs=ds,T.renderDefaultNorthPole=_s!==0):(Xs=Cs,T.renderDefaultSouthPole=_s!==0);const Ds=mw(se.mix),_n=((Un,Xn,nn,Bs,yn,jn,In,Sr,xr,gr,Kn,pa,Ea,na)=>Vu(Un,Xn,nn,Bs,new Float32Array(16),new Float32Array(9),[0,0],yn,[0,0],[0,0,0,0],1,{opacity:1,mix:0},In,[0,0],xr,2,Kn,pa,Ea,1,0,na))(T,Et,Ts,tt,o.al(T.transform.zoom),0,W,0,_s,0,Ds,se.offset,se.range,Q),pn=T.getOrCreateProgram("raster",{defines:Ut});T.uploadCommonUniforms(ht,pn,null),pn.draw(T,ct.TRIANGLES,Xt,we,kt,ue,_n,W.id,Xs,es,is)}function Wb(R){if(R.isOrthographic)return[0,0,0,0];const N=R._nearZ,T=R.projection.farthestPixelDistance(R),B=T-N,W=.2*R.height,Q=N+W;return[N,T,(Q-W-N)/B,(Q-N)/B]}function u2(R,N,T,B){if(R)return N instanceof to&&R instanceof il?N.getTextureDescriptor(R,T,!0):{texture:R.texture,mix:mw(B.mix),offset:B.offset,buffer:0,tileSize:1}}var Kb=o.e8([{name:"a_index",type:"Int16",components:1}]);class yh{constructor(N,T,B,W){const Q={width:B[0],height:B[1],data:null},se=N.gl;this.targetColorTexture=new o.T(N,Q,se.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(N,Q,se.RGBA8,{useMipmap:!1}),this.context=N,this.updateParticleTexture(T,W),this.lastInvalidatedAt=0}updateParticleTexture(N,T){if(this.particleTextureDimension===T.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const B=this.context.gl,W=T.width*T.height;this.particleTexture0=new o.T(this.context,T,B.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,T,B.RGBA8,{premultiply:!1,useMipmap:!1});const Q=new o.e9;Q.reserve(W);for(let se=0;se0){const Ds=o.ec(T.canonical,we),_n=o.ed(Ds);Ye=o.aD(new Float32Array(16),we.globeMatrix,_n),o.aD(Ye,we.projMatrix,Ye)}const tt=o.bb();tt[12]+=2*W/(o.o.devicePixelRatio*we.width),tt[13]+=2*Q/(o.o.devicePixelRatio*we.height),o.aD(Ye,tt,Ye);const ht=R.getOrCreateProgram("debug",{defines:Qe}),ct=N.getTileByID(T.key);R.terrain&&R.terrain.setupElevationDraw(ct,ht);const St=Yr.disabled,kt=Va.disabled,Ut=R.colorModeForRenderPass(),Xt="$debug";ue.activeTexture.set(Te.TEXTURE0),R.emptyTexture.bind(Te.LINEAR,Te.CLAMP_TO_EDGE),De?ct._makeGlobeTileDebugBuffers(R.context,we):ct._makeDebugTileBoundsBuffers(R.context,we.projection);const Et=ct._tileDebugBuffer||R.debugBuffer,Ts=ct._tileDebugIndexBuffer||R.debugIndexBuffer,ds=ct._tileDebugSegments||R.debugSegments;if(ht.draw(R,Te.LINE_STRIP,St,kt,Ut,ba.disabled,To(Ye,B.toPremultipliedRenderColor(null)),Xt,Et,Ts,ds,null,null,null,[ct._globeTileDebugBorderBuffer]),se){const Ds=ct.latestRawTileData,_n=Math.floor((Ds&&Ds.byteLength||0)/1024);let pn=T.canonical.toString();T.overscaledZ!==T.canonical.z&&(pn+=` => ${T.overscaledZ}`),pn+=` ${ct.state}`,pn+=` ${_n}kb`,function(Un,Xn){Un.initDebugOverlayCanvas();const nn=Un.debugOverlayCanvas,Bs=Un.context.gl,yn=Un.debugOverlayCanvas.getContext("2d");yn.clearRect(0,0,nn.width,nn.height),yn.shadowColor="white",yn.shadowBlur=2,yn.lineWidth=1.5,yn.strokeStyle="white",yn.textBaseline="top",yn.font="bold 36px Open Sans, sans-serif",yn.fillText(Xn,5,5),yn.strokeText(Xn,5,5),Un.debugOverlayTexture.update(nn),Un.debugOverlayTexture.bind(Bs.LINEAR,Bs.CLAMP_TO_EDGE)}(R,pn)}const Cs=N.getTile(T).tileSize,es=512/Math.min(Cs,512)*(T.overscaledZ/we.zoom)*.5,is=ct._tileDebugTextBuffer||R.debugBuffer,_s=ct._tileDebugTextIndexBuffer||R.quadTriangleIndexBuffer,Xs=ct._tileDebugTextSegments||R.debugSegments;ht.draw(R,Te.TRIANGLES,St,kt,$a.alphaBlended,ba.disabled,To(Ye,o.aq.transparent.toPremultipliedRenderColor(null),es),Xt,is,_s,Xs,null,null,null,[ct._globeTileDebugTextBuffer])}function e3(R,N,T,B){Ky(R,0,N+T/2,R.transform.width,T,B)}function O1(R,N,T,B){Ky(R,N-T/2,0,T,R.transform.height,B)}function Ky(R,N,T,B,W,Q){const se=R.context,ue=se.gl;ue.enable(ue.SCISSOR_TEST),ue.scissor(N*o.o.devicePixelRatio,T*o.o.devicePixelRatio,B*o.o.devicePixelRatio,W*o.o.devicePixelRatio),se.clear({color:Q}),ue.disable(ue.SCISSOR_TEST)}const ik=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Lh}=ik;function gp(R,N,T,B){R.emplaceBack(N,T,B)}class Mu{constructor(N){this.vertexArray=new o.ee,this.indices=new o.dC,gp(this.vertexArray,-1,-1,1),gp(this.vertexArray,1,-1,1),gp(this.vertexArray,-1,1,1),gp(this.vertexArray,1,1,1),gp(this.vertexArray,-1,-1,-1),gp(this.vertexArray,1,-1,-1),gp(this.vertexArray,-1,1,-1),gp(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=N.createVertexBuffer(this.vertexArray,Lh),this.indexBuffer=N.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function mx(R,N,T,B,W,Q){const se=R.context.gl,ue=N.paint.get("sky-atmosphere-color"),we=N.paint.get("sky-atmosphere-halo-color"),Te=N.paint.get("sky-atmosphere-sun-intensity"),De=((Qe,Ye,tt,ht,ct)=>({u_matrix_3f:Qe,u_sun_direction:Ye,u_sun_intensity:tt,u_color_tint_r:[ht.r,ht.g,ht.b,ht.a],u_color_tint_m:[ct.r,ct.g,ct.b,ct.a],u_luminance:5e-5}))(o.eg(o.dE(),B),W,Te,ue.toPremultipliedRenderColor(null),we.toPremultipliedRenderColor(null));se.framebufferTexture2D(se.FRAMEBUFFER,se.COLOR_ATTACHMENT0,se.TEXTURE_CUBE_MAP_POSITIVE_X+Q,N.skyboxTexture,0),T.draw(R,se.TRIANGLES,Yr.disabled,Va.disabled,$a.unblended,ba.frontCW,De,"skyboxCapture",N.skyboxGeometry.vertexBuffer,N.skyboxGeometry.indexBuffer,N.skyboxGeometry.segment)}const a5=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class ok{constructor(N){const T=new o.eh;T.emplaceBack(-1,1,1,0,0),T.emplaceBack(1,1,1,1,0),T.emplaceBack(1,-1,1,1,1),T.emplaceBack(-1,-1,1,0,1);const B=new o.dC;B.emplaceBack(0,1,2),B.emplaceBack(2,3,0),this.vertexBuffer=N.createVertexBuffer(T,a5.members),this.indexBuffer=N.createIndexBuffer(B),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const i5=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 G0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class o5{constructor(N){this.colorModeAlphaBlendedWriteRGB=new $a([1,ac,1,ac],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new $a([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new G0,this.updateNeeded=!0}update(N){const T=N.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new ok(T);const B=this.params.sizeRange,W=this.params.intensityRange,Q=function(De){const Qe=o.em(30),Ye=[];for(let tt=0;tt{const es=Q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Cs&&es.push("ALPHA_PASS");const is=N.getOrCreateProgram("globeAtmosphere",{defines:es}),_s=((Ds,_n,pn,Un,Xn,nn,Bs,yn,jn,In,Sr,xr)=>({u_frustum_tl:Ds,u_frustum_tr:_n,u_frustum_br:pn,u_frustum_bl:Un,u_horizon:Xn,u_transition:nn,u_fadeout_range:Bs,u_atmosphere_fog_color:yn.toArray01(),u_high_color:jn.toArray01(),u_space_color:In.toArray01(),u_temporal_offset:Sr,u_horizon_angle:xr}))(Q.frustumCorners.TL,Q.frustumCorners.TR,Q.frustumCorners.BR,Q.frustumCorners.BL,Q.frustumCorners.horizon,ue,St,De,Ye,ht,Ut,Ts);N.uploadCommonUniforms(B,is);const Xs=this.atmosphereBuffer;Xs&&is.draw(N,W.TRIANGLES,se,Va.disabled,Cs?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,ba.backCW,_s,Cs?"atmosphere_glow_alpha":"atmosphere_glow",Xs.vertexBuffer,Xs.indexBuffer,Xs.segments)};ds(!1),ds(!0)}drawStars(N,T){const B=o.aC(T.properties.get("star-intensity"),0,1);if(B===0)return;const W=N.context,Q=W.gl,se=N.transform,ue=N.getOrCreateProgram("stars"),we=o.bL([]);o.bN(we,we,-se._pitch),o.bM(we,we,-se.angle),o.bN(we,we,o.ap(se._center.lat)),o.ek(we,we,-o.ap(se._center.lng));const Te=o.bR(new Float32Array(16),we),De=o.aD([],se.starsProjMatrix,Te),Qe=o.eg([],Te),Ye=o.el([],Qe),tt=[0,1,0];o.dG(tt,tt,Ye),o.bJ(tt,tt,this.params.sizeMultiplier);const ht=[1,0,0];o.dG(ht,ht,Ye),o.bJ(ht,ht,this.params.sizeMultiplier);const ct=(St=tt,kt=ht,Ut=B,{u_matrix:Float32Array.from(De),u_up:St,u_right:kt,u_intensity_multiplier:Ut});var St,kt,Ut;N.uploadCommonUniforms(W,ue),this.starsVx&&this.starsIdx&&ue.draw(N,Q.TRIANGLES,Yr.disabled,Va.disabled,this.colorModeAlphaBlendedWriteRGB,ba.disabled,ct,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class ey{constructor(){this.visibleTiles=[]}updateBorders(N,T){const B=[],W=[],Q=N._getRenderableCoordinates(!1,!0);for(const we of Q){const Te=N.getTile(we);if(!Te.hasData())continue;const De=Te.getBucket(T);De&&(De.isEmpty()||(B.push(we.key),W.push({bucket:De,tileID:we.canonical})))}let se=B.length!==this.visibleTiles.length;if(!se){B.sort();for(let we=0;wewe.tileID.z-Te.tileID.z||we.tileID.x-Te.tileID.x||we.tileID.y-Te.tileID.y);for(const we of W){const Te=new Array,De=new Array,Qe=we.bucket;for(const Ye of Qe.featuresOnBorder)ue.has(Ye.featureId)?De.push(Ye.footprintIndex):(ue.add(Ye.featureId),Te.push(Ye.footprintIndex));Qe.updateFootprintHiddenFlags(Te,o.en,!1),Qe.updateFootprintHiddenFlags(De,o.en,!0)}}}function JL(R,N){const T=[...R],B=N.cameraWorldSizeForFog/N.worldSize,W=o.b9([]);return o.cC(W,W,[B,B,1]),o.aD(T,W,T),o.aD(T,N.worldToFogMatrix,T),T}function Vi(R,N,T,B,W){const Q=T.material,se=B.context,{baseColorTexture:ue,metallicRoughnessTexture:we}=Q.pbrMetallicRoughness,{normalTexture:Te,occlusionTexture:De,emissionTexture:Qe}=Q;function Ye(ht,ct,St){if(ht&&(R.push(ct),se.activeTexture.set(se.gl.TEXTURE0+St),ht.gfxTexture)){const{minFilter:kt,magFilter:Ut,wrapS:Xt,wrapT:Et}=ht.sampler;ht.gfxTexture.bindExtraParam(kt,Ut,Xt,Et)}}Ye(ue,"HAS_TEXTURE_u_baseColorTexture",5),Ye(we,"HAS_TEXTURE_u_metallicRoughnessTexture",6),Ye(Te,"HAS_TEXTURE_u_normalTexture",7),Ye(De,"HAS_TEXTURE_u_occlusionTexture",8),Ye(Qe,"HAS_TEXTURE_u_emissionTexture",9),W&&(W.texture||(W.texture=new o.dR(B.context,W.image,[W.image.height,W.image.height,W.image.height],se.gl.RGBA8)),se.activeTexture.set(se.gl.TEXTURE0+10),W.texture&&W.texture.bind(se.gl.LINEAR,se.gl.CLAMP_TO_EDGE),R.push("APPLY_LUT_ON_GPU")),T.texcoordBuffer&&(R.push("HAS_ATTRIBUTE_a_uv_2f"),N.push(T.texcoordBuffer)),T.colorBuffer&&(R.push(T.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),N.push(T.colorBuffer)),T.normalBuffer&&(R.push("HAS_ATTRIBUTE_a_normal_3f"),N.push(T.normalBuffer)),T.pbrBuffer&&(R.push("HAS_ATTRIBUTE_a_pbr"),R.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),N.push(T.pbrBuffer)),Q.alphaMode!=="OPAQUE"&&Q.alphaMode!=="MASK"||R.push("UNPREMULT_TEXTURE_IN_SHADER"),Q.defined||R.push("DIFFUSE_SHADED");const tt=B.shadowRenderer;tt&&(R.push("RENDER_SHADOWS"),tt.useNormalOffset&&R.push("NORMAL_OFFSET"))}function l5(R,N,T,B,W,Q){const se=R.modelOpacity,ue=N.context,we=new Yr(N.context.gl.LEQUAL,R.isLightMesh?Yr.ReadOnly:Yr.ReadWrite,N.depthRangeFor3D),Te=N.transform,De=R.mesh,Qe=De.material,Ye=Qe.pbrMetallicRoughness,tt=N.style.fog;let ht;ht=N.transform.projection.zAxisUnit==="pixels"?[...R.nodeModelMatrix]:o.aD([],B.zScaleMatrix,R.nodeModelMatrix),o.aD(ht,B.negCameraPosMatrix,ht);const ct=o.b7([],ht);o.e6(ct,ct);const St=T.paint.get("model-color-use-theme").constantOr("default")==="none",kt=T.paint.get("model-emissive-strength").constantOr(0),Ut=Pc(new Float32Array(R.worldViewProjection),new Float32Array(ht),new Float32Array(ct),null,N,se,Ye.baseColorFactor,Qe.emissiveFactor,Ye.metallicFactor,Ye.roughnessFactor,Qe,kt,T,void 0,void 0,R.materialOverride,R.modelColor),Xt={defines:[]},Et=[],Ts=N.shadowRenderer;Ts&&(Ts.useNormalOffset=!1),Vi(Xt.defines,Et,De,N,St?null:T.lut);let ds=null;if(tt){const is=JL(R.nodeModelMatrix,N.transform);if(ds=new Float32Array(is),Te.projection.name!=="globe"){const _s=De.aabb.min,Xs=De.aabb.max,[Ds,_n]=tt.getOpacityForBounds(is,_s[0],_s[1],Xs[0],Xs[1]);Xt.overrideFog=Ds>=Hr||_n>=Hr}}const Cs=Gd(N,T.paint.get("model-cutoff-fade-range"));Cs.shouldRenderCutoff&&Xt.defines.push("RENDER_CUTOFF");const es=N.getOrCreateProgram("model",Xt);N.uploadCommonUniforms(ue,es,null,ds,Cs),N.renderPass!=="shadow"&&Ts&&Ts.setupShadowsFromMatrix(R.nodeModelMatrix,es),es.draw(N,ue.gl.TRIANGLES,we,W,Q,De.material.doubleSided?ba.disabled:ba.backCCW,Ut,T.id,De.vertexBuffer,De.indexBuffer,De.segments,T.paint,N.transform.zoom,void 0,Et)}function t3(R,N){return R.style._importedAsBasemap?"basemap":N.scope}function nT(R,N,T,B,W,Q,se,ue,we,Te){const De=R.transform,Qe=!!N.isGeometryBloom&&N.isGeometryBloom;if(Qe&&R.renderPass==="shadow")return;const Ye=De.projection.name==="globe"?o.ev(T,De):[...T];o.aD(Ye,Ye,N.globalMatrix);const tt=o.aD([],B,Ye);if(N.meshes)for(const ht of N.meshes){const ct=ue.get(ht.material.name);if(ct&&ct.opacity<=0)continue;if(ht.material.alphaMode!=="BLEND"){se.push({mesh:ht,depth:0,modelIndex:W,worldViewProjection:tt,nodeModelMatrix:Ye,isLightMesh:Qe,materialOverride:ct,modelOpacity:we,modelColor:Te,node:N,modelMatrix:T});continue}const St=o.ah([],ht.centroid,tt);!De.isOrthographic&&St[2]<=0||Q.push({mesh:ht,depth:St[2],modelIndex:W,worldViewProjection:tt,nodeModelMatrix:Ye,isLightMesh:Qe,materialOverride:ct,modelOpacity:we,modelColor:Te,node:N,modelMatrix:T})}if(N.children)for(const ht of N.children)nT(R,ht,T,B,W,Q,se,ue,we,Te)}function c5(R,N,T,B){const W=T.shadowRenderer;if(!W)return;const Q=W.getShadowPassDepthMode(),se=W.calculateShadowPassMatrixFromMatrix(N),ue=Ph(se);T.getOrCreateProgram("modelDepth").draw(T,T.context.gl.TRIANGLES,Q,Va.disabled,$a.disabled,ba.disabled,ue,B.id,R.vertexBuffer,R.indexBuffer,R.segments,B.paint,T.transform.zoom,void 0,void 0)}function rT(R,N,T,B){const W=function(De,Qe){if(Qe.footprintDebugMesh)return Qe.footprintDebugMesh;if(!Qe.footprint)return null;const Ye=De.context,tt=Qe.footprint.vertices,ht=Qe.footprint.indices,ct=new o.dB;ct.reserve(tt.length);for(const _s of tt)ct.emplaceBack(_s.x,_s.y);const St=new o.dC;St.reserve(ht.length);for(let _s=0;_s0){const Ye=Q.terrain,tt=Ye.findDEMTileFor(ue);tt&&tt.dem?we=o.ex.create(Ye,ue,tt):Qe=0}if(Qe===0&&(se.terrainElevationMin=0,se.terrainElevationMax=0),Qe===se.validForExaggeration&&(Qe===0||we&&we._demTile&&we._demTile.tileID===se.validForDEMTile.id&&we._dem._timestamp===se.validForDEMTile.timestamp))return!1;for(const Ye in se.instancesPerModel){const tt=se.instancesPerModel[Ye];for(let ht=0;htTe&&(Te=tt.max)}const De=o.aC(B.x,Q,se)-B.x,Qe=o.aC(B.y,ue,we)-B.y,Ye=o.bU(Te,N.center.lat)-B.z;return N._zoomFromMercatorZ(Math.sqrt(De*De+Qe*Qe+Ye*Ye))}function ld(R,N,T,B,W,Q,se){const ue=R.context,we=R.renderPass==="shadow",Te=R.shadowRenderer,De=we&&Te?Te.getShadowPassDepthMode():new Yr(ue.gl.LEQUAL,Yr.ReadWrite,R.depthRangeFor3D),Qe=R.isTileAffectedByFog(Q),Ye=R.transform.projection.name==="globe";if(T.meshes)for(const tt of T.meshes){const ht=Ye?[]:["MODEL_POSITION_ON_GPU"],ct=[];let St,kt,Ut;const Xt=!Ye&&B.instancedDataArray.length>20;Xt&&ht.push("INSTANCED_ARRAYS");const Et=Gd(R,N.paint.get("model-cutoff-fade-range"));if(Et.shouldRenderCutoff&&ht.push("RENDER_CUTOFF"),we&&Te)St=R.getOrCreateProgram("modelDepth",{defines:ht}),kt=Ph(se.shadowTileMatrix,se.shadowTileMatrix,Float32Array.from(T.globalMatrix)),Ut=$a.disabled;else{Vi(ht,ct,tt,R,N.paint.get("model-color-use-theme").constantOr("default")==="none"?null:N.lut),St=R.getOrCreateProgram("model",{defines:ht,overrideFog:Qe});const ds=tt.material,Cs=ds.pbrMetallicRoughness,es=N.paint.get("model-opacity").constantOr(1),is=N.paint.get("model-emissive-strength").constantOr(0);kt=Pc(Q.expandedProjMatrix,Float32Array.from(T.globalMatrix),new Float32Array(16),null,R,es,Cs.baseColorFactor,ds.emissiveFactor,Cs.metallicFactor,Cs.roughnessFactor,ds,is,N,W),Te&&(se.shadowUniformsInitialized?St.setShadowUniformValues(ue,Te.getShadowUniformValues()):(Te.setupShadows(Q.toUnwrapped(),St,"model-tile"),se.shadowUniformsInitialized=!0)),Ut=Et.shouldRenderCutoff||es<1||ds.alphaMode!=="OPAQUE"?$a.alphaBlended:$a.unblended}R.uploadCommonUniforms(ue,St,Q.toUnwrapped(),null,Et);const Ts=tt.material.doubleSided?ba.disabled:ba.backCCW;if(Xt)ct.push(B.instancedDataBuffer),St.draw(R,ue.gl.TRIANGLES,De,Va.disabled,Ut,Ts,kt,N.id,tt.vertexBuffer,tt.indexBuffer,tt.segments,N.paint,R.transform.zoom,void 0,ct,B.instancedDataArray.length);else{const ds=we?"u_instance":"u_normal_matrix";for(let Cs=0;Cswe[1]?se:we,Q[0]=T.max[0],se=o.aE(o.bE(),Q,W),ue=se[1]we[1]?se:we,Q[1]=T.min[1],se=o.aE(o.bE(),Q,W),ue=se[1]we[1]?se:we;const Te=o.aC(B[0],0,1),De=100*N.pixelsPerMeter*o.aC(B[1],0,1),Qe=o.aC(B[2],0,1),Ye=o.ey(o.bE(),ue,we,Te),tt=Math.tan(.5*N.fovX),ht=-Ye[2]*tt;if(De===0)return Ye[1]<-Math.abs(ht)?Qe:1;const ct=(-Math.abs(ht)-Ye[1])/De,St=(Ut,Xt,Et)=>(1-Et)*Ut+Et*Xt,kt=o.aC(St(1,Qe,ct),Qe,1);return St(1,kt,o.aC((N.pitch-20)/20,0,1))}class iT{}class eI{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(N,T,B){{const Qe=this._storage.get(T.id);if(Qe)return Qe.lastUsedFrameIdx=N,Qe.buf}const W=B.gl,Q=W.getBufferParameter(W.ELEMENT_ARRAY_BUFFER,W.BUFFER_SIZE),se=new ArrayBuffer(Q),ue=new Int16Array(se);W.getBufferSubData(W.ELEMENT_ARRAY_BUFFER,0,new Int16Array(se));const we=new o.eA;for(let Qe=0;Qe30&&(B.buf.destroy(),this._storage.delete(T))}destroy(){for(const[N,T]of this._storage)T.buf.destroy(),this._storage.delete(N)}}class tI{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const ck=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 sI{constructor(N){this.revealStart=11,this.revealRange=2}}const oT=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class Dz{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(N,T){const B=N.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const se=new o.eB,ue=new o.dC;se.emplaceBack(-1,-1),se.emplaceBack(1,-1),se.emplaceBack(1,1),se.emplaceBack(-1,1),ue.emplaceBack(0,1,2),ue.emplaceBack(0,2,3),this.vignetteVx=N.context.createVertexBuffer(se,oT.members),this.vignetteIdx=N.context.createIndexBuffer(ue)}const W=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){N.uploadCommonUniforms(N.context,B);const se={u_vignetteShape:(Q={vignetteShape:[T.start,T.range,Math.pow(10,T.fadePower)],vignetteColor:[T.color.r,T.color.g,T.color.b,T.color.a*T.strength]}).vignetteShape,u_vignetteColor:Q.vignetteColor};B.draw(N,N.context.gl.TRIANGLES,Yr.disabled,Va.disabled,$a.alphaBlended,ba.disabled,se,"vignette",this.vignetteVx,this.vignetteIdx,W)}var Q}}class lT{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(N,T){const B=N.getFreeCameraOptions().position,W=B.toAltitude(),Q=B.toLngLat(),se=o.ap(Q.lng),ue=o.ap(Q.lat),we=N.pixelsPerMeter/T,Te=se*o.eD,De=o.eD*Math.log(Math.tan(Math.PI/4+ue/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 Qe=-this._offsetYPrev+De,Ye=-this._elevationPrev+W;this._accumulatedOffsetX+=(-this._offsetXPrev+Te)*we,this._accumulatedOffsetY+=Qe*we,this._accumulatedElevation+=Ye*we,this._offsetXPrev=Te,this._offsetYPrev=De,this._elevationPrev=W}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function ie(R,N){return[-(R[0]-Math.floor(R[0]/N)*N),-(R[1]-Math.floor(R[1]/N)*N),-(R[2]-Math.floor(R[2]/N)*N)]}function de(R){const N=o.em(1323123451230),T=[];for(let B=0;B Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(N){const T=N.context;if(!this.particlesVx){const B=de(this.particlesCount),W=new o.eE,Q=new o.dC;let se=0;const ue=o.em(1323123451230);for(let we=0;weB)return;const W=Re(0,1,T.revealStart,T.revealStart+T.revealRange,B);if(!this.particlesVx||!this.particlesIdx)return;const Q=structuredClone(this._params);let se=[-Q.direction.x,Q.direction.y,-100];o.ay(se,se);const ue=structuredClone(this._vignetteParams);ue.strength*=W,Q.overrideStyleParameters||(Q.intensity=N.style.rain.state.density,Q.timeFactor=N.style.rain.state.intensity,Q.color=structuredClone(N.style.rain.state.color),se=structuredClone(N.style.rain.state.direction),Q.screenThinning.intensity=N.style.rain.state.centerThinning,Q.dropletSizeX=N.style.rain.state.dropletSize[0],Q.dropletSizeYScale=N.style.rain.state.dropletSize[1]/N.style.rain.state.dropletSize[0],Q.distortionStrength=100*N.style.rain.state.distortionStrength,ue.strength=1,ue.color=structuredClone(N.style.rain.state.vignetteColor));const we=this.updateOnRender(N,Q.timeFactor),Te=N.context,De=Te.gl,Qe=N.transform;this.screenTexture&&this.screenTexture.size[0]===N.width&&this.screenTexture.size[1]===N.height||(this.screenTexture=new o.T(Te,{width:N.width,height:N.height,data:null},De.RGBA8)),Q.distortionStrength>0&&(Te.activeTexture.set(De.TEXTURE0),this.screenTexture.bind(De.LINEAR,De.CLAMP_TO_EDGE),De.copyTexSubImage2D(De.TEXTURE_2D,0,0,0,0,0,N.width,N.height));const Ye=N.getOrCreateProgram("rainParticle");N.uploadCommonUniforms(Te,Ye),Te.activeTexture.set(De.TEXTURE0),this.screenTexture.bind(De.LINEAR,De.CLAMP_TO_EDGE);const tt=[Q.color.r,Q.color.g,Q.color.b,Q.color.a],ht=(ct,St)=>{const kt=ie(this._movement.getPosition(),ct),Ut=Q.dropletSizeX,Xt=Q.dropletSizeX*Q.dropletSizeYScale,Et=N.width/2,Ts=N.height/2,ds=Re(0,Q.screenThinning.start,0,1,Q.screenThinning.intensity),Cs=Re(.001,Q.screenThinning.range,0,1,Q.screenThinning.intensity),es=Re(0,Q.screenThinning.particleOffset,0,1,Q.screenThinning.intensity),is=(_s={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:kt,velocityConeAperture:Q.velocityConeAperture,velocity:Q.velocity,boxSize:ct,rainDropletSize:[Ut,Xt],distortionStrength:Q.distortionStrength,rainDirection:se,color:tt,screenSize:[Qe.width,Qe.height],thinningCenterPos:[Et,Ts],thinningShape:[ds,Cs,Math.pow(10,Q.screenThinning.fadePower)],thinningAffectedRatio:Q.screenThinning.affectedRatio,thinningParticleOffset:es,shapeDirectionalPower:Q.shapeDirPower,shapeNormalPower:Q.shapeNormalPower,mode:St?0:1},{u_modelview:Float32Array.from(_s.modelview),u_projection:Float32Array.from(_s.projection),u_time:_s.time,u_cam_pos:_s.camPos,u_texScreen:0,u_velocityConeAperture:_s.velocityConeAperture,u_velocity:_s.velocity,u_boxSize:_s.boxSize,u_rainDropletSize:_s.rainDropletSize,u_distortionStrength:_s.distortionStrength,u_rainDirection:_s.rainDirection,u_color:_s.color,u_screenSize:_s.screenSize,u_thinningCenterPos:_s.thinningCenterPos,u_thinningShape:_s.thinningShape,u_thinningAffectedRatio:_s.thinningAffectedRatio,u_thinningParticleOffset:_s.thinningParticleOffset,u_shapeDirectionalPower:_s.shapeDirectionalPower,u_shapeNormalPower:_s.shapeNormalPower,u_mode:_s.mode});var _s;const Xs=Math.round(Q.intensity*this.particlesCount),Ds=o.dy.simpleSegment(0,0,4*Xs,2*Xs);Ye.draw(N,De.TRIANGLES,Yr.disabled,Va.disabled,$a.alphaBlended,ba.disabled,is,"rain_particles",this.particlesVx,this.particlesIdx,Ds)};Q.distortionStrength>0&&ht(Q.boxSize,!0),ht(Q.boxSize,!1),this._vignette.draw(N,ue)}}const Pt=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 Hs extends st{constructor(N){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 sI("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(N){const T=N.context;if(!this.particlesVx){const B=de(this.particlesCount),W=new o.eF,Q=new o.dC;let se=0;const ue=o.em(1323123451230);for(let we=0;wese)return;const ue=Re(0,1,Q.revealStart,Q.revealStart+Q.revealRange,se);W.strength*=ue,T.overrideStyleParameters||(T.intensity=N.style.snow.state.density,T.timeFactor=N.style.snow.state.intensity,T.color=structuredClone(N.style.snow.state.color),B=structuredClone(N.style.snow.state.direction),T.screenThinning.intensity=N.style.snow.state.centerThinning,T.billboardSize=2.79*N.style.snow.state.flakeSize,W.strength=1,W.color=structuredClone(N.style.snow.state.vignetteColor));const we=this.updateOnRender(N,T.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Te=N.context,De=Te.gl,Qe=N.transform,Ye=N.getOrCreateProgram("snowParticle");N.uploadCommonUniforms(Te,Ye),((tt,ht,ct)=>{const St=ie(this._movement.getPosition(),tt),kt=Qe.width/2,Ut=Qe.height/2,Xt=Re(0,ct.screenThinning.start,0,1,ct.screenThinning.intensity),Et=Re(.001,ct.screenThinning.range,0,1,ct.screenThinning.intensity),Ts=Re(0,ct.screenThinning.particleOffset,0,1,ct.screenThinning.intensity),ds=(Cs={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:St,velocityConeAperture:ct.velocityConeAperture,velocity:ct.velocity,horizontalOscillationRadius:ct.horizontalOscillationRadius,horizontalOscillationRate:ct.horizontalOscillationRate,boxSize:tt,billboardSize:1*ct.billboardSize,simpleShapeParameters:[ct.shapeFadeStart,ct.shapeFadePower],screenSize:[Qe.width,Qe.height],thinningCenterPos:[kt,Ut],thinningShape:[Xt,Et,Math.pow(10,ct.screenThinning.fadePower)],thinningAffectedRatio:ct.screenThinning.affectedRatio,thinningParticleOffset:Ts,color:[ct.color.r,ct.color.g,ct.color.b,ct.color.a],direction:B},{u_modelview:Float32Array.from(Cs.modelview),u_projection:Float32Array.from(Cs.projection),u_time:Cs.time,u_cam_pos:Cs.camPos,u_velocityConeAperture:Cs.velocityConeAperture,u_velocity:Cs.velocity,u_horizontalOscillationRadius:Cs.horizontalOscillationRadius,u_horizontalOscillationRate:Cs.horizontalOscillationRate,u_boxSize:Cs.boxSize,u_billboardSize:Cs.billboardSize,u_simpleShapeParameters:Cs.simpleShapeParameters,u_screenSize:Cs.screenSize,u_thinningCenterPos:Cs.thinningCenterPos,u_thinningShape:Cs.thinningShape,u_thinningAffectedRatio:Cs.thinningAffectedRatio,u_thinningParticleOffset:Cs.thinningParticleOffset,u_particleColor:Cs.color,u_direction:Cs.direction});var Cs;const es=Math.round(ct.intensity*this.particlesCount),is=o.dy.simpleSegment(0,0,4*es,2*es);this.particlesVx&&this.particlesIdx&&Ye.draw(N,De.TRIANGLES,Yr.disabled,Va.disabled,$a.alphaBlended,ba.disabled,ds,"snow_particles",this.particlesVx,this.particlesIdx,is)})(T.boxSize,0,T),this._vignette.draw(N,W)}}const Qn={symbol:function(R,N,T,B,W){if(R.renderPass!=="translucent")return;const Q=Va.disabled,se=R.colorModeForRenderPass(),ue=T.layout.get("text-variable-anchor"),we=T.layout.get("text-size-scale-range"),Te=o.aC(R.scaleFactor,we[0],we[1]);ue&&function(Ye,tt,ht,ct,St,kt,Ut,Xt){const Et=tt.transform,Ts=St==="map",ds=kt==="map";for(const Cs of Ye){const es=ct.getTile(Cs),is=es.getBucket(ht);if(!is||!is.text||!is.text.segments.get().length)continue;const _s=o.bj(is.textSizeData,Et.zoom,Xt),Xs=Jh(Cs,is.getProjection(),Et),Ds=Et.calculatePixelsToTileUnitsMatrix(es),_n=mc(Xs,es.tileID.canonical,ds,Ts,Et,is.getProjection(),Ds),pn=is.hasIconTextFit()&&is.hasIconData();_s&&od(is,Ts,ds,Ut,Et,_n,Cs,Math.pow(2,Et.zoom-es.tileID.overscaledZ),_s,pn)}}(B,R,T,N,T.layout.get("text-rotation-alignment"),T.layout.get("text-pitch-alignment"),W,Te);const De=T.paint.get("icon-opacity").constantOr(1)!==0,Qe=T.paint.get("text-opacity").constantOr(1)!==0;T.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(De||Qe)?xp(R,N,T,B,Q,se):(De&&xp(R,N,T,B,Q,se,{onlyIcons:!0}),Qe&&xp(R,N,T,B,Q,se,{onlyText:!0})),N.map.showCollisionBoxes&&(kr(R,N,T,B,T.paint.get("text-translate"),T.paint.get("text-translate-anchor"),!0),kr(R,N,T,B,T.paint.get("icon-translate"),T.paint.get("icon-translate-anchor"),!1))},circle:function(R,N,T,B){if(R.renderPass!=="translucent")return;const W=T.paint.get("circle-opacity"),Q=T.paint.get("circle-stroke-width"),se=T.paint.get("circle-stroke-opacity"),ue=T.layout.get("circle-sort-key").constantOr(1)!==void 0,we=T.paint.get("circle-emissive-strength");if(W.constantOr(1)===0&&(Q.constantOr(1)===0||se.constantOr(1)===0))return;const Te=R.context,De=Te.gl,Qe=R.transform,Ye=!(!R.terrain||!R.terrain.enabled),tt=T.layout.get("circle-elevation-reference"),ht=R.depthModeForSublayer(0,Yr.ReadOnly),ct=new Yr(R.context.gl.LEQUAL,Yr.ReadOnly,R.depthRangeFor3D),St=tt==="none"||Ye?ht:ct,kt=Va.disabled,Ut=R.colorModeForDrapableLayerRenderPass(we),Xt=Qe.projection.name==="globe",Et=[o.aH(Qe.center.lng),o.aL(Qe.center.lat)],Ts=[];for(let Cs=0;CsCs.sortKey-es.sortKey);const ds={useDepthForOcclusion:Qe.depthOcclusionForSymbolsAndCircles};for(const Cs of Ts){const{programConfiguration:es,program:is,layoutVertexBuffer:_s,dynamicBuffers:Xs,indexBuffer:Ds,uniformValues:_n,tile:pn}=Cs.state,Un=Cs.segments;R.terrain&&R.terrain.setupElevationDraw(pn,is,ds),R.uploadCommonUniforms(Te,is,pn.tileID.toUnwrapped()),is.draw(R,De.TRIANGLES,St,kt,Ut,ba.disabled,_n,T.id,_s,Ds,Un,T.paint,Qe.zoom,es,Xs)}},heatmap:function(R,N,T,B){if(T.paint.get("heatmap-opacity")!==0)if(R.renderPass==="offscreen"){const W=R.context,Q=W.gl,se=Va.disabled,ue=new $a([Q.ONE,Q.ONE,Q.ONE,Q.ONE],o.aq.transparent,[!0,!0,!0,!0]),we=R.transform.projection.name==="globe"?.5:.25;T.heatmapFbo=Bp.createWithTexture(W,T.heatmapFbo,R.width*we,R.height*we),W.clear({color:o.aq.transparent});const Te=R.transform,De=Te.projection.name==="globe",Qe=De?["PROJECTION_GLOBE_VIEW"]:[],Ye=De?ba.frontCCW:ba.disabled,tt=[o.aH(Te.center.lng),o.aL(Te.center.lat)];for(let ht=0;ht({u_image:0,u_color_ramp:1,u_opacity:Qe.paint.get("heatmap-opacity")}))(0,Q),Q.id,W.viewportBuffer,W.quadTriangleIndexBuffer,W.viewportSegments,Q.paint,W.transform.zoom)}(R,T))},line:function(R,N,T,B){const W=T.paint.get("line-opacity"),Q=T.paint.get("line-width");if(W.constantOr(1)===0||Q.constantOr(1)===0)return;const se=T.paint.get("line-blend-mode");if(se!=="default"&&R.transform.projection.name!=="globe")return R.terrain&&R.terrain.renderingToTexture?void function(ue,we,Te,De,Qe){if(ue.renderPass!=="translucent")return;const Ye=ue.context,tt=Ye.gl,ht=ue.terrain;if(!ht)return;const ct=Ye.bindFramebuffer.current,St=ue.emissiveMode==="mrt-fallback";Te.lineBlendDrapeFbo=Bp.createWithTexture(Ye,Te.lineBlendDrapeFbo,ht.drapeBufferSize[0],ht.drapeBufferSize[1],!0),Te.lineBlendDrapeStencil=Te.lineBlendDrapeFbo._stencilRbo,St&&tt.drawBuffers([tt.COLOR_ATTACHMENT0]),Ye.clear({color:vf[Qe].clearColor,depth:1,stencil:0});const kt=ue.currentStencilSource,Ut=ue._tileClippingMaskIDs,Xt=ue.nextStencilID;ue.currentStencilSource=void 0,ue._tileClippingMaskIDs={},ue.nextStencilID=1;const Et=ue._terrain;ue._terrain=null,ue._renderTileClippingMasks(Te,we,De),Xu(ue,we,Te,De,vf[Qe].colorMode,!0),ue._terrain=Et,ue.currentStencilSource=kt,ue._tileClippingMaskIDs=Ut,ue.nextStencilID=Xt,Ye.bindFramebuffer.set(ct),St&&tt.drawBuffers([tt.COLOR_ATTACHMENT0,tt.COLOR_ATTACHMENT1]);const Ts=ht.drapeBufferSize;Ye.viewport.set([0,0,Ts[0],Ts[1]]);const ds=Te.lineBlendDrapeFbo;if(!ds)return;Ye.activeTexture.set(tt.TEXTURE0),tt.bindTexture(tt.TEXTURE_2D,ds.colorAttachment0.get());const Cs=Qe==="additive"?1:Te.paint.get("line-opacity").constantOr(1),es=Te.paint.get("line-emissive-strength").constantOr(0),is=Qe==="additive"?ue.colorModeForDrapableLayerRenderPass(es):vf[Qe].colorMode;ue.getOrCreateProgram("lineBlendComposite").draw(ue,tt.TRIANGLES,Yr.disabled,Va.disabled,is,ba.disabled,bc(0,Cs,vf[Qe].compositeUniformValue),Te.id,ue.viewportBuffer,ue.quadTriangleIndexBuffer,ue.viewportSegments,Te.paint,ue.transform.zoom)}(R,N,T,B,se):R.renderPass==="offscreen"?void function(ue,we,Te,De,Qe){const Ye=ue.context,tt=Math.ceil(ue.width),ht=Math.ceil(ue.height);Te.lineBlendFbo=Bp.createWithTexture(Ye,Te.lineBlendFbo,tt,ht,!0),Te.lineBlendStencil=Te.lineBlendFbo._stencilRbo,Ye.clear({color:vf[Qe].clearColor,depth:1,stencil:0});const ct=ue.currentStencilSource,St=ue._tileClippingMaskIDs,kt=ue.nextStencilID;ue.currentStencilSource=void 0,ue._tileClippingMaskIDs={},ue.nextStencilID=1,ue._renderTileClippingMasks(Te,we,De);const Ut=ue.renderPass;ue.renderPass="translucent",Xu(ue,we,Te,De,vf[Qe].colorMode),ue.renderPass=Ut,ue.currentStencilSource=ct,ue._tileClippingMaskIDs=St,ue.nextStencilID=kt,Ye.viewport.set([0,0,ue.width,ue.height])}(R,N,T,B,se):R.renderPass==="translucent"?void function(ue,we,Te){const De=ue.context,Qe=De.gl,Ye=we.lineBlendFbo;if(!Ye)return;De.activeTexture.set(Qe.TEXTURE0),Qe.bindTexture(Qe.TEXTURE_2D,Ye.colorAttachment0.get());const tt=Te==="additive"?1:we.paint.get("line-opacity").constantOr(1),ht=Te==="additive"?ue.colorModeForDrapableLayerRenderPass(we.paint.get("line-emissive-strength").constantOr(0)):vf[Te].colorMode;ue.getOrCreateProgram("lineBlendComposite").draw(ue,Qe.TRIANGLES,Yr.disabled,Va.disabled,ht,ba.disabled,bc(0,tt,vf[Te].compositeUniformValue),we.id,ue.viewportBuffer,ue.quadTriangleIndexBuffer,ue.viewportSegments,we.paint,ue.transform.zoom)}(R,T,se):void 0;R.renderPass==="translucent"&&Xu(R,N,T,B)},fill:function(R,N,T,B){const W=T.paint.get("fill-color"),Q=T.paint.get("fill-opacity");if(Q.constantOr(1)===0)return;const se=T.paint.get("fill-emissive-strength"),ue=R.colorModeForDrapableLayerRenderPass(se),we=T.paint.get("fill-pattern"),Te=R.opaquePassEnabledForLayer()&&!we.constantOr(1)&&W.constantOr(o.aq.transparent).a===1&&Q.constantOr(0)===1?"opaque":"translucent";let De="none";T.layout.get("fill-elevation-reference")!=="none"?De="road":T.paint.get("fill-z-offset").constantOr(1)!==0&&(De="offset");const Qe=!(!R.terrain||!R.terrain.enabled),Ye={painter:R,sourceCache:N,layer:T,coords:B,colorMode:ue,elevationType:De,terrainEnabled:Qe,pass:Te};if(R.renderPass==="shadow")return void(R.shadowRenderer&&De==="road"&&!Qe&&function(ht){const{painter:ct,sourceCache:St,layer:kt,coords:Ut}=ht,Xt=ct.context.gl,Et=ht.painter.shadowRenderer;for(const Ts of Ut){const ds=St.getTile(Ts),Cs=ds.getBucket(kt);if(!Cs)continue;const es=Cs.elevatedStructures;if(!es||!es.shadowCasterSegments||es.shadowCasterSegments.segments[0].primitiveLength===0)continue;ct.prepareDrawTile();const is=Cs.bufferData.programConfigurations.get(kt.id),_s=ct.isTileAffectedByFog(Ts),Xs=ct.getOrCreateProgram("elevatedStructuresDepth",{config:is,overrideFog:_s}),Ds=Et.calculateShadowPassMatrixFromTile(ds.tileID.toUnwrapped());ct.uploadCommonUniforms(ct.context,Xs,Ts.toUnwrapped());const _n=Oi(Ds,0);Xs.draw(ct,Xt.TRIANGLES,Et.getShadowPassDepthMode(),Va.disabled,$a.disabled,ba.disabled,_n,kt.id,es.vertexBuffer,es.indexBuffer,es.shadowCasterSegments,kt.paint,ct.transform.zoom,is)}}(Ye));const tt=R.emissiveMode==="mrt-fallback";if(De!=="offset"){if(D1(Ye,!1,tt),De==="road"){const ht=!Qe&&R.renderPass==="translucent";ht&&Hb(R,N,T,B,"geometry"),D1(Ye,!0,tt,Va.disabled),ht&&function(ct){const{painter:St,sourceCache:kt,layer:Ut,coords:Xt,colorMode:Et}=ct,Ts=St.context.gl,ds=ct.painter.shadowRenderer,Cs=!!ds&&ds.enabled,es=new Yr(St.context.gl.LEQUAL,Yr.ReadOnly,St.depthRangeFor3D);let is=[0,0,0];if(Cs){const Xs=St.style.directionalLight,Ds=St.style.ambientLight;Xs&&Ds&&(is=_m(St.style,Xs,Ds))}const _s=Xs=>{for(const Ds of Xt){const _n=kt.getTile(Ds),pn=_n.getBucket(Ut);if(!pn)continue;const Un=pn.elevatedStructures;if(!Un)continue;let Xn,nn;if(Xs?(Xn=Un.renderableBridgeSegments,nn=Un.bridgeProgramConfigurations.get(Ut.id)):(Xn=Un.renderableTunnelSegments,nn=Un.tunnelProgramConfigurations.get(Ut.id)),!Xn||Xn.segments[0].primitiveLength===0)continue;nn.updatePaintBuffers(),St.prepareDrawTile();const Bs=St.isTileAffectedByFog(Ds),yn=[];Cs&&yn.push("RENDER_SHADOWS","NORMAL_OFFSET");const jn=St.getOrCreateProgram("elevatedStructures",{config:nn,overrideFog:Bs,defines:yn}),In=St.translatePosMatrix(Ds.projMatrix,_n,Ut.paint.get("fill-translate"),Ut.paint.get("fill-translate-anchor"));Cs&&ds.setupShadows(_n.tileID.toUnwrapped(),jn,"vector-tile");const Sr=Al(In,is);St.uploadCommonUniforms(St.context,jn,Ds.toUnwrapped()),jn.draw(St,Ts.TRIANGLES,es,Va.disabled,Et,ba.backCCW,Sr,Ut.id,Un.vertexBuffer,Un.indexBuffer,Xn,Ut.paint,St.transform.zoom,nn,[Un.vertexBufferNormal])}};_s(!0),_s(!1)}(Ye)}}else D1(Ye,!1,tt,R.stencilModeFor3D())},"fill-extrusion":function(R,N,T,B){const W=T.paint.get("fill-extrusion-opacity"),Q=R.context,se=Q.gl,ue=R.terrain,we=ue&&ue.renderingToTexture;if(W===0)return;const Te=R.emissiveMode==="mrt-fallback",De=R.conflationActive&&R.style.isLayerClipped(T,N.getSource()),Qe=R.style.order.indexOf(T.fqid);if(De&&function(Ye,tt,ht,ct,St){for(const kt of ct){const Ut=tt.getTile(kt).getBucket(ht);Ut&&(Ut.updateReplacement(kt,Ye.replacementSource,St),Ut.uploadCentroid(Ye.context))}}(R,N,T,B,Qe),ue||De)for(const Ye of B){const tt=N.getTile(Ye).getBucket(T);tt&&V0(R.context,N,Ye,tt,T,ue,De)}if(R.renderPass==="shadow"&&R.shadowRenderer){if(ue&&W<.65&&T._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const Ye=R.shadowRenderer.getShadowPassDepthMode();$p(R,N,T,B,Ye,Va.disabled,$a.disabled,De)}else if(R.renderPass==="translucent"){const Ye=!T.paint.get("fill-extrusion-pattern").constantOr(1),tt=T.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!we&&tt.a!==0){const ht=new Yr(R.context.gl.LEQUAL,Yr.ReadWrite,R.depthRangeFor3D);W===1&&Ye?$p(R,N,T,B,ht,Va.disabled,$a.unblended,De):($p(R,N,T,B,ht,Va.disabled,$a.disabled,De),$p(R,N,T,B,ht,R.stencilModeFor3D(),R.colorModeForRenderPass(),De),R.resetStencilClippingMasks())}if(R.style.enable3dLights()&&Ye&&(!ue&&R.transform.projection.name!=="globe"||we)){const ht=T.paint.get("fill-extrusion-opacity"),ct=T.paint.get("fill-extrusion-ambient-occlusion-intensity"),St=T.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),kt=T.paint.get("fill-extrusion-flood-light-intensity"),Ut=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Xt=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ut?null:T.lut).toArray01().slice(0,3),Et=ct>0&&St>0,Ts=kt>0,ds=(is,_s,Xs)=>(1-Xs)*is+Xs*_s,Cs=new ux;Cs.translate=T.paint.get("fill-extrusion-translate"),Cs.translateAnchor=T.paint.get("fill-extrusion-translate-anchor"),Cs.edgeRadius=T.layout.get("fill-extrusion-edge-radius"),Cs.cutoffFadeRange=T.paint.get("fill-extrusion-cutoff-fade-range");const es=is=>{const _s=R.depthModeForSublayer(1,Yr.ReadOnly,se.LEQUAL,!0),Xs=T.paint.get(is?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Ds=ds(.1,3,Xs),_n=R._showOverdrawInspector;if(!_n){const pn=new Va({func:se.ALWAYS,mask:255},255,255,se.KEEP,se.KEEP,se.REPLACE),Un=new $a([se.ONE,se.ONE,se.ONE,se.ONE],o.aq.transparent,[!1,!1,!1,!0],se.MIN);Wy(Cs,R,N,T,B,_s,pn,Un,ba.disabled,is,"sdf",ht,ct,St,kt,Xt,Ds,De,!1)}{const pn=_n?Va.disabled:new Va({func:se.EQUAL,mask:255},255,255,se.KEEP,se.DECR,se.DECR),Un=_n?R.colorModeForRenderPass():new $a([se.ONE_MINUS_DST_ALPHA,se.DST_ALPHA,se.ONE,se.ONE],o.aq.transparent,[!0,!0,!0,!0]);Wy(Cs,R,N,T,B,_s,pn,Un,ba.disabled,is,"color",ht,ct,St,kt,Xt,Ds,De,!1)}};if(we){const is=()=>{const Xs=ue.drapeBufferSize[0],Ds=ue.drapeBufferSize[1];let _n=ue.framebufferCopyTexture;return _n&&(!_n||_n.size[0]===Xs&&_n.size[1]===Ds)||(_n&&_n.destroy(),_n=ue.framebufferCopyTexture=new o.T(Q,new o.q({width:Xs,height:Ds}),se.RGBA8)),_n.bind(se.LINEAR,se.CLAMP_TO_EDGE),se.copyTexSubImage2D(se.TEXTURE_2D,0,0,0,0,0,Xs,Ds),_n},_s=(Xs,Ds,_n)=>{const pn=R.depthModeForSublayer(1,Yr.ReadOnly,se.LEQUAL,!1),Un=T.paint.get(Xs?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Xn=ds(.1,3,Un);{const nn=new $a([se.ONE,se.ONE,se.ONE,se.ONE],o.aq.transparent,[!1,!1,!1,!0]);Wy(Cs,R,N,T,B,pn,Va.disabled,nn,ba.disabled,Xs,"clear",ht,ct,St,kt,Xt,Xn,De,Ds)}{const nn=new Va({func:se.ALWAYS,mask:255},255,255,se.KEEP,se.KEEP,se.REPLACE),Bs=new $a([se.ONE,se.ONE,se.ONE,se.ONE],o.aq.transparent,[!1,!1,!1,!0],se.MIN);Wy(Cs,R,N,T,B,pn,nn,Bs,ba.disabled,Xs,"sdf",ht,ct,St,kt,Xt,Xn,De,Ds)}Te&&!Xs&&(_n=is());{const nn=Xs?se.ZERO:se.ONE_MINUS_DST_ALPHA,Bs=new Va({func:se.EQUAL,mask:255},255,255,se.KEEP,se.DECR,se.DECR),yn=new $a([nn,se.DST_ALPHA,se.ONE_MINUS_DST_ALPHA,se.ZERO],o.aq.transparent,[!0,!0,!0,!0]);Wy(Cs,R,N,T,B,pn,Bs,yn,ba.disabled,Xs,"color",ht,ct,St,kt,Xt,Xn,De,Ds)}if(!Te||Xs){const nn=new $a([se.ONE,se.ONE,se.ONE,Xs?se.ZERO:se.ONE],o.aq.transparent,[!1,!1,!1,!0],Xs?se.FUNC_ADD:se.MAX);Wy(Cs,R,N,T,B,pn,Va.disabled,nn,ba.disabled,Xs,"clear",ht,ct,St,kt,Xt,Xn,De,Ds,_n)}else{se.drawBuffers([se.NONE,se.COLOR_ATTACHMENT1]);const nn=new Va({func:se.EQUAL,mask:255},254,255,se.KEEP,se.DECR,se.DECR),Bs=new $a([se.ONE,se.ONE,se.ONE,se.ONE],o.aq.transparent,[!0,!1,!1,!1],se.MAX);Wy(Cs,R,N,T,B,pn,nn,Bs,ba.disabled,Xs,"emissive",ht,ct,St,kt,Xt,Xn,De,Ds,_n),se.drawBuffers([se.COLOR_ATTACHMENT0])}};if(Et||Ts){let Xs;R.prepareDrawTile(),Te&&!Et||(Xs=is()),Et&&_s(!0,!1,Xs),Ts&&_s(!1,!0,Xs)}}else Et&&es(!0),Ts&&es(!1),(Et||Ts)&&R.resetStencilClippingMasks()}}},building:function(R,N,T,B){R.currentLayer0&&Q>0,Te=!0;const De=T.paint.get("building-vertical-scale");if(De<=0)return;R.shadowRenderer||(Te=!1);const Qe=R.conflationActive&&R.style.isLayerClipped(T,N.getSource()),Ye=R.style.order.indexOf(T.fqid);if(function(tt,ht,ct,St,kt,Ut){for(const Xt of Ut){const Et=ht.getTile(Xt).getBucket(ct);Et&&(kt&&Et.updateReplacement(Xt,tt.replacementSource,St),Et.uploadUpdatedIndexBuffer(tt.context))}}(R,N,T,Ye,Qe,B),function(tt,ht,ct,St){for(const kt of St){const Ut=ht.getTile(kt).getBucket(ct);Ut&&Ut.needsEvaluation()&&Ut.uploadUpdatedColorBuffer(tt.context)}}(R,N,T,B),T.resetLayerRenderingStats(R),R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0),R.renderPass==="shadow"&&R.shadowRenderer){const tt=[],ht=R.shadowRenderer.getShadowPassDepthMode();Bv({painter:R,source:N,layer:T,coords:B,defines:tt,blendMode:$a.disabled,depthMode:ht,opacity:ue,verticalScale:De,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(R.renderPass==="translucent"){let tt=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Te&&(tt=tt.concat("RENDER_SHADOWS")),R.shadowRenderer&&R.shadowRenderer.useNormalOffset&&(tt=tt.concat("NORMAL_OFFSET"));const ht=T.paint.get("building-facade-emissive-chance"),ct=T.paint.get("building-ambient-occlusion-intensity"),St=T.paint.get("building-flood-light-intensity"),kt=T.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Ut=T.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(kt?null:T.lut).toArray01().slice(0,3),Xt=T.paint.get("building-flood-light-ground-attenuation"),Et=St>0,Ts=new Yr(R.context.gl.LEQUAL,Yr.ReadWrite,R.depthRangeFor3D);ue<1&&Bv({painter:R,source:N,layer:T,coords:B,defines:tt,blendMode:$a.disabled,depthMode:Ts,opacity:ue,verticalScale:De,facadeEmissiveChance:ht,facadeAOIntensity:ct,floodLightIntensity:St,floodLightColor:Ut,depthOnly:!0});const ds=R.colorModeForRenderPass();Bv({painter:R,source:N,layer:T,coords:B,defines:tt,blendMode:ds,depthMode:Ts,opacity:ue,verticalScale:De,facadeEmissiveChance:ht,facadeAOIntensity:ct,floodLightIntensity:St,floodLightColor:Ut});const Cs=T.paint.get("building-front-cutoff");l2(R.transform.pitch,Cs,!!R.terrain),we&&kg(R,N,T,B,!0,ue,W,Q,St,Ut,se,Qe),Et&&kg(R,N,T,B,!1,ue,W,Q,St,Ut,Xt,Qe)}else if(R.renderPass==="light-beam"){const tt=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],ht=new Yr(R.context.gl.LEQUAL,Yr.ReadOnly,R.depthRangeFor3D);Bv({painter:R,source:N,layer:T,coords:B,defines:tt,blendMode:$a.alphaBlended,depthMode:ht,opacity:ue,verticalScale:De,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1),R.resetStencilClippingMasks()},hillshade:function(R,N,T,B){if(R.renderPass!=="offscreen"&&R.renderPass!=="translucent"||R.style.disableElevatedTerrain)return;const W=R.context,Q=R.terrain&&R.terrain.renderingToTexture,[se,ue]=R.renderPass!=="translucent"||Q?[{},B]:R.stencilConfigForOverlap(B);for(const we of ue){const Te=N.getTile(we);if(Te.needsHillshadePrepare&&R.renderPass==="offscreen")tT(R,Te,T);else if(R.renderPass==="translucent"){const De=R.depthModeForSublayer(0,Yr.ReadOnly),Qe=T.paint.get("hillshade-emissive-strength"),Ye=R.colorModeForDrapableLayerRenderPass(Qe),tt=Q&&R.terrain?R.terrain.stencilModeForRTTOverlap(we):se[we.overscaledZ];XL(R,we,Te,T,De,tt,Ye)}}W.viewport.set([0,0,R.width,R.height]),R.resetStencilClippingMasks()},raster:function(R,N,T,B,W,Q){if(R.renderPass!=="translucent")return;const se=T.paint.get("raster-opacity");if(se===0)return;const ue=R.transform.projection.name==="globe",we=T.paint.get("raster-elevation")!==0,Te=we&&ue,De=R.terrain&&R.terrain.exaggeration()>0&&we&&T.paint.get("raster-elevation-reference")==="ground",Qe=!ue&&De;if(R.renderElevatedRasterBackface&&!Te)return;const Ye=R.context,tt=Ye.gl,ht=N.getSource(),ct=function(is,_s,Xs,Ds,_n){const pn=_s.paint.get("raster-color"),Un=is.type==="raster-array",Xn=[],nn=_s.paint.get("raster-resampling"),Bs=_s.paint.get("raster-color-mix");let yn=_s.paint.get("raster-color-range");const jn=[Bs[0],Bs[1],Bs[2],0],In=Bs[3];let Sr=nn==="nearest"?Ds.NEAREST:Ds.LINEAR;if(Un&&(Xn.push("RASTER_ARRAY"),pn||Xn.push("RASTER_COLOR"),nn==="linear"&&Xn.push("RASTER_ARRAY_LINEAR"),Sr=Ds.NEAREST,!yn&&is.rasterLayers)){const xr=is.rasterLayers.find(({id:gr})=>gr===_s.sourceLayer);xr&&xr.fields&&xr.fields.range&&(yn=xr.fields.range)}if(yn=yn||[0,1],pn){Xn.push("RASTER_COLOR"),Xs.activeTexture.set(Ds.TEXTURE2),_s.updateColorRamp(yn);let xr=_s.colorRampTexture;xr||(xr=_s.colorRampTexture=new o.T(Xs,_s.colorRamp,Ds.RGBA8)),xr.bind(Sr,Ds.CLAMP_TO_EDGE)}return _n&&Xn.push("USE_MRT1"),{mix:jn,range:yn,offset:In,defines:Xn,resampling:Sr}}(ht,T,Ye,tt,R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback");if(ht instanceof o.aV&&!B.length&&!ue)return;const St=T.paint.get("raster-emissive-strength"),kt=R.colorModeForDrapableLayerRenderPass(St),Ut=R.terrain&&R.terrain.renderingToTexture,Xt=!R.options.moving,Et=T.paint.get("raster-resampling")==="nearest"?tt.NEAREST:tt.LINEAR;if(ht instanceof o.aV&&!B.length&&(ht.onNorthPole||ht.onSouthPole)){const is=we?R.stencilModeFor3D():Va.disabled;return void Gb(!!ht.onNorthPole,null,R,N,T,St,ct,ba.disabled,is)}if(!B.length)return;const[Ts,ds]=ht instanceof o.aV||Ut?[{},B]:R.stencilConfigForOverlap(B),Cs=ds[ds.length-1].overscaledZ;Te&&ct.defines.push("PROJECTION_GLOBE_VIEW"),we&&ct.defines.push("RENDER_CUTOFF","ELEVATED"),De&&ct.defines.push("ELEVATION_REFERENCE_GROUND");const es=(is,_s,Xs)=>{for(const Ds of is){const _n=Ds.toUnwrapped(),pn=N.getTile(Ds);if(Ut&&(!pn||!pn.hasData()))continue;Ye.activeTexture.set(tt.TEXTURE0);const Un=u2(pn,ht,T,ct);if(!Un||!Un.texture)continue;const{texture:Xn,mix:nn,offset:Bs,tileSize:yn,buffer:jn}=Un;let In,Sr;Ut?(In=Yr.disabled,Sr=Ds.projMatrix):we?(In=new Yr(tt.LEQUAL,Yr.ReadWrite,R.depthRangeFor3D),Sr=ue?Float32Array.from(R.transform.expandedFarZProjMatrix):R.transform.calculateProjMatrix(_n,Xt)):(In=R.depthModeForSublayer(Ds.overscaledZ-Cs,se===1?Yr.ReadWrite:Yr.ReadOnly,tt.LESS),Sr=R.transform.calculateProjMatrix(_n,Xt));const xr=R.terrain&&Ut?R.terrain.stencilModeForRTTOverlap(Ds):Ts[Ds.overscaledZ],gr=Q?0:T.paint.get("raster-fade-duration");pn.registerFadeDuration(gr);const Kn=N.findLoadedParent(Ds,0),pa=jt(pn,Kn,N,R.transform,gr);let Ea,na;!pa.isFading&&pn.refreshedUponExpiration&&(pn.refreshedUponExpiration=!1),R.terrain&&R.terrain.prepareDrawTile(),Ye.activeTexture.set(tt.TEXTURE0),Xn.bind(Et,tt.CLAMP_TO_EDGE),Ye.activeTexture.set(tt.TEXTURE1),Kn?(Kn.texture&&Kn.texture.bind(Et,tt.CLAMP_TO_EDGE),Ea=Math.pow(2,Kn.tileID.overscaledZ-pn.tileID.overscaledZ),na=[pn.tileID.canonical.x*Ea%1,pn.tileID.canonical.y*Ea%1]):Xn.bind(Et,tt.CLAMP_TO_EDGE),"useMipmap"in Xn&&Ye.extTextureFilterAnisotropic&&R.transform.pitch>20&&tt.texParameterf(tt.TEXTURE_2D,Ye.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Ye.extTextureFilterAnisotropicMax);const ma=R.transform;let hi;const Ei=we?Wb(ma):[0,0,0,0];let ki,io,ti,oo,Si,ol=0;if(Te&&ht instanceof o.aV&&ht.coordinates.length>3)ki=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),io=Float32Array.from(ma.globeMatrix),ti=Float32Array.from(o.dq(ma)),oo=[o.aH(ma.center.lng),o.aL(ma.center.lat)],hi=ht.elevatedGlobePerspectiveTransform,Si=ht.elevatedGlobeGridMatrix||new Float32Array(9);else if(Te){const bl=o.dr(Ds.canonical);ol=o.ds(bl.getCenter().lat),ki=Float32Array.from(o.du(o.dv(Ds.canonical))),io=Float32Array.from(ma.globeMatrix),ti=Float32Array.from(o.dq(ma)),oo=[o.aH(ma.center.lng),o.aL(ma.center.lat)],hi=[0,0],Si=Float32Array.from(o.dt(Ds.canonical,bl,ol,ma.worldSize/ma._pixelsPerMercatorPixel))}else hi=ht instanceof o.aV?ht.perspectiveTransform:[0,0],ki=new Float32Array(16),io=new Float32Array(9),ti=new Float32Array(16),oo=[0,0],Si=new Float32Array(9);const _c=Vu(R,Sr,ki,io,ti,Si,na||[0,0],o.al(R.transform.zoom),oo,Ei,Ea||1,pa,T,hi,we?T.paint.get("raster-elevation"):0,2,nn,Bs,ct.range,yn,jn,St),Yd=R.isTileAffectedByFog(Ds),$c=R.getOrCreateProgram("raster",{defines:ct.defines,overrideFog:Yd});if(R.uploadCommonUniforms(Ye,$c,_n),ht instanceof o.aV){const bl=ht.elevatedGlobeVertexBuffer,Zi=ht.elevatedGlobeIndexBuffer;if(Ut||!ue)ht.boundsBuffer&&ht.boundsSegments&&$c.draw(R,tt.TRIANGLES,In,Va.disabled,kt,ba.disabled,_c,T.id,ht.boundsBuffer,R.quadTriangleIndexBuffer,ht.boundsSegments);else if(bl&&Zi){const Xi=ma.zoom<=o.cJ?ht.elevatedGlobeSegments:ht.getSegmentsForLongitude(ma.center.lng);Xi&&$c.draw(R,tt.TRIANGLES,In,Va.disabled,kt,_s,_c,T.id,bl,Zi,Xi)}}else if(Te){In=new Yr(tt.LEQUAL,Yr.ReadOnly,R.depthRangeFor3D);const bl=R.globeSharedBuffers;if(bl){De&&(R.terrain.setupElevationDraw(pn,$c),R.uploadCommonUniforms(Ye,$c,pn.tileID.toUnwrapped()));const[Zi,Xi,Uc]=bl.getGridBuffers(ol,!1),uu=$c.getAttributeLocation(tt,"a_texture_pos");uu!==-1&&tt.vertexAttribI4ui(uu,0,0,0,0),$c.draw(R,tt.TRIANGLES,In,Xs||xr,R.colorModeForRenderPass(),_s,_c,T.id,Zi,Xi,Uc)}}else if(Qe)In=new Yr(tt.LEQUAL,Yr.ReadWrite,R.depthRangeFor3D),R.terrain.setupElevationDraw(pn,$c),R.uploadCommonUniforms(Ye,$c,pn.tileID.toUnwrapped()),ma.pitch>20&&$c.draw(R,tt.TRIANGLES,In,Va.disabled,$a.disabled,ba.frontCCW,_c,T.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments),$c.draw(R,tt.TRIANGLES,In,xr,kt,ba.backCCW,_c,T.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments);else{const{tileBoundsBuffer:bl,tileBoundsIndexBuffer:Zi,tileBoundsSegments:Xi}=R.getTileBoundsBuffers(pn);$c.draw(R,tt.TRIANGLES,In,xr,kt,ba.disabled,_c,T.id,bl,Zi,Xi)}}if(!(ht instanceof o.aV)&&Te)for(const Ds of is){const _n=Ds.canonical.y===(1<o.d$[jn](_n));nn.push(_n);const Bs=_n.canonical.x,yn=_n.canonical.y;for(const jn of nn){const In=Et.getTile(_s?jn.wrapped():jn);if(!In)continue;const Sr=In.rasterParticleState;if(!Sr)continue;const xr=jn.canonical.x+(1<Cs.tileID)),tt&&(Te.activeTexture.set(De.TEXTURE0),R.imageManager.bind(R.context,T.scope));const ds=[];if(R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&ds.push("USE_MRT1"),we){const Cs=R.getOrCreateProgram(Xt,{overrideFog:!1,overrideRtt:!0,defines:ds}),es=new Float32Array(o.b9([])),is=new o.aR(0,0,0,0,0),_s=tt?Dd(es,ue,se,R,0,T.scope,ht,we,{tileID:is,tileSize:Ye}):Op(es,ue,se,W.toPremultipliedRenderColor(Q?null:T.lut));return void Cs.draw(R,De.TRIANGLES,kt,St,Ut,ba.disabled,_s,T.id,R.viewportBuffer,R.quadTriangleIndexBuffer,R.viewportSegments)}for(const Cs of Ts){const es=R.isTileAffectedByFog(Cs),is=R.getOrCreateProgram(Xt,{overrideFog:es,defines:ds}),_s=Cs.toUnwrapped(),Xs=B?Cs.projMatrix:R.transform.calculateProjMatrix(_s);R.prepareDrawTile();const Ds=N?N.getTile(Cs):Et?Et[Cs.key]:new o.b0(Cs,Ye,Qe.zoom,R),_n=tt?Dd(Xs,ue,se,R,0,T.scope,ht,we,{tileID:Cs,tileSize:Ye}):Op(Xs,ue,se,W.toPremultipliedRenderColor(Q?null:T.lut));R.uploadCommonUniforms(Te,is,_s);const{tileBoundsBuffer:pn,tileBoundsIndexBuffer:Un,tileBoundsSegments:Xn}=R.getTileBoundsBuffers(Ds);is.draw(R,De.TRIANGLES,kt,St,Ut,ba.disabled,_n,T.id,pn,Un,Xn)}},sky:function(R,N,T){const B=R._atmosphere?o.al(R.transform.zoom):1,W=T.paint.get("sky-opacity")*B;if(W===0)return;const Q=R.context,se=T.paint.get("sky-type"),ue=new Yr(Q.gl.LEQUAL,Yr.ReadOnly,[0,1]),we=R.frameCounter/1e3%1;se==="atmosphere"?R.renderPass==="offscreen"?T.needsSkyboxCapture(R)&&(function(Te,De){const Qe=Te.context,Ye=Qe.gl;let tt=De.skyboxFbo;if(!tt){tt=De.skyboxFbo=Qe.createFramebuffer(32,32,1,null),De.skyboxGeometry=new Mu(Qe),De.skyboxTexture=Qe.gl.createTexture(),Ye.bindTexture(Ye.TEXTURE_CUBE_MAP,De.skyboxTexture),Ye.texParameteri(Ye.TEXTURE_CUBE_MAP,Ye.TEXTURE_WRAP_S,Ye.CLAMP_TO_EDGE),Ye.texParameteri(Ye.TEXTURE_CUBE_MAP,Ye.TEXTURE_WRAP_T,Ye.CLAMP_TO_EDGE),Ye.texParameteri(Ye.TEXTURE_CUBE_MAP,Ye.TEXTURE_MIN_FILTER,Ye.LINEAR),Ye.texParameteri(Ye.TEXTURE_CUBE_MAP,Ye.TEXTURE_MAG_FILTER,Ye.LINEAR);for(let kt=0;kt<6;++kt)Ye.texImage2D(Ye.TEXTURE_CUBE_MAP_POSITIVE_X+kt,0,Ye.RGBA,32,32,0,Ye.RGBA,Ye.UNSIGNED_BYTE,null)}Qe.bindFramebuffer.set(tt.framebuffer),Qe.viewport.set([0,0,32,32]);const ht=De.getCenter(Te,!0),ct=Te.getOrCreateProgram("skyboxCapture"),St=new Float64Array(16);o.b9(St),o.ef(St,St,.5*-Math.PI),mx(Te,De,ct,St,ht,0),o.b9(St),o.ef(St,St,.5*Math.PI),mx(Te,De,ct,St,ht,1),o.b9(St),o.cE(St,St,.5*-Math.PI),mx(Te,De,ct,St,ht,2),o.b9(St),o.cE(St,St,.5*Math.PI),mx(Te,De,ct,St,ht,3),o.b9(St),mx(Te,De,ct,St,ht,4),o.b9(St),o.ef(St,St,Math.PI),mx(Te,De,ct,St,ht,5),Qe.viewport.set([0,0,Te.width,Te.height])}(R,T),T.markSkyboxValid(R)):R.renderPass==="sky"&&function(Te,De,Qe,Ye,tt){const ht=Te.context,ct=ht.gl,St=Te.transform,kt=Te.getOrCreateProgram("skybox");ht.activeTexture.set(ct.TEXTURE0),ct.bindTexture(ct.TEXTURE_CUBE_MAP,De.skyboxTexture);const Ut=((Xt,Et,Ts,ds,Cs)=>({u_matrix:Xt,u_sun_direction:Et,u_cubemap:0,u_opacity:ds,u_temporal_offset:Cs}))(St.skyboxMatrix,De.getCenter(Te,!1),0,Ye,tt);Te.uploadCommonUniforms(ht,kt),kt.draw(Te,ct.TRIANGLES,Qe,Va.disabled,Te.colorModeForRenderPass(),ba.backCW,Ut,"skybox",De.skyboxGeometry.vertexBuffer,De.skyboxGeometry.indexBuffer,De.skyboxGeometry.segment)}(R,T,ue,W,we):se==="gradient"&&R.renderPass==="sky"&&function(Te,De,Qe,Ye,tt){const ht=Te.context,ct=ht.gl,St=Te.transform,kt=Te.getOrCreateProgram("skyboxGradient");De.skyboxGeometry||(De.skyboxGeometry=new Mu(ht)),ht.activeTexture.set(ct.TEXTURE0);let Ut=De.colorRampTexture;Ut||(Ut=De.colorRampTexture=new o.T(ht,De.colorRamp,ct.RGBA8)),Ut.bind(ct.LINEAR,ct.CLAMP_TO_EDGE);const Xt=((Et,Ts,ds,Cs,es)=>({u_matrix:Et,u_color_ramp:0,u_center_direction:Ts,u_radius:o.ap(ds),u_opacity:Cs,u_temporal_offset:es}))(St.skyboxMatrix,De.getCenter(Te,!1),De.paint.get("sky-gradient-radius"),Ye,tt);Te.uploadCommonUniforms(ht,kt),kt.draw(Te,ct.TRIANGLES,Qe,Va.disabled,Te.colorModeForRenderPass(),ba.backCW,Xt,"skyboxGradient",De.skyboxGeometry.vertexBuffer,De.skyboxGeometry.indexBuffer,De.skyboxGeometry.segment)}(R,T,ue,W,we)},custom:function(R,N,T,B){const W=R.context,Q=T.implementation;if(!R.transform.projection.unsupportedLayers||!R.transform.projection.unsupportedLayers.includes("custom")||R.terrain&&(R.terrain.renderingToTexture||R.renderPass==="offscreen")&&T.isDraped(N)){if(R.renderPass==="offscreen"){const se=Q.prerender;if(se){if(R.setCustomLayerDefaults(),W.setColorMode(R.colorModeForRenderPass()),R.transform.projection.name==="globe"){const ue=R.transform.pointMerc;se.call(Q,W.gl,R.transform.customLayerMatrix(),R.transform.getProjection(),R.transform.globeToMercatorMatrix(),o.al(R.transform.zoom),[ue.x,ue.y],R.transform.pixelsPerMeterRatio)}else se.call(Q,W.gl,R.transform.customLayerMatrix());W.setDirty(),R.setBaseState()}}else if(R.renderPass==="translucent"){if(R.terrain&&R.terrain.renderingToTexture){const ue=Q.renderToTile;if(ue){const we=B[0].canonical,Te={x:we.x+B[0].wrap*(Q.wrapTileId?0:1<{Te&&(Te.useNormalOffset=!0,De||(Te.enabled=!0))},Ye=N.getSource();if(R.renderPass==="light-beam"&&Ye.type!=="batched-model")return;if(Ye.type==="vector"||Ye.type==="geojson")return function(Et,Ts,ds,Cs,es){const is=Et.transform,_s=is.projection.name==="globe",Xs=is.getFreeCameraOptions().position;if(!Et.modelManager)return;const Ds=Et.modelManager;ds.modelManager=Ds;const _n=Et.shadowRenderer;if(!ds._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const pn=ds._unevaluatedLayout._values["model-id"],Un=Object.assign({},ds.layout.get("model-id").parameters),Xn=Et.style.order.indexOf(ds.fqid),nn=ds.paint.get("model-opacity").constantOr(1);for(const Bs of Cs){const yn=Ts.getTile(Bs).getBucket(ds);if(!yn||yn.projection.name!==is.projection.name)continue;const jn=yn.getModelUris();if(jn&&!yn.modelsRequested&&(Ds.addModelsFromBucket(jn,es),yn.modelsRequested=!0),_s)Un.zoom=Bs.overscaledZ;else{const na=W0(Bs,is);Un.zoom=na}const In=pn.possiblyEvaluate(Un);if(ur(Et,yn,Bs),dr.shadowUniformsInitialized=!1,dr.useSingleShadowCascade=!!_n&&_n.getMaxCascadeForTile(Bs.toUnwrapped())===0,Et.renderPass==="shadow"&&_n){if(Et.currentShadowCascade===1&&yn.isInsideFirstShadowMapFrustum)continue;const na=is.calculatePosMatrix(Bs.toUnwrapped(),is.worldSize);if(dr.tileMatrix.set(na),dr.shadowTileMatrix=Float32Array.from(_n.calculateShadowPassMatrixFromMatrix(na)),dr.aabb.min=[0,0,0],dr.aabb.max[0]=dr.aabb.max[1]=o.an,dr.aabb.max[2]=0,s3(yn,dr,Et,ds.scope))continue}const Sr=1<0&&Et.style.isLayerClipped(ds,Ts.getSource())&&yn.updateReplacement(Bs,Et.replacementSource,Xn,ds.scope)&&(yn.uploaded=!1,yn.upload(Et.context));let gr=0;const Kn=new Array,pa=new Array,Ea=new Array;for(let na in yn.instancesPerModel){const ma=yn.instancesPerModel[na];ma.features.length>0&&!_s&&(na=In.evaluate(ma.features[0].feature,{}));const hi=Ds.getModel(na,es);if(hi||Ds.hasURLBeenRequested(na)||yn.modelUris.includes(na)||(yn.modelUris.push(na),yn.modelsRequested=!1),hi&&hi.uploaded)if(_s){const Ei=o.bJ([],[Xs.x,Xs.y,Xs.z],Et.transform.worldSize);o.eo(Ei,Ei);for(let ki=0;ki0&&oo.elevationUpdate(na.terrain,ki,ti,hi.source),oo.needsReEvaluation(na,io,hi)&&oo.evaluate(hi))}})(Et,Ts,ds,Cs),function(){const na=new Map;let ma,hi,Ei;Kn?(ma=Cs.length-1,hi=-1,Ei=-1):(ma=0,hi=Cs.length,Ei=1);const ki=new Float64Array(16),io=o.ce(),ti=new o.P(0,0);for(let oo=ma;oo!==hi;oo+=Ei){const Si=Cs[oo],ol=Ts.getTile(Si).getBucket(ds);if(!ol||!ol.uploaded)continue;let _c=!1;Xs&&(_c=Xs.getMaxCascadeForTile(Si.toUnwrapped())===0);const Yd=is.calculatePosMatrix(Si.toUnwrapped(),is.worldSize),$c=ol.modelTraits;!Sr&&Kn&&(o.b7(ki,Yd),o.ah(io,_n,ki),ti.x=io[0],ti.y=io[1]);const bl=[];ol.setFilter(ds.filter);for(const Zi of ol.getNodesInfo()){if(Zi.hiddenByReplacement||!Zi.node.meshes)continue;const Xi=Zi.node;let Uc=0;Et.terrain&&Xi.elevation&&(Uc=Xi.elevation*Et.terrain.exaggeration());const uu=(()=>{const bf=Zi.aabb;return In.min=[...bf.min],In.max=[...bf.max],In.min[2]+=Uc,In.max[2]+=Uc,o.ah(In.min,In.min,Yd),o.ah(In.max,In.max,Yd),In})(),_l=Zi.evaluatedScale;if(_l[0]<=1&&_l[1]<=1&&_l[2]<=1&&uu.intersects(xr)===0)continue;if(!Sr&&Kn){const bf=.16666666666666666;Zi.cameraCollisionOpacity=_n[0]>uu.min[0]&&_n[0]uu.min[1]&&_n[1]!Kn||Zi.opacity===1&&Xi.opacity===1?Zi.depthXi.depth?-1:1);for(const Zi of bl){const Xi=Zi.nodeInfo,Uc=Xi.node;if(Et._debugParams.show3DModelFootprints&&Uc.footprint){const jo=Uc.id||Uc.name||"footprint";na.has(jo)||na.set(jo,{node:Uc,mvp:Zi.wvpForTile})}let uu=o.aD([],nn,Zi.tileModelMatrix);o.aD(uu,Un,uu);const _l=o.b7([],uu);o.e6(_l,_l),o.cC(_l,_l,Ws),uu=o.aD(uu,uu,Uc.globalMatrix);const Fi=Et.renderPass==="light-beam",Rd=ds.paint.get("model-color-use-theme").constantOr("default")==="none",wc=$c&o.ez.HasMapboxMeshFeatures,Dh=wc?0:Xi.evaluatedRMEA[0][2];for(let jo=0;jo=Hr||Uv>=Hr}}const Kl=Lc.material;let B1;Kl.occlusionTexture&&Kl.occlusionTexture.offsetScale&&(B1=Kl.occlusionTexture.offsetScale,Gm.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const $1=Et.getOrCreateProgram("model",Gm);!Sr&&Xs&&Xs.setupShadowsFromMatrix(Zi.tileModelMatrix,$1,Xs.useNormalOffset),Et.uploadCommonUniforms(es,$1,null,$v);const Xc=Kl.pbrMetallicRoughness;Xc.metallicFactor=.9,Xc.roughnessFactor=.5;const cd=Pc(new Float32Array(Yx),new Float32Array(uu),new Float32Array(_l),new Float32Array(Uc.globalMatrix),Et,Zi.opacity,Xc.baseColorFactor,Kl.emissiveFactor,Xc.metallicFactor,Xc.roughnessFactor,Kl,Dh,ds,[0,0,0],B1);!km&&(Xi.hasTranslucentParts||Zi.opacity<1)&&$1.draw(Et,es.gl.TRIANGLES,yn,Va.disabled,$a.disabled,ba.backCCW,cd,ds.id,Lc.vertexBuffer,Lc.indexBuffer,Lc.segments,ds.paint,Et.transform.zoom,void 0,bf),$1.draw(Et,es.gl.TRIANGLES,km?jn:yn,Va.disabled,km||Zi.opacity<1||Xi.hasTranslucentParts?$a.alphaBlended:$a.unblended,ba.backCCW,cd,ds.id,Lc.vertexBuffer,Lc.indexBuffer,Lc.segments,ds.paint,Et.transform.zoom,void 0,bf)}}}if(Et._debugParams.show3DModelFootprints&&na.size>0){const oo=Array.from(na.keys()).sort();for(const Si of oo){const{node:ol,mvp:_c}=na.get(Si);rT(Et,0,ol,_c)}}}()}(R,N,T,B),void Qe();if(Ye.type!=="model")return;const tt=Ye.getModels(),ht=[],ct=R.transform.getFreeCameraOptions().position,St=o.bJ([],[ct.x,ct.y,ct.z],R.transform.worldSize);o.eo(St,St);const kt=[],Ut=[];let Xt=0;for(const Et of tt){const Ts=N.getFeatureState("",Et.id),ds={type:"Unknown",id:Et.id,properties:Et.featureProperties},Cs=T.paint.get("model-rotation").evaluate(ds,Ts),es=T.paint.get("model-scale").evaluate(ds,Ts),is=T.paint.get("model-translation").evaluate(ds,Ts),_s=T.paint.get("model-opacity").evaluate(ds,Ts);aT(T,Et.id,Ts,Et.featureProperties,Et.nodeOverrideNames,Et.nodeOverrides),lk(T,Et.id,Ts,Et.featureProperties,Et.materialOverrideNames,Et.materialOverrides),Et.nodeOverrides.size>0&&Et.computeBoundsAndApplyParent(),Et.computeModelMatrix(R,Cs,es,is,ue,se,!1);const Xs=o.b9([]),Ds=o.e2(Et.position.lat,R.transform.zoom),_n=o.bP([],[1,1,1/Ds]);o.bx(Xs,Xs,St),ht.push({zScaleMatrix:_n,negCameraPosMatrix:Xs});for(const pn of Et.nodes)nT(R,pn,Et.matrix,R.transform.expandedFarZProjMatrix,Xt,kt,Ut,Et.materialOverrides,_s);Xt++}if(kt.sort((Et,Ts)=>Ts.depth-Et.depth),R.renderPass!=="shadow"){if(R._debugParams.show3DModelFootprints){const Et=R.transform.projMatrix,Ts=new Map,ds=(es,is)=>{if(es.footprint){const _s=es.id||es.name||"footprint";if(!Ts.has(_s)){const Xs=o.aD([],Et,is);Ts.set(_s,{node:es,mvp:Xs})}}};for(const es of Ut)ds(es.node,es.modelMatrix);for(const es of kt)ds(es.node,es.modelMatrix);const Cs=Array.from(Ts.keys()).sort();for(const es of Cs){const{node:is,mvp:_s}=Ts.get(es);rT(R,0,is,_s)}}Up(R,T,kt,Ut,ht),Qe()}else{for(const Et of Ut)c5(Et.mesh,Et.nodeModelMatrix,R,T);for(const Et of kt)c5(Et.mesh,Et.nodeModelMatrix,R,T);Qe()}}},Br={line:function(R,N,T){if(R.hasElevatedBuckets=!1,R.hasNonElevatedBuckets=!1,R._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||R._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(N){const B=N.getVisibleCoordinates();for(const W of B){const Q=N.getTile(W).getBucket(R);if(Q&&(Q.elevationType!=="none"?R.hasElevatedBuckets=!0:R.hasNonElevatedBuckets=!0,R.hasElevatedBuckets&&R.hasNonElevatedBuckets))break}}}else R.hasNonElevatedBuckets=!0},model:function(R,N,T){const B=N.getSource();if(!B.loaded())return;if(B.type==="vector"||B.type==="geojson")return void(T.modelManager&&T.modelManager.upload(T,t3(T,R)));if(B.type==="batched-model"||B.type!=="model")return;const W=B.getModels();for(const Q of W)Q.upload(T.context)},raster:function(R,N,T){const B=N.getSource();if(!(B instanceof to&&B.loaded()))return;const W=R.sourceLayer||B.rasterLayerIds&&B.rasterLayerIds[0];if(!W)return;const Q=R.paint.get("raster-array-band")||B.getInitialBand(W);if(Q==null)return;const se=N.getIds().map(ue=>N.getTileByID(ue));for(const ue of se)ue.updateNeeded(R.id,Q)&&B.prepareTile(ue,W,R.id,Q)},"raster-particle":function(R,N,T){const B=N.getSource();if(!(B instanceof to&&B.loaded()))return;const W=R.sourceLayer||B.rasterLayerIds&&B.rasterLayerIds[0];if(!W)return;const Q=R.paint.get("raster-particle-array-band")||B.getInitialBand(W);if(Q==null)return;const se=N.getIds().map(ue=>N.getTileByID(ue));for(const ue of se)ue.updateNeeded(R.id,Q)&&B.prepareTile(ue,W,R.id,Q)}},Ka={fill:Hb},no={fill:function(R,N,T,B){if(!T.layout||T.layout.get("fill-elevation-reference")==="none"||T.paint.get("fill-opacity").constantOr(1)===0)return;const W=R.context.gl,Q=new Yr(W.LEQUAL,Yr.ReadOnly,R.depthRangeFor3D),se=new Va({func:W.ALWAYS,mask:255},255,255,W.KEEP,W.KEEP,W.REPLACE),ue=R.transform.getFreeCameraOptions().position,we=R.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const Te of B){const De=N.getTile(Te),Qe=De.getBucket(T);if(!Qe)continue;const Ye=Qe.elevatedStructures;if(!Ye||Ye.depthSegments.segments[0].primitiveLength===0)continue;const tt=I1(Te.toUnwrapped(),ue),ht=R.translatePosMatrix(Te.projMatrix,De,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor")),ct=Yi(ht,tt,0,1,0);we.draw(R,W.TRIANGLES,Q,se,$a.disabled,ba.disabled,ct,T.id,Ye.vertexBuffer,Ye.indexBuffer,Ye.depthSegments,T.paint,R.transform.zoom)}}};class ic{constructor(N,T,B,W,Q){this.context=new Nm(N,T),this.transform=B,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 se=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const we of se)this._debugParams.enabledLayers[we]=!0;for(const we of se);this.occlusionParams=new tI,this.setup(),this.numSublayers=zc.maxUnderzooming+zc.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 yd(this),this._wireframeDebugCache=new eI,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const ue=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,ue,N.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=W,this.maxFrontCutoffRawStart=0,this.worldview=Q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(N,T){const B=!!N&&!!N.terrain&&this.transform.projection.supportsTerrain;if(!(B||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Ms(this,N));const W=this._terrain;this.transform.elevation=B?W:null,W.update(N,this.transform,T),this.transform.elevation&&!W.enabled&&(this.transform.elevation=null)}_updateFog(N){const T=N.fog;if(!T||this.transform.projection.name==="globe"||T.getOpacity(this.transform.pitch)<1||T.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[B,W]=T.getFovAdjustedRange(this.transform._fov);if(B>W)return void(this.transform.fogCullDistSq=null);const Q=B+.78*(W-B);this.transform.fogCullDistSq=Q*Q}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(N){N&&!this._terrain&&(this._terrain=new Ms(this,this.style)),this._forceTerrainMode=N}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(N,T){if(this.width=N*o.o.devicePixelRatio,this.height=T*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const B of this.style.order)this.style._mergedLayers[B].resize()}setup(){const N=this.context,T=new o.dB;T.emplaceBack(0,0),T.emplaceBack(o.an,0),T.emplaceBack(0,o.an),T.emplaceBack(o.an,o.an),this.tileExtentBuffer=N.createVertexBuffer(T,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const B=new o.dB;B.emplaceBack(0,0),B.emplaceBack(o.an,0),B.emplaceBack(0,o.an),B.emplaceBack(o.an,o.an),this.debugBuffer=N.createVertexBuffer(B,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const W=new o.dB;W.emplaceBack(-1,-1),W.emplaceBack(1,-1),W.emplaceBack(-1,1),W.emplaceBack(1,1),this.viewportBuffer=N.createVertexBuffer(W,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const Q=new o.eH;Q.emplaceBack(0,0,0,0),Q.emplaceBack(o.an,0,o.an,0),Q.emplaceBack(0,o.an,0,o.an),Q.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=N.createVertexBuffer(Q,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const se=new o.dC;se.emplaceBack(0,1,2),se.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=N.createIndexBuffer(se);const ue=new o.eJ;for(const Te of[0,1,3,2,0])ue.emplaceBack(Te);this.debugIndexBuffer=N.createIndexBuffer(ue),this.emptyTexture=new o.T(N,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),N.gl.RGBA8),this.identityMat=o.bb();const we=this.context.gl;this.stencilClearMode=new Va({func:we.ALWAYS,mask:0},0,255,we.ZERO,we.ZERO,we.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(N){return N._makeTileBoundsBuffers(this.context,this.transform.projection),N._tileBoundsBuffer?{tileBoundsBuffer:N._tileBoundsBuffer,tileBoundsIndexBuffer:N._tileBoundsIndexBuffer,tileBoundsSegments:N._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const N=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,N.TRIANGLES,Yr.disabled,this.stencilClearMode,$a.disabled,ba.disabled,xt(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(N,T,B){if(!T||this.currentStencilSource===T.id||!N.isTileClipped()||!B||B.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let ue=!1;for(const we of B)if(this._tileClippingMaskIDs[we.key]===void 0){ue=!0;break}if(!ue)return}this.currentStencilSource=T.id;const W=this.context,Q=W.gl;this.nextStencilID+B.length>256&&this.clearStencil(),W.setColorMode($a.disabled),W.setDepthMode(Yr.disabled);const se=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const ue of B){const we=T.getTile(ue),Te=this._tileClippingMaskIDs[ue.key]=this.nextStencilID++,{tileBoundsBuffer:De,tileBoundsIndexBuffer:Qe,tileBoundsSegments:Ye}=this.getTileBoundsBuffers(we);se.draw(this,Q.TRIANGLES,Yr.disabled,new Va({func:Q.ALWAYS,mask:0},Te,255,Q.KEEP,Q.KEEP,Q.REPLACE),$a.disabled,ba.disabled,xt(ue.projMatrix),"$clipping",De,Qe,Ye)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const N=this.nextStencilID++,T=this.context.gl;return new Va({func:T.NOTEQUAL,mask:255},N,255,T.KEEP,T.KEEP,T.REPLACE)}stencilModeForClipping(N){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(N);const T=this.context.gl;return new Va({func:T.EQUAL,mask:255},this._tileClippingMaskIDs[N.key],0,T.KEEP,T.KEEP,T.REPLACE)}stencilConfigForOverlap(N){const T=this.context.gl,B=N.sort((se,ue)=>ue.overscaledZ-se.overscaledZ),W=B[B.length-1].overscaledZ,Q=B[0].overscaledZ-W+1;if(Q>1){this.currentStencilSource=void 0,this.nextStencilID+Q>256&&this.clearStencil();const se={};for(let ue=0;uethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((N,T)=>N+T/this._fpsHistory.length,0))}render(N,T){const B=o.o.now();this._dt=B-this._timeStamp,this._timeStamp=B,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=N.map.repaint,this.style=N,this.options=T;const W=this.style._mergedLayers,Q=!(!this.terrain||!this.terrain.enabled),se=()=>this.style._getOrder(Q).filter(nn=>{const Bs=W[nn];return!(Bs.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Bs.type]});let ue=se(),we=!1,Te=!1,De=null,Qe=0,Ye=!1;for(const nn of ue){const Bs=W[nn];Bs.visibility!=="none"&&(Bs.type==="circle"?we=!0:Bs.type==="building"?(De=Bs,++Qe):Bs.type==="symbol"&&(Bs.hasOcclusionOpacityProperties?Te=!0:we=!0))}this.updateEmissiveMode();let tt=ue.map(nn=>W[nn]);const ht=this.style._mergedSourceCaches;this.imageManager=N.imageManager,this.modelManager=N.modelManager,this.symbolFadeChange=N.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const nn in ht){const Bs=ht[nn];Bs.used&&(Bs.prepare(this.context),Bs.getSource().usedInConflation&&++Qe)}let ct=!1;for(const nn of tt)nn.isHidden(this.transform.zoom)||(nn.type==="clip"&&(ct=!0),this.prepareLayer(nn));const St={},kt={},Ut={},Xt={},Et={};for(const nn in ht){const Bs=ht[nn];St[nn]=Bs.getVisibleCoordinates(),kt[nn]=St[nn].slice().reverse(),Ut[nn]=Bs.getVisibleCoordinates(!0).reverse(),Xt[nn]=Bs.getShadowCasterCoordinates(),Et[nn]=Bs.sortCoordinatesByDistance(St[nn])}const Ts=nn=>{const Bs=this.style.getLayerSourceCache(nn);return Bs&&Bs.used?Bs.getSource():null};if(Qe||ct||this._clippingActiveLastFrame){const nn=[],Bs=[];let yn=0;for(const jn of tt)this.isSourceForClippingOrConflation(jn,Ts(jn))&&(nn.push(jn),Bs.push(yn)),yn++;if(nn&&(ct||nn.length>1)||this._clippingActiveLastFrame){ct=!1;const jn=[];for(let In=0;In0){const jn=Ts(Bs);jn&&(this.minCutoffZoom=Math.max(jn.minzoom,this.minCutoffZoom)),Bs.minzoom&&(this.minCutoffZoom=Math.max(Bs.minzoom,this.minCutoffZoom))}Bs.is3D(Q)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=nn),this._lastOcclusionLayer=nn)}const ds=this.style&&this.style.fog;ds?(this._fogVisible=ds.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=ds.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Ut),this.opaquePassCutoff=0,ue=se(),tt=ue.map(nn=>W[nn]));const Cs=this._shadowRenderer;if(Cs){Cs.updateShadowParameters(this.transform,this.style.directionalLight);for(const nn in ht)for(const Bs of St[nn]){let yn={min:0,max:0};this.terrain&&(yn=this.terrain.getMinMaxForTile(Bs)||yn),Cs.addShadowReceiver(Bs.toUnwrapped(),yn.min,yn.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 o5(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const es=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),is=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(es&&!this._snow&&(this._snow=new Hs(this)),!es&&this._snow&&(this._snow.destroy(),delete this._snow),is&&!this._rain&&(this._rain=new dt(this)),!is&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),De){this.buildingTileBorderManager||(this.buildingTileBorderManager=new ey);const nn=this.style.getLayerSourceCache(De);this.buildingTileBorderManager.updateBorders(nn,De)}if(!We.has(this.context.gl))return;this.renderPass="offscreen";for(const nn of tt){const Bs=N.getLayerSourceCache(nn);if(!nn.hasOffscreenPass()||nn.isHidden(this.transform.zoom))continue;const yn=Bs?kt[Bs.id]:void 0;(nn.type==="custom"||nn.type==="raster"||nn.type==="raster-particle"||nn.isSky()||yn&&yn.length)&&this.renderLayer(this,Bs,nn,yn)}this.depthRangeFor3D=[0,1-(tt.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Xt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const _s=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Xs=(()=>{if(T.showOverdrawInspector)return o.aq.black;const nn=this.style.fog;if(nn&&this.transform.projection.supportsFog){const Bs=this.style.getLut(nn.scope);if(!_s){const yn=nn.properties.get("color-use-theme")==="none",jn=nn.properties.get("color").toNonPremultipliedRenderColor(yn?null:Bs).toArray01();return new o.aq(...jn)}if(_s){const yn=nn.properties.get("space-color-use-theme")==="none",jn=nn.properties.get("space-color").toNonPremultipliedRenderColor(yn?null:Bs).toArray01();return new o.aq(...jn)}}return o.aq.transparent})();if(this.context.clear({color:Xs,depth:1}),this.clearStencil(),this._showOverdrawInspector=T.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&_s&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=ue.length-1;this.currentLayer>=0;this.currentLayer--){const nn=tt[this.currentLayer],Bs=N.getLayerSourceCache(nn);if(nn.isSky())continue;const yn=Bs?(nn.is3D(Q)?Et:kt)[Bs.id]:void 0;this._renderTileClippingMasks(nn,Bs,yn),this.renderLayer(this,Bs,nn,yn)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&_s&&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 yn=this.currentLayer;this.depthOcclusion=!0;for(const jn of this.layersWithOcclusionOpacity){this.currentLayer=jn;const In=tt[this.currentLayer],Sr=N.getLayerSourceCache(In),xr=Sr?kt[Sr.id]:void 0;this.terrain||this._renderTileClippingMasks(In,Sr,Sr?St[Sr.id]:void 0),this.renderLayer(this,Sr,In,xr)}this.depthOcclusion=!1,this.currentLayer=yn,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 nn=null;tt.forEach(Bs=>{const yn=N.getLayerSourceCache(Bs);yn&&!Bs.isHidden(this.transform.zoom)&&yn.getVisibleCoordinates().length&&(!nn||nn.getSource().maxzoom0?T.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(N,T,B){const W=B===void 0?this.terrain&&this.terrain.renderingToTexture:B,Q=[];return this.style&&this.style.enable3dLights()&&(N==="globeRaster"||N==="terrainRaster"?(Q.push("LIGHTING_3D_MODE"),Q.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):W||Q.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(Q.push("TERRAIN"),this.linearFloatFilteringSupported()&&Q.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&Q.push("GLOBE"),!this._fogVisible||W||T!==void 0&&!T||Q.push("FOG"),W&&Q.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Q.push("OVERDRAW_INSPECTOR"),Q}getOrCreateProgram(N,T){this.cache=this.cache||{};const B=T&&T.defines||[],W=T&&T.config,Q=this.currentGlobalDefines(N,T&&T.overrideFog,T&&T.overrideRtt).concat(B),se=Jn.cacheKey(Qj[N],N,Q,W);return this.cache[se]||(this.cache[se]=new Jn(this.context,N,Qj[N],W,zp[N],Q)),this.cache[se]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const N=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(N.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new o.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(N,T){if(this.style.enable3dLights()){const B=this.style.directionalLight,W=this.style.ambientLight;if(B&&W){const Q=((se,ue,we)=>{const Te=se.properties.get("direction"),De=se.properties.get("color-use-theme")==="none",Qe=se.properties.get("color").toNonPremultipliedRenderColor(De?null:we.getLut(se.scope)).toArray01(),Ye=se.properties.get("intensity"),tt=ue.properties.get("color-use-theme")==="none",ht=ue.properties.get("color").toNonPremultipliedRenderColor(tt?null:we.getLut(ue.scope)).toArray01(),ct=ue.properties.get("intensity"),St=[Te.x,Te.y,Te.z],kt=o.dD(ht,ct),Ut=o.dD(Qe,Ye);return{u_lighting_ambient_color:kt,u_lighting_directional_dir:St,u_lighting_directional_color:Ut,u_ground_radiance:zs(St,Ut,kt)}})(B,W,this.style);T.setLightsUniformValues(N,Q)}}}uploadCommonUniforms(N,T,B,W,Q){if(this.uploadCommonLightUniforms(N,T),this.terrain&&this.terrain.renderingToTexture)return;const se=this.style.fog;if(se){const ue=se.getOpacity(this.transform.pitch),we=((Te,De,Qe,Ye,tt,ht,ct,St,kt,Ut,Xt,Et)=>{const Ts=Te.transform,ds=De.properties.get("color-use-theme")==="none",Cs=De.properties.get("color").toNonPremultipliedRenderColor(ds?null:Te.style.getLut(De.scope)).toArray01();Cs[3]=Ye;const es=Te.frameCounter/1e3%1,[is,_s]=De.properties.get("vertical-range");return{u_fog_matrix:Qe?Ts.calculateFogTileMatrix(Qe):Et||Te.identityMat,u_fog_range:De.getFovAdjustedRange(Ts._fov),u_fog_color:Cs,u_fog_horizon_blend:De.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(is,_s),_s],u_fog_temporal_offset:es,u_frustum_tl:tt,u_frustum_tr:ht,u_frustum_br:ct,u_frustum_bl:St,u_globe_pos:kt,u_globe_radius:Ut,u_viewport:Xt,u_globe_transition:o.al(Ts.zoom),u_is_globe:+(Ts.projection.name==="globe")}})(this,se,B,ue,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],W);T.setFogUniformValues(N,we)}Q&&T.setCutoffUniformValues(N,Q.uniformValues)}setTileLoadedFlag(N){this.tileLoaded=N}saveCanvasCopy(){const N=this.canvasCopy();N&&(this.frameCopies.push(N),this.tileLoaded=!1)}canvasCopy(){const N=this.context.gl,T=N.createTexture();return N.bindTexture(N.TEXTURE_2D,T),N.copyTexImage2D(N.TEXTURE_2D,0,N.RGBA,0,0,N.drawingBufferWidth,N.drawingBufferHeight,0),T}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const N=this.style&&this.style.fog;return!!N&&N.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const N=this._backgroundTiles,T=this._backgroundTiles={},B=this.transform.coveringTiles({tileSize:512});for(const W of B)T[W.key]=N[W.key]||new o.b0(W,512,this.transform.tileZoom,this,void 0,this.worldview);return T}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(N,T){return!(!N.is3D(!(!this.terrain||!this.terrain.enabled))||N.type!=="clip"&&N.type!=="building"&&(N.minzoom&&N.minzoom>this.transform.zoom||(this.style._clipLayerPresent||N.sourceLayer!=="building"&&N.sourceLayer!=="procedural_buildings")&&(!T||T.type!=="batched-model")))}isTileAffectedByFog(N){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let T=this._cachedTileFogOpacities[N.key];return T||(this._cachedTileFogOpacities[N.key]=T=this.style.fog.getOpacityForTile(N)),T[0]>=Hr||T[1]>=Hr}setupDepthForOcclusion(N,T,B){const W=this.context,Q=W.gl,se=!!B;var ue;B||(B={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),W.activeTexture.set(Q.TEXTURE3),N&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),B.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],B.u_depth_range_unpack=[2/((ue=this.depthRangeFor3D)[1]-ue[0]),-1-2*ue[0]/(ue[1]-ue[0])],B.u_occluder_half_size=.5*this.occlusionParams.occluderSize,B.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),W.activeTexture.set(Q.TEXTURE0),se||T.setTerrainUniformValues(W,B)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const N=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=N?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Ri(R,N){let T=!1,B=null;const W=()=>{B=null,T&&(R(),B=setTimeout(W,N),T=!1)};return()=>(T=!0,B||W(),B)}class Ih{constructor(N){this._hashName=N&&encodeURIComponent(N),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Ri(this._updateHashUnthrottled.bind(this),300)}addTo(N){return this._map=N,window.addEventListener("hashchange",this._onHashChange,!1),N.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const N=this._map;if(!N)return"";const T=oc(N);if(this._hashName){const B=this._hashName;let W=!1;const Q=location.hash.slice(1).split("&").map(se=>{const ue=se.split("=")[0];return ue===B?(W=!0,`${ue}=${T}`):se}).filter(se=>se);return W||Q.push(`${B}=${T}`),`#${Q.join("&")}`}return`#${T}`}_getCurrentHash(){const N=location.hash.replace("#","");if(this._hashName){let T;return N.split("&").map(B=>B.split("=")).forEach(B=>{B[0]===this._hashName&&(T=B)}),(T&&T[1]||"").split("/")}return N.split("/")}_onHashChange(){const N=this._map;if(!N)return!1;const T=this._getCurrentHash();if(T.length>=3&&!T.some(B=>isNaN(Number(B)))){const B=N.dragRotate.isEnabled()&&N.touchZoomRotate.isEnabled()?+(T[3]||0):N.getBearing();return N.jumpTo({center:[+T[2],+T[1]],zoom:+T[0],bearing:B,pitch:+(T[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function oc(R,N){const T=R.getCenter(),B=Math.round(100*R.getZoom())/100,W=Math.ceil((B*Math.LN2+Math.log(512/360/.5))/Math.LN10),Q=Math.pow(10,W),se=Math.round(T.lng*Q)/Q,ue=Math.round(T.lat*Q)/Q,we=R.getBearing(),Te=R.getPitch();let De=N?`/${se}/${ue}/${B}`:`${B}/${ue}/${se}`;return(we||Te)&&(De+="/"+Math.round(10*we)/10),Te&&(De+=`/${Math.round(Te)}`),De}const Kx={linearity:.3,easing:o.eN(0,0,.3,1)},K0=Object.assign({deceleration:2500,maxSpeed:1400},Kx),Ir=Object.assign({deceleration:20,maxSpeed:1400},Kx),Ln=Object.assign({deceleration:1e3,maxSpeed:360},Kx),Wn=Object.assign({deceleration:1e3,maxSpeed:90},Kx);class Hi{constructor(N){this._map=N,this.clear()}clear(){this._inertiaBuffer=[]}record(N){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:N})}_drainInertiaBuffer(){const N=this._inertiaBuffer,T=o.o.now();for(;N.length>0&&T-N[0].time>160;)N.shift()}_onMoveEnd(N){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const T={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:Q}of this._inertiaBuffer)T.zoom+=Q.zoomDelta||0,T.bearing+=Q.bearingDelta||0,T.pitch+=Q.pitchDelta||0,Q.panDelta&&T.pan._add(Q.panDelta),Q.around&&(T.around=Q.around),Q.pinchAround&&(T.pinchAround=Q.pinchAround);const B=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,W={};if(T.pan.mag()){const Q=xl(T.pan.mag(),B,Object.assign({},K0,N||{}));W.offset=T.pan.mult(Q.amount/T.pan.mag()),W.center=this._map.transform.center,ao(W,Q)}if(T.zoom){const Q=xl(T.zoom,B,Ir);W.zoom=this._map.transform.zoom+Q.amount,ao(W,Q)}if(T.bearing){const Q=xl(T.bearing,B,Ln);W.bearing=this._map.transform.bearing+o.aC(Q.amount,-179,179),ao(W,Q)}if(T.pitch){const Q=xl(T.pitch,B,Wn);W.pitch=this._map.transform.pitch+Q.amount,ao(W,Q)}if(W.zoom||W.bearing){const Q=T.pinchAround===void 0?T.around:T.pinchAround;W.around=Q?this._map.unproject(Q):this._map.getCenter()}return this.clear(),W.noMoveStart=!0,W}}function ao(R,N){(!R.duration||R.durationT.unproject(we)),ue=Q.reduce((we,Te,De,Qe)=>we.add(Te.div(Qe.length)),new o.P(0,0));super(N,{points:Q,point:ue,lngLats:se,lngLat:T.unproject(ue),originalEvent:B}),this._defaultPrevented=!1}}class qp extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(N,T){super("wheel",{originalEvent:T}),this._defaultPrevented=!1}}class Ad{constructor(N,T){this._map=N,this._clickTolerance=T.clickTolerance}reset(){this._mousedownPos=void 0}wheel(N){return this._firePreventable(new qp(this._map,N))}mousedown(N,T){return this._mousedownPos=T,this._firePreventable(new bo(N.type,this._map,N))}mouseup(N){this._map.fire(new bo(N.type,this._map,N))}preclick(N){const T=new MouseEvent("preclick",N);this._map.fire(new bo(T.type,this._map,T))}click(N,T){this._mousedownPos&&this._mousedownPos.dist(T)>=this._clickTolerance||(this.preclick(N),this._map.fire(new bo(N.type,this._map,N)))}dblclick(N){return this._firePreventable(new bo(N.type,this._map,N))}mouseover(N){this._map.fire(new bo(N.type,this._map,N))}mouseout(N){this._map.fire(new bo(N.type,this._map,N))}touchstart(N){return this._firePreventable(new Jl(N.type,this._map,N))}touchmove(N){this._map.fire(new Jl(N.type,this._map,N))}touchend(N){this._map.fire(new Jl(N.type,this._map,N))}touchcancel(N){this._map.fire(new Jl(N.type,this._map,N))}_firePreventable(N){if(this._map.fire(N),N.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Zb{constructor(N){this._map=N}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(N){this._map.fire(new bo(N.type,this._map,N))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new bo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(N){this._delayContextMenu?this._contextMenuEvent=N:this._map.fire(new bo(N.type,this._map,N)),this._map.listens("contextmenu")&&N.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class nI{constructor(N,T){this._map=N,this._el=N.getCanvasContainer(),this._container=N.getContainer(),this._clickTolerance=T.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(N,T){this.isEnabled()&&N.shiftKey&&N.button===0&&(S(),this._startPos=this._lastPos=T,this._active=!0)}mousemoveWindow(N,T){if(!this._active)return;const B=T,W=this._startPos,Q=this._lastPos;if(!W||!Q||Q.equals(B)||!this._box&&B.dist(W){this._box&&(this._box.style.transform=`translate(${se}px,${we}px)`,this._box.style.width=ue-se+"px",this._box.style.height=Te-we+"px")})}mouseupWindow(N,T){if(!this._active)return;const B=this._startPos,W=T;if(B&&N.button===0){if(this.reset(),P(),B.x!==W.x||B.y!==W.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:N})),{cameraAnimation:Q=>Q.fitScreenCoordinates(B,W,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",N)}}keydown(N){this._active&&N.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",N))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),C(),delete this._startPos,delete this._lastPos}_fireEvent(N,T){return this._map.fire(new o.C(N,{originalEvent:T}))}}function rI(R,N){const T={};for(let B=0;Bthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=N.timeStamp),B.length===this.numTouches&&(this.centroid=function(W){const Q=new o.P(0,0);for(const se of W)Q._add(se);return Q.div(W.length)}(T),this.touches=rI(B,T)))}touchmove(N,T,B){if(this.aborted||!this.centroid)return;const W=rI(B,T);for(const Q in this.touches){const se=W[Q];(!se||se.dist(this.touches[Q])>30)&&(this.aborted=!0)}}touchend(N,T,B){if((!this.centroid||N.timeStamp-this.startTime>500)&&(this.aborted=!0),B.length===0){const W=!this.aborted&&this.centroid;if(this.reset(),W)return W}}}class h2{constructor(N){this.singleTap=new Xb(N),this.numTaps=N.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(N,T,B){this.singleTap.touchstart(N,T,B)}touchmove(N,T,B){this.singleTap.touchmove(N,T,B)}touchend(N,T,B){const W=this.singleTap.touchend(N,T,B);if(W){const Q=N.timeStamp-this.lastTime<500,se=!this.lastTap||this.lastTap.dist(W)<30;if(Q&&se||this.reset(),this.count++,this.lastTime=N.timeStamp,this.lastTap=W,this.count===this.numTaps)return this.reset(),W}}}class cT{constructor(){this._zoomIn=new h2({numTouches:1,numTaps:2}),this._zoomOut=new h2({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(N,T,B){this._zoomIn.touchstart(N,T,B),this._zoomOut.touchstart(N,T,B)}touchmove(N,T,B){this._zoomIn.touchmove(N,T,B),this._zoomOut.touchmove(N,T,B)}touchend(N,T,B){const W=this._zoomIn.touchend(N,T,B),Q=this._zoomOut.touchend(N,T,B);return W?(this._active=!0,N.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:se=>se.easeTo({duration:300,zoom:se.getZoom()+1,around:se.unproject(W)},{originalEvent:N})}):Q?(this._active=!0,N.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:se=>se.easeTo({duration:300,zoom:se.getZoom()-1,around:se.unproject(Q)},{originalEvent:N})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const Rz=0,CK=2,AK={[Rz]:1,[CK]:2},dk={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class aI{constructor(N){this.reset(),this._clickTolerance=N.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(N,T){return!1}_move(N,T){return{}}mousedown(N,T){if(this._lastPoint)return;const B=D(N);this._correctButton(N,B)&&(this._lastPoint=T,this._eventButton=B)}mousemoveWindow(N,T){const B=this._lastPoint;if(B){if(N.preventDefault(),this._eventButton!=null&&function(W,Q){const se=AK[Q];return W.buttons===void 0||(W.buttons&se)!==se}(N,this._eventButton))this.reset();else if(this._moved||!(T.dist(B)0&&(this._active=!0);const W=rI(B,T),Q=new o.P(0,0),se=new o.P(0,0);let ue=0;for(const Te in W){const De=W[Te],Qe=this._touches[Te];Qe&&(Q._add(De),se._add(De.sub(Qe)),ue++,W[Te]=De)}if(this._touches=W,ue{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class oI{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(N){}_move(N,T,B){return{}}touchstart(N,T,B){this._firstTwoTouches||B.length<2||(this._firstTwoTouches=[B[0].identifier,B[1].identifier],this._start([T[0],T[1]]))}touchmove(N,T,B){const W=this._firstTwoTouches;if(!W)return;N.preventDefault();const[Q,se]=W,ue=Qu(B,T,Q),we=Qu(B,T,se);if(!ue||!we)return;const Te=this._aroundCenter?null:ue.add(we).div(2);return this._move([ue,we],Te,N)}touchend(N,T,B){if(!this._firstTwoTouches)return;const[W,Q]=this._firstTwoTouches,se=Qu(B,T,W),ue=Qu(B,T,Q);se&&ue||(this._active&&P(),this.reset())}touchcancel(){this.reset()}enable(N){this._enabled=!0,this._aroundCenter=!!N&&N.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function Qu(R,N,T){for(let B=0;BMath.abs(R.x)}class MK extends oI{constructor(N){super(),this._map=N}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(N){this._lastPoints=N,lI(N[0].sub(N[1]))&&(this._valid=!1)}_move(N,T,B){const W=this._lastPoints;if(!W)return;const Q=N[0].sub(W[0]),se=N[1].sub(W[1]);return this._map._cooperativeGestures&&!o.eO()&&B.touches.length<3||(this._valid=this.gestureBeginsVertically(Q,se,B.timeStamp),!this._valid)?void 0:(this._lastPoints=N,this._active=!0,{pitchDelta:(Q.y+se.y)/2*-.5})}gestureBeginsVertically(N,T,B){if(this._valid!==void 0)return this._valid;const W=N.mag()>=2,Q=T.mag()>=2;if(!W&&!Q)return;if(!W||!Q)return this._firstMove==null&&(this._firstMove=B),B-this._firstMove<100&&void 0;const se=N.y>0==T.y>0;return lI(N)&&lI(T)&&se}}const PK={panStep:100,bearingStep:15,pitchStep:10};class a3{constructor(){const N=PK;this._panStep=N.panStep,this._bearingStep=N.bearingStep,this._pitchStep=N.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(N){if(N.altKey||N.ctrlKey||N.metaKey)return;let T=0,B=0,W=0,Q=0,se=0;switch(N.keyCode){case 61:case 107:case 171:case 187:T=1;break;case 189:case 109:case 173:T=-1;break;case 37:N.shiftKey?B=-1:(N.preventDefault(),Q=-1);break;case 39:N.shiftKey?B=1:(N.preventDefault(),Q=1);break;case 38:N.shiftKey?W=1:(N.preventDefault(),se=-1);break;case 40:N.shiftKey?W=-1:(N.preventDefault(),se=1);break;default:return}return this._rotationDisabled&&(B=0,W=0),{cameraAnimation:ue=>{const we=ue.getZoom();ue.easeTo({duration:300,easeId:"keyboardHandler",easing:LK,zoom:T?Math.round(we)+T*(N.shiftKey?2:1):we,bearing:ue.getBearing()+B*this._bearingStep,pitch:ue.getPitch()+W*this._pitchStep,offset:[-Q*this._panStep,-se*this._panStep],center:ue.getCenter()},{originalEvent:N})}}}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 LK(R){return R*(2-R)}const i3=4.000244140625,IK=1/450;class Bz{constructor(N,T){this._map=N,this._el=N.getCanvasContainer(),this._handler=T,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=IK,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(N){this._defaultZoomRate=N}setWheelZoomRate(N){this._wheelZoomRate=N}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(N){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!N&&N.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(N){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(N.ctrlKey||N.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let T=N.deltaMode===WheelEvent.DOM_DELTA_LINE?40*N.deltaY:N.deltaY;const B=o.o.now(),W=B-(this._lastWheelEventTime||0);this._lastWheelEventTime=B,T!==0&&T%i3===0?this._type="wheel":T!==0&&Math.abs(T)<4?this._type="trackpad":W>400?(this._type=null,this._lastValue=T,this._timeout=window.setTimeout(this._onTimeout,40,N)):this._type||(this._type=Math.abs(W*T)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,T+=this._lastValue)),N.shiftKey&&T&&(T/=4),this._type&&(this._lastWheelEvent=N,this._delta-=T,this._active||this._start(N)),N.preventDefault()}_onTimeout(N){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(N)}_start(N){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const T=M(this._el,N);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:T,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const N=this._map.transform;this._type==="wheel"&&N.projection.wrap&&(N._center.lng>=180||N._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const T=()=>N._terrainEnabled()&&this._aroundCoord?N.computeZoomRelativeTo(this._aroundCoord):N.zoom;if(this._delta!==0){const Te=this._type==="wheel"&&Math.abs(this._delta)>i3?this._wheelZoomRate:this._defaultZoomRate;let De=2/(1+Math.exp(-Math.abs(this._delta*Te)));this._delta<0&&De!==0&&(De=1/De);const Qe=T(),Ye=Math.pow(2,Qe),tt=typeof this._targetZoom=="number"?N.zoomScale(this._targetZoom):Ye;this._targetZoom=Math.min(N.maxZoom,Math.max(N.minZoom,N.scaleZoom(tt*De))),this._type==="wheel"&&(this._startZoom=Qe,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const B=typeof this._targetZoom=="number"?this._targetZoom:T(),W=this._startZoom,Q=this._easing;let se,ue=!1;if(this._type==="wheel"&&W&&Q){const Te=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),De=Q(Te);se=o.am(W,B,De),Te<1?this._frameId||(this._frameId=!0):ue=!0}else se=B,ue=!0;this._active=!0,ue&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let we=se-T();return we*this._lastDelta<0&&(we=0),{noInertia:!0,needsRenderFrame:!ue,zoomDelta:we,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(N){let T=o.eP;if(this._prevEase){const B=this._prevEase,W=(o.o.now()-B.start)/B.duration,Q=B.easing(W+.01)-B.easing(W),se=.27/Math.sqrt(Q*Q+1e-4)*.01,ue=Math.sqrt(.0729-se*se);T=o.eN(se,ue,.25,1)}return this._prevEase={start:o.o.now(),duration:N,easing:T},T}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=g("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(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 $z{constructor(N,T){this._clickZoom=N,this._tapZoom=T}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 Uz{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(N,T){return N.preventDefault(),{cameraAnimation:B=>{B.easeTo({duration:300,zoom:B.getZoom()+(N.shiftKey?-1:1),around:B.unproject(T)},{originalEvent:N})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class jie{constructor(){this._tap=new h2({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(N,T,B){this._swipePoint||(this._tapTime&&N.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?B.length>0&&(this._swipePoint=T[0],this._swipeTouch=B[0].identifier):this._tap.touchstart(N,T,B))}touchmove(N,T,B){if(this._tapTime){if(this._swipePoint){if(B[0].identifier!==this._swipeTouch)return;const W=T[0],Q=W.y-this._swipePoint.y;return this._swipePoint=W,N.preventDefault(),this._active=!0,{zoomDelta:Q/128}}}else this._tap.touchmove(N,T,B)}touchend(N,T,B){this._tapTime?this._swipePoint&&B.length===0&&this.reset():this._tap.touchend(N,T,B)&&(this._tapTime=N.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class DK{constructor(N,T,B){this._el=N,this._mousePan=T,this._touchPan=B}enable(N){this._inertiaOptions=N||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class Nie{constructor(N,T,B){this._pitchWithRotate=N.pitchWithRotate,this._mouseRotate=T,this._mousePitch=B}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 kie{constructor(N,T,B,W){this._el=N,this._touchZoom=T,this._touchRotate=B,this._tapDragZoom=W,this._rotationDisabled=!1,this._enabled=!0}enable(N){this._touchZoom.enable(N),this._rotationDisabled||this._touchRotate.enable(N),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 cI=R=>R.zoom||R.drag||R.pitch||R.rotate;class Sie extends o.C{}class Cie{constructor(){this.constants=[1,1,.01],this.radius=0}setup(N,T){const B=o.ax([],T,N);this.radius=o.ai(B[2]<0?o.eR([],B,this.constants):[B[0],B[1],0])}projectRay(N){o.eR(N,N,this.constants),o.ay(N,N),o.eS(N,N,this.constants);const T=o.bJ([],N,this.radius);if(T[2]>0){const B=o.bJ([],[0,0,1],o.bi(T,[0,0,1])),W=o.bJ([],o.ay([],[T[0],T[1],0]),this.radius),Q=o.cT([],T,o.bJ([],o.ax([],o.cT([],W,B),T),2));T[0]=Q[0],T[1]=Q[1]}return T}}function dI(R){return R.panDelta&&R.panDelta.mag()||R.zoomDelta||R.bearingDelta||R.pitchDelta}class Aie{constructor(N,T){this._map=N,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Hi(N),this._bearingSnap=T.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Cie,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(T),o.aZ(["handleEvent","handleWindowEvent"],this);const B=this._el;this._listeners=[[B,"touchstart",{passive:!0}],[B,"touchmove",{passive:!1}],[B,"touchend",void 0],[B,"touchcancel",void 0],[B,"mousedown",void 0],[B,"mousemove",void 0],[B,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[B,"mouseover",void 0],[B,"mouseout",void 0],[B,"dblclick",void 0],[B,"click",void 0],[B,"keydown",{capture:!1}],[B,"keyup",void 0],[B,"wheel",{passive:!1}],[B,"contextmenu",void 0],[window,"blur",void 0]];for(const[W,Q,se]of this._listeners){const ue=W===document?this.handleWindowEvent:this.handleEvent;W.addEventListener(Q,ue,se)}}destroy(){for(const[N,T,B]of this._listeners){const W=N===document?this.handleWindowEvent:this.handleEvent;N.removeEventListener(T,W,B)}}_addDefaultHandlers(N){const T=this._map,B=T.getCanvasContainer();this._add("mapEvent",new Ad(T,N));const W=T.boxZoom=new nI(T,N);this._add("boxZoom",W);const Q=new cT,se=new Uz;T.doubleClickZoom=new $z(se,Q),this._add("tapZoom",Q),this._add("clickZoom",se);const ue=new jie;this._add("tapDragZoom",ue);const we=T.touchPitch=new MK(T);this._add("touchPitch",we);const Te=new Fz(N),De=new iI(N);T.dragRotate=new Nie(N,Te,De),this._add("mouseRotate",Te,["mousePitch"]),this._add("mousePitch",De,["mouseRotate"]);const Qe=new Qb(N),Ye=new EK(T,N);T.dragPan=new DK(B,Qe,Ye),this._add("mousePan",Qe),this._add("touchPan",Ye,["touchZoom","touchRotate"]);const tt=new r3,ht=new TK;T.touchZoomRotate=new kie(B,ht,tt,ue),this._add("touchRotate",tt,["touchPan","touchZoom"]),this._add("touchZoom",ht,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Zb(T));const ct=T.scrollZoom=new Bz(T,this);this._add("scrollZoom",ct,["mousePan"]);const St=T.keyboard=new a3;this._add("keyboard",St);for(const kt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])N.interactive&&N[kt]&&T[kt].enable(N[kt])}_add(N,T,B){this._handlers.push({handlerName:N,handler:T,allowed:B}),this._handlersById[N]=T}stop(N){if(!this._updatingCamera){for(const{handler:T}of this._handlers)T.reset();this._inertia.clear(),this._fireEvents({},{},N),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:N}of this._handlers)if(N.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!cI(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(N,T,B){for(const W in N)if(W!==B&&(!T||T.indexOf(W)<0))return!0;return!1}handleWindowEvent(N){this.handleEvent(N,`${N.type}Window`)}_getMapTouches(N){const T=[];for(const B of N)this._el.contains(B.target)&&T.push(B);return T}handleEvent(N,T){this._updatingCamera=!0;const B=N.type==="renderFrame",W=B?void 0:N,Q={needsRenderFrame:!1},se={},ue={},we=N.touches?this._getMapTouches(N.touches):void 0,Te=we?I(this._el,we):B?void 0:M(this._el,N);for(const{handlerName:Ye,handler:tt,allowed:ht}of this._handlers){if(!tt.isEnabled())continue;let ct;this._blockedByActive(ue,ht,Ye)?tt.reset():tt[T||N.type]&&(ct=tt[T||N.type](N,Te,we),this.mergeHandlerResult(Q,se,ct,Ye,W),ct&&ct.needsRenderFrame&&this._triggerRenderFrame()),(ct||tt.isActive())&&(ue[Ye]=tt)}const De={};for(const Ye in this._previousActiveHandlers)ue[Ye]||(De[Ye]=W);this._previousActiveHandlers=ue,(Object.keys(De).length||dI(Q))&&(this._changes.push([Q,se,De]),this._triggerRenderFrame()),(Object.keys(ue).length||dI(Q))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Qe}=Q;Qe&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Qe(this._map))}mergeHandlerResult(N,T,B,W,Q){if(!B)return;Object.assign(N,B);const se={handlerName:W,originalEvent:B.originalEvent||Q};B.zoomDelta!==void 0&&(T.zoom=se),B.panDelta!==void 0&&(T.drag=se),B.pitchDelta!==void 0&&(T.pitch=se),B.bearingDelta!==void 0&&(T.rotate=se)}_applyChanges(){const N={},T={},B={};for(const[W,Q,se]of this._changes)W.panDelta&&(N.panDelta=(N.panDelta||new o.P(0,0))._add(W.panDelta)),W.zoomDelta&&(N.zoomDelta=(N.zoomDelta||0)+W.zoomDelta),W.bearingDelta&&(N.bearingDelta=(N.bearingDelta||0)+W.bearingDelta),W.pitchDelta&&(N.pitchDelta=(N.pitchDelta||0)+W.pitchDelta),W.around!==void 0&&(N.around=W.around),W.aroundCoord!==void 0&&(N.aroundCoord=W.aroundCoord),W.pinchAround!==void 0&&(N.pinchAround=W.pinchAround),W.noInertia&&(N.noInertia=W.noInertia),Object.assign(T,Q),Object.assign(B,se);this._updateMapTransform(N,T,B),this._changes=[]}_updateMapTransform(N,T,B){const W=this._map,Q=W.transform,se=Ut=>[Ut.x,Ut.y,Ut.z];if((()=>{const Ut=this._eventsInProgress.drag;return Ut&&!this._handlersById[Ut.handlerName].isActive()})()&&!dI(N)){const Ut=Q.zoom;Q.cameraElevationReference="sea",this._originalZoom!=null&&Q._orthographicProjectionAtLowPitch&&Q.projection.name!=="globe"&&Q.pitch===0?(Q.cameraElevationReference="ground",Q.zoom=this._originalZoom):(Q.recenterOnTerrain(),Q.cameraElevationReference="ground"),Ut!==Q.zoom&&this._map._update(!0)}if(Q._isCameraConstrained&&W._stop(!0),!dI(N))return void this._fireEvents(T,B,!0);let{panDelta:ue,zoomDelta:we,bearingDelta:Te,pitchDelta:De,around:Qe,aroundCoord:Ye,pinchAround:tt}=N;Q._isCameraConstrained&&(we>0&&(we=0),Q._isCameraConstrained=!1),tt!==void 0&&(Qe=tt),(we||(Ut=>T[Ut]&&!this._eventsInProgress[Ut])("drag"))&&Qe&&(this._dragOrigin=se(Q.pointCoordinate3D(Qe)),this._originalZoom=Q.zoom,this._trackingEllipsoid.setup(Q._camera.position,this._dragOrigin)),Q.cameraElevationReference="sea",W._stop(!0),Qe=Qe||W.transform.centerPoint,Te&&(Q.bearing+=Te),De&&(Q.pitch+=De),Q._updateCameraState();const ht=[0,0,0];if(ue)if(Q.projection.name==="mercator"){const Ut=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Qe).dir),Xt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Qe.sub(ue)).dir);ht[0]=Xt[0]-Ut[0],ht[1]=Xt[1]-Ut[1]}else{const Ut=Q.pointCoordinate(Qe);if(Q.projection.name==="globe"){ue=ue.rotate(-Q.angle);const Xt=Q._pixelsPerMercatorPixel/Q.worldSize;ht[0]=-ue.x*o.eQ(o.bV(Ut.y))*Xt,ht[1]=-ue.y*o.eQ(Q.center.lat)*Xt}else{const Xt=Q.pointCoordinate(Qe.sub(ue));Ut&&Xt&&(ht[0]=Xt.x-Ut.x,ht[1]=Xt.y-Ut.y)}}const ct=Q.zoom,St=[0,0,0];if(we){const Ut=se(Ye||Q.pointCoordinate3D(Qe)),Xt={dir:o.ay([],o.ax([],Ut,Q._camera.position))};if(Xt.dir[2]<0){const Et=Q.zoomDeltaToMovement(Ut,we);o.bJ(St,Xt.dir,Et)}}const kt=o.cT(ht,ht,St);Q._translateCameraConstrained(kt),we&&Math.abs(Q.zoom-ct)>1e-4&&Q.recenterOnTerrain(),Q.cameraElevationReference="ground",this._map._update(),N.noInertia||this._inertia.record(N),this._fireEvents(T,B,!0)}_fireEvents(N,T,B){const W=cI(this._eventsInProgress),Q=cI(N),se={};for(const De in N){const{originalEvent:Qe}=N[De];this._eventsInProgress[De]||(se[`${De}start`]=Qe),this._eventsInProgress[De]=N[De]}!W&&Q&&this._fireEvent("movestart",Q.originalEvent);for(const De in se)this._fireEvent(De,se[De]);Q&&this._fireEvent("move",Q.originalEvent);for(const De in N){const{originalEvent:Qe}=N[De];this._fireEvent(De,Qe)}const ue={};let we;for(const De in this._eventsInProgress){const{handlerName:Qe,originalEvent:Ye}=this._eventsInProgress[De];this._handlersById[Qe].isActive()||(delete this._eventsInProgress[De],we=T[Qe]||Ye,ue[`${De}end`]=we)}for(const De in ue)this._fireEvent(De,ue[De]);const Te=cI(this._eventsInProgress);if(B&&(W||Q)&&!Te){this._updatingCamera=!0;const De=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Qe=Ye=>Ye!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new Sie("renderFrame",{timeStamp:N})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const RK="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Eie extends o.E{constructor(N,T){super(),this._moving=!1,this._zooming=!1,this.transform=N,this._bearingSnap=T.bearingSnap,this._respectPrefersReducedMotion=T.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(N,T){return this.jumpTo({center:N},T)}panBy(N,T,B){return N=o.P.convert(N).mult(-1),this.panTo(this.transform.center,Object.assign({offset:N},T),B)}panTo(N,T,B){return this.easeTo(Object.assign({center:N},T),B)}getZoom(){return this.transform.zoom}setZoom(N,T){return this.jumpTo({zoom:N},T),this}zoomTo(N,T,B){return this.easeTo(Object.assign({zoom:N},T),B)}zoomIn(N,T){return this.zoomTo(this.getZoom()+1,N,T),this}zoomOut(N,T){return this.zoomTo(this.getZoom()-1,N,T),this}getBearing(){return this.transform.bearing}setBearing(N,T){return this.jumpTo({bearing:N},T),this}getPadding(){return this.transform.padding}setPadding(N,T){return this.jumpTo({padding:N},T),this}rotateTo(N,T,B){return this.easeTo(Object.assign({bearing:N},T),B)}resetNorth(N,T){return this.rotateTo(0,Object.assign({duration:1e3},N),T),this}resetNorthPitch(N,T){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},N),T),this}snapToNorth(N,T){return Math.abs(this.getBearing())N.aspect?B/(2*Math.tan(.5*N.fovX)*N.aspect):W/(2*Math.tan(.5*N.fovY)*N.aspect)}_cameraForBoundsOnGlobe(N,T,B,W,Q,se){const ue=N.clone(),we=this._extendCameraOptions(se);ue.bearing=W,ue.pitch=Q;const Te=o.aU.convert(T),De=o.aU.convert(B),Qe=.5*(Te.lat+De.lat),Ye=.5*(Te.lng+De.lng),tt=o.eT(Qe,Ye),ht=o.ay([],tt),ct=o.ay([],o.bh([],ht,[0,1,0])),St=o.bh([],ct,ht),kt=[ct[0],ct[1],ct[2],0,St[0],St[1],St[2],0,ht[0],ht[1],ht[2],0,0,0,0,1],Ut=[tt,o.eT(Te.lat,Te.lng),o.eT(De.lat,Te.lng),o.eT(De.lat,De.lng),o.eT(Te.lat,De.lng),o.eT(Qe,Te.lng),o.eT(Qe,De.lng),o.eT(Te.lat,Ye),o.eT(De.lat,Ye)];let Xt=o.cU.fromPoints(Ut.map(jn=>[o.bi(ct,jn),o.bi(St,jn),o.bi(ht,jn)]));const Et=o.ah([],Xt.center,kt);o.eU(Et)===0&&o.eV(Et,0,0,1),o.ay(Et,Et),o.bJ(Et,Et,o.aF),ue.center=o.eW(Et);const Ts=ue.getWorldToCameraMatrix(),ds=o.b7(new Float64Array(16),Ts);Xt=o.cU.applyTransform(Xt,o.aD([],Ts,kt));const Cs=this._extendAABB(Xt,ue,we,W);if(!Cs)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Xt=Cs,o.ah(Et,Et,Ts);const es=.5*(Xt.max[2]-Xt.min[2]),is=this._minimumAABBFrustumDistance(ue,Xt),_s=o.bJ([],[0,0,1],es),Xs=o.cT(_s,Et,_s),Ds=is+(ue.pitch===0?0:o.bf(Et,Xs)),_n=ue.globeCenterInViewSpace,pn=o.ax([],Et,[_n[0],_n[1],_n[2]]);o.ay(pn,pn),o.bJ(pn,pn,Ds);const Un=o.cT([],Et,pn);o.ah(Un,Un,ds);const Xn=o.eD/o.aF,nn=o.ai(Un),Bs=o.bU(Math.max(nn*Xn-o.eD,Number.EPSILON),0),yn=Math.min(ue.zoomFromMercatorZAdjusted(Bs),we.maxZoom);return yn>.5*(o.cJ+o.cv)?(ue.setProjection({name:"mercator"}),ue.zoom=yn,this._cameraForBounds(ue,T,B,W,Q,se)):{center:ue.center,zoom:yn,bearing:W,pitch:Q}}_extendAABB(N,T,B,W){const Q=.5*((B.padding.left||0)+(B.padding.right||0)),se=.5*((B.padding.top||0)+(B.padding.bottom||0)),ue=se,we=Q,Te=Q,De=se,Qe=T.width-(we+Te),Ye=T.height-(ue+De),tt=o.ax([],N.max,N.min),ht=Math.min(Qe/tt[0],Ye/tt[1]),ct=Math.min(T.scaleZoom(T.scale*ht),B.maxZoom);if(isNaN(ct))return null;const St=T.scale/T.zoomScale(ct),kt=new o.cU([N.min[0]-we*St,N.min[1]-De*St,N.min[2]],[N.max[0]+Te*St,N.max[1]+ue*St,N.max[2]]),Ut=(typeof B.offset.x=="number"&&typeof B.offset.y=="number"?new o.P(B.offset.x,B.offset.y):o.P.convert(B.offset)).rotate(-o.ap(W));return kt.center[0]-=Ut.x*St,kt.center[1]+=Ut.y*St,kt}queryTerrainElevation(N,T){const B=this.transform.elevation;return B?(T=Object.assign({},{exaggerated:!0},T),B.getAtPoint(o.ag.fromLngLat(N),null,T.exaggerated)):null}_cameraForBounds(N,T,B,W,Q,se){if(N.projection.name==="globe")return this._cameraForBoundsOnGlobe(N,T,B,W,Q,se);const ue=N.clone(),we=this._extendCameraOptions(se);ue.bearing=W,ue.pitch=Q;const Te=o.aU.convert(T),De=o.aU.convert(B),Qe=new o.aU(Te.lng,De.lat),Ye=new o.aU(De.lng,Te.lat),tt=ue.project(Te),ht=ue.project(De),ct=this.queryTerrainElevation(Te),St=this.queryTerrainElevation(De),kt=this.queryTerrainElevation(Qe),Ut=this.queryTerrainElevation(Ye),Xt=[[tt.x,tt.y,Math.min(ct||0,St||0,kt||0,Ut||0)],[ht.x,ht.y,Math.max(ct||0,St||0,kt||0,Ut||0)]];let Et=o.cU.fromPoints(Xt);const Ts=ue.getWorldToCameraMatrix(),ds=o.b7(new Float64Array(16),Ts);Et=o.cU.applyTransform(Et,Ts);const Cs=this._extendAABB(Et,ue,we,W);if(!Cs)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Et=Cs;const es=.5*o.ax([],Et.max,Et.min)[2],is=this._minimumAABBFrustumDistance(ue,Et),_s=[0,0,1,0];o.aE(_s,_s,Ts),o.eX(_s,_s);const Xs=o.bJ([],_s,is+es),Ds=o.cT([],Et.center,Xs);o.ah(Et.center,Et.center,ds),o.ah(Ds,Ds,ds);const _n=ue.unproject(new o.P(Et.center[0],Et.center[1])),pn=o.eY(ue.projection,_n),Un=Math.pow(2,pn),Xn=Math.min(ue._zoomFromMercatorZ(Ds[2]*ue.pixelsPerMeter*Un/ue.worldSize),we.maxZoom);return ue.mercatorFromTransition&&Xn<.5*(o.cJ+o.cv)?(ue.setProjection({name:"globe"}),ue.zoom=Xn,this._cameraForBounds(ue,T,B,W,Q,se)):{center:_n,zoom:Xn,bearing:W,pitch:Q}}fitBounds(N,T,B){const W=this.cameraForBounds(N,T);return this._fitInternal(W,T,B)}fitScreenCoordinates(N,T,B,W,Q){const se=o.P.convert(N),ue=o.P.convert(T),we=new o.P(Math.min(se.x,ue.x),Math.min(se.y,ue.y)),Te=new o.P(Math.max(se.x,ue.x),Math.max(se.y,ue.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(se,ue))return this;const De=this.transform.pointLocation3D(we),Qe=this.transform.pointLocation3D(Te),Ye=this.transform.pointLocation3D(new o.P(we.x,Te.y)),tt=this.transform.pointLocation3D(new o.P(Te.x,we.y)),ht=[Math.min(De.lng,Qe.lng,Ye.lng,tt.lng),Math.min(De.lat,Qe.lat,Ye.lat,tt.lat)],ct=[Math.max(De.lng,Qe.lng,Ye.lng,tt.lng),Math.max(De.lat,Qe.lat,Ye.lat,tt.lat)],St=W&&W.pitch?W.pitch:this.getPitch(),kt=this._cameraForBounds(this.transform,ht,ct,B,St,W);return this._fitInternal(kt,W,Q)}_fitInternal(N,T,B){return N?(T=Object.assign(N,T)).linear?this.easeTo(T,B):this.flyTo(T,B):this}jumpTo(N,T){this.stop();const B=N.preloadOnly?this.transform.clone():this.transform;let W=!1,Q=!1,se=!1;"zoom"in N&&B.zoom!==+N.zoom&&(W=!0,B.zoom=+N.zoom),N.center!==void 0&&(B.center=o.aU.convert(N.center)),"bearing"in N&&B.bearing!==+N.bearing&&(Q=!0,B.bearing=+N.bearing),"pitch"in N&&B.pitch!==+N.pitch&&(se=!0,B.pitch=+N.pitch);const ue=typeof N.padding=="number"?this._extendPadding(N.padding):N.padding;if(N.padding!=null&&!B.isPaddingEqual(ue))if(N.retainPadding===!1){const we=B.clone();we.padding=ue,B.setLocationAtPoint(B.center,we.centerPoint)}else B.padding=ue;return N.preloadOnly?(this._preloadTiles(B),this):(this.fire(new o.C("movestart",T)).fire(new o.C("move",T)),W&&this.fire(new o.C("zoomstart",T)).fire(new o.C("zoom",T)).fire(new o.C("zoomend",T)),Q&&this.fire(new o.C("rotatestart",T)).fire(new o.C("rotate",T)).fire(new o.C("rotateend",T)),se&&this.fire(new o.C("pitchstart",T)).fire(new o.C("pitch",T)).fire(new o.C("pitchend",T)),this.fire(new o.C("moveend",T)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(RK),this.transform.getFreeCameraOptions()}setFreeCameraOptions(N,T){const B=this.transform;if(!B.projection.supportsFreeCamera)return o.w(RK),this;this.stop();const W=B.zoom,Q=B.pitch,se=B.bearing;B.setFreeCameraOptions(N);const ue=W!==B.zoom,we=Q!==B.pitch,Te=se!==B.bearing;return this.fire(new o.C("movestart",T)).fire(new o.C("move",T)),ue&&this.fire(new o.C("zoomstart",T)).fire(new o.C("zoom",T)).fire(new o.C("zoomend",T)),Te&&this.fire(new o.C("rotatestart",T)).fire(new o.C("rotate",T)).fire(new o.C("rotateend",T)),we&&this.fire(new o.C("pitchstart",T)).fire(new o.C("pitch",T)).fire(new o.C("pitchend",T)),this.fire(new o.C("moveend",T)),this}easeTo(N,T){this._stop(!1,N.easeId),((N=Object.assign({offset:[0,0],duration:500,easing:o.eP},N)).animate===!1||this._prefersReducedMotion(N))&&(N.duration=0);const B=this.transform,W=this.getZoom(),Q=this.getBearing(),se=this.getPitch(),ue=this.getPadding(),we="zoom"in N?+N.zoom:W,Te="bearing"in N?this._normalizeBearing(N.bearing,Q):Q,De="pitch"in N?+N.pitch:se,Qe=this._extendPadding(N.padding),Ye=o.P.convert(N.offset);let tt,ht,ct;if(B.projection.name==="globe"){const _s=o.ag.fromLngLat(B.center),Xs=Ye.rotate(-B.angle);_s.x+=Xs.x/B.worldSize,_s.y+=Xs.y/B.worldSize;const Ds=_s.toLngLat(),_n=o.aU.convert(N.center||Ds);this._normalizeCenter(_n),tt=B.centerPoint.add(Xs),ht=new o.P(_s.x,_s.y).mult(B.worldSize),ct=new o.P(o.aH(_n.lng),o.aL(_n.lat)).mult(B.worldSize).sub(ht)}else{tt=B.centerPoint.add(Ye);const _s=B.pointLocation(tt),Xs=o.aU.convert(N.center||_s);this._normalizeCenter(Xs),ht=B.project(_s),ct=B.project(Xs).sub(ht)}const St=B.zoomScale(we-W);let kt,Ut;N.around&&(kt=o.aU.convert(N.around),Ut=B.locationPoint(kt));const Xt=this._zooming||we!==W,Et=this._rotating||Q!==Te,Ts=this._pitching||De!==se,ds=!B.isPaddingEqual(Qe),Cs=N.retainPadding===!1?B.clone():B,es=_s=>Xs=>{if(Xt&&(_s.zoom=o.am(W,we,Xs)),Et&&(_s.bearing=o.am(Q,Te,Xs)),Ts&&(_s.pitch=o.am(se,De,Xs)),ds&&(Cs.interpolatePadding(ue,Qe,Xs),tt=Cs.centerPoint.add(Ye)),kt)_s.setLocationAtPoint(kt,Ut);else{const Ds=_s.zoomScale(_s.zoom-W),_n=we>W?Math.min(2,St):Math.max(.5,St),pn=Math.pow(_n,1-Xs),Un=_s.unproject(ht.add(ct.mult(Xs*pn)).mult(Ds));_s.setLocationAtPoint(_s.renderWorldCopies?Un.wrap():Un,tt)}return N.preloadOnly||this._fireMoveEvents(T),_s};if(N.preloadOnly){const _s=this._emulate(es,N.duration,B);return this._preloadTiles(_s),this}const is={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Xt,this._rotating=Et,this._pitching=Ts,this._padding=ds,this._easeId=N.easeId,this._prepareEase(T,N.noMoveStart,is),this._ease(es(B),_s=>{B.cameraElevationReference==="sea"&&B.recenterOnTerrain(),this._afterEase(T,_s)},N),this}_prepareEase(N,T,B={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),T||B.moving||this.fire(new o.C("movestart",N)),this._zooming&&!B.zooming&&this.fire(new o.C("zoomstart",N)),this._rotating&&!B.rotating&&this.fire(new o.C("rotatestart",N)),this._pitching&&!B.pitching&&this.fire(new o.C("pitchstart",N))}_fireMoveEvents(N){this.fire(new o.C("move",N)),this._zooming&&this.fire(new o.C("zoom",N)),this._rotating&&this.fire(new o.C("rotate",N)),this._pitching&&this.fire(new o.C("pitch",N))}_afterEase(N,T){if(this._easeId&&T&&this._easeId===T)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const B=this._zooming,W=this._rotating,Q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,B&&this.fire(new o.C("zoomend",N)),W&&this.fire(new o.C("rotateend",N)),Q&&this.fire(new o.C("pitchend",N)),this.fire(new o.C("moveend",N))}flyTo(N,T){if(this._prefersReducedMotion(N)){const jn=o.aJ(N,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(jn,T)}this.stop(),N=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},N);const B=this.transform,W=this.getZoom(),Q=this.getBearing(),se=this.getPitch(),ue=this.getPadding(),we="zoom"in N?o.aC(+N.zoom,B.minZoom,B.maxZoom):W,Te="bearing"in N?this._normalizeBearing(N.bearing,Q):Q,De="pitch"in N?+N.pitch:se,Qe=this._extendPadding(N.padding),Ye=B.zoomScale(we-W),tt=o.P.convert(N.offset);let ht=B.centerPoint.add(tt);const ct=B.pointLocation(ht),St=o.aU.convert(N.center||ct);this._normalizeCenter(St);const kt=B.project(ct),Ut=B.project(St).sub(kt);let Xt=N.curve;const Et=Math.max(B.width,B.height),Ts=Et/Ye,ds=Ut.mag();if("minZoom"in N){const jn=o.aC(Math.min(N.minZoom,W,we),B.minZoom,B.maxZoom),In=Et/B.zoomScale(jn-W);Xt=Math.sqrt(In/ds*2)}const Cs=Xt*Xt;function es(jn){const In=(Ts*Ts-Et*Et+(jn?-1:1)*Cs*Cs*ds*ds)/(2*(jn?Ts:Et)*Cs*ds);return Math.log(Math.sqrt(In*In+1)-In)}function is(jn){return(Math.exp(jn)-Math.exp(-jn))/2}function _s(jn){return(Math.exp(jn)+Math.exp(-jn))/2}const Xs=es(0);let Ds=function(jn){return _s(Xs)/_s(Xs+Xt*jn)},_n=function(jn){return Et*((_s(Xs)*(is(In=Xs+Xt*jn)/_s(In))-is(Xs))/Cs)/ds;var In},pn=(es(1)-Xs)/Xt;if(Math.abs(ds)<1e-6||!isFinite(pn)){if(Math.abs(Et-Ts)<1e-6)return this.easeTo(N,T);const jn=TsN.maxDuration&&(N.duration=0);const Un=Q!==Te,Xn=De!==se,nn=!B.isPaddingEqual(Qe),Bs=N.retainPadding===!1?B.clone():B,yn=jn=>In=>{const Sr=In*pn,xr=1/Ds(Sr);jn.zoom=In===1?we:W+jn.scaleZoom(xr),Un&&(jn.bearing=o.am(Q,Te,In)),Xn&&(jn.pitch=o.am(se,De,In)),nn&&(Bs.interpolatePadding(ue,Qe,In),ht=Bs.centerPoint.add(tt));const gr=In===1?St:jn.unproject(kt.add(Ut.mult(_n(Sr))).mult(xr));return jn.setLocationAtPoint(jn.renderWorldCopies?gr.wrap():gr,ht),jn._updateCameraOnTerrain(),N.preloadOnly||this._fireMoveEvents(T),jn};if(N.preloadOnly){const jn=this._emulate(yn,N.duration,B);return this._preloadTiles(jn),this}return this._zooming=!0,this._rotating=Un,this._pitching=Xn,this._padding=nn,this._prepareEase(T,!1),this._ease(yn(B),()=>this._afterEase(T),N),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(N){}_cancelRenderFrame(N){}_stop(N,T){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const B=this._onEaseEnd;this._onEaseEnd=void 0,B.call(this,T)}if(!N){const B=this.handlers;B&&B.stop(!1)}return this}_ease(N,T,B){B.animate===!1||B.duration===0?(N(1),T()):(this._easeStart=o.o.now(),this._easeOptions=B,this._onEaseFrame=N,this._onEaseEnd=T,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const N=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),T=this._onEaseFrame;T&&T(this._easeOptions.easing(N)),N<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(N,T){N=o.bs(N,-180,180);const B=Math.abs(N-T);return Math.abs(N-360-T)180?-360:B<-180?360:0}_prefersReducedMotion(N){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(N&&N.essential)}_emulate(N,T,B){const W=Math.ceil(15*T/1e3),Q=[],se=N(B.clone());for(let ue=0;ue<=W;ue++){const we=se(ue/W);Q.push(we.clone())}return Q}_preloadTiles(N,T){}}class FK{constructor(N={}){this.options=N,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(N){const T=this.options&&this.options.compact,B=N._getUIString("AttributionControl.ToggleAttribution");this._map=N,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=g("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",B);const W=g("span","mapboxgl-ctrl-icon",this._compactButton);return W.setAttribute("aria-hidden","true"),W.setAttribute("title",B),this._innerContainer=g("div","mapboxgl-ctrl-attrib-inner",this._container),T&&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),T===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let N=this._editLink;N||(N=this._editLink=this._container.querySelector(".mapbox-improve-map"));const T=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(N){const B=T.reduce((W,Q,se)=>(Q.value&&(W+=`${Q.key}=${Q.value}${seW.length-Q.length),N=N.filter((W,Q)=>{for(let se=Q+1;se=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?N=[...this.options.customAttribution,...N]:N.unshift(this.options.customAttribution));const B=N.map(W=>function(Q){const se=new DOMParser().parseFromString(Q,"text/html");return Array.from(se.body.querySelectorAll("*")).reverse().forEach(ue=>{const we=ue.textContent||"";if(ue.tagName!=="A")return void ue.replaceWith(...ue.childNodes);const Te=ue.getAttribute("href");if(!Te||!/^(https?:|mailto:)/i.test(Te))return void ue.replaceWith(se.createTextNode(we));const De=se.createElement("a");De.href=Te,De.textContent=we,De.rel="noopener nofollow";const Qe=ue.getAttribute("class");Qe&&(De.className=Qe),ue.replaceWith(De)}),se.body.innerHTML}(W)).join(" | ");B!==this._attribHTML&&(this._attribHTML=B,N.length?(this._innerContainer.innerHTML=B,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 OK{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(N){this._map=N,this._container=g("div","mapboxgl-ctrl");const T=g("a","mapboxgl-ctrl-logo");return T.target="_blank",T.rel="noopener nofollow",T.href="https://www.mapbox.com/",T.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),T.setAttribute("rel","noopener nofollow"),this._container.appendChild(T),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(N){N&&N.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const N=this._map.style._sourceCaches;if(Object.entries(N).length===0)return!0;for(const T in N){const B=N[T].getSource();if(B.hasOwnProperty("mapbox_logo")&&!B.mapbox_logo)return!1}return!0}_updateCompact(){const N=this._container.children;if(N.length){const T=N[0];this._map.getCanvasContainer().offsetWidth<250?T.classList.add("mapboxgl-compact"):T.classList.remove("mapboxgl-compact")}}}class Tie{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(N){const T=++this._id;return this._queue.push({callback:N,id:T,cancelled:!1}),T}remove(N){const T=this._currentlyRunning,B=T?this._queue.concat(T):this._queue;for(const W of B)if(W.id===N)return void(W.cancelled=!0)}run(N=0){const T=this._currentlyRunning=this._queue;this._queue=[];for(const B of T)if(!B.cancelled&&(B.callback(N),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class zDe{constructor(N){this.jumpTo(N)}getValue(N){if(N<=this._startTime)return this._start;if(N>=this._endTime)return this._end;const T=o.dn((N-this._startTime)/(this._endTime-this._startTime));return this._start*(1-T)+this._end*T}isEasing(N){return N>=this._startTime&&N<=this._endTime}jumpTo(N){this._startTime=-1/0,this._endTime=-1/0,this._start=N,this._end=N}easeTo(N,T,B){this._start=this.getValue(T),this._end=N,this._startTime=T,this._endTime=T+B}}const BDe={"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 Bc extends o.C{constructor(N,T,B,W){const{point:Q,lngLat:se,originalEvent:ue,target:we}=N;super(N.type,{point:Q,lngLat:se,originalEvent:ue,target:we}),this.preventDefault=()=>{N.preventDefault()},this.id=T,this.interaction=B,this.feature=W}}class qz{constructor(N){this.map=N,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(N,T){if(this.typeById.has(N))throw new Error(`Interaction id "${N}" already exists.`);const B=T.filter;let W=T.type;B&&this.filters.set(N,o.dg(B)),W==="mouseover"&&(W="mouseenter"),W==="mouseout"&&(W="mouseleave");const Q=this.interactionsByType.get(W)||new Map;W==="mouseenter"||W==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(N,T)):Q.size===0&&this.map.on(W,this.handleType),Q.size===0&&this.interactionsByType.set(W,Q),Q.set(N,T),this.typeById.set(N,W)}get(N){const T=this.typeById.get(N);if(!T)return;const B=this.interactionsByType.get(T);return B?B.get(N):void 0}remove(N){const T=this.typeById.get(N);if(!T)return;this.typeById.delete(N),this.filters.delete(N);const B=this.interactionsByType.get(T);B&&(B.delete(N),T==="mouseenter"||T==="mouseleave"?(this.delegatedInteractions.delete(N),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):B.size===0&&this.map.off(T,this.handleType))}queryTargets(N,T){const B=[];for(const[W,Q]of T)Q.target&&B.push({targetId:W,target:Q.target,filter:this.filters.get(W)});return this.map.style.queryRenderedTargets(N,B,this.map.transform)}handleMove(N){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const T=this.queryTargets(N.point,Array.from(this.delegatedInteractions).reverse());T.length&&(N.type="mouseenter",this.handleType(N,T));const B=new Map;for(const[W,{feature:Q}]of this.prevHoveredFeatures)this.hoveredFeatures.has(W)||B.set(Q.id,Q);B.size&&(N.type="mouseleave",this.handleType(N,Array.from(B.values())))}handleOut(N){const T=Array.from(this.hoveredFeatures.values()).map(({feature:B})=>B);T.length&&(N.type="mouseleave",this.handleType(N,T)),this.hoveredFeatures.clear()}handleType(N,T){const B=N.type==="mouseenter";if(B&&!this.interactionsByType.has(N.type))return void o.w("mouseenter interaction required for mouseleave to work.");const W=Array.from(this.interactionsByType.get(N.type)).reverse(),Q=!!T;T=T||this.queryTargets(N.point,W);let se=!1;const ue=new Set;for(const we of T){for(const[Te,De]of W){if(!De.target)continue;const Qe=we.variants?we.variants[Te]:null;if(Qe){for(const Ye of Qe){if(pi(Ye,we,ue,Te))continue;const tt=new o.di(we,Ye),ht=ho(Ye,we,Te);Q&&tt.id!==void 0&&(tt.state=this.map.getFeatureState(tt));const ct=B?this.prevHoveredFeatures.get(ht):null,St=new Bc(N,Te,De,tt),kt=ct?ct.stop:De.handler(St);if(B&&this.hoveredFeatures.set(ht,{feature:we,stop:kt}),kt!==!1){se=!0;break}}if(se)break}}if(se)break}if(!se)for(const[we,Te]of W){const{handler:De,target:Qe}=Te;if(!Qe&&De(new Bc(N,we,Te,null))!==!1)break}}}function $De(R,N){if(Array.isArray(R)&&Array.isArray(N)){const T=new Set(R),B=new Set(N);return T.size===B.size&&R.every(W=>B.has(W))}return o.b6(R,N)}const UDe={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},qDe={showCompass:!0,showZoom:!0,visualizePitch:!1};class uI{constructor(N,T,B=!1){this._clickTolerance=10,this.element=T,this.mouseRotate=new Fz({clickTolerance:N.dragRotate._mouseRotate._clickTolerance}),this.map=N,B&&(this.mousePitch=new iI({clickTolerance:N.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),T.addEventListener("mousedown",this.mousedown),T.addEventListener("touchstart",this.touchstart,{passive:!1}),T.addEventListener("touchmove",this.touchmove),T.addEventListener("touchend",this.touchend),T.addEventListener("touchcancel",this.reset)}down(N,T){this.mouseRotate.mousedown(N,T),this.mousePitch&&this.mousePitch.mousedown(N,T),S()}move(N,T){const B=this.map,W=this.mouseRotate.mousemoveWindow(N,T),Q=W&&W.bearingDelta;if(Q&&B.setBearing(B.getBearing()+Q),this.mousePitch){const se=this.mousePitch.mousemoveWindow(N,T),ue=se&&se.pitchDelta;ue&&B.setPitch(B.getPitch()+ue)}}off(){const N=this.element;N.removeEventListener("mousedown",this.mousedown),N.removeEventListener("touchstart",this.touchstart),N.removeEventListener("touchmove",this.touchmove),N.removeEventListener("touchend",this.touchend),N.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){C(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(N){this.down(Object.assign({},N,{button:N.button,type:N.type,ctrlKey:!0,preventDefault:()=>N.preventDefault()}),M(this.element,N)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(N){this.move(N,M(this.element,N))}mouseup(N){this.mouseRotate.mouseupWindow(N),this.mousePitch&&this.mousePitch.mouseupWindow(N),this.offTemp()}touchstart(N){N.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=I(this.element,N.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>N.preventDefault()},this._startPos))}touchmove(N){N.targetTouches.length!==1?this.reset():(this._lastPos=I(this.element,N.targetTouches)[0],this.move({buttons:1,preventDefault:()=>N.preventDefault()},this._lastPos))}touchend(N){N.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)T.width||N.y>T.height;T.locationPoint3D(B).distSqr(N)180;){const B=T.locationPoint3D(R);if(B.x>=0&&B.y>=0&&B.x<=T.width&&B.y<=T.height)break;R.lng>T.center.lng?R.lng-=360:R.lng+=360}return R}const hI={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%)"},z1={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Jb extends o.E{constructor(N,T){super(),(N instanceof HTMLElement||T)&&(N=Object.assign({element:N},T)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:B="center",color:W="#3FB1CE",scale:Q=1,draggable:se=!1,clickTolerance:ue=0,rotation:we=z1.rotation,rotationAlignment:Te=z1.rotationAlignment,pitchAlignment:De=z1.pitchAlignment,occludedOpacity:Qe=z1.occludedOpacity,altitude:Ye=z1.altitude}=N||{};this._anchor=B,this._color=W,this._scale=Q,this._draggable=se,this._clickTolerance=ue,this._rotation=we,this._rotationAlignment=Te,this._pitchAlignment=De,this._occludedOpacity=Qe,this._altitude=Ye,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),N&&N.element?(this._element=N.element,this._offset=o.P.convert(N&&N.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(N&&N.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",ct=>{ct.preventDefault()}),this._element.addEventListener("mousedown",ct=>{ct.preventDefault()});const tt=this._element.classList;for(const ct in hI)tt.remove(`mapboxgl-marker-anchor-${ct}`);tt.add(`mapboxgl-marker-anchor-${this._anchor}`);const ht=N&&N.className?N.className.trim().split(/\s+/):[];tt.add(...ht),this._popup=null}_createDefaultMarker(){const N=g("div"),T=v("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},N);if(this._altitude===0){const B=v("radialGradient",{id:"shadowGradient"},v("defs",{},T));v("stop",{offset:"10%","stop-opacity":.4},B),v("stop",{offset:"100%","stop-opacity":.05},B),v("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},T)}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"},T),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"},T),v("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},T),N}addTo(N){return N===this._map||(this.remove(),this._map=N,N.getCanvasContainer().appendChild(this._element),N.on("move",this._updateMoving),N.on("moveend",this._update),N.on("remove",this._clearFadeTimer),N._addMarker(this),this.setDraggable(this._draggable),this._update(),N.on("click",this._onMapClick)),this}remove(){const N=this._map;return N&&(N.off("click",this._onMapClick),N.off("move",this._updateMoving),N.off("moveend",this._update),N.off("mousedown",this._addDragHandler),N.off("touchstart",this._addDragHandler),N.off("mouseup",this._onUp),N.off("touchend",this._onUp),N.off("mousemove",this._onMove),N.off("touchmove",this._onMove),N.off("remove",this._clearFadeTimer),N._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(N){return this._lngLat=o.aU.convert(N),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(N){return N===this._altitude||(this._defaultMarker&&(this._altitude===0&&N!==0||this._altitude!==0&&N===0)&&(this._element=this._createDefaultMarker()),this._altitude=N||z1.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(N){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute("role"),this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),N){if(!("offset"in N.options)){const W=Math.sqrt(Math.pow(13.5,2)/2);N.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[W,-1*(38.1-13.5+W)],"bottom-right":[-W,-1*(38.1-13.5+W)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=N,N._marker=this,N._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(N){const T=N.code,B=N.charCode||N.keyCode;T!=="Space"&&T!=="Enter"&&B!==32&&B!==13||this.togglePopup()}_onMapClick(N){const T=N.originalEvent.target,B=this._element;this._popup&&(T===B||B.contains(T))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const N=this._popup;return N?(N.isOpen()?(N.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(N.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const N=this._map,T=this._pos;if(!N||!T)return!1;const B=N.unproject(T,this._altitude),W=N.getFreeCameraOptions();if(!W.position)return!1;const Q=W.position.toLngLat();return Q.distanceTo(B)<.9*Q.distanceTo(this._lngLat)}_evaluateOpacity(){const N=this._map;if(!N)return;const T=this._pos;if(!T||T.x<0||T.x>N.transform.width||T.y<0||T.y>N.transform.height)return void this._clearFadeTimer();const B=N.unproject(T,this._altitude);let W;N._showingGlobe()&&o.e$(N.transform,this._lngLat)?W=0:(W=1-N._queryFogOpacity(B),N.transform._terrainEnabled()&&N.getTerrain()&&this._behindTerrain()&&(W*=this._occludedOpacity)),this._element.style.opacity=`${W}`,this._element.style.pointerEvents=W>0?"auto":"none",this._popup&&this._popup._setOpacity(W),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const N=this._pos;if(!N||!this._map)return;const T=this._offset.mult(this._scale);this._element.style.transform=` translate(${N.x}px,${N.y}px) ${hI[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${T.x}px,${T.y}px) `}_calculateXYTransform(){const N=this._pos,T=this._map,B=this.getPitchAlignment();if(!T||!N||B!=="map")return"";if(!T._showingGlobe()){const we=T.getPitch();return we?`rotateX(${we}deg)`:""}const W=o.cH(o.f0(T.transform,this._lngLat)),Q=N.sub(o.f1(T.transform)),se=Math.abs(Q.x)+Math.abs(Q.y);if(se===0)return"";const ue=W/se;return`rotateX(${-Q.y*ue}deg) rotateY(${Q.x*ue}deg)`}_calculateZTransform(){const N=this._pos,T=this._map;if(!T||!N)return"";let B=0;const W=this.getRotationAlignment();if(W==="map")if(T._showingGlobe()){const Q=T.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),se=T.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Q);B=o.cH(Math.atan2(se.y,se.x))-90}else B=-T.getBearing();else if(W==="horizon"){const Q=o.aj(4,6,T.getZoom()),se=o.f1(T.transform);se.y+=Q*T.transform.height;const ue=N.sub(se),we=o.cH(Math.atan2(ue.y,ue.x));B=(we>90?we-270:we+90)*(1-Q)}return B+=this._rotation,B?`rotateZ(${B}deg)`:""}_update(N){cancelAnimationFrame(this._updateFrameId);const T=this._map;T&&(T.transform.renderWorldCopies&&(this._lngLat=zK(this._lngLat,this._pos,T.transform)),this._pos=T.project(this._lngLat,this._altitude),N===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),T._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(T._showingGlobe()||T.getTerrain()||T.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(N){return this._offset=o.P.convert(N),this._update(),this}addClassName(N){return this._element.classList.add(N),this}removeClassName(N){return this._element.classList.remove(N),this}toggleClassName(N){return this._element.classList.toggle(N)}_onMove(N){const T=this._map;if(!T)return;const B=this._pointerdownPos,W=this._positionDelta;if(B&&W){if(!this._isDragging){const Q=this._clickTolerance||T._clickTolerance;if(N.point.dist(B)R.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(R.minPitch!=null&&R.maxPitch!=null&&R.minPitch>R.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(R.minPitch!=null&&R.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(R.maxPitch!=null&&R.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");R.antialias&&o.eZ(window)&&(R.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 ph(R.minZoom,R.maxZoom,R.minPitch,R.maxPitch,R.renderWorldCopies,null,null),R),this._repaint=!!R.repaint,this._interactive=R.interactive,this._minTileCacheSize=R.minTileCacheSize,this._maxTileCacheSize=R.maxTileCacheSize,this._failIfMajorPerformanceCaveat=R.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=R.preserveDrawingBuffer,this._antialias=R.antialias,this._trackResize=R.trackResize,this._bearingSnap=R.bearingSnap,this._refreshExpiredTiles=R.refreshExpiredTiles,this._fadeDuration=R.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=R.crossSourceCollisions,this._collectResourceTiming=R.collectResourceTiming,this._language=this._parseLanguage(R.language),this._worldview=R.worldview,this._renderTaskQueue=new Tie,this._domRenderTaskQueue=new Tie,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},BDe,R.locale),this._clickTolerance=R.clickTolerance,this._cooperativeGestures=R.cooperativeGestures,this._performanceMetricsCollection=R.performanceMetricsCollection,this._tessellationStep=R.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=R.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new zDe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=R.scaleFactor,this._requestManager=new V(R.transformRequest,R.accessToken,R.testMode);const T=re(R.accessToken||o.g.ACCESS_TOKEN);if(T&&"atlas"in T&&typeof T.atlas=="number"&&(this._tokenExpiration=T.atlas),this._silenceAuthErrors=!!R.testMode,this._contextCreateOptions=R.contextCreateOptions?Object.assign({},R.contextCreateOptions):{},typeof R.container=="string"){const B=document.getElementById(R.container);if(!B)throw new Error(`Container '${R.container.toString()}' not found.`);this._container=B}else{if(!(R.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=R.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."),R.maxBounds&&this.setMaxBounds(R.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 Aie(this,R),this._localFontFamily=R.localFontFamily,this._localIdeographFontFamily=R.localIdeographFontFamily,this._useServerFontComposition=R.useServerFontComposition,(R.style||!R.testMode)&&this.setStyle(R.style||o.g.DEFAULT_STYLE,{config:R.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),R.projection&&this.setProjection(R.projection),R.hash&&(this._hash=new Ih(typeof R.hash=="string"&&R.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){N.center==null&&N.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:R.center,zoom:R.zoom,bearing:R.bearing,pitch:R.pitch});const B=R.bounds;B&&(this.resize(),this.fitBounds(B,Object.assign({},R.fitBoundsOptions,{duration:0})))}this.resize(),R.attributionControl&&this.addControl(new FK({customAttribution:R.customAttribution})),this._logoControl=new OK,this.addControl(this._logoControl,R.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",B=>{this._update(B.dataType==="style"),this.fire(new o.C(`${B.dataType}data`,B))}),this.on("dataloading",B=>{this.fire(new o.C(`${B.dataType}dataloading`,B))}),this._interactions=new qz(this)}_getMapId(){return this._mapId}addControl(R,N){if(N===void 0&&(N=R.getDefaultPosition?R.getDefaultPosition():"top-right"),!R||!R.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 T=R.onAdd(this);this._controls.push(R);const B=this._controlPositions[N];return N.indexOf("bottom")!==-1?B.insertBefore(T,B.firstChild):B.appendChild(T),this}removeControl(R){if(!R||!R.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 N=this._controls.indexOf(R);return N>-1&&this._controls.splice(N,1),R.onRemove(this),this}hasControl(R){return this._controls.indexOf(R)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(R){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const N=!this._moving;return N&&this.fire(new o.C("movestart",R)).fire(new o.C("move",R)),this.fire(new o.C("resize",R)),N&&this.fire(new o.C("moveend",R)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(R){return this.transform.setMaxBounds(o.aK.convert(R)),this._update()}setMinZoom(R){if((R=R??-2)>=-2&&R<=this.transform.maxZoom)return this.transform.minZoom=R,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=R,this._update(),this.getZoom()>R?this.setZoom(R):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(R){if((R=R??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(R>=0&&R<=this.transform.maxPitch)return this.transform.minPitch=R,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(R>=this.transform.minPitch)return this.transform.maxPitch=R,this._update(),this.getPitch()>R?this.setPitch(R):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(R){return this._scaleFactor=R,this.painter.scaleFactor=R,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(N=>N.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(R){return this.transform.renderWorldCopies=R,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(R){return R==="auto"?navigator.language:Array.isArray(R)?R.length===0?void 0:R.map(N=>N==="auto"?navigator.language:N):R}setLanguage(R){const N=this._parseLanguage(R);if(!this.style||N===this._language)return this;this._language=N,this.style.reloadSources();for(const T of this._controls)T._setLanguage&&T._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(R){return this.style&&R!==this._worldview?(this._worldview=R,this._styleDirty=!0,this.style.setWorldview(R),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(R){return this._lazyInitEmptyStyle(),R?typeof R=="string"&&(R={name:R}):R=null,this._useExplicitProjection=!!R,this._prioritizeAndUpdateProjection(R,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const R=this.transform,N=R.projection.name;let T;N==="globe"&&R.zoom>=o.cv?(R.setMercatorFromTransition(),T=!0):N==="mercator"&&R.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(R),this.style.applyProjectionUpdate();const B=this.transform.getProjection().name==="mercator"&&T!==this.transform.mercatorFromTransition;return(N||B)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(R,N){return this.transform.locationPoint3D(o.aU.convert(R),N)}unproject(R,N){return this.transform.pointLocation3D(o.P.convert(R),N)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(R,N,T){const B=W=>{let Q=[];if(Array.isArray(N)){const se=N.filter(ue=>this.getLayer(ue));Q=se.length?this.queryRenderedFeatures(W,{layers:se}):[]}else Q=this.queryRenderedFeatures(W,{target:N});return Q};if(R==="mouseenter"||R==="mouseover"){let W=!1;return{listener:T,targets:N,delegates:{mousemove:se=>{const ue=B(se.point);ue.length?W||(W=!0,T.call(this,new bo(R,this,se.originalEvent,{features:ue}))):W=!1},mouseout:()=>{W=!1}}}}if(R==="mouseleave"||R==="mouseout"){let W=!1;return{listener:T,targets:N,delegates:{mousemove:ue=>{B(ue.point).length?W=!0:W&&(W=!1,T.call(this,new bo(R,this,ue.originalEvent)))},mouseout:ue=>{W&&(W=!1,T.call(this,new bo(R,this,ue.originalEvent)))}}}}{const W=Q=>{const se=B(Q.point);se.length&&(Q.features=se,T.call(this,Q),delete Q.features)};return{listener:T,targets:N,delegates:{[R]:W}}}}on(R,N,T){if(typeof N=="function"||T===void 0)return super.on(R,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const B=this._createDelegatedListener(R,N,T);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[R]=this._delegatedListeners[R]||[],this._delegatedListeners[R].push(B);for(const W in B.delegates)this.on(W,B.delegates[W]);return this}once(R,N,T){if(typeof N=="function"||T===void 0)return super.once(R,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const B=this._createDelegatedListener(R,N,T);for(const W in B.delegates)this.once(W,B.delegates[W]);return this}off(R,N,T){if(typeof N=="function"||T===void 0)return super.off(R,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const B=this._delegatedListeners?this._delegatedListeners[R]:void 0;return B&&(W=>{for(let Q=0;Q{if(T){const W=typeof T=="string"?T:T instanceof Error?T.message:T.error;o.w(`Unable to perform style diff: ${W}. Rebuilding the style from scratch.`),this._updateStyle(R,N)}else B&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=N.localIdeographFontFamily,this._localFontFamily=N.localFontFamily,this._updateStyle(R,N))}_getUIString(R){const N=this._locale[R];if(N==null)throw new Error(`Missing UI string '${R}'`);return N}_updateStyle(R,N){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),R){const T=Object.assign({},N);N&&N.config&&(T.initialConfig=N.config,delete T.config),this.style=new xh(this,T).load(R),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new xh(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(R){return R==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(R)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${R}".`))),!1)}_isTargetValid(R){return"featuresetId"in R?this._isValidId("importId"in R?R.importId:R.featuresetId):"layerId"in R&&this._isValidId(R.layerId)}_areTargetsValid(R){if(Array.isArray(R)){for(const N of R)if(!this._isValidId(N))return!1;return!0}return this._isTargetValid(R)}addSource(R,N){return this._isValidId(R)?(this._lazyInitEmptyStyle(),this.style.addSource(R,N),this._update(!0)):this}isSourceLoaded(R){return!!this._isValidId(R)&&!!this.style&&this.style._isSourceCacheLoaded(R)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(R,N,T){this._lazyInitEmptyStyle(),this.style.addSourceType(R,N,T)}removeSource(R){return this._isValidId(R)?(this.style.removeSource(R),this._updateTerrain(),this._update(!0)):this}getSource(R){return this._isValidId(R)?this.style.getOwnSource(R):null}addImage(R,N,{pixelRatio:T=1,sdf:B=!1,stretchX:W,stretchY:Q,content:se}={}){this._lazyInitEmptyStyle();const ue=o.I.from(R);if(N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap){const{width:we,height:Te,data:De}=o.o.getImageData(N);this.style.addImage(ue,{data:new o.q({width:we,height:Te},De),pixelRatio:T,stretchX:W,stretchY:Q,content:se,sdf:B,version:0,usvg:!1})}else if(N.width===void 0||N.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:we,height:Te}=N,De=N;this.style.addImage(ue,{data:new o.q({width:we,height:Te},new Uint8Array(De.data)),pixelRatio:T,stretchX:W,stretchY:Q,content:se,sdf:B,usvg:!1,version:0,userImage:De}),De.onAdd&&De.onAdd(this,R)}}updateImage(R,N){this._lazyInitEmptyStyle();const T=o.I.from(R),B=this.style.getImage(T);if(!B)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 W=N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap?o.o.getImageData(N):N,{width:Q,height:se,data:ue}=W;if(Q===void 0||se===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(Q!==(B.usvg?B.icon.usvg_tree.width:B.data.width)||se!==(B.usvg?B.icon.usvg_tree.height:B.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${Q}, ${se}) must be that same as the previous version of the image (${B.data.width}, ${B.data.height})`)));const we=!(N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap);let Te=!1;B.usvg?(B.data=new o.q({width:Q,height:se},new Uint8Array(ue)),B.usvg=!1,B.icon=void 0,Te=!0):B.data.replace(ue,we),this.style.updateImage(T,B,Te)}hasImage(R){return R?!!this.style&&!!this.style.getImage(o.I.from(R)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(R){this.style.removeImage(o.I.from(R))}loadImage(R,N){o.n(this._requestManager.transformRequest(R,o.R.Image),(T,B)=>{N(T,B)})}listImages(){return this.style.listImages().map(R=>R.name)}addModel(R,N){this._lazyInitEmptyStyle(),this.style.addModel(R,N)}hasModel(R){return R?this.style.hasModel(R):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(R){this.style.removeModel(R)}listModels(){return this.style.listModels()}addLayer(R,N){return this._isValidId(R.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(R,N),this._update(!0)):this}getSlot(R){const N=this.getLayer(R);return N&&N.slot||null}setSlot(R,N){return this.style.setSlot(R,N),this.style.mergeLayers(),this._update(!0)}addImport(R,N){return this.style.addImport(R,N).catch(T=>this.fire(new o.B(new Error("Failed to add import",T)))),this}updateImport(R,N){return typeof N!="string"&&N.id!==R?(this.removeImport(R),this.addImport(N)):(this.style.updateImport(R,N),this._update(!0))}removeImport(R){return this.style.removeImport(R),this}moveImport(R,N){return this.style.moveImport(R,N),this._update(!0)}moveLayer(R,N){return this._isValidId(R)?(this.style.moveLayer(R,N),this._update(!0)):this}removeLayer(R){return this._isValidId(R)?(this.style.removeLayer(R),this._update(!0)):this}getLayer(R){if(!this._isValidId(R))return null;const N=this.style.getOwnLayer(R);return N?N.type==="custom"?N.implementation:N.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(R,N,T){return this._isValidId(R)?(this.style.setLayerZoomRange(R,N,T),this._update(!0)):this}setFilter(R,N,T={}){return this._isValidId(R)?(this.style.setFilter(R,N,T),this._update(!0)):this}getFilter(R){return this._isValidId(R)?this.style.getFilter(R):null}setPaintProperty(R,N,T,B={}){return this._isValidId(R)?(this.style.setPaintProperty(R,N,T,B),this._update(!0)):this}getPaintProperty(R,N){return this._isValidId(R)?this.style.getPaintProperty(R,N):null}setLayoutProperty(R,N,T,B={}){return this._isValidId(R)?(this.style.setLayoutProperty(R,N,T,B),this._update(!0)):this}getLayoutProperty(R,N){return this._isValidId(R)?this.style.getLayoutProperty(R,N):null}setLayerProperty(R,N,T,B={}){return this._isValidId(R)?(N==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(R,N,T,B),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(R){return this.style.setGlyphsUrl(R),this._update(!0)}getSchema(R){return this.style.getSchema(R)}setSchema(R,N){return this.style.setSchema(R,N),this._update(!0)}getConfig(R){return this.style.getConfig(R)}setConfig(R,N){return this.style.setConfig(R,N),this._update(!0)}getConfigProperty(R,N){return this.style.getConfigProperty(R,N)}setConfigProperty(R,N,T){return this.style.setConfigProperty(R,N,T),this._update(!0)}getFeaturesetDescriptors(R){return this.style.getFeaturesetDescriptors(R)}setLights(R){if(this._lazyInitEmptyStyle(),R&&R.length===1&&R[0].type==="flat"){const N=R[0];N.properties?this.style.setFlatLight(N.properties,N.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(R),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const R=this.style.getLights()||[];return R.length===0&&R.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),R}setLight(R,N={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:R}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(R){return this._lazyInitEmptyStyle(),!R&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(R),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(R){return this._lazyInitEmptyStyle(),this.style.setFog(R),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(R){return this._lazyInitEmptyStyle(),this.style.setSnow(R),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(R){return this._lazyInitEmptyStyle(),this.style.setRain(R),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(R){return this._lazyInitEmptyStyle(),this.style.setColorTheme(R),this._update(!0)}setImportColorTheme(R,N){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(R,N),this._update(!0)}setCamera(R){return this.style.setCamera(R),this._triggerCameraUpdate(R)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(R){const N=this.transform.nearClipOffset!==R;return this.transform.nearClipOffset=R,this._update(N)}_triggerCameraUpdate(R){return this._update(this.transform.setOrthographicProjectionAtLowPitch(R["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(R){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(R),this.transform):0}setFeatureState(R,N){return R.source&&!this._isValidId(R.source)?this:(this.style.setFeatureState(R,N),this._update())}removeFeatureState(R,N){return R.source&&!this._isValidId(R.source)?this:(this.style.removeFeatureState(R,N),this._update())}getFeatureState(R){return R.source&&!this._isValidId(R.source)?null:this.style.getFeatureState(R)}_selectIndoorFloor(R){this.style.indoorManager.selectFloor(R)}_setIndoorActiveFloorsVisibility(R){this.style.indoorManager.setActiveFloorsVisibility(R)}getIndoorTileOptions(R,N){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(R,N):null}_updateContainerDimensions(){if(!this._container)return;const R=this._container.getBoundingClientRect().width||400,N=this._container.getBoundingClientRect().height||300;let T,B,W,Q=this._container;for(;Q&&(!B||!W);){const se=window.getComputedStyle(Q).transform;se&&se!=="none"&&(T=se.match(/matrix.*\((.+)\)/)[1].split(", "),T[0]&&T[0]!=="0"&&T[0]!=="1"&&(B=T[0]),T[3]&&T[3]!=="0"&&T[3]!=="1"&&(W=T[3])),Q=Q.parentElement}this._containerWidth=B?Math.abs(R/B):R,this._containerHeight=W?Math.abs(N/W):N}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&o.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const R=this._container;R.classList.add("mapboxgl-map"),(this._missingCSSCanary=g("div","mapboxgl-canary",R)).style.visibility="hidden",this._detectMissingCSS();const N=this._canvasContainer=g("div","mapboxgl-canvas-container",R);this._canvas=g("canvas","mapboxgl-canvas",N),this._interactive&&(N.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const T=this._controlContainer=g("div","mapboxgl-control-container",R),B=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(W=>{B[W]=g("div",`mapboxgl-ctrl-${W}`,T)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(R,N){const T=o.o.devicePixelRatio||1;this._canvas.width=T*Math.ceil(R),this._canvas.height=T*Math.ceil(N),this._canvas.style.width=`${R}px`,this._canvas.style.height=`${N}px`}_addMarker(R){this._markers.push(R)}_removeMarker(R){const N=this._markers.indexOf(R);N!==-1&&this._markers.splice(N,1)}_addPopup(R){this._popups.push(R)}_removePopup(R){const N=this._popups.indexOf(R);N!==-1&&this._popups.splice(N,1)}_setupPainter(){const R=Object.assign({},f.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),N=this._canvas.getContext("webgl2",R);N?(qe(N,!0),this.painter=new ic(N,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",T=>{if(T.dataType==="source"){const B=this.transform.elevation?this.transform.elevation._source():null;B&&T.sourceCacheId===B.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(N)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(R){R.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:R}))}_contextRestored(R){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:R}))}_onMapScroll(R){if(R.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(R){return this.style?(this._styleDirty=this._styleDirty||R,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(R){return this._update(),this._renderTaskQueue.add(R)}_cancelRenderFrame(R){this._renderTaskQueue.remove(R)}_requestDomTask(R){!this.loaded()||this.loaded()&&!this.isMoving()?R():this._domRenderTaskQueue.add(R)}_render(R){let N;this.fire(new o.C("renderstart")),++this._frameId;const T=this.painter.context.extTimerQuery,B=o.o.now(),W=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(N=W.createQuery(),W.beginQuery(T.TIME_ELAPSED_EXT,N)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(R),this._domRenderTaskQueue.run(R),this._removed)return;this._updateProjectionTransition();const Q=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const we=this.transform.zoom,Te=this.transform.pitch,De=o.o.now(),Qe=new o.ae(we,{now:De,fadeDuration:Q,pitch:Te,transition:this.style.transition,worldview:this._worldview});this.style.update(Qe)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let se=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),se=this._updateAverageElevation(B),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):se=this._updateAverageElevation(B),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Q,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:Q,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.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(),N){const we=o.o.now()-B;W.endQuery(T.TIME_ELAPSED_EXT),setTimeout(()=>{const Te=W.getQueryParameter(N,W.QUERY_RESULT)/1e6;W.deleteQuery(N),this.fire(new o.C("gpu-timing-frame",{cpuTime:we,gpuTime:Te}))},50)}if(this.listens("gpu-timing-layer")){const we=this.painter.collectGpuTimers();setTimeout(()=>{const Te=this.painter.queryGpuTimers(we);this.fire(new o.C("gpu-timing-layer",{layerTimes:Te}))},50)}if(this.listens("gpu-timing-deferred-render")){const we=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const Te=this.painter.queryGpuTimeDeferredRender(we);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:Te}))},50)}const ue=this._sourcesDirty||this._styleDirty||this._placementDirty||se;if(ue||this._repaint)this.triggerRepaint();else{const we=this.idle();if(we&&(se=this._updateAverageElevation(B,!0)),se)this.triggerRepaint();else if(this._triggerFrame(!1),we&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const Te=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:Te})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||ue||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&_e(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(R){for(const N of this._markers)R&&!this.getRenderWorldCopies()&&(N._lngLat=N._lngLat.wrap()),N._update();for(const N of this._popups)!R||this.getRenderWorldCopies()||N._trackPointer||(N._lngLat=N._lngLat.wrap()),N._update()}_updateAverageElevation(R,N=!1){const T=W=>(this.transform.averageElevation=W,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&T(0);const B=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(B||(N||R-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(R)){const W=this.transform.averageElevation;let Q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Q)?Q=0:this._averageElevationLastSampledAt=R;const se=Math.abs(W-Q);if(se>1){if(this._isInitialLoad||B)return this._averageElevation.jumpTo(Q),T(Q);this._averageElevation.easeTo(Q,R,300)}else if(se>1e-4)return this._averageElevation.jumpTo(Q),T(Q)}return!!this._averageElevation.isEasing(R)&&T(this._averageElevation.getValue(R))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const R=this.painter.context.gl;qe(R,!1),this._logoControl instanceof OK&&this._logoControl._updateLogo(),R&&R.clear(R.DEPTH_BUFFER_BIT|R.COLOR_BUFFER_BIT|R.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){Se(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,R=>{R&&(R.message!==G&&R.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),he(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Ee(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Pe(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){ke(this._requestManager._customAccessToken)}_updateTerrain(){const R=this._isDragging();this.painter.updateTerrain(this.style,R)}_calculateSpeedIndex(){const R=this.painter.canvasCopy(),N=this.painter.getCanvasCopiesAndTimestamps();N.timeStamps.push(performance.now());const T=this.painter.context.gl,B=T.createFramebuffer();function W(Q){T.framebufferTexture2D(T.FRAMEBUFFER,T.COLOR_ATTACHMENT0,T.TEXTURE_2D,Q,0);const se=new Uint8Array(T.drawingBufferWidth*T.drawingBufferHeight*4);return T.readPixels(0,0,T.drawingBufferWidth,T.drawingBufferHeight,T.RGBA,T.UNSIGNED_BYTE,se),se}return T.bindFramebuffer(T.FRAMEBUFFER,B),this._canvasPixelComparison(W(R),N.canvasCopies.map(W),N.timeStamps)}_canvasPixelComparison(R,N,T){let B=T[1]-T[0];const W=R.length/4;for(let Q=0;Q{const T=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,T&&this._render(N)}))}_preloadTiles(R){const N=this.style?this.style.getSourceCaches():[];return o.t(N,(T,B)=>T._preloadTiles(R,B),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(R){this._trackResize&&this.resize({originalEvent:R})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(R){this._showTileBoundaries!==R&&(this._showTileBoundaries=R,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(R){this._showParseStatus!==R&&(this._showParseStatus=R,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(R){this._showTerrainWireframe!==R&&(this._showTerrainWireframe=R,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(R){this._showLayers2DWireframe!==R&&(this._showLayers2DWireframe=R,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(R){this._showLayers3DWireframe!==R&&(this._showLayers3DWireframe=R,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(R){this._speedIndexTiming!==R&&(this._speedIndexTiming=R,this._update())}get showPadding(){return!!this._showPadding}set showPadding(R){this._showPadding!==R&&(this._showPadding=R,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(R){this._showCollisionBoxes!==R&&(this._showCollisionBoxes=R,this.style&&R?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(R){this._showOverdrawInspector!==R&&(this._showOverdrawInspector=R,this._update())}get repaint(){return!!this._repaint}set repaint(R){this._repaint!==R&&(this._repaint=R,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(R){this._vertices=R,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(R){this._showTileAABBs!==R&&(this._showTileAABBs=R,R&&this._update())}_setCacheLimits(R,N){o.e_(R,N)}get version(){return c}},NavigationControl:class{constructor(R={}){this.options=Object.assign({},qDe,R),this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",N=>N.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",N=>{this._map&&this._map.zoomIn({},{originalEvent:N})}),g("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",N=>{this._map&&this._map.zoomOut({},{originalEvent:N})}),g("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",N=>{const T=this._map;T&&(this.options.visualizePitch?T.resetNorthPitch({},{originalEvent:N}):T.resetNorth({},{originalEvent:N}))}),this._compassIcon=g("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const R=this._map;if(!R)return;const N=R.getZoom(),T=N===R.getMaxZoom(),B=N===R.getMinZoom();this._zoomInButton.disabled=T,this._zoomOutButton.disabled=B,this._zoomInButton.setAttribute("aria-disabled",T.toString()),this._zoomOutButton.setAttribute("aria-disabled",B.toString())}_rotateCompassArrow(){const R=this._map;if(!R)return;const N=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(R.transform.pitch*(Math.PI/180)),.5)}) rotateX(${R.transform.pitch}deg) rotateZ(${R.transform.angle*(180/Math.PI)}deg)`:`rotate(${R.transform.angle*(180/Math.PI)}deg)`;R._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=N)})}onAdd(R){return this._map=R,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),R.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&R.on("pitch",this._rotateCompassArrow),R.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new uI(R,this._compass,this.options.visualizePitch)),this._container}onRemove(){const R=this._map;R&&(this._container.remove(),this.options.showZoom&&R.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&R.off("pitch",this._rotateCompassArrow),R.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(R,N){const T=g("button",R,this._container);return T.type="button",T.addEventListener("click",N),T}_setButtonTitle(R,N){if(!this._map)return;const T=this._map._getUIString(`NavigationControl.${N}`);R.setAttribute("aria-label",T),R.firstElementChild&&R.firstElementChild.setAttribute("title",T)}},GeolocateControl:class extends o.E{constructor(R={}){super();const N=navigator.geolocation;this.options=Object.assign({geolocation:N},mI,R),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Ri(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(R){return this._map=R,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(R){const N=(T=!!this.options.geolocation)=>{this._supportsGeolocation=T,R(T)};this._supportsGeolocation!==void 0?R(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(T=>N(T.state!=="denied")).catch(()=>N()):N()}_isOutOfMapMaxBounds(R){const N=this._map.getMaxBounds(),T=R.coords;return!!N&&(T.longitudeN.getEast()||T.latitudeN.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(R){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(R))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",R)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=R,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(R),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(R),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:R.coords,timestamp:R.timestamp},R.toJSON?{toJSON:R.toJSON.bind(R)}:{}))),this._finish()}}_updateCamera(R){const N=new o.aU(R.coords.longitude,R.coords.latitude),T=R.coords.accuracy,B=this._map.getBearing(),W=Object.assign({bearing:B},this.options.fitBoundsOptions);this._map.fitBounds(N.toBounds(T),W,{geolocateSource:!0})}_updateMarker(R){if(R){const N=new o.aU(R.coords.longitude,R.coords.latitude);this._accuracyCircleMarker.setLngLat(N).addTo(this._map),this._userLocationDotMarker.setLngLat(N).addTo(this._map),this._accuracy=R.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const R=this._map.transform,N=o.bU(1,R._center.lat)*R.worldSize,T=Math.ceil(2*this._accuracy*N);this._circleElement.style.width=`${T}px`,this._circleElement.style.height=`${T}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(R){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(R.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 N=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(R.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:R.code,message:R.message,PERMISSION_DENIED:R.PERMISSION_DENIED,POSITION_UNAVAILABLE:R.POSITION_UNAVAILABLE,TIMEOUT:R.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const R=this.options.positionOptions.timeout;R&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},R))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(R){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",N=>N.preventDefault()),this._geolocateButton=g("button","mapboxgl-ctrl-geolocate",this._container),g("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",R===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const N=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N)}else{const N=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=g("div","mapboxgl-user-location"),this._dotElement.appendChild(g("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(g("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Jb({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=g("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Jb({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",N=>{N.geolocateSource||this._watchState!=="ACTIVE_LOCK"||N.originalEvent&&N.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(R){this._userLocationDotMarker&&(R.webkitCompassHeading?this._heading=R.webkitCompassHeading:R.absolute===!0&&(this._heading=-1*R.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 R;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(R={maximumAge:6e5,timeout:0},this._noTimeout=!0):(R=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,R),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(R){return this.options.followUserLocation=R??mI.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 R=()=>{const N="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(N,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(N=>{N==="granted"&&R()}).catch(console.error):R()}_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:FK,ScaleControl:class{constructor(R={}){this.options=Object.assign({},Hm,R),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const R=this.options.maxWidth||100,N=this._map,T=N._containerHeight/2,B=N._containerWidth/2-R/2,W=N.unproject([B,T]),Q=N.unproject([B+R,T]),se=W.distanceTo(Q);if(this.options.unit==="imperial"){const ue=3.2808*se;ue>5280?this._setScale(R,ue/5280,"mile"):this._setScale(R,ue,"foot")}else this.options.unit==="nautical"?this._setScale(R,se/1852,"nautical-mile"):se>=1e3?this._setScale(R,se/1e3,"kilometer"):this._setScale(R,se,"meter")}_setScale(R,N,T){this._map._requestDomTask(()=>{const B=function(Q){const se=Math.pow(10,`${Math.floor(Q)}`.length-1);let ue=Q/se;return ue=ue>=10?10:ue>=5?5:ue>=3?3:ue>=2?2:ue>=1?1:function(we){const Te=Math.pow(10,Math.ceil(-Math.log(we)/Math.LN10));return Math.round(we*Te)/Te}(ue),se*ue}(N),W=B/N;this._container.innerHTML=T!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:T}).format(B):`${B} ${e_[T]}`,this._container.style.width=R*W+"px"})}onAdd(R){return this._map=R,this._language=R.getLanguage(),this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-scale",R.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(R){this._language=R,this._update()}setUnit(R){this.options.unit=R,this._update()}},FullscreenControl:class{constructor(R={}){this._fullscreen=!1,R&&R.container&&(R.container instanceof HTMLElement?this._container=R.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(R){return this._map=R,this._container||(this._container=this._map.getContainer()),this._controlContainer=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",o.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const R=this._fullscreenButton=g("button","mapboxgl-ctrl-fullscreen",this._controlContainer);g("span","mapboxgl-ctrl-icon",R).setAttribute("aria-hidden","true"),R.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const R=this._getTitle();this._fullscreenButton.setAttribute("aria-label",R),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",R)}_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(R){return this._map=R,this._container=g("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 R=this._map.style.indoorManager;R.off("selector-update",this._onIndoorUpdate),R.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(R.getControlState())}}_createButton(R,N){const T=g("button",R,this._container);return T.type="button",T.addEventListener("click",N),T}_setButtonTitle(R,N){R.setAttribute("aria-label",N),R.textContent=N}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(R){if(!R||!R.floors||R.floors.length===0)return this._model=R,void(this._container.style.display="none");const N=this._model;this._model=R,this._container.style.display="inline-block";const T=!N||N.floors.length!==R.floors.length||N.floors.some((B,W)=>B.id!==R.floors[W].id);if(T&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),R.selectedFloorId){if(R.selectedFloorId!==this._lastSelectedFloorId||T){const B=R.floors.findIndex(W=>W.id===R.selectedFloorId);if(B!==-1){const W=R.floors.length;let Q,se;W<=5?(Q=0,se=W-1):this._visibleFloorStart===0?(Q=0,se=3):this._visibleFloorStart>=W-3?(Q=W-3-1,se=W-1):(Q=this._visibleFloorStart,se=this._visibleFloorStart+3-1),Bse&&(this._visibleFloorStart=B-2)}}this._lastSelectedFloorId=R.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const R=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);g("span","mapboxgl-ctrl-icon",R).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||R.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(R);const N=this._model.floors,T=N.length;if(T<=5)return void N.forEach(se=>this._createFloorButton(se));const B=this._visibleFloorStart===0,W=this._visibleFloorStart>=T-3;if(B)this._createFloorButton(N[0]);else{const se=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);g("span","mapboxgl-ctrl-icon",se).setAttribute("aria-hidden","true"),this._container.appendChild(se)}let Q=[];if(Q=B?N.slice(1,4):W?N.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):N.slice(this._visibleFloorStart,this._visibleFloorStart+3),Q.forEach(se=>this._createFloorButton(se)),W)this._createFloorButton(N[T-1]);else{const se=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);g("span","mapboxgl-ctrl-icon",se).setAttribute("aria-hidden","true"),this._container.appendChild(se)}}_createFloorButton(R){const N=this._createButton("mapboxgl-ctrl-level-button",()=>{const Q=R.id;this._model&&this._model.selectedFloorId===Q&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(Q))}),T=(R.name||"").trim(),B=R.zIndex.toString(),W=T?Array.from(T).slice(0,3).join(""):B;this._setButtonTitle(N,W),this._model&&this._model.activeFloorsVisible&&R.id===this._model.selectedFloorId&&N.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(N)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,this._visibleFloorStart===1&&(this._visibleFloorStart=0);const R=this._model&&this._model.floors||[];if(R.length>3){const N=R.length-3;this._visibleFloorStart===N-1&&(this._visibleFloorStart=N-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const R=this._model.floors.length-3;this._visibleFloorStartR&&(this._visibleFloorStart=R),this._render())}}},Popup:class extends o.E{constructor(R){super(),this.options=Object.assign(Object.create(pI),R),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(R&&R.className?R.className.trim().split(/\s+/):[])}addTo(R){return this._map&&this.remove(),this._map=R,this.options.closeOnClick&&R.on("preclick",this._onClose),this.options.closeOnMove&&R.on("move",this._onClose),R.on("remove",this.remove),this._update(),R._addPopup(this),this._focusFirstElement(),this._trackPointer?(R.on("mousemove",this._onMouseEvent),R.on("mouseup",this._onMouseEvent),R._canvasContainer.classList.add("mapboxgl-track-pointer")):R.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 R=this._map;return R&&(R.off("move",this._update),R.off("move",this._onClose),R.off("preclick",this._onClose),R.off("click",this._onClose),R.off("remove",this.remove),R.off("mousemove",this._onMouseEvent),R.off("mouseup",this._onMouseEvent),R.off("drag",this._onMouseEvent),R._canvasContainer&&R._canvasContainer.classList.remove("mapboxgl-track-pointer"),R._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(R){this._lngLat=o.aU.convert(R),this._pos=null,this._trackPointer=!1,this._update();const N=this._map;return N&&(N.on("move",this._update),N.off("mousemove",this._onMouseEvent),N._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(R){return this._altitude=R,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const R=this._map;return R&&(R.off("move",this._update),R.on("mousemove",this._onMouseEvent),R.on("drag",this._onMouseEvent),R._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(R){return this.setDOMContent(document.createTextNode(R))}setHTML(R){const N=document.createDocumentFragment(),T=document.createElement("body");let B;for(T.innerHTML=R;B=T.firstChild,B;)N.appendChild(B);return this.setDOMContent(N)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(R){return this.options.maxWidth=R,this._update(),this}setDOMContent(R){let N=this._content;if(N)for(;N.hasChildNodes();)N.firstChild&&N.removeChild(N.firstChild);else N=this._content=g("div","mapboxgl-popup-content",this._container||void 0);if(N.appendChild(R),this.options.closeButton){const T=this._closeButton=g("button","mapboxgl-popup-close-button",N);T.type="button",T.setAttribute("aria-label","Close popup"),T.innerHTML='',T.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(R){return this._classList.add(R),this._updateClassList(),this}removeClassName(R){return this._classList.delete(R),this._updateClassList(),this}setOffset(R){return this.options.offset=R,this._update(),this}toggleClassName(R){let N;return this._classList.delete(R)?N=!1:(this._classList.add(R),N=!0),this._updateClassList(),N}_onMouseEvent(R){this._update(R.point)}_getAnchor(R){if(this.options.anchor)return this.options.anchor;const N=this._map,T=this._container,B=this._pos;if(!N||!T||!B)return"bottom";const W=T.offsetWidth,Q=T.offsetHeight,se=B.xN.transform.width-W/2;if(B.y+RN.transform.height-Q){if(se)return"bottom-left";if(ue)return"bottom-right"}return se?"left":ue?"right":"bottom"}_updateClassList(){const R=this._container;if(!R)return;const N=[...this._classList];N.push("mapboxgl-popup"),this._anchor&&N.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&N.push("mapboxgl-popup-track-pointer"),R.className=N.join(" ")}_update(R){const N=this._map,T=this._content;if(!N||!this._lngLat&&!this._trackPointer||!T)return;let B=this._container;if(B||(B=this._container=g("div","mapboxgl-popup",N.getContainer()),this._tip=g("div","mapboxgl-popup-tip",B),B.appendChild(T)),this.options.maxWidth&&B.style.maxWidth!==this.options.maxWidth&&(B.style.maxWidth=this.options.maxWidth),N.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=zK(this._lngLat,this._pos,N.transform)),!this._trackPointer||R){const W=this._pos=this._trackPointer&&R instanceof o.P?R:N.project(this._lngLat,this._altitude),Q=Vz(this.options.offset),se=this._anchor=this._getAnchor(Q.y),ue=Vz(this.options.offset,se),we=W.add(ue).round();N._requestDomTask(()=>{this._container&&se&&(this._container.style.transform=`${hI[se]} translate(${we.x}px,${we.y}px)`)})}if(!this._marker&&N._showingGlobe()){const W=o.e$(N.transform,this._lngLat)?0:1;this._setOpacity(W)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const R=this._container.querySelector(VDe);R&&R.focus()}_onClose(){this.remove()}_setOpacity(R){this._container&&(this._container.style.opacity=`${R}`),this._content&&(this._content.style.pointerEvents=R?"auto":"none")}},Marker:Jb,Style:xh,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:F0,Evented:o.E,config:o.g,prewarm:function(){qt().acquire(nt)},clearPrewarmedResources:function(){const R=ut;R&&(R.isPreloaded()&&R.numActive()===1?(R.release(nt),ut=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(R){o.g.ACCESS_TOKEN=R},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(R){o.g.API_URL=R},get workerCount(){return Ge.workerCount},set workerCount(R){Ge.workerCount=R},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(R){o.g.MAX_PARALLEL_IMAGE_REQUESTS=R},clearStorage(R){o.f7(R)},get workerUrl(){return $e.workerUrl},set workerUrl(R){$e.workerUrl=R},get workerClass(){return $e.workerClass},set workerClass(R){$e.workerClass=R},get workerParams(){return $e.workerParams},set workerParams(R){$e.workerParams=R},get dracoUrl(){return o.f6()},set dracoUrl(R){o.g.DRACO_URL=o.o.resolveURL(R)},get meshoptUrl(){return o.f5()},set meshoptUrl(R){const N=o.o.resolveURL(R);o.g.MESHOPT_URL=N,o.g.MESHOPT_SIMD_URL=N},get buildingGenUrl(){return o.f4()},set buildingGenUrl(R){o.g.BUILDING_GEN_URL=o.o.resolveURL(R)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(lOt);var zMs=lOt.exports;const Od=kd(zMs),Lft={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},Ift={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 BMs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function $Ms({listings:s,isLoading:t}){const n=zn(),r=_.useRef(null),a=_.useRef(null),i=_.useRef([]),[l,o]=_.useState(""),[c,d]=_.useState(!0);return _.useEffect(()=>{(async()=>{d(!0);try{const{data:m}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();m!=null&&m.value&&o(m.value)}catch(m){console.error("Error fetching mapbox token:",m)}d(!1)})()},[]),_.useEffect(()=>{if(!r.current||!l||a.current)return;Od.accessToken=l;const h=s.filter(f=>f.latitude!=null&&f.longitude!=null);let m=[-98.5795,39.8283],p=4;if(h.length>0){const f=h.reduce((v,y)=>v+y.longitude,0)/h.length,g=h.reduce((v,y)=>v+y.latitude,0)/h.length;m=[f,g],p=h.length===1?12:10}return a.current=new Od.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:p,center:m}),a.current.addControl(new Od.NavigationControl,"top-right"),()=>{var f;(f=a.current)==null||f.remove(),a.current=null}},[l]),_.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(m=>m.remove()),i.current=[];const h=s.filter(m=>m.latitude!=null&&m.longitude!=null);if(h.forEach(m=>{var S,C,E;const p=Lft[m.status]||"#10B981",f=((S=m.photos)==null?void 0:S.find(P=>P.is_primary))||((C=m.photos)==null?void 0:C[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,y=document.createElement("div");y.className="cursor-pointer",y.innerHTML=`
`;const b=new Od.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${f!=null&&f.photo_url?``:""}
${BMs(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${Ift[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(E=m.agent)!=null&&E.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),w=new Od.Marker(y).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(w)}),h.length>1){const m=new Od.LngLatBounds;h.forEach(p=>m.extend([p.longitude,p.latitude])),a.current.fitBounds(m,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),_.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(ln,{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(Lft).map(([h,m])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:m}}),e.jsx("span",{className:"text-xs text-gray-600",children:Ift[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const zOe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},UMs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},TB="#0d0d0d",Dft="#1a1a1a",Zd="#c9a84c",AT="#f0d78c";function dOt(){const[s,t]=_.useState(""),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(-1),u=_.useRef(null),[h,m]=_.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:p}=_Ms(),f=_.useMemo(()=>{if(!p)return[];const F=s.trim().toLowerCase(),q=[...p.cities.map(V=>({label:V.label,value:V.city,type:"city",count:V.count})),...p.neighborhoods.map(V=>({label:V.label,value:V.neighborhood,type:"neighborhood",count:V.count})),...p.zips.map(V=>({label:`ZIP ${V.label}`,value:V.zip,type:"zip",count:V.count}))];return(F?q.filter(V=>V.label.toLowerCase().includes(F)||V.value.toLowerCase().includes(F)):q).slice(0,8)},[p,s]);_.useEffect(()=>{const F=q=>{u.current&&!u.current.contains(q.target)&&o(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[]);const{data:g,isLoading:v}=bMs({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}),y=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F),b=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},w=s||h.status||h.propertyType||h.minPrice||h.maxPrice,S=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),C=F=>S?`/${F.slug||F.id}`:`/public/listing/${F.slug||F.id}`,{featured:E,restListings:P,luxeCount:M,cities:I,activeCount:D}=_.useMemo(()=>{const F=g||[],q=F.filter(ve=>ve.status==="active"),G=q.length>0?q:F,V=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[H,K,Z]=V.split("-").map(Number),oe=Math.floor(Date.UTC(H,K-1,Z)/864e5),re=G.length>0?G[oe%G.length]:void 0,ae=F.filter(ve=>!re||ve.id!==re.id),J=Array.from(new Set(F.map(ve=>ve.city).filter(Boolean))).slice(0,8),te=F.filter(ve=>(ve.price||0)>=1e6).length,ce=q.length;return{featured:re,restListings:ae,luxeCount:te,cities:J,activeCount:ce}},[g]);return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{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:TB,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: ${Zd}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Zd}, 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(or,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:FH,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(or,{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 ${Zd}`,color:Zd},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(F=>!F),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Zd}`,color:Zd},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(er,{className:"w-5 h-5"}):e.jsx(ZA,{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(or,{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 ${Zd}`,color:Zd},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:OMs,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:Zd}}),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:AT},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 ${Zd}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Zd}}),e.jsx(pe,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:F=>{t(F.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:F=>{if(!(!l||f.length===0))if(F.key==="ArrowDown")F.preventDefault(),d(q=>Math.min(q+1,f.length-1));else if(F.key==="ArrowUp")F.preventDefault(),d(q=>Math.max(q-1,0));else if(F.key==="Enter"&&c>=0){F.preventDefault();const q=f[c];t(q.value),o(!1)}else F.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(uP,{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:Zd,color:TB},onClick:()=>o(!1),children:[e.jsx(Rr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&f.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:Zd},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:f.map((F,q)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(q),onClick:()=>{t(F.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===q?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[F.type==="city"&&e.jsx(Ha,{className:"h-4 w-4 shrink-0",style:{color:Zd}}),F.type==="neighborhood"&&e.jsx(oi,{className:"h-4 w-4 shrink-0",style:{color:Zd}}),F.type==="zip"&&e.jsx(sa,{className:"h-4 w-4 shrink-0",style:{color:Zd}}),e.jsx("span",{className:"text-white/90 truncate",children:F.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[F.count," ",F.count===1?"listing":"listings"]})]})},`${F.type}-${F.value}-${q}`))})]}),l&&s.trim()&&f.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(ls,{value:h.status||"all",onValueChange:F=>m({...h,status:F==="all"?"":F}),children:[e.jsx(rs,{className:"lu-input-dark",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any status"}),Object.entries(zOe).map(([F,q])=>e.jsx(He,{value:F,children:q},F))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(ls,{value:h.propertyType||"all",onValueChange:F=>m({...h,propertyType:F==="all"?"":F}),children:[e.jsx(rs,{className:"lu-input-dark",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any type"}),Object.entries(UMs).map(([F,q])=>e.jsx(He,{value:F,children:q},F))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(pe,{type:"number",placeholder:"No min",value:h.minPrice,onChange:F=>m({...h,minPrice:F.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(pe,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:F=>m({...h,maxPrice:F.target.value}),className:"lu-input-dark"})]}),w&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(z,{variant:"ghost",size:"sm",onClick:b,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(er,{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:((g==null?void 0:g.length)??0).toString()},{label:"Active Now",value:D.toString()},{label:"Luxury $1M+",value:M.toString()}].map(F=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:AT},children:F.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:F.label})]},F.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(cl,{className:"h-4 w-4 animate-bounce"})]})]})]}),I.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:Dft,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:[...I,...I,...I].map((F,q)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[F,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Zd}})]},q))})}),E&&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:Zd}}),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:AT},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(or,{to:C(E),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 q,G;const F=((q=E.photos)==null?void 0:q.find(V=>V.is_primary))||((G=E.photos)==null?void 0:G[0]);return F?e.jsx("img",{src:F.photo_url,alt:E.property_address||E.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(sa,{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:Zd,color:TB},children:zOe[E.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(Ha,{className:"h-3.5 w-3.5",style:{color:Zd}}),E.city,E.state?`, ${E.state}`:""]}),E.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:E.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:AT},children:y(E.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[E.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(mj,{className:"h-4 w-4",style:{color:Zd}}),E.bedrooms," bd"]}),E.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ey,{className:"h-4 w-4",style:{color:Zd}}),E.bathrooms," ba"]}),E.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(jb,{className:"h-4 w-4",style:{color:Zd}}),E.square_footage.toLocaleString()," sf"]})]}),E.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:E.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Zd},children:["View Residence ",e.jsx(Da,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:Dft},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:Zd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Zd}})]}),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:AT},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((F,q)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(ln,{className:"aspect-[4/5] bg-white/5"}),e.jsx(ln,{className:"h-6 w-32 bg-white/5"}),e.jsx(ln,{className:"h-4 w-full bg-white/5"})]},q))}):P.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:P.map(F=>{var G,V,H,K,Z;const q=((G=F.photos)==null?void 0:G.find(oe=>oe.is_primary))||((V=F.photos)==null?void 0:V[0]);return e.jsxs(or,{to:C(F),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[q?e.jsx("img",{src:q.photo_url,alt:F.property_address||F.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(sa,{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:Zd,border:`1px solid ${Zd}`},children:zOe[F.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:[F.bedrooms&&e.jsxs("span",{children:[F.bedrooms," bd"]}),F.bathrooms&&e.jsxs("span",{children:[F.bathrooms," ba"]}),F.square_footage&&e.jsxs("span",{children:[F.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(Ha,{className:"h-3 w-3",style:{color:Zd}}),F.city,F.state?`, ${F.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:AT},children:y(F.price)}),F.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:F.property_address}),((H=F.agent)==null?void 0:H.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(oi,{className:"h-3 w-3"}),F.agent.name,(((K=F.agent.brokerage)==null?void 0:K.name)||F.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((Z=F.agent.brokerage)==null?void 0:Z.name)||F.agent.brokerage_name]})]})]})]},F.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 ${Zd}`},children:e.jsx(sa,{className:"h-8 w-8",style:{color:Zd}})}),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."}),w&&e.jsx(z,{onClick:b,style:{background:Zd,color:TB},className:"hover:brightness-110",children:"Clear filters"})]})]})}),g&&g.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:Zd}}),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:AT},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($Ms,{listings:g,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%, ${TB} 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:Zd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Zd}})]}),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:AT},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:Zd,color:TB},children:["Explore LevelUp",e.jsx(Da,{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:FH,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(X6s,{}),e.jsx(Q6s,{})]})}const qMs=_.lazy(()=>Fa(()=>import("./PublicHomeValue-tBxxPKg1.js"),[]));function VMs(){const s=Pd(),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(dOt,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(_.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(qMs,{})}):r.startsWith("public/")?null:e.jsx(zJe,{slugOverride:r})}const HMs=_.lazy(()=>Fa(()=>import("./CommercialMarketplace-CHLuqeTU.js"),[]));function GMs(){const t=Pd().pathname.slice(1);return t?t.startsWith("public/")?null:e.jsx(zJe,{slugOverride:t}):e.jsx(_.Suspense,{fallback:e.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:e.jsx(HMs,{})})}function UPe({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 uOt=s=>rt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await U.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await U.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 U.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 U.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await U.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=U.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...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}),WMs=()=>rt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),KMs=s=>rt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),hOt=()=>{const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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"]}),ne.success("Agent card created")},onError:t=>ne.error(t.message)})},mOt=()=>{const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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"]}),ne.success("Agent card updated")},onError:t=>ne.error(t.message)})},zd=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await U.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:{}})},YMs=async(s,t)=>{const{error:n}=await U.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},pOt=s=>rt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await U.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function qPe({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(!1),y=async b=>{if(b.preventDefault(),!i.trim()){ne.error("Please enter your name");return}v(!0);try{await YMs(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}),zd(n,"lead_submitted",r),U.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}}).catch(w=>console.error("Card lead notify failed:",w)),ne.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),f("")}catch{ne.error("Something went wrong. Please try again.")}finally{v(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(_r,{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:y,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-name",children:"Name *"}),e.jsx(pe,{id:"lead-name",value:i,onChange:b=>l(b.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(pe,{id:"lead-phone",type:"tel",value:d,onChange:b=>u(b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-email",children:"Email"}),e.jsx(pe,{id:"lead-email",type:"email",value:o,onChange:b=>c(b.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(ls,{value:h,onValueChange:m,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select one"})}),e.jsxs(as,{children:[e.jsx(He,{value:"buy",children:"Buy a home"}),e.jsx(He,{value:"sell",children:"Sell my home"}),e.jsx(He,{value:"both",children:"Buy & Sell"}),e.jsx(He,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(pe,{id:"lead-message",value:p,onChange:b=>f(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(z,{type:"submit",className:"w-full rounded-2xl",disabled:g,children:g?"Sending...":"Submit"})]})]})})}const ZMs=s=>rt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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}),XMs=s=>rt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),QMs=()=>{const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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]}),ne.success("Block added")},onError:t=>ne.error(t.message)})},JMs=()=>{const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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"]}),ne.success("Block updated")},onError:t=>ne.error(t.message)})},ePs=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ne.success("Block removed")},onError:t=>ne.error(t.message)})};function tPs(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 sPs(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 nPs={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 rPs({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=sPs(n.video_url),i=r||!!a,l=r?tPs(n.video_url):a||n.video_url;return e.jsx("div",{className:nPs[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 aPs={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 iPs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=_.useState(0);if(r.length===0)return null;const l=aPs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(wj,{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(Wc,{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(yi,{className:"h-4 w-4"})})]})]})}const oPs={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 lPs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=oPs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const cPs={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 dPs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=cPs[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:()=>zd(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(mr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const gVe={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 uPs({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 hPs={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 mPs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=hPs[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=gVe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>zd(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(uPs,{path:c.icon,color:c.color})},o)})})]})}function VPe({cardId:s,variant:t}){const{data:n}=ZMs(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(rPs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(iPs,{block:l,variant:t},l.id);case"specialties":return e.jsx(lPs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(dPs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(mPs,{block:i,cardId:s,variant:t})]})}async function pPs(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 fPs(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 HPe(s){const{first:t,last:n}=fPs(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 pPs(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),ne.success("Contact saved!")}function xPs({card:s}){var y;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((y=s.profile)==null?void 0:y.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{zd(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),zd(s.id,"button_click","book"))},m=()=>{var b,w;zd(s.id,"contact_saved"),HPe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(w=s.profile)==null?void 0:w.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{zd(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),ne.success("Link copied!")},f=()=>{a("referral"),n(!0),zd(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),zd(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(ja,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(xi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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(z,{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(va,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(z,{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(qi,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(z,{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(on,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(z,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(ya,{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(Ia,{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(UPe,{card:s,variant:"standard"}),e.jsx(VPe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(z,{variant:"ghost",onClick:m,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Ga,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(z,{variant:"ghost",onClick:()=>{zd(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(Ia,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(z,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(On,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(z,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Pl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(z,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(sd,{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((b,w)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>zd(s.id,"button_click",`social_${b.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[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(qPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function gPs({card:s}){var y;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((y=s.profile)==null?void 0:y.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{zd(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),zd(s.id,"button_click","book"))},m=()=>{var b,w;zd(s.id,"contact_saved"),HPe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(w=s.profile)==null?void 0:w.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{zd(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),ne.success("Link copied!")},f=()=>{a("referral"),n(!0),zd(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),zd(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(ja,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(xi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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:va,label:"Call",handler:c},{icon:qi,label:"Text",handler:d},{icon:on,label:"Email",handler:u}].map(({icon:b,label:w,handler:S})=>e.jsxs("button",{onClick:S,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(b,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:w})]},w))}),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(ya,{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(Ia,{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(UPe,{card:s,variant:"luxury"}),e.jsx(VPe,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:m,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Ga,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{zd(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(Ia,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&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(On,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a 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(Pl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(sd,{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((b,w)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>zd(s.id,"button_click",`social_${b.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[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(qPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function yPs({card:s}){var w,S,C,E;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((w=s.profile)==null?void 0:w.name)||"Agent",l=i.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2),o={accent:((S=s.bold_theme_colors)==null?void 0:S.accent)||"#ff5722",dark:((C=s.bold_theme_colors)==null?void 0:C.dark)||"#1a1a2e",button:((E=s.bold_theme_colors)==null?void 0:E.button)||"#ff5722"},c=(P,M)=>{const I=parseInt(P.replace("#",""),16),D=Math.max(0,(I>>16)-M),F=Math.max(0,(I>>8&255)-M),q=Math.max(0,(I&255)-M);return`#${(D<<16|F<<8|q).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(P,M)=>{zd(s.id,"button_click",P),M()},u=()=>d("call",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),h=()=>d("text",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),m=()=>d("email",()=>{var P;(P=s.profile)!=null&&P.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),p=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),zd(s.id,"button_click","book"))},f=()=>{var P,M;zd(s.id,"contact_saved"),HPe({name:i,phone:(P=s.profile)==null?void 0:P.phone,email:(M=s.profile)==null?void 0:M.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},g=async()=>{zd(s.id,"share_event");const P=`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:P})}catch{}else await navigator.clipboard.writeText(P),ne.success("Link copied!")},v=()=>{a("referral"),n(!0),zd(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),zd(s.id,"button_click","connect")},b={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(ja,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(xi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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:va,label:"Call",handler:u},{icon:qi,label:"Text",handler:h},{icon:on,label:"Email",handler:m}].map(({icon:P,label:M,handler:I})=>e.jsxs("button",{onClick:I,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(P,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:M})]},M))}),e.jsxs("button",{onClick:p,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(ya,{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(Ia,{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(UPe,{card:s,variant:"bold"}),e.jsx(VPe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Ga,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{zd(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(Ia,{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(On,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Pl,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),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(sd,{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((P,M)=>e.jsx("a",{href:P.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>zd(s.id,"button_click",`social_${P.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:b[P.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(qPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function vPs({card:s}){var y;const[t,n]=_.useState(!1),[r,a]=_.useState("booking"),i=((y=s.profile)==null?void 0:y.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{zd(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),zd(s.id,"button_click","book"))},m=()=>{var b,w;zd(s.id,"contact_saved"),HPe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(w=s.profile)==null?void 0:w.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{zd(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),ne.success("Link copied!")},f=()=>{a("referral"),n(!0),zd(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),zd(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(ja,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(xi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Na,{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:va,label:"Call",handler:c},{icon:qi,label:"Text",handler:d},{icon:on,label:"Email",handler:u}].map(({icon:b,label:w,handler:S})=>e.jsxs("button",{onClick:S,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(b,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:w})]},w))}),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(ya,{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(Ia,{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(UPe,{card:s,variant:"classic"}),e.jsx(VPe,{cardId:s.id,variant:"classic"}),e.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:m,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Ga,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{zd(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(Ia,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&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(On,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a 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(Pl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(sd,{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((b,w)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>zd(s.id,"button_click",`social_${b.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[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(qPe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function BJe({card:s}){switch(s.theme){case"luxury":return e.jsx(gPs,{card:s});case"bold":return e.jsx(yPs,{card:s});case"classic":return e.jsx(vPs,{card:s});case"standard":default:return e.jsx(xPs,{card:s})}}function bPs(){const s=Pd();_.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(_Ps,{slug:t})}function _Ps({slug:s}){return e.jsx(wPs,{slug:s})}function wPs({slug:s}){var i;const{data:t,isLoading:n,error:r}=uOt(s);if(_.useEffect(()=>{t!=null&&t.id&&zd(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(ln,{className:"h-28 w-28 rounded-full"}),e.jsx(ln,{className:"h-6 w-48"}),e.jsx(ln,{className:"h-4 w-36"})]}),e.jsx(ln,{className:"h-12 w-full"}),e.jsx(ln,{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(dl,{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(BJe,{card:t})]})}function fOt({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=_.useState(r||""),[c,d]=_.useState(a||""),[u,h]=_.useState(i||""),[m,p]=_.useState(""),[f,g]=_.useState(""),[v,y]=_.useState(!1),[b,w]=_.useState(!1),S=async C=>{if(C.preventDefault(),!l.trim()){ne.error("Please enter your name");return}y(!0);try{const{error:E}=await U.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:f.trim()||null});if(E)throw E;try{await U.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}U.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:f.trim()||void 0}}).catch(P=>console.error("Presentation lead notify failed:",P)),w(!0)}catch{ne.error("Something went wrong. Please try again.")}finally{y(!1)}};return b?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(Wr,{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:S,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(pe,{id:"pres-lead-name",value:l,onChange:C=>o(C.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(pe,{id:"pres-lead-phone",type:"tel",value:u,onChange:C=>h(C.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(pe,{id:"pres-lead-email",type:"email",value:c,onChange:C=>d(C.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(ls,{value:m,onValueChange:p,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select one"})}),e.jsxs(as,{children:[e.jsx(He,{value:"buy",children:"Buy a home"}),e.jsx(He,{value:"sell",children:"Sell my home"}),e.jsx(He,{value:"both",children:"Buy & Sell"}),e.jsx(He,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(pe,{id:"pres-lead-message",value:f,onChange:C=>g(C.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(z,{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 jPs(){const s=Pd();_.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(NPs,{shareToken:t})}function NPs({shareToken:s}){var f;const[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(0),[o,c]=_.useState(!1);_.useEffect(()=>{d()},[s]);const d=async()=>{const{data:g,error:v}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!g){c(!0),a(!1);return}const{data:y}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",g.owner_user_id).single();let b;if(y!=null&&y.brokerage_id){const{data:S}=await U.from("brokerages").select("name").eq("id",y.brokerage_id).single();b=(S==null?void 0:S.name)||void 0}let w=null;if(g.contact_id){const{data:S}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",g.contact_id).single();w=S}n({...g,owner_name:y==null?void 0:y.name,owner_email:y==null?void 0:y.email,owner_phone:y==null?void 0:y.phone,owner_avatar:y==null?void 0:y.avatar_url,owner_title:(y==null?void 0:y.title)||void 0,brokerage_name:b,contact_name:w?[w.first_name,w.last_name].filter(Boolean).join(" "):void 0,contact_email:(w==null?void 0:w.email)||void 0,contact_phone:(w==null?void 0:w.phone)||void 0}),a(!1);try{await U.rpc("log_presentation_view",{p_presentation_id:g.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await U.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=g=>{const v=g.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(g.includes("iframe.mediadelivery.net/play/")){const w=g.replace("/play/","/embed/"),S=w.includes("?")?"&":"?";return`${w}${S}responsive=true`}if(g.includes("iframe.mediadelivery.net")){const w=g.includes("?")?"&":"?";return`${g}${w}responsive=true`}const y=g.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(y)return`https://www.loom.com/embed/${y[1]}`;const b=g.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return b?`https://iframe.mediadelivery.net/embed/${b[1]}/${b[2]}?responsive=true`:g};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(ln,{className:"h-12 w-3/4 mx-auto"}),e.jsx(ln,{className:"h-64 w-full"}),e.jsx(ln,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(g=>g.is_visible!==!1),p=m[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[p!=null&&p.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((g,v)=>e.jsx("button",{onClick:()=>l(v),className:Ct("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:g.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:g.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:g.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?"}),(f=t.cta_url)!=null&&f.trim()?e.jsxs(z,{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(mr,{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(fOt,{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 kPs(){const{user:s}=hs(),t=ha(),{data:n}=K_();return rt({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await U.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 U.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 U.from("profiles").select("id, name").in("id",c);h==null||h.forEach(m=>{m.name&&(d[m.id]=m.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function iwr(s){const{user:t}=hs();return rt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function xOt(s){const{user:t}=hs(),n=$t();return _.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=U.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()=>{U.removeChannel(a)}},[s,n]),rt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await U.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 SPs(){const s=$t(),t=ha();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),la({title:"Open house created!"})},onError:n=>{la({title:"Error",description:n.message,variant:"destructive"})}})}function gOt(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{error:r}=await U.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 CPs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),la({title:"Open house deleted"})}})}function yOt(s){return rt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await U.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 U.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 APs(s){const{user:t}=hs();return rt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function EPs(s){return rt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await U.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 TPs(){return mt({mutationFn:async s=>{const{error:t}=await U.from("open_house_survey_responses").insert(s);if(t)throw t}})}function MPs(s){const{user:t}=hs();return rt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await U.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 U.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 PPs(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 LPs(){const s=$t();return mt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await U.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 IPs(){const s=$t();return mt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.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 DPs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function RPs(){return mt({mutationFn:async s=>{const t=crypto.randomUUID(),{error:n}=await U.from("open_house_visitors").insert({...s,id:t});if(n)throw n;return{id:t}}})}function FPs(){return mt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await U.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function OPs(){return mt({mutationFn:async s=>{await U.rpc("increment_open_house_scan",{_slug:s})}})}async function vOt(s){const{data:t,error:n}=await U.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 U.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function zPs(s){const{user:t}=hs();return rt({queryKey:["open-house-rooms",s],queryFn:()=>vOt(s),enabled:!!t&&!!s})}function BPs(s){return rt({queryKey:["public-open-house-rooms",s],queryFn:()=>vOt(s),enabled:!!s})}function $Ps(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 UPs(){const s=$t();return mt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await U.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 qPs(){const s=$t();return mt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.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 VPs(){const s=$t();return mt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await U.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 HPs(){const s=$t();return mt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.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 GPs(){const s=$t();return mt({mutationFn:async({open_house_id:t,orderedIds:n})=>{for(let r=0;r{const r=["open-house-rooms",t];await s.cancelQueries({queryKey:r});const a=s.getQueryData(r);if(a){const i=new Map(a.map(o=>[o.id,o])),l=n.map((o,c)=>({...i.get(o),sort_order:c})).filter(Boolean);s.setQueryData(r,l)}return{prev:a,key:r}},onError:(t,n,r)=>{r!=null&&r.prev&&s.setQueryData(r.key,r.prev)},onSettled:(t,n,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function WPs(){const s=$t();return mt({mutationFn:async({open_house_id:t,room_id:n,orderedIds:r})=>{for(let a=0;a{const a=["open-house-rooms",t];await s.cancelQueries({queryKey:a});const i=s.getQueryData(a);return i&&s.setQueryData(a,i.map(l=>{if(l.id!==n)return l;const o=new Map(l.media.map(c=>[c.id,c]));return{...l,media:r.map((c,d)=>{const u=o.get(c);return u?{...u,sort_order:d}:null}).filter(Boolean)}})),{prev:i,key:a}},onError:(t,n,r)=>{r!=null&&r.prev&&s.setQueryData(r.key,r.prev)},onSettled:(t,n,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function KPs(s){const{user:t}=hs();return rt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await U.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 YPs(){const s=$t();return mt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await U.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 GPe="Switch",[ZPs,owr]=uf(GPe),[XPs,QPs]=ZPs(GPe),bOt=_.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,[m,p]=_.useState(null),f=el(t,w=>p(w)),g=_.useRef(!1),v=m?u||!!m.closest("form"):!0,[y,b]=Gg({prop:a,defaultProp:i??!1,onChange:d,caller:GPe});return e.jsxs(XPs,{scope:n,checked:y,disabled:o,children:[e.jsx(ci.button,{type:"button",role:"switch","aria-checked":y,"aria-required":l,"data-state":NOt(y),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:f,onClick:wa(s.onClick,w=>{b(S=>!S),v&&(g.current=w.isPropagationStopped(),g.current||w.stopPropagation())})}),v&&e.jsx(jOt,{control:m,bubbles:!g.current,name:r,value:c,checked:y,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});bOt.displayName=GPe;var _Ot="SwitchThumb",wOt=_.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=QPs(_Ot,n);return e.jsx(ci.span,{"data-state":NOt(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});wOt.displayName=_Ot;var JPs="SwitchBubbleInput",jOt=_.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=_.useRef(null),o=el(l,i),c=Jre(n),d=Rre(t);return _.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const f=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(f)}},[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}})});jOt.displayName=JPs;function NOt(s){return s?"checked":"unchecked"}var kOt=bOt,eLs=wOt;const mn=_.forwardRef(({className:s,...t},n)=>e.jsx(kOt,{className:Ct("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(eLs,{className:Ct("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")})}));mn.displayName=kOt.displayName;const tLs=["Excellent","Good","Neutral","Bad","Very Bad"],sLs=[5,4,3,2,1];function nLs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=TPs(),[i,l]=_.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,p)=>{l(f=>({...f,[m]:{rating_value:p}}))},u=(m,p)=>{l(f=>({...f,[m]:{text_value:p}}))},h=async()=>{const m=Object.entries(i).filter(([,p])=>p.rating_value!=null||p.text_value&&p.text_value.trim()).map(([p,f])=>{var g;return{visitor_id:t,question_id:p,rating_value:f.rating_value??null,text_value:((g=f.text_value)==null?void 0:g.trim())||null}});if(m.length>0)try{await a.mutateAsync(m)}catch{}n()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:r,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),tLs.map(m=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:m})},m))]}),o.map(m=>e.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[e.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:m.question_text}),sLs.map(p=>{var f;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,p),className:`w-6 h-6 rounded-full border-2 transition-all ${((f=i[m.id])==null?void 0:f.rating_value)===p?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},p)})]},m.id))]}),c.map(m=>{var p;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:m.question_text}),e.jsx(Ps,{value:((p=i[m.id])==null?void 0:p.text_value)||"",onChange:f=>u(m.id,f.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx(z,{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(bt,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function yVe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function rLs({rooms:s}){var h;const[t,n]=_.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=_.useState(null),i=s.find(m=>m.id===t)||s[0],l=r!==null?i==null?void 0:i.media[r]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(m=>m===null||o===0?m:(m-1+o)%o),u=()=>a(m=>m===null||o===0?m:(m+1)%o);return _.useEffect(()=>{if(r===null)return;const m=p=>{p.key==="Escape"?c():p.key==="ArrowLeft"?d():p.key==="ArrowRight"&&u()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(m=>e.jsxs("button",{onClick:()=>n(m.id),className:Ct("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===m.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[m.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:m.media.length})]},m.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((m,p)=>e.jsx("button",{onClick:()=>a(p),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:m.kind==="video"?e.jsxs(e.Fragment,{children:[yVe(m.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(Xr,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:m.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},m.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(r??0)+1," / ",o]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),c()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),o>1&&e.jsx("button",{onClick:m=>{m.stopPropagation(),d()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:e.jsx(Wc,{className:"h-6 w-6"})}),l.kind==="video"?yVe(l.url)?e.jsx("iframe",{src:`${l.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:m=>m.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:m=>m.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:m=>m.stopPropagation()}),o>1&&e.jsx("button",{onClick:m=>{m.stopPropagation(),u()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:e.jsx(yi,{className:"h-6 w-6"})})]})]}):null}function aLs({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=_.useRef(null),[r,a]=_.useState(0);_.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:Ct("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"?yVe(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(Wc,{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(yi,{className:"h-4 w-4"})]})]})]})}const BOe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:qi},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:ya},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:$r},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:Nd}},iLs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function oLs(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 lLs({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var Oe;const l=s.profiles,o=((Oe=l==null?void 0:l.name)==null?void 0:Oe.split(" ").map(ke=>ke[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState(r||""),[g,v]=_.useState(a||""),[y,b]=_.useState(!1),[w,S]=_.useState(null),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(""),[F,q]=_.useState([]),[G,V]=_.useState(""),[H,K]=_.useState(""),[Z,oe]=_.useState(""),[re,ae]=_.useState(""),J=oLs(s.price),te=s.tour_mode==="rooms",{data:ce=[]}=BPs(te?s.id:void 0),ve=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),me=ke=>{u(ke),m(""),E(""),M(""),D(""),q([]),V(""),K(""),oe(""),ae("")},he=()=>{u(null)},ge=ke=>{q(Ve=>Ve.includes(ke)?Ve.filter(_e=>_e!==ke):[...Ve,ke])},Ee=ke=>ke==="showing"?{preferred_date:C||null,preferred_time:P||null,alternate_date:I||null}:ke==="disclosure"?{requested_documents:F}:ke==="offer"?{offer_amount:G||null,financing:H||null,timeline:Z||null,pre_approved:re||null}:{},Ne=d?d==="showing"?!!C:d==="question"?h.trim().length>0:!0:!1,Pe=async()=>{if(d){if(i){la({title:"Preview mode",description:"Lead not sent — this is just a preview."}),S(d),setTimeout(()=>{u(null),S(null)},1500);return}b(!0);try{const ke=Ee(d),{error:Ve}=await U.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:p.trim()||null,phone:g.trim()||null,visitor_name:n,...ke}});if(Ve)throw Ve;U.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:p.trim()||null,visitor_phone:g.trim()||null,extras:ke}}).catch(()=>{}),S(d),la({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{he(),S(null)},1400)}catch(ke){la({title:"Something went wrong",description:ke.message,variant:"destructive"})}finally{b(!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(Ha,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),J&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:J}),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(mj,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ey,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(jb,{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(ja,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(xi,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(Na,{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(va,{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(on,{className:"h-4 w-4"})})]})]}),te&&ce.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(rLs,{rooms:ce}),e.jsx(aLs,{rooms:ce})]}),ve.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:ve.map(ke=>{const Ve=BOe[ke],_e=Ve.icon;return e.jsxs("button",{onClick:()=>me(ke),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(_e,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Ve.label})]},ke)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(Wg,{open:!!d,onOpenChange:ke=>!ke&&he(),children:e.jsx(gg,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(Dy,{className:"text-left",children:[e.jsx(Ry,{children:BOe[d].title}),e.jsxs(Z9,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),w===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(Mr,{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(ee,{className:"text-xs",children:"Email"}),e.jsx(pe,{type:"email",value:p,onChange:ke=>f(ke.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{type:"tel",value:g,onChange:ke=>v(ke.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(ee,{className:"text-xs",children:"Preferred date *"}),e.jsx(pe,{type:"date",value:C,onChange:ke=>E(ke.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Preferred time"}),e.jsx(pe,{type:"time",value:P,onChange:ke=>M(ke.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(pe,{type:"date",value:I,onChange:ke=>D(ke.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:iLs.map(ke=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(za,{checked:F.includes(ke),onCheckedChange:()=>ge(ke)}),e.jsx("span",{children:ke})]},ke))})]}),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(ee,{className:"text-xs",children:"Estimated offer"}),e.jsx(pe,{value:G,onChange:ke=>V(ke.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Financing"}),e.jsxs(ls,{value:H,onValueChange:K,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"Cash",children:"Cash"}),e.jsx(He,{value:"Conventional",children:"Conventional"}),e.jsx(He,{value:"FHA",children:"FHA"}),e.jsx(He,{value:"VA",children:"VA"}),e.jsx(He,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Timeline"}),e.jsxs(ls,{value:Z,onValueChange:oe,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"ASAP",children:"ASAP"}),e.jsx(He,{value:"30 days",children:"30 days"}),e.jsx(He,{value:"60 days",children:"60 days"}),e.jsx(He,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(ls,{value:re,onValueChange:ae,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"Yes",children:"Yes"}),e.jsx(He,{value:"No",children:"No"}),e.jsx(He,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ps,{value:h,onChange:ke=>m(ke.target.value),placeholder:BOe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(z,{onClick:Pe,disabled:y||!Ne,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:y?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const cLs=Gj({first_name:Jo().trim().min(1,"First name is required").max(50),last_name:Jo().trim().max(50).optional(),email:Jo().trim().email("Please enter a valid email").max(255).optional().or(jx("")),phone:Jo().trim().max(20).optional().or(jx(""))}),dLs=[{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 SOt({slug:s}={}){var qe;const t=Mi(),n=s||t.slug,[r]=Gl(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=yOt(n),d=RPs(),u=FPs(),h=OPs(),m=_.useRef(!1),[p,f]=_.useState("welcome"),[g,v]=_.useState(null),[y,b]=_.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[w,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(""),[F,q]=_.useState(""),[G,V]=_.useState(i),H=_.useCallback(()=>{v(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),S(""),E(!1),M(!1),D(""),q(""),V(i),f(a?"info":"welcome")},[a]),K=_.useCallback((Be,Ze)=>{l!=null&&l.id&&U.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Be,first_name:Ze.first_name??y.first_name,last_name:Ze.last_name??y.last_name,email:Ze.email??y.email,phone:Ze.phone??y.phone,visitor_intent:Ze.visitor_intent??w,message:Ze.message,wants_market_updates:Ze.wants_market_updates??C,has_agent:Ze.has_agent??P,working_with_agent_name:Ze.working_with_agent_name??I,visitor_address:Ze.visitor_address??y.visitor_address}}).catch($e=>console.error("Guest book lead notify failed:",$e))},[l==null?void 0:l.id,y,w,C,P,I]);_.useEffect(()=>{if(!a||p!=="done")return;V(i);const Be=setInterval(()=>{V(Ze=>Ze<=1?(clearInterval(Be),H(),0):Ze-1)},1e3);return()=>clearInterval(Be)},[a,p,H]),_.useEffect(()=>{if(!a)return;f(Ze=>Ze==="welcome"?"info":Ze);let Be=null;return(async()=>{var Ze,$e;try{Be=await(($e=(Ze=navigator.wakeLock)==null?void 0:Ze.request)==null?void 0:$e.call(Ze,"screen"))}catch{}})(),()=>{var Ze;try{(Ze=Be==null?void 0:Be.release)==null||Ze.call(Be)}catch{}}},[a]);const Z=_.useCallback(()=>{var Ze;const Be=document.documentElement;document.fullscreenElement||(Ze=Be.requestFullscreen||Be.webkitRequestFullscreen)==null||Ze.call(Be).catch(()=>{})},[]),{data:oe,isLoading:re}=EPs(l==null?void 0:l.id),ae=!!(l!=null&&l.enable_survey),J=(l==null?void 0:l.ask_visitor_intent)!==!1,te=(l==null?void 0:l.ask_visitor_address)===!0;_.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const Be=`oh_scan_${l.id}`;if(sessionStorage.getItem(Be)){m.current=!0;return}m.current=!0,sessionStorage.setItem(Be,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),_.useEffect(()=>{p==="pending_survey"&&(re||f(ae&&((oe==null?void 0:oe.length)??0)>0?"survey":"done"))},[p,re,ae,oe]);const ce=Be=>{if(!Be)return"";const[Ze,$e]=Be.split(":"),Xe=parseInt(Ze),nt=Xe>=12?"PM":"AM";return`${Xe>12?Xe-12:Xe||12}:${$e} ${nt}`},ve=async()=>{q("");const Be=cLs.safeParse(y);if(!Be.success){q(Be.error.issues[0].message);return}if(!y.email&&!y.phone){q("Please provide either an email or phone number");return}const Ze=(l==null?void 0:l.kind)==="virtual";let $e=null;if(!g&&(l!=null&&l.id))try{const Xe=await d.mutateAsync({open_house_id:l.id,first_name:y.first_name.trim(),last_name:y.last_name.trim()||void 0,email:y.email.trim()||void 0,phone:y.phone.trim()||void 0,visitor_address:te&&y.visitor_address.trim()?y.visitor_address.trim():void 0,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:Ze?!1:J});$e=Xe.id,v(Xe.id)}catch{if(Ze){q("We could not start the virtual tour. Please try again.");return}}if(Ze){J?f("intent"):($e&&K($e,{}),f("done"));return}if(!J){$e&&K($e,{}),ae?!re&&oe&&oe.length>0?f("survey"):f("pending_survey"):f("done");return}f("intent")},me=async Be=>{S(Be);try{let Ze=g;if(Ze?await u.mutateAsync({visitor_id:Ze,visitor_intent:Be,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null,partial_signin:!1}):(Ze=(await d.mutateAsync({open_house_id:l.id,first_name:y.first_name.trim(),last_name:y.last_name.trim()||void 0,email:y.email.trim()||void 0,phone:y.phone.trim()||void 0,visitor_address:te&&y.visitor_address.trim()?y.visitor_address.trim():void 0,visitor_intent:Be,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:!1})).id,v(Ze)),Ze&&K(Ze,{visitor_intent:Be,wants_market_updates:C,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null}),(l==null?void 0:l.kind)==="virtual"){f("done");return}ae?!re&&oe&&oe.length>0?f("survey"):f("pending_survey"):f("done")}catch{q("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(sa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const he=l.profiles,ge=((qe=he==null?void 0:he.name)==null?void 0:qe.split(" ").map(Be=>Be[0]).join("").slice(0,2))||"?",Ee=l.event_type==="community",Ne=l.kind==="virtual",Pe=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Ne&&(Pe||p==="done"))return!Pe&&!g?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(dl,{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"})]}),Pe&&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(lLs,{openHouse:l,visitorId:Pe?"preview":g,visitorName:Pe?"Preview Visitor":`${y.first_name} ${y.last_name}`.trim(),visitorEmail:Pe?"":y.email,visitorPhone:Pe?"":y.phone,previewMode:Pe})]});const ke=`${Ne?"Virtual Open House":Ee?"Community Event":"Open House"} — ${l.property_address}`,_e=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Ys(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,he!=null&&he.name?`Hosted by ${he.name}`:null].filter(Boolean).join(" · "),Ae=l.photo_url||"",Se=Ae&&Ae.includes("/storage/v1/object/public/")?Ae.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Ae||"https://dashboard.relevelup.com/og-image.png",We=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:ke}),e.jsx("meta",{name:"description",content:_e||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ke}),e.jsx("meta",{property:"og:description",content:_e||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:Se}),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:We}),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:ke}),e.jsx("meta",{name:"twitter:description",content:_e||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Se}),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(ja,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(xi,{src:(he==null?void 0:he.avatar_url)||"",alt:(he==null?void 0:he.name)||""}),e.jsx(Na,{className:"bg-white/10 text-white text-lg",children:ge})]}),e.jsx("p",{className:"text-white/60 text-sm",children:he==null?void 0:he.name}),(he==null?void 0:he.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:he.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ha,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ne&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),Ys(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(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:Ee?e.jsx(oi,{className:"h-5 w-5 text-white"}):e.jsx(sa,{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(Ha,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ne&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),Ys(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[p==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs(z,{onClick:()=>f("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Da,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),p==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>f("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(ka,{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(ee,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(pe,{value:y.first_name,onChange:Be=>b(Ze=>({...Ze,first_name:Be.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(pe,{value:y.last_name,onChange:Be=>b(Ze=>({...Ze,last_name:Be.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(pe,{type:"email",value:y.email,onChange:Be=>b(Ze=>({...Ze,email:Be.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(pe,{type:"tel",value:y.phone,onChange:Be=>b(Ze=>({...Ze,phone:Be.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),te&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(pe,{value:y.visitor_address,onChange:Be=>b(Ze=>({...Ze,visitor_address:Be.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:C,onChange:Be=>E(Be.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:P?"Yes":"No"}),e.jsx(mn,{checked:P,onCheckedChange:M})]})]}),P&&e.jsx(pe,{value:I,onChange:Be=>D(Be.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),F&&e.jsx("p",{className:"text-destructive text-sm",children:F}),e.jsxs(z,{onClick:ve,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Da,{className:"h-5 w-5 ml-2"})]})]}),p==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>f("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(ka,{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:dLs.map(Be=>e.jsxs("button",{onClick:()=>me(Be.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:Be.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Be.label})]},Be.value))}),F&&e.jsx("p",{className:"text-destructive text-sm text-center",children:F})]}),p==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),p==="survey"&&g&&oe&&e.jsx(nLs,{questions:oe,visitorId:g,onComplete:()=>f("done"),onSkip:()=>f("done")}),p==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(Mr,{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, ",y.first_name,". ",Ee?"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($r,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(he==null?void 0:he.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:he.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(z,{onClick:H,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",G,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(xq,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:Z,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(QQ,{className:"h-3 w-3"})})]})]})})]})}function uLs(s){return rt({queryKey:["open-house-rsvps",s],queryFn:async()=>{const{data:t,error:n}=await U.from("open_house_rsvps").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function hLs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("open_house_rsvps").insert({open_house_id:t.open_house_id,first_name:t.first_name,last_name:t.last_name||null,email:t.email||null,phone:t.phone||null,has_agent:t.has_agent??!1,working_with_agent_name:t.working_with_agent_name||null,message:t.message||null});if(n)throw n;return null},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rsvps",n.open_house_id]})}})}function mLs(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await U.from("open_house_rsvps").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}function pLs(s){const t=$t();return mt({mutationFn:async({id:n,checkedIn:r})=>{const{error:a}=await U.from("open_house_rsvps").update({checked_in_at:r?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}const fLs=Gj({first_name:Jo().trim().min(1,"First name is required").max(50),last_name:Jo().trim().max(50).optional(),email:Jo().trim().email("Please enter a valid email").max(255),phone:Jo().trim().max(20).optional().or(jx("")),message:Jo().trim().max(500).optional().or(jx(""))}),$Oe=s=>{if(!s)return"";const[t,n]=s.split(":"),r=parseInt(t,10),a=r>=12?"PM":"AM";return`${r>12?r-12:r||12}:${n} ${a}`},xLs=s=>{if(!s)return null;const[t,n,r]=s.split(/[-/T]/).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)};function COt({slug:s}={}){const t=Mi(),n=s||t.slug,{data:r,isLoading:a,error:i}=yOt(n),l=hLs(),[o,c]=_.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(!1),y=_.useMemo(()=>xLs(r==null?void 0:r.event_date),[r==null?void 0:r.event_date]),b=_.useMemo(()=>{const M=r==null?void 0:r.photo_url;return M?M.includes("/storage/v1/object/public/")?M.replace("/object/public/","/render/image/public/")+"?width=1600&quality=80":M:""},[r]),w=r==null?void 0:r.profiles,S=[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),C=async()=>{f("");const M=fLs.safeParse(o);if(!M.success){f(M.error.issues[0].message);return}try{await l.mutateAsync({open_house_id:r.id,first_name:o.first_name.trim(),last_name:o.last_name.trim()||void 0,email:o.email.trim(),phone:o.phone.trim()||void 0,has_agent:d,working_with_agent_name:d&&h.trim()?h.trim():void 0,message:o.message.trim()||void 0}),v(!0)}catch(I){f((I==null?void 0:I.message)||"Something went wrong. Please try again.")}},E=_.useMemo(()=>{if(!r||!y)return"";const M=V=>String(V).padStart(2,"0"),I=`${y.getFullYear()}${M(y.getMonth()+1)}${M(y.getDate())}`,D=(r.start_time||"12:00").slice(0,5).replace(":","")+"00",F=(r.end_time||"14:00").slice(0,5).replace(":","")+"00",q=encodeURIComponent(`Open House — ${r.property_address}`),G=encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${q}&dates=${I}T${D}/${I}T${F}&location=${G}`},[r,y,S]);if(a)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:e.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(i||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:e.jsxs("div",{className:"text-white/80",children:[e.jsx(sa,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),e.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),e.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const P=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "))}`;return e.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[e.jsxs(dl,{children:[e.jsx("title",{children:`RSVP — Open House at ${r.property_address}`}),e.jsx("meta",{name:"description",content:`Reserve your spot for the open house at ${r.property_address}${y?` on ${Ys(y,"EEEE, MMMM d")}`:""}.`})]}),e.jsxs("header",{className:"relative",children:[e.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[b&&e.jsx("img",{src:b,alt:r.property_address,className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),e.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:r.property_address}),S&&e.jsxs("p",{className:"mt-1 text-white/70",children:[S," ",r.zip||""]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[y&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ya,{className:"h-4 w-4 text-[#d4b978]"}),Ys(y,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Zr,{className:"h-4 w-4 text-[#d4b978]"}),$Oe(r.start_time),r.end_time?` – ${$Oe(r.end_time)}`:""]})]})]})})]}),e.jsx("div",{className:"h-1 bg-gradient-to-r from-[#b8975a] via-[#d4b978] to-[#b8975a]"})]}),e.jsxs("main",{className:"mx-auto max-w-3xl px-5 py-8 sm:py-12 space-y-8",children:[(r.price||r.beds||r.baths||r.sqft)&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[r.price?e.jsx(kle,{icon:e.jsx(sa,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(kle,{icon:e.jsx(W4,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(kle,{icon:e.jsx(Ey,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(kle,{icon:e.jsx(Q4,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(r.sqft).toLocaleString()}):null]}),r.property_description&&e.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:r.property_description}),e.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:g?e.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:e.jsx(Mr,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"You're on the list!"}),e.jsxs("p",{className:"mt-2 text-[#5b6b72]",children:["We'll see you ",y?Ys(y,"EEEE, MMMM d"):"soon",r.start_time?` at ${$Oe(r.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),e.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[E&&e.jsx(z,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:e.jsxs("a",{href:E,target:"_blank",rel:"noreferrer",children:[e.jsx(v0,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),e.jsx(z,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:P,target:"_blank",rel:"noreferrer",children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):e.jsxs("div",{className:"p-6 sm:p-8",children:[e.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),e.jsx("p",{className:"mt-1 text-sm text-[#5b6b72]",children:"Let us know you're coming and we'll save you a spot and send a reminder."}),e.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-first",children:"First name *"}),e.jsx(pe,{id:"rsvp-first",value:o.first_name,onChange:M=>c(I=>({...I,first_name:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-last",children:"Last name"}),e.jsx(pe,{id:"rsvp-last",value:o.last_name,onChange:M=>c(I=>({...I,last_name:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-email",children:"Email *"}),e.jsx(pe,{id:"rsvp-email",type:"email",value:o.email,onChange:M=>c(I=>({...I,email:M.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-phone",children:"Phone"}),e.jsx(pe,{id:"rsvp-phone",type:"tel",value:o.phone,onChange:M=>c(I=>({...I,phone:M.target.value})),className:"h-11"})]})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",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 text-[#1b3a4b]",children:"Are you working with an agent?"}),e.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),e.jsx(mn,{checked:d,onCheckedChange:u})]}),d&&e.jsx(pe,{value:h,onChange:M=>m(M.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),e.jsxs("div",{className:"mt-4 space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),e.jsx(Ps,{id:"rsvp-msg",rows:3,value:o.message,onChange:M=>c(I=>({...I,message:M.target.value})),className:"resize-y"})]}),p&&e.jsx("p",{className:"mt-3 text-sm text-destructive",children:p}),e.jsx(z,{onClick:C,disabled:l.isPending,className:"mt-6 h-12 w-full bg-gradient-to-r from-[#1b3a4b] to-[#406E71] text-base hover:opacity-95",children:l.isPending?"Reserving…":e.jsxs(e.Fragment,{children:["RSVP for this open house",e.jsx(Da,{className:"ml-2 h-4 w-4"})]})}),e.jsx("p",{className:"mt-3 text-center text-xs text-[#8b979c]",children:"We'll only use your info to follow up about this property."})]})}),(w==null?void 0:w.name)&&e.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[e.jsxs(ja,{className:"h-14 w-14",children:[e.jsx(xi,{src:w.avatar_url||void 0,alt:w.name}),e.jsx(Na,{children:w.name.slice(0,1)})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-[#a08a5f]",children:"Hosted by"}),e.jsx("p",{className:"font-semibold text-[#1b3a4b]",children:w.name}),w.title&&e.jsx("p",{className:"text-sm text-[#5b6b72]",children:w.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[w.phone&&e.jsx("a",{href:`tel:${w.phone}`,children:w.phone}),w.email&&e.jsx("a",{href:`mailto:${w.email}`,className:"truncate",children:w.email})]})]})]}),e.jsx("div",{className:"text-center",children:e.jsxs("a",{href:P,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function kle({icon:s,label:t,value:n}){return e.jsxs("div",{className:"rounded-xl bg-white border border-[#e9e2da] px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#9aa5aa]",children:[s,t]}),e.jsx("div",{className:"mt-1 text-lg font-semibold text-[#1b3a4b]",children:n})]})}function lwr(s){const{user:t}=hs();return rt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await U.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 cwr(){const s=$t(),{user:t}=hs();return mt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await U.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 dwr(){const s=$t();return mt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await U.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 gLs(s){return rt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await U.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)-1&&s.splice(n,1)}const pC=(s,t,n)=>n>t?t:n{},OH=()=>{};const WP={},EOt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function TOt(s){return typeof s=="object"&&s!==null}const MOt=s=>/^0[^.\s]+$/u.test(s);function POt(s){let t;return()=>(t===void 0&&(t=s()),t)}const wN=s=>s,vLs=(s,t)=>n=>t(s(n)),rae=(...s)=>s.reduce(vLs),pte=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class VJe{constructor(){this.subscriptions=[]}add(t){return qJe(this.subscriptions,t),()=>SAe(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,cN=s=>s/1e3;function LOt(s,t){return t?s*(1e3/t):0}const IOt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,bLs=1e-7,_Ls=12;function wLs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=IOt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>bLs&&++o<_Ls);return l}function aae(s,t,n,r){if(s===t&&n===r)return wN;const a=i=>wLs(i,0,1,s,n);return i=>i===0||i===1?i:IOt(a(i),t,r)}const DOt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,ROt=s=>t=>1-s(1-t),FOt=aae(.33,1.53,.69,.99),HJe=ROt(FOt),OOt=DOt(HJe),zOt=s=>s>=1?1:(s*=2)<1?.5*HJe(s):.5*(2-Math.pow(2,-10*(s-1))),GJe=s=>1-Math.sin(Math.acos(s)),BOt=ROt(GJe),$Ot=DOt(GJe),jLs=aae(.42,0,1,1),NLs=aae(0,0,.58,1),UOt=aae(.42,0,.58,1),kLs=s=>Array.isArray(s)&&typeof s[0]!="number",qOt=s=>Array.isArray(s)&&typeof s[0]=="number",Rft={linear:wN,easeIn:jLs,easeInOut:UOt,easeOut:NLs,circIn:GJe,circInOut:$Ot,circOut:BOt,backIn:HJe,backInOut:OOt,backOut:FOt,anticipate:zOt},SLs=s=>typeof s=="string",Fft=s=>{if(qOt(s)){OH(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return aae(t,n,r,a)}else if(SLs(s))return OH(Rft[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),Rft[s];return s},Sle=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Oft={value:null,addProjectionMetrics:null};function CLs(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,m=!1,p=!1)=>{const g=p&&a?n:r;return m&&l.add(h),g.add(h),h},cancel:h=>{r.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const m=n;n=r,r=m,n.forEach(d),t&&Oft.value&&Oft.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const ALs=40;function VOt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=Sle.reduce((w,S)=>(w[S]=CLs(i,t?S:void 0),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:p,postRender:f}=l,g=()=>{const w=WP.useManualTiming,S=w?a.timestamp:performance.now();n=!1,w||(a.delta=r?1e3/60:Math.max(Math.min(S-a.timestamp,ALs),1)),a.timestamp=S,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),p.process(a),f.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(g))},v=()=>{n=!0,r=!0,a.isProcessing||s(g)};return{schedule:Sle.reduce((w,S)=>{const C=l[S];return w[S]=(E,P=!1,M=!1)=>(n||v(),C.schedule(E,P,M)),w},{}),cancel:w=>{for(let S=0;S(R4e===void 0&&mb.set(ov.isProcessing||WP.useManualTiming?ov.timestamp:performance.now()),R4e),set:s=>{R4e=s,queueMicrotask(ELs)}},HOt=s=>t=>typeof t=="string"&&t.startsWith(s),GOt=HOt("--"),TLs=HOt("var(--"),WJe=s=>TLs(s)?MLs.test(s.split("/*")[0].trim()):!1,MLs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function zft(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const gW={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},fte={...gW,transform:s=>pC(0,1,s)},Cle={...gW,default:1},MJ=s=>Math.round(s*1e5)/1e5,KJe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function PLs(s){return s==null}const LLs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,YJe=(s,t)=>n=>!!(typeof n=="string"&&LLs.test(n)&&n.startsWith(s)||t&&!PLs(n)&&Object.prototype.hasOwnProperty.call(n,t)),WOt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(KJe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},ILs=s=>pC(0,255,s),qOe={...gW,transform:s=>Math.round(ILs(s))},wF={test:YJe("rgb","red"),parse:WOt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+qOe.transform(s)+", "+qOe.transform(t)+", "+qOe.transform(n)+", "+MJ(fte.transform(r))+")"};function DLs(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 vVe={test:YJe("#"),parse:DLs,transform:wF.transform},iae=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),JT=iae("deg"),nC=iae("%"),No=iae("px"),RLs=iae("vh"),FLs=iae("vw"),Bft={...nC,parse:s=>nC.parse(s)/100,transform:s=>nC.transform(s*100)},rU={test:YJe("hsl","hue"),parse:WOt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+nC.transform(MJ(t))+", "+nC.transform(MJ(n))+", "+MJ(fte.transform(r))+")"},Lg={test:s=>wF.test(s)||vVe.test(s)||rU.test(s),parse:s=>wF.test(s)?wF.parse(s):rU.test(s)?rU.parse(s):vVe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?wF.transform(s):rU.transform(s),getAnimatableNone:s=>{const t=Lg.parse(s);return t.alpha=0,Lg.transform(t)}},OLs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function zLs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(KJe))==null?void 0:t.length)||0)+(((n=s.match(OLs))==null?void 0:n.length)||0)>0}const KOt="number",YOt="color",BLs="var",$Ls="var(",$ft="${}",ULs=/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 zH(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(ULs,c=>(Lg.test(c)?(r.color.push(i),a.push(YOt),n.push(Lg.parse(c))):c.startsWith($Ls)?(r.var.push(i),a.push(BLs),n.push(c)):(r.number.push(i),a.push(KOt),n.push(parseFloat(c))),++i,$ft)).split($ft);return{values:n,split:o,indexes:r,types:a}}function qLs(s){return zH(s).values}function ZOt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Lg.test(s)?Lg.getAnimatableNone(s):s,GLs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:HLs(s);function WLs(s){const t=zH(s);return ZOt(t)(t.values.map((r,a)=>GLs(r,t.split[a])))}const jS={test:zLs,parse:qLs,createTransformer:VLs,getAnimatableNone:WLs};function VOe(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 KLs({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=VOe(c,o,s+1/3),i=VOe(c,o,s),l=VOe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function CAe(s,t){return n=>n>0?t:s}const Ep=(s,t,n)=>s+(t-s)*n,HOe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},YLs=[vVe,wF,rU],ZLs=s=>YLs.find(t=>t.test(s));function Uft(s){const t=ZLs(s);if(KPe(!!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===rU&&(n=KLs(n)),n}const qft=(s,t)=>{const n=Uft(s),r=Uft(t);if(!n||!r)return CAe(s,t);const a={...n};return i=>(a.red=HOe(n.red,r.red,i),a.green=HOe(n.green,r.green,i),a.blue=HOe(n.blue,r.blue,i),a.alpha=Ep(n.alpha,r.alpha,i),wF.transform(a))},bVe=new Set(["none","hidden"]);function XLs(s,t){return bVe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function QLs(s,t){return n=>Ep(s,t,n)}function ZJe(s){return typeof s=="number"?QLs:typeof s=="string"?WJe(s)?CAe:Lg.test(s)?qft:tIs:Array.isArray(s)?XOt:typeof s=="object"?Lg.test(s)?qft:JLs:CAe}function XOt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>ZJe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function eIs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=jS.createTransformer(t),r=zH(s),a=zH(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?bVe.has(s)&&!a.values.length||bVe.has(t)&&!r.values.length?XLs(s,t):rae(XOt(eIs(r,a),a.values),n):(KPe(!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"),CAe(s,t))};function QOt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?Ep(s,t,n):ZJe(s)(s,t)}const sIs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>Im.update(t,n),stop:()=>KP(t),now:()=>ov.isProcessing?ov.timestamp:mb.now()}},JOt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=AAe?1/0:t}function nIs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(XJe(r),AAe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:cN(a)}}const Pf={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 _Ve(s,t){return s*Math.sqrt(1-t*t)}const rIs=12;function aIs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,p=_Ve(d,l),f=Math.exp(-h);return GOe-m/p*f},i=d=>{const h=d*l*s,m=h*n+n,p=Math.pow(l,2)*Math.pow(d,2)*s,f=Math.exp(-h),g=_Ve(Math.pow(d,2),l);return(-a(d)+GOe>0?-1:1)*((m-p)*f)/g}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-GOe+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=aIs(a,i,o);if(s=B_(s),isNaN(c))return{stiffness:Pf.stiffness,damping:Pf.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const oIs=["duration","bounce"],lIs=["stiffness","damping","mass"];function Vft(s,t){return t.some(n=>s[n]!==void 0)}function cIs(s){let t={velocity:Pf.velocity,stiffness:Pf.stiffness,damping:Pf.damping,mass:Pf.mass,isResolvedFromDuration:!1,...s};if(!Vft(s,lIs)&&Vft(s,oIs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*pC(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Pf.mass,stiffness:a,damping:i}}else{const n=iIs({...s,velocity:0});t={...t,...n,mass:Pf.mass},t.isResolvedFromDuration=!0}return t}function EAe(s=Pf.visualDuration,t=Pf.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:m,isResolvedFromDuration:p}=cIs({...n,velocity:-cN(n.velocity||0)}),f=m||0,g=d/(2*Math.sqrt(c*u)),v=l-i,y=cN(Math.sqrt(c/u)),b=Math.abs(v)<5;r||(r=b?Pf.restSpeed.granular:Pf.restSpeed.default),a||(a=b?Pf.restDelta.granular:Pf.restDelta.default);let w,S,C,E,P,M;if(g<1)C=_Ve(y,g),E=(f+g*y*v)/C,w=D=>{const F=Math.exp(-g*y*D);return l-F*(E*Math.sin(C*D)+v*Math.cos(C*D))},P=g*y*E+v*C,M=g*y*v-E*C,S=D=>Math.exp(-g*y*D)*(P*Math.sin(C*D)+M*Math.cos(C*D));else if(g===1){w=F=>l-Math.exp(-y*F)*(v+(f+y*v)*F);const D=f+y*v;S=F=>Math.exp(-y*F)*(y*D*F-f)}else{const D=y*Math.sqrt(g*g-1);w=V=>{const H=Math.exp(-g*y*V),K=Math.min(D*V,300);return l-H*((f+g*y*v)*Math.sinh(K)+D*v*Math.cosh(K))/D};const F=(f+g*y*v)/D,q=g*y*F-v*D,G=g*y*v-F*D;S=V=>{const H=Math.exp(-g*y*V),K=Math.min(D*V,300);return H*(q*Math.sinh(K)+G*Math.cosh(K))}}const I={calculatedDuration:p&&h||null,velocity:D=>B_(S(D)),next:D=>{if(!p&&g<1){const q=Math.exp(-g*y*D),G=Math.sin(C*D),V=Math.cos(C*D),H=l-q*(E*G+v*V),K=B_(q*(P*G+M*V));return o.done=Math.abs(K)<=r&&Math.abs(l-H)<=a,o.value=o.done?l:H,o}const F=w(D);if(p)o.done=D>=h;else{const q=B_(S(D));o.done=Math.abs(q)<=r&&Math.abs(l-F)<=a}return o.value=o.done?l:F,o},toString:()=>{const D=Math.min(XJe(I),AAe),F=JOt(q=>I.next(D*q).value,D,30);return D+"ms "+F},toTransition:()=>{}};return I}EAe.applyToOptions=s=>{const t=nIs(s,100,EAe);return s.ease=t.ease,s.duration=B_(t.duration),s.type="keyframes",s};const dIs=5;function e7t(s,t,n){const r=Math.max(t-dIs,0);return LOt(n-s(r),t-r)}function wVe({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},p=M=>o!==void 0&&Mc,f=M=>o===void 0?c:c===void 0||Math.abs(o-M)-g*Math.exp(-M/r),w=M=>y+b(M),S=M=>{const I=b(M),D=w(M);m.done=Math.abs(I)<=d,m.value=m.done?y:D};let C,E;const P=M=>{p(m.value)&&(C=M,E=EAe({keyframes:[m.value,f(m.value)],velocity:e7t(w,M,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return P(0),{calculatedDuration:null,next:M=>{let I=!1;return!E&&C===void 0&&(I=!0,S(M),P(M)),C!==void 0&&M>=C?E.next(M-C):(!I&&S(M),m)}}}function uIs(s,t,n){const r=[],a=n||WP.mix||QOt,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=uIs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(pC(s[0],s[i-1],u)):d}function mIs(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=pte(0,t,r);s.push(Ep(n,1,a))}}function pIs(s){const t=[0];return mIs(t,s.length-1),t}function fIs(s,t){return s.map(n=>n*t)}function xIs(s,t){return s.map(()=>t||UOt).splice(0,s.length-1)}function PJ({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=kLs(r)?r.map(Fft):Fft(r),i={done:!1,value:t[0]},l=fIs(n&&n.length===t.length?n:pIs(t),s),o=hIs(l,t,{ease:Array.isArray(a)?a:xIs(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const gIs=s=>s!==null;function YPe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(gIs),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const yIs={decay:wVe,inertia:wVe,tween:PJ,keyframes:PJ,spring:EAe};function t7t(s){typeof s.type=="string"&&(s.type=yIs[s.type])}class QJe{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 vIs=s=>s/100;class TAe extends QJe{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!==mb.now()&&this.tick(mb.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;t7t(t);const{type:n=PJ,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||PJ;c!==PJ&&typeof o[0]!="number"&&(this.mixKeyframes=rae(vIs,QOt(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=XJe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:p,type:f,onUpdate:g,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 y=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?y<0:y>a;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let w=this.currentTime,S=r;if(h){const M=Math.min(this.currentTime,a)/o;let I=Math.floor(M),D=M%1;!D&&M>=1&&(D=1),D===1&&I--,I=Math.min(I,h+1),!!(I%2)&&(m==="reverse"?(D=1-D,p&&(D-=p/o)):m==="mirror"&&(S=l)),w=pC(0,1,D)*o}let C;b?(this.delayState.value=u[0],C=this.delayState):C=S.next(w),i&&!b&&(C.value=i(C.value));let{done:E}=C;!b&&c!==null&&(E=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&E);return P&&f!==wVe&&(C.value=YPe(u,this.options,v,this.speed)),g&&g(C.value),P&&this.finish(),C}then(t,n){return this.finished.then(t,n)}get duration(){return cN(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+cN(t)}get time(){return cN(this.currentTime)}set time(t){t=B_(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 e7t(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(mb.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=cN(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=sIs,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(mb.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 bIs(s){for(let t=1;ts*180/Math.PI,jVe=s=>{const t=jF(Math.atan2(s[1],s[0]));return NVe(t)},_Is={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:jVe,rotateZ:jVe,skewX:s=>jF(Math.atan(s[1])),skewY:s=>jF(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},NVe=s=>(s=s%360,s<0&&(s+=360),s),Hft=jVe,Gft=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),Wft=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),wIs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Gft,scaleY:Wft,scale:s=>(Gft(s)+Wft(s))/2,rotateX:s=>NVe(jF(Math.atan2(s[6],s[5]))),rotateY:s=>NVe(jF(Math.atan2(-s[2],s[0]))),rotateZ:Hft,rotate:Hft,skewX:s=>jF(Math.atan(s[4])),skewY:s=>jF(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function kVe(s){return s.includes("scale")?1:0}function SVe(s,t){if(!s||s==="none")return kVe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=wIs,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=_Is,a=o}if(!a)return kVe(t);const i=r[t],l=a[1].split(",").map(NIs);return typeof i=="function"?i(l):l[i]}const jIs=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return SVe(n,t)};function NIs(s){return parseFloat(s.trim())}const yW=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],vW=new Set(yW),Kft=s=>s===gW||s===No,kIs=new Set(["x","y","z"]),SIs=yW.filter(s=>!kIs.has(s));function CIs(s){const t=[];return SIs.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const EM={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})=>SVe(t,"x"),y:(s,{transform:t})=>SVe(t,"y")};EM.translateX=EM.x;EM.translateY=EM.y;const N7=new Set;let CVe=!1,AVe=!1,EVe=!1;function s7t(){if(AVe){const s=Array.from(N7).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=CIs(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)})}AVe=!1,CVe=!1,N7.forEach(s=>s.complete(EVe)),N7.clear()}function n7t(){N7.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(AVe=!0)})}function AIs(){EVe=!0,n7t(),s7t(),EVe=!1}class JJe{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?(N7.add(this),CVe||(CVe=!0,Im.read(n7t),Im.resolveKeyframes(s7t))):(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])}bIs(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),N7.delete(this)}cancel(){this.state==="scheduled"&&(N7.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const EIs=s=>s.startsWith("--");function r7t(s,t,n){EIs(t)?s.style.setProperty(t,n):s.style[t]=n}const TIs={};function a7t(s,t){const n=POt(s);return()=>TIs[t]??n()}const MIs=a7t(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),i7t=a7t(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),wX=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,Yft={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:wX([0,.65,.55,1]),circOut:wX([.55,0,1,.45]),backIn:wX([.31,.01,.66,-.59]),backOut:wX([.33,1.53,.69,.99])};function o7t(s,t){if(s)return typeof s=="function"?i7t()?JOt(s,t):"ease-out":qOt(s)?wX(s):Array.isArray(s)?s.map(n=>o7t(n,t)||Yft.easeOut):Yft[s]}function PIs(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=o7t(o,a);Array.isArray(h)&&(u.easing=h);const m={delay:r,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(m.pseudoElement=d),s.animate(u,m)}function l7t(s){return typeof s=="function"&&"applyToOptions"in s}function LIs({type:s,...t}){return l7t(s)&&i7t()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class c7t extends QJe{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,OH(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=LIs(t);this.animation=PIs(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=YPe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),r7t(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 cN(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+cN(t)}get time(){return cN(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=B_(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&&MIs()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),wN):a(this)}}const d7t={anticipate:zOt,backInOut:OOt,circInOut:$Ot};function IIs(s){return s in d7t}function DIs(s){typeof s.ease=="string"&&IIs(s.ease)&&(s.ease=d7t[s.ease])}const WOe=10;class RIs extends c7t{constructor(t){DIs(t),t7t(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 TAe({...l,autoplay:!1}),c=Math.max(WOe,mb.now()-this.startTime),d=pC(0,WOe,c-WOe),u=o.sample(c).value,{name:h}=this.options;i&&h&&r7t(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const Zft=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(jS.test(s)||s==="0")&&!s.startsWith("url("));function FIs(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function qIs(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 UIs()&&n&&(u7t.has(n)||$Is.has(n)&&BIs(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const VIs=40;class HIs extends QJe{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 f;super(),this.stop=()=>{var g,v;this._animation&&(this._animation.stop(),(g=this.stopTimeline)==null||g.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=mb.now();const m={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},p=(u==null?void 0:u.KeyframeResolver)||JJe;this.keyframeResolver=new p(o,(g,v,y)=>this.onKeyframesResolved(g,v,m,!y),c,d,u),(f=this.keyframeResolver)==null||f.scheduleResolve()}onKeyframesResolved(t,n,r,a){var y,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=mb.now();let h=!0;OIs(t,i,l,o)||(h=!1,(WP.instantAnimations||!c)&&(u==null||u(YPe(t,r,n))),t[0]=t[t.length-1],TVe(r),r.repeat=0);const p={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>VIs?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},f=h&&!d&&qIs(p),g=(b=(y=p.motionValue)==null?void 0:y.owner)==null?void 0:b.current;let v;if(f)try{v=new RIs({...p,element:g})}catch{v=new TAe(p)}else v=new TAe(p);v.finished.then(()=>{this.notifyFinished()}).catch(wN),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(),AIs()),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 h7t(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 GIs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function WIs(s){const t=GIs.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const KIs=4;function m7t(s,t,n=1){OH(n<=KIs,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=WIs(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return EOt(l)?parseFloat(l):l}return WJe(a)?m7t(a,t,n+1):a}const YIs={type:"spring",stiffness:500,damping:25,restSpeed:10},ZIs=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),XIs={type:"keyframes",duration:.8},QIs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},JIs=(s,{keyframes:t})=>t.length>2?XIs:vW.has(s)?s.startsWith("scale")?ZIs(t[1]):YIs:QIs;function p7t(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function eet(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?p7t(n,s):n}const e8s=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function t8s(s){for(const t in s)if(!e8s.has(t))return!0;return!1}const tet=(s,t,n,r={},a,i)=>l=>{const o=eet(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-B_(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:m=>{t.set(m),o.onUpdate&&o.onUpdate(m)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};t8s(o)||Object.assign(u,JIs(s,u)),u.duration&&(u.duration=B_(u.duration)),u.repeatDelay&&(u.repeatDelay=B_(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(TVe(u),u.delay===0&&(h=!0)),(WP.instantAnimations||WP.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,TVe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=YPe(u.keyframes,o);if(m!==void 0){Im.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new TAe(u):new HIs(u)};function Xft(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function set(s,t,n,r){if(typeof t=="function"){const[a,i]=Xft(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]=Xft(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function k7(s,t,n){const r=s.getProps();return set(r,t,n!==void 0?n:r.custom,s)}const f7t=new Set(["width","height","top","left","right","bottom",...yW]),Qft=30,s8s=s=>!isNaN(parseFloat(s));class n8s{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=mb.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=mb.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=s8s(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 VJe);const r=this.events[t].add(n);return t==="change"?()=>{r(),Im.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=mb.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Qft)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Qft);return LOt(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 BH(s,t){return new n8s(s,t)}const MVe=s=>Array.isArray(s);function r8s(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,BH(n))}function a8s(s){return MVe(s)?s[s.length-1]||0:s}function i8s(s,t){const n=k7(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=a8s(i[l]);r8s(s,l,o)}}const xv=s=>!!(s&&s.getVelocity);function o8s(s){return!!(xv(s)&&s.add)}function PVe(s,t){const n=s.getValue("willChange");if(o8s(n))return n.add(t);if(!n&&WP.WillChange){const r=new WP.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function net(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const l8s="framerAppearId",x7t="data-"+net(l8s);function g7t(s){return s.props[x7t]}function c8s({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function y7t(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?p7t(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 m in o){const p=s.getValue(m,s.latestValues[m]??null),f=o[m];if(f===void 0||h&&c8s(h,m))continue;const g={delay:n,...eet(i||{},m)},v=p.get();if(v!==void 0&&!p.isAnimating()&&!Array.isArray(f)&&f===v&&!g.velocity){Im.update(()=>p.set(f));continue}let y=!1;if(window.MotionHandoffAnimation){const S=g7t(s);if(S){const C=window.MotionHandoffAnimation(S,m,Im);C!==null&&(g.startTime=C,y=!0)}}PVe(s,m);const b=d??s.shouldReduceMotion;p.start(tet(m,p,f,b&&f7t.has(m)?{type:!1}:g,s,y));const w=p.animation;w&&u.push(w)}if(l){const m=()=>Im.update(()=>{l&&i8s(s,l)});u.length?Promise.all(u).then(m):m()}return u}function LVe(s,t,n={}){var c;const r=k7(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(y7t(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return d8s(s,t,d,u,h,m,n)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,u]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>u())}else return Promise.all([i(),l(n.delay)])}function d8s(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(LVe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+h7t(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function u8s(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>LVe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=LVe(s,t,n);else{const a=typeof t=="function"?k7(s,t,n.custom):t;r=Promise.all(y7t(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const h8s={test:s=>s==="auto",parse:s=>s},v7t=s=>t=>t.test(s),b7t=[gW,No,nC,JT,FLs,RLs,h8s],Jft=s=>b7t.find(v7t(s));function m8s(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||MOt(s):!0}const p8s=new Set(["brightness","contrast","saturate","opacity"]);function f8s(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(KJe)||[];if(!r)return s;const a=n.replace(r,"");let i=p8s.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const x8s=/\b([a-z-]*)\(.*?\)/gu,IVe={...jS,getAnimatableNone:s=>{const t=s.match(x8s);return t?t.map(f8s).join(" "):s}},DVe={...jS,getAnimatableNone:s=>{const t=jS.parse(s);return jS.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},ext={...gW,transform:Math.round},g8s={rotate:JT,rotateX:JT,rotateY:JT,rotateZ:JT,scale:Cle,scaleX:Cle,scaleY:Cle,scaleZ:Cle,skew:JT,skewX:JT,skewY:JT,distance:No,translateX:No,translateY:No,translateZ:No,x:No,y:No,z:No,perspective:No,transformPerspective:No,opacity:fte,originX:Bft,originY:Bft,originZ:No},ret={borderWidth:No,borderTopWidth:No,borderRightWidth:No,borderBottomWidth:No,borderLeftWidth:No,borderRadius:No,borderTopLeftRadius:No,borderTopRightRadius:No,borderBottomRightRadius:No,borderBottomLeftRadius:No,width:No,maxWidth:No,height:No,maxHeight:No,top:No,right:No,bottom:No,left:No,inset:No,insetBlock:No,insetBlockStart:No,insetBlockEnd:No,insetInline:No,insetInlineStart:No,insetInlineEnd:No,padding:No,paddingTop:No,paddingRight:No,paddingBottom:No,paddingLeft:No,paddingBlock:No,paddingBlockStart:No,paddingBlockEnd:No,paddingInline:No,paddingInlineStart:No,paddingInlineEnd:No,margin:No,marginTop:No,marginRight:No,marginBottom:No,marginLeft:No,marginBlock:No,marginBlockStart:No,marginBlockEnd:No,marginInline:No,marginInlineStart:No,marginInlineEnd:No,fontSize:No,backgroundPositionX:No,backgroundPositionY:No,...g8s,zIndex:ext,fillOpacity:fte,strokeOpacity:fte,numOctaves:ext},y8s={...ret,color:Lg,backgroundColor:Lg,outlineColor:Lg,fill:Lg,stroke:Lg,borderColor:Lg,borderTopColor:Lg,borderRightColor:Lg,borderBottomColor:Lg,borderLeftColor:Lg,filter:IVe,WebkitFilter:IVe,mask:DVe,WebkitMask:DVe},_7t=s=>y8s[s],v8s=new Set([IVe,DVe]);function w7t(s,t){let n=_7t(s);return v8s.has(n)||(n=jS),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const b8s=new Set(["auto","none","0"]);function _8s(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function aet(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 j7t=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function F4e(s){return TOt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:iet,cancel:uwr}=VOt(queueMicrotask,!1),Ek={x:!1,y:!1};function N7t(){return Ek.x||Ek.y}function j8s(s){return s==="x"||s==="y"?Ek[s]?null:(Ek[s]=!0,()=>{Ek[s]=!1}):Ek.x||Ek.y?null:(Ek.x=Ek.y=!0,()=>{Ek.x=Ek.y=!1})}function k7t(s,t){const n=aet(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function N8s(s){return!(s.pointerType==="touch"||N7t())}function k8s(s,t,n={}){const[r,a,i]=k7t(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",f)},h=v=>{d&&(d(v),d=void 0),u()},m=v=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(v))},p=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},f=v=>{if(v.pointerType!=="touch"){if(o){c=!0;return}h(v)}},g=v=>{if(!N8s(v))return;c=!1;const y=t(l,v);typeof y=="function"&&(d=y,l.addEventListener("pointerleave",f,a))};l.addEventListener("pointerenter",g,a),l.addEventListener("pointerdown",p,a)}),i}const S7t=(s,t)=>t?s===t?!0:S7t(s,t.parentElement):!1,oet=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,S8s=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function C8s(s){return S8s.has(s.tagName)||s.isContentEditable===!0}const A8s=new Set(["INPUT","SELECT","TEXTAREA"]);function E8s(s){return A8s.has(s.tagName)||s.isContentEditable===!0}const O4e=new WeakSet;function txt(s){return t=>{t.key==="Enter"&&s(t)}}function KOe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const T8s=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=txt(()=>{if(O4e.has(n))return;KOe(n,"down");const a=txt(()=>{KOe(n,"up")}),i=()=>KOe(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 sxt(s){return oet(s)&&!N7t()}const nxt=new WeakSet;function M8s(s,t,n={}){const[r,a,i]=k7t(s,n),l=o=>{const c=o.currentTarget;if(!sxt(o)||nxt.has(o))return;O4e.add(c),n.stopPropagation&&nxt.add(o);const d=t(c,o),u=(p,f)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),O4e.has(c)&&O4e.delete(c),sxt(p)&&typeof d=="function"&&d(p,{success:f})},h=p=>{u(p,c===window||c===document||n.useGlobalTarget||S7t(c,p.target))},m=p=>{u(p,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",m,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),F4e(o)&&(o.addEventListener("focus",d=>T8s(d,a)),!C8s(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function cet(s){return TOt(s)&&"ownerSVGElement"in s}const z4e=new WeakMap;let e6;const C7t=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:cet(r)&&"getBBox"in r?r.getBBox()[t]:r[n],P8s=C7t("inline","width","offsetWidth"),L8s=C7t("block","height","offsetHeight");function I8s({target:s,borderBoxSize:t}){var n;(n=z4e.get(s))==null||n.forEach(r=>{r(s,{get width(){return P8s(s,t)},get height(){return L8s(s,t)}})})}function D8s(s){s.forEach(I8s)}function R8s(){typeof ResizeObserver>"u"||(e6=new ResizeObserver(D8s))}function F8s(s,t){e6||R8s();const n=aet(s);return n.forEach(r=>{let a=z4e.get(r);a||(a=new Set,z4e.set(r,a)),a.add(t),e6==null||e6.observe(r)}),()=>{n.forEach(r=>{const a=z4e.get(r);a==null||a.delete(t),a!=null&&a.size||e6==null||e6.unobserve(r)})}}const B4e=new Set;let aU;function O8s(){aU=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};B4e.forEach(t=>t(s))},window.addEventListener("resize",aU)}function z8s(s){return B4e.add(s),aU||O8s(),()=>{B4e.delete(s),!B4e.size&&typeof aU=="function"&&(window.removeEventListener("resize",aU),aU=void 0)}}function rxt(s,t){return typeof s=="function"?z8s(s):F8s(s,t)}function B8s(s){return cet(s)&&s.tagName==="svg"}const $8s=[...b7t,Lg,jS],U8s=s=>$8s.find(v7t(s)),axt=()=>({translate:0,scale:1,origin:0,originPoint:0}),iU=()=>({x:axt(),y:axt()}),ixt=()=>({min:0,max:0}),uy=()=>({x:ixt(),y:ixt()}),q8s=new WeakMap;function ZPe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function xte(s){return typeof s=="string"||Array.isArray(s)}const det=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],uet=["initial",...det];function XPe(s){return ZPe(s.animate)||uet.some(t=>xte(s[t]))}function A7t(s){return!!(XPe(s)||s.variants)}function V8s(s,t,n){for(const r in t){const a=t[r],i=n[r];if(xv(a))s.addValue(r,a);else if(xv(i))s.addValue(r,BH(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,BH(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const RVe={current:null},E7t={current:!1},H8s=typeof window<"u";function G8s(){if(E7t.current=!0,!!H8s)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>RVe.current=s.matches;s.addEventListener("change",t),t()}else RVe.current=!1}const oxt=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let MAe={};function T7t(s){MAe=s}function W8s(){return MAe}class K8s{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=JJe,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const p=mb.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(E7t.current||G8s(),this.shouldReduceMotion=RVe.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(),KP(this.notifyUpdate),KP(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&&u7t.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new c7t({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:B_(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=vW.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Im.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 MAe){const n=MAe[t];if(!n)continue;const{isEnabled:r,Feature:a}=n;if(!this.features[t]&&a&&r(this.props)&&(this.features[t]=new a(this)),this.features[t]){const i=this.features[t];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):uy()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){const r=this.values.get(t);n!==r&&(r&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=BH(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"&&(EOt(r)||MOt(r))?r=parseFloat(r):!U8s(r)&&jS.test(n)&&(r=w7t(t,n)),this.setBaseTarget(t,xv(r)?r.get():r)),xv(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=set(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&&!xv(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 VJe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){iet.render(this.render)}}class M7t extends K8s{constructor(){super(...arguments),this.KeyframeResolver=w8s}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;xv(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class jL{constructor(t){this.isMounted=!1,this.node=t}update(){}}function P7t({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function Y8s({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function Z8s(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 YOe(s){return s===void 0||s===1}function FVe({scale:s,scaleX:t,scaleY:n}){return!YOe(s)||!YOe(t)||!YOe(n)}function KR(s){return FVe(s)||L7t(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function L7t(s){return lxt(s.x)||lxt(s.y)}function lxt(s){return s&&s!=="0%"}function PAe(s,t,n){const r=s-n,a=t*r;return n+a}function cxt(s,t,n,r,a){return a!==void 0&&(s=PAe(s,a,r)),PAe(s,n,r)+t}function OVe(s,t=0,n=1,r,a){s.min=cxt(s.min,t,n,r,a),s.max=cxt(s.max,t,n,r,a)}function I7t(s,{x:t,y:n}){OVe(s.x,t.translate,t.scale,t.originPoint),OVe(s.y,n.translate,n.scale,n.originPoint)}const dxt=.999999999999,uxt=1.0000000000001;function X8s(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;cdxt&&(t.x=1),t.ydxt&&(t.y=1)}function w4(s,t){s.min+=t,s.max+=t}function hxt(s,t,n,r,a=.5){const i=Ep(s.min,s.max,a);OVe(s,t,n,i,r)}function mxt(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function $4e(s,t,n){const r=n??s;hxt(s.x,mxt(t.x,r.x),t.scaleX,t.scale,t.originX),hxt(s.y,mxt(t.y,r.y),t.scaleY,t.scale,t.originY)}function D7t(s,t){return P7t(Z8s(s.getBoundingClientRect(),t))}function Q8s(s,t,n){const r=D7t(s,n),{scroll:a}=t;return a&&(w4(r.x,a.offset.x),w4(r.y,a.offset.y)),r}const J8s={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},eDs=yW.length;function tDs(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(No.test(s))s=parseFloat(s);else return s;const n=pxt(s,t.target.x),r=pxt(s,t.target.y);return`${n}% ${r}%`}},sDs={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=jS.parse(s);if(a.length>5)return r;const i=jS.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=Ep(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},zVe={borderRadius:{...KY,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:KY,borderTopRightRadius:KY,borderBottomLeftRadius:KY,borderBottomRightRadius:KY,boxShadow:sDs};function F7t(s,{layout:t,layoutId:n}){return vW.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!zVe[s]||s==="opacity")}function met(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)(xv(r[o])||a&&xv(a[o])||F7t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function nDs(s){return window.getComputedStyle(s)}class rDs extends M7t{constructor(){super(...arguments),this.type="html",this.renderInstance=R7t}readValueFromInstance(t,n){var r;if(vW.has(n))return(r=this.projection)!=null&&r.isProjecting?kVe(n):jIs(t,n);{const a=nDs(t),i=(GOt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return D7t(t,n)}build(t,n,r){het(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return met(t,n,r)}}const aDs={offset:"stroke-dashoffset",array:"stroke-dasharray"},iDs={offset:"strokeDashoffset",array:"strokeDasharray"};function oDs(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?aDs:iDs;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const lDs=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function O7t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(het(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:m}=s;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const p of lDs)h[p]!==void 0&&(m[p]=h[p],delete h[p]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&oDs(h,a,i,l,!1)}const z7t=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"]),B7t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function cDs(s,t,n,r){R7t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(z7t.has(a)?a:net(a),t.attrs[a])}function $7t(s,t,n){const r=met(s,t,n);for(const a in s)if(xv(s[a])||xv(t[a])){const i=yW.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class dDs extends M7t{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=uy}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(vW.has(n)){const r=_7t(n);return r&&r.default||0}return n=z7t.has(n)?n:net(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return $7t(t,n,r)}build(t,n,r){O7t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){cDs(t,n,r,a)}mount(t){this.isSVGTag=B7t(t.tagName),super.mount(t)}}const uDs=uet.length;function U7t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?U7t(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})=>u8s(s,n,r)))}function fDs(s){let t=pDs(s),n=fxt(),r=!0,a=!1;const i=d=>(u,h)=>{var p;const m=k7(s,h,d==="exit"?(p=s.presenceContext)==null?void 0:p.custom:void 0);if(m){const{transition:f,transitionEnd:g,...v}=m;u={...u,...v,...g}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=U7t(s.parent)||{},m=[],p=new Set;let f={},g=1/0;for(let y=0;yg&&C,D=!1;const F=Array.isArray(S)?S:[S];let q=F.reduce(i(b),{});E===!1&&(q={});const{prevResolvedValues:G={}}=w,V={...G,...q},H=oe=>{I=!0,p.has(oe)&&(D=!0,p.delete(oe)),w.needsAnimating[oe]=!0;const re=s.getValue(oe);re&&(re.liveStyle=!1)};for(const oe in V){const re=q[oe],ae=G[oe];if(f.hasOwnProperty(oe))continue;let J=!1;MVe(re)&&MVe(ae)?J=!q7t(re,ae):J=re!==ae,J?re!=null?H(oe):p.add(oe):re!==void 0&&p.has(oe)?H(oe):w.protectedKeys[oe]=!0}w.prevProp=S,w.prevResolvedValues=q,w.isActive&&(f={...f,...q}),(r||a)&&s.blockInitialAnimation&&(I=!1);const K=P&&M;I&&(!K||D)&&m.push(...F.map(oe=>{const re={type:b};if(typeof oe=="string"&&(r||a)&&!K&&s.manuallyAnimateOnMount&&s.parent){const{parent:ae}=s,J=k7(ae,oe);if(ae.enteringChildren&&J){const{delayChildren:te}=J.transition||{};re.delay=h7t(ae.enteringChildren,s,te)}}return{animation:oe,options:re}}))}if(p.size){const y={};if(typeof u.initial!="boolean"){const b=k7(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(y.transition=b.transition)}p.forEach(b=>{const w=s.getBaseTarget(b),S=s.getValue(b);S&&(S.liveStyle=!0),y[b]=w??null}),m.push({animation:y})}let v=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(v=!1),r=!1,a=!1,v?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(p=>{var f;return(f=p.animationState)==null?void 0:f.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=fxt(),a=!0}}}function xDs(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!q7t(t,s):!1}function TI(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function fxt(){return{animate:TI(!0),whileInView:TI(),whileHover:TI(),whileTap:TI(),whileDrag:TI(),whileFocus:TI(),exit:TI()}}function BVe(s,t){s.min=t.min,s.max=t.max}function _k(s,t){BVe(s.x,t.x),BVe(s.y,t.y)}function xxt(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const V7t=1e-4,gDs=1-V7t,yDs=1+V7t,H7t=.01,vDs=0-H7t,bDs=0+H7t;function pb(s){return s.max-s.min}function _Ds(s,t,n){return Math.abs(s-t)<=n}function gxt(s,t,n,r=.5){s.origin=r,s.originPoint=Ep(t.min,t.max,s.origin),s.scale=pb(n)/pb(t),s.translate=Ep(n.min,n.max,s.origin)-s.originPoint,(s.scale>=gDs&&s.scale<=yDs||isNaN(s.scale))&&(s.scale=1),(s.translate>=vDs&&s.translate<=bDs||isNaN(s.translate))&&(s.translate=0)}function LJ(s,t,n,r){gxt(s.x,t.x,n.x,r?r.originX:void 0),gxt(s.y,t.y,n.y,r?r.originY:void 0)}function yxt(s,t,n,r=0){const a=r?Ep(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+pb(t)}function wDs(s,t,n,r){yxt(s.x,t.x,n.x,r==null?void 0:r.x),yxt(s.y,t.y,n.y,r==null?void 0:r.y)}function vxt(s,t,n,r=0){const a=r?Ep(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+pb(t)}function LAe(s,t,n,r){vxt(s.x,t.x,n.x,r==null?void 0:r.x),vxt(s.y,t.y,n.y,r==null?void 0:r.y)}function bxt(s,t,n,r,a){return s-=t,s=PAe(s,1/n,r),a!==void 0&&(s=PAe(s,1/a,r)),s}function jDs(s,t=0,n=1,r=.5,a,i=s,l=s){if(nC.test(t)&&(t=parseFloat(t),t=Ep(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Ep(i.min,i.max,r);s===i&&(o-=t),s.min=bxt(s.min,t,n,o,a),s.max=bxt(s.max,t,n,o,a)}function _xt(s,t,[n,r,a],i,l){jDs(s,t[n],t[r],t[a],t.scale,i,l)}const NDs=["x","scaleX","originX"],kDs=["y","scaleY","originY"];function wxt(s,t,n,r){_xt(s.x,t,NDs,n?n.x:void 0,r?r.x:void 0),_xt(s.y,t,kDs,n?n.y:void 0,r?r.y:void 0)}function jxt(s){return s.translate===0&&s.scale===1}function G7t(s){return jxt(s.x)&&jxt(s.y)}function Nxt(s,t){return s.min===t.min&&s.max===t.max}function SDs(s,t){return Nxt(s.x,t.x)&&Nxt(s.y,t.y)}function kxt(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function W7t(s,t){return kxt(s.x,t.x)&&kxt(s.y,t.y)}function Sxt(s){return pb(s.x)/pb(s.y)}function Cxt(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function q5(s){return[s("x"),s("y")]}function CDs(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:m,skewX:p,skewY:f}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),m&&(r+=`rotateY(${m}deg) `),p&&(r+=`skewX(${p}deg) `),f&&(r+=`skewY(${f}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 K7t=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],ADs=K7t.length,Axt=s=>typeof s=="string"?parseFloat(s):s,Ext=s=>typeof s=="number"||No.test(s);function EDs(s,t,n,r,a,i){a?(s.opacity=Ep(0,n.opacity??1,TDs(r)),s.opacityExit=Ep(t.opacity??1,0,MDs(r))):i&&(s.opacity=Ep(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(pte(s,t,r))}function PDs(s,t,n){const r=xv(s)?s:BH(s);return r.start(tet("",r,t,n)),r.animation}function gte(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const LDs=(s,t)=>s.depth-t.depth;class IDs{constructor(){this.children=[],this.isDirty=!1}add(t){qJe(this.children,t),this.isDirty=!0}remove(t){SAe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(LDs),this.isDirty=!1,this.children.forEach(t)}}function DDs(s,t){const n=mb.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(KP(r),s(i-t))};return Im.setup(r,!0),()=>KP(r)}function U4e(s){return xv(s)?s.get():s}class RDs{constructor(){this.members=[]}add(t){qJe(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&&(SAe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(SAe(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 q4e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},ZOe=["","X","Y","Z"],FDs=1e3;let ODs=0;function XOe(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function Z7t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=g7t(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",Im,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&Z7t(r)}function X7t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=ODs++,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($Ds),this.nodes.forEach(WDs),this.nodes.forEach(KDs),this.nodes.forEach(UDs)},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;Im.read(()=>{h=window.innerWidth}),s(l,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,u&&u(),u=DDs(m,250),q4e.hasAnimatedSinceResize&&(q4e.hasAnimatedSinceResize=!1,this.nodes.forEach(Lxt)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const f=this.options.transition||d.getDefaultTransition()||JDs,{onLayoutAnimationStart:g,onLayoutAnimationComplete:v}=d.getProps(),y=!this.targetLayout||!W7t(this.targetLayout,p),b=!h&&m;if(this.options.layoutRoot||this.resumeFrom||b||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...eet(f,"layout"),onPlay:g,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b)}else h||Lxt(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),KP(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(YDs),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&&Z7t(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&&!pb(this.snapshot.measuredBox.x)&&!pb(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 C=S/1e3;Ixt(h.x,l.x,C),Ixt(h.y,l.y,C),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(LAe(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),XDs(this.relativeTarget,this.relativeTargetOrigin,m,C),w&&SDs(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=uy()),_k(w,this.relativeTarget)),g&&(this.animationValues=u,EDs(u,d,this.latestValues,C,b,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},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&&(KP(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Im.update(()=>{q4e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=BH(0)),this.motionValue.jump(0,!1),this.currentAnimation=PDs(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(FDs),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&&Q7t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||uy();const h=pb(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=pb(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}_k(o,c),$4e(o,u),LJ(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new RDs),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&&XOe("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(Mxt),this.root.sharedNodes.clear()}}}function zDs(s){s.updateLayout()}function BDs(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")q5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=pb(m);m.min=r[h].min,m.max=m.min+p});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";BVe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else Q7t(i,t.layoutBox,r)&&q5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=pb(r[h]);m.max=m.min+p,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+p)});const o=iU();LJ(o,r,t.layoutBox);const c=iU();l?LJ(c,s.applyTransform(a,!0),t.measuredBox):LJ(c,r,t.layoutBox);const d=!G7t(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:p}=h;if(m&&p){const f=s.options.layoutAnchor||void 0,g=uy();LAe(g,t.layoutBox,m.layoutBox,f);const v=uy();LAe(v,r,p.layoutBox,f),W7t(g,v)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=v,s.relativeTargetOrigin=g,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 $Ds(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 UDs(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function qDs(s){s.clearSnapshot()}function Mxt(s){s.clearMeasurements()}function VDs(s){s.isLayoutDirty=!0,s.updateLayout()}function Pxt(s){s.isLayoutDirty=!1}function HDs(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function GDs(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function Lxt(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function WDs(s){s.resolveTargetDelta()}function KDs(s){s.calcProjection()}function YDs(s){s.resetSkewAndRotation()}function ZDs(s){s.removeLeadSnapshot()}function Ixt(s,t,n){s.translate=Ep(t.translate,0,n),s.scale=Ep(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function Dxt(s,t,n,r){s.min=Ep(t.min,n.min,r),s.max=Ep(t.max,n.max,r)}function XDs(s,t,n,r){Dxt(s.x,t.x,n.x,r),Dxt(s.y,t.y,n.y,r)}function QDs(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const JDs={duration:.45,ease:[.4,0,.1,1]},Rxt=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),Fxt=Rxt("applewebkit/")&&!Rxt("chrome/")?Math.round:wN;function Oxt(s){s.min=Fxt(s.min),s.max=Fxt(s.max)}function eRs(s){Oxt(s.x),Oxt(s.y)}function Q7t(s,t,n){return s==="position"||s==="preserve-aspect"&&!_Ds(Sxt(t),Sxt(n),.2)}function tRs(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const sRs=X7t({attachResizeListener:(s,t)=>gte(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}),QOe={current:void 0},J7t=X7t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!QOe.current){const s=new sRs({});s.mount(window),s.setOptions({layoutScroll:!0}),QOe.current=s}return QOe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),pet=_.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function zxt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function nRs(...s){return t=>{let n=!1;const r=s.map(a=>{const i=zxt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:p,height:f,top:g,left:v,right:y,bottom:b}=c.current;if(t||i===!1||!o.current||!p||!f)return;const w=n==="left"?`left: ${v}`:`right: ${y}`,S=r==="bottom"?`bottom: ${b}`:`top: ${g}`;o.current.dataset.motionPopId=l;const C=document.createElement("style");d&&(C.nonce=d);const E=a??document.head;return E.appendChild(C),C.sheet&&C.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${p}px !important; height: ${f}px !important; ${w}px !important; ${S}px !important; } `),()=>{var P;(P=o.current)==null||P.removeAttribute("data-motion-pop-id"),E.contains(C)&&E.removeChild(C)}},[t]),e.jsx(aRs,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:_.cloneElement(s,{ref:h})})}const oRs=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=UJe(lRs),h=_.useId();let m=!0,p=_.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:f=>{u.set(f,!0);for(const g of u.values())if(!g)return;r&&r()},register:f=>(u.set(f,!1),()=>u.delete(f))}),[n,u,r]);return i&&m&&(p={...p}),_.useMemo(()=>{u.forEach((f,g)=>u.set(g,!1))},[n]),_.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(iRs,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(WPe.Provider,{value:p,children:s})};function lRs(){return new Map}function e9t(s=!0){const t=_.useContext(WPe);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=_.useId();_.useEffect(()=>{if(s)return a(i)},[s]);const l=_.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const Ale=s=>s.key||"";function Bxt(s){const t=[];return _.Children.forEach(s,n=>{_.isValidElement(n)&&t.push(n)}),t}const bW=({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]=e9t(l),m=_.useMemo(()=>Bxt(s),[s]),p=l&&!u?[]:m.map(Ale),f=_.useRef(!0),g=_.useRef(m),v=UJe(()=>new Map),y=_.useRef(new Set),[b,w]=_.useState(m),[S,C]=_.useState(m);AOt(()=>{f.current=!1,g.current=m;for(let M=0;M{const I=Ale(M),D=l&&!u?!1:m===S||p.includes(I),F=()=>{if(y.current.has(I))return;if(v.has(I))y.current.add(I),v.set(I,!0);else return;let q=!0;v.forEach(G=>{G||(q=!1)}),q&&(P==null||P(),C(g.current),l&&(h==null||h()),r&&r())};return e.jsx(oRs,{isPresent:D,initial:!f.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:D?void 0:F,anchorX:o,anchorY:c,children:M},I)})})},t9t=_.createContext({strict:!1}),$xt={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 Uxt=!1;function cRs(){if(Uxt)return;const s={};for(const t in $xt)s[t]={isEnabled:n=>$xt[t].some(r=>!!n[r])};T7t(s),Uxt=!0}function s9t(){return cRs(),W8s()}function dRs(s){const t=s9t();for(const n in s)t[n]={...t[n],...s[n]};T7t(t)}const uRs=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 IAe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||uRs.has(s)}let n9t=s=>!IAe(s);function hRs(s){typeof s=="function"&&(n9t=t=>t.startsWith("on")?!IAe(t):s(t))}try{hRs(require("@emotion/is-prop-valid").default)}catch{}function mRs(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||xv(s[a])||(n9t(a)||n===!0&&IAe(a)||!t&&!IAe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const QPe=_.createContext({});function pRs(s,t){if(XPe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||xte(n)?n:void 0,animate:xte(r)?r:void 0}}return s.inherit!==!1?t:{}}function fRs(s){const{initial:t,animate:n}=pRs(s,_.useContext(QPe));return _.useMemo(()=>({initial:t,animate:n}),[qxt(t),qxt(n)])}function qxt(s){return Array.isArray(s)?s.join(" "):s}const fet=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function r9t(s,t,n){for(const r in t)!xv(t[r])&&!F7t(r,n)&&(s[r]=t[r])}function xRs({transformTemplate:s},t){return _.useMemo(()=>{const n=fet();return het(n,t,s),Object.assign({},n.vars,n.style)},[t])}function gRs(s,t){const n=s.style||{},r={};return r9t(r,n,s),Object.assign(r,xRs(s,t)),r}function yRs(s,t){const n={},r=gRs(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 a9t=()=>({...fet(),attrs:{}});function vRs(s,t,n,r){const a=_.useMemo(()=>{const i=a9t();return O7t(i,t,B7t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};r9t(i,s.style,s),a.style={...i,...a.style}}return a}const bRs=["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 xet(s){return typeof s!="string"||s.includes("-")?!1:!!(bRs.indexOf(s)>-1||/[A-Z]/u.test(s))}function _Rs(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??xet(s)?vRs:yRs)(t,r,a,s),d=mRs(t,typeof s=="string",i),u=s!==_.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=_.useMemo(()=>xv(h)?h.get():h,[h]);return _.createElement(s,{...u,children:m})}function wRs({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:jRs(n,r,a,s),renderState:t()}}function jRs(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=U4e(i[m]);let{initial:l,animate:o}=s;const c=XPe(s),d=A7t(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"&&!ZPe(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p(t,n)=>{const r=_.useContext(QPe),a=_.useContext(WPe),i=()=>wRs(s,t,r,a);return n?i():UJe(i)},NRs=i9t({scrapeMotionValuesFromProps:met,createRenderState:fet}),kRs=i9t({scrapeMotionValuesFromProps:$7t,createRenderState:a9t}),SRs=Symbol.for("motionComponentSymbol");function CRs(s,t,n){const r=_.useRef(n);_.useInsertionEffect(()=>{r.current=n});const a=_.useRef(null);return _.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 o9t=_.createContext({});function k$(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function ARs(s,t,n,r,a,i){var w,S;const{visualElement:l}=_.useContext(QPe),o=_.useContext(t9t),c=_.useContext(WPe),d=_.useContext(pet),u=d.reducedMotion,h=d.skipAnimations,m=_.useRef(null),p=_.useRef(!1);r=r||o.renderer,!m.current&&r&&(m.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),p.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const f=m.current,g=_.useContext(o9t);f&&!f.projection&&a&&(f.type==="html"||f.type==="svg")&&ERs(m.current,n,a,g);const v=_.useRef(!1);_.useInsertionEffect(()=>{f&&v.current&&f.update(n,c)});const y=n[x7t],b=_.useRef(!!y&&typeof window<"u"&&!((w=window.MotionHandoffIsComplete)!=null&&w.call(window,y))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,y)));return AOt(()=>{p.current=!0,f&&(v.current=!0,window.MotionIsMounted=!0,f.updateFeatures(),f.scheduleRenderMicrotask(),b.current&&f.animationState&&f.animationState.animateChanges())}),_.useEffect(()=>{f&&(!b.current&&f.animationState&&f.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var C;(C=window.MotionHandoffMarkAsComplete)==null||C.call(window,y)}),b.current=!1),f.enteringChildren=void 0)}),f}function ERs(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:l9t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&k$(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function l9t(s){if(s)return s.options.allowProjection!==!1?s.projection:l9t(s.parent)}function JOe(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&dRs(r);const i=n?n==="svg":xet(s),l=i?kRs:NRs;function o(d,u){let h;const m={..._.useContext(pet),...d,layoutId:TRs(d)},{isStatic:p}=m,f=fRs(d),g=l(d,p);if(!p&&typeof window<"u"){MRs();const v=PRs(m);h=v.MeasureLayout,f.visualElement=ARs(s,g,m,a,v.ProjectionNode,i)}return e.jsxs(QPe.Provider,{value:f,children:[h&&f.visualElement?e.jsx(h,{visualElement:f.visualElement,...m}):null,_Rs(s,d,CRs(g,f.visualElement,u),g,p,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=_.forwardRef(o);return c[SRs]=s,c}function TRs({layoutId:s}){const t=_.useContext($Je).id;return t&&s!==void 0?t+"-"+s:s}function MRs(s,t){_.useContext(t9t).strict}function PRs(s){const t=s9t(),{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 LRs(s,t){if(typeof Proxy>"u")return JOe;const n=new Map,r=(i,l)=>JOe(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,JOe(l,void 0,s,t)),n.get(l))})}const IRs=(s,t)=>t.isSVG??xet(s)?new dDs(t):new rDs(t,{allowProjection:s!==_.Fragment});class DRs extends jL{constructor(t){super(t),t.animationState||(t.animationState=fDs(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ZPe(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 RRs=0;class FRs extends jL{constructor(){super(...arguments),this.id=RRs++,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=k7(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...h}=c;for(const m in h)(i=this.node.getValue(m))==null||i.jump(h[m])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);n&&!t&&a.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const ORs={animation:{Feature:DRs},exit:{Feature:FRs}};function oae(s){return{point:{x:s.pageX,y:s.pageY}}}const zRs=s=>t=>oet(t)&&s(t,oae(t));function IJ(s,t,n,r){return gte(s,t,zRs(n),r)}const c9t=({current:s})=>s?s.ownerDocument.defaultView:null,Vxt=(s,t)=>Math.abs(s-t);function BRs(s,t){const n=Vxt(s.x,t.x),r=Vxt(s.y,t.y);return Math.sqrt(n**2+r**2)}const Hxt=new Set(["auto","scroll"]);class d9t{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=p=>{this.handleScroll(p.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Ele(this.lastRawMoveEventInfo,this.transformPagePoint));const p=e7e(this.lastMoveEventInfo,this.history),f=this.startEvent!==null,g=BRs(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!f&&!g)return;const{point:v}=p,{timestamp:y}=ov;this.history.push({...v,timestamp:y});const{onStart:b,onMove:w}=this.handlers;f||(b&&b(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),w&&w(this.lastMoveEvent,p)},this.handlePointerMove=(p,f)=>{this.lastMoveEvent=p,this.lastRawMoveEventInfo=f,this.lastMoveEventInfo=Ele(f,this.transformPagePoint),Im.update(this.updatePoint,!0)},this.handlePointerUp=(p,f)=>{this.end();const{onEnd:g,onSessionEnd:v,resumeAnimation:y}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&y&&y(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=e7e(p.type==="pointercancel"?this.lastMoveEventInfo:Ele(f,this.transformPagePoint),this.history);this.startEvent&&g&&g(p,b),v&&v(p,b)},!oet(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=oae(t),d=Ele(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=ov;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,e7e(d,this.history)),this.removeListeners=rae(IJ(this.contextWindow,"pointermove",this.handlePointerMove),IJ(this.contextWindow,"pointerup",this.handlePointerUp),IJ(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(Hxt.has(r.overflowX)||Hxt.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),Im.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),KP(this.updatePoint)}}function Ele(s,t){return t?{point:t(s.point)}:s}function Gxt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function e7e({point:s},t){return{point:s,delta:Gxt(s,u9t(t)),offset:Gxt(s,$Rs(t)),velocity:URs(t,.1)}}function $Rs(s){return s[0]}function u9t(s){return s[s.length-1]}function URs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=u9t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>B_(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>B_(t)*2&&(r=s[1]);const i=cN(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 qRs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?Ep(n,s,r.max):Math.min(s,n)),s}function Wxt(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 VRs(s,{top:t,left:n,bottom:r,right:a}){return{x:Wxt(s.x,n,a),y:Wxt(s.y,t,r)}}function Kxt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=pte(t.min,t.max-r,s.min):r>a&&(n=pte(s.min,s.max-a,t.min)),pC(0,1,n)}function WRs(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 $Ve=.35;function KRs(s=$Ve){return s===!1?s=0:s===!0&&(s=$Ve),{x:Yxt(s,"left","right"),y:Yxt(s,"top","bottom")}}function Yxt(s,t,n){return{min:Zxt(s,t),max:Zxt(s,n)}}function Zxt(s,t){return typeof s=="number"?s:s[t]||0}const YRs=new WeakMap;class ZRs{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=uy(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=h=>{n&&this.snapToCursor(oae(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:p,dragPropagation:f,onDragStart:g}=this.getProps();if(p&&!f&&(this.openDragLock&&this.openDragLock(),this.openDragLock=j8s(p),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),q5(y=>{let b=this.getAxisMotionValue(y).get()||0;if(nC.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const S=w.layout.layoutBox[y];S&&(b=pb(S)*(parseFloat(b)/100))}}this.originPoint[y]=b}),g&&Im.update(()=>g(h,m),!1,!0),PVe(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:f,onDirectionLock:g,onDrag:v}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=m;if(f&&this.currentDirection===null){this.currentDirection=QRs(y),this.currentDirection!==null&&g&&g(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),v&&Im.update(()=>v(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new d9t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:c9t(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&&Im.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||!Tle(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=qRs(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&&k$(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=VRs(r.layoutBox,t):this.constraints=!1,this.elastic=KRs(n),a!==this.constraints&&!k$(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&q5(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=WRs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!k$(t))return!1;const r=t.current;OH(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=Q8s(r,a.root,this.visualElement.getTransformPagePoint());let l=HRs(a.layout.layoutBox,i);if(n){const o=n(Y8s(l));this.hasMutatedConstraints=!!o,o&&(l=P7t(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=q5(u=>{if(!Tle(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,p=a?40:1e7,f={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,f)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return PVe(this.visualElement,t),r.start(tet(t,r,0,n,this.visualElement,!1))}stopAnimation(){q5(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){q5(n=>{const{drag:r}=this.getProps();if(!Tle(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]-Ep(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!k$(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};q5(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=GRs({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(),q5(l=>{if(!Tle(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Ep(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;YRs.set(this.visualElement,this);const t=this.visualElement.current,n=IJ(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,p=m!==t&&E8s(m);u&&h&&!p&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();k$(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=XRs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Im.read(a);const o=gte(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(q5(h=>{const m=this.getAxisMotionValue(h);m&&(this.originPoint[h]+=d[h].translate,m.set(m.get()+d[h].translate))}),this.visualElement.render())});return()=>{o(),n(),l(),c&&c(),r&&r()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=$Ve,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Xxt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function XRs(s,t,n){const r=rxt(s,Xxt(n)),a=rxt(t,Xxt(n));return()=>{r(),a()}}function Tle(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function QRs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class JRs extends jL{constructor(t){super(t),this.removeGroupControls=wN,this.removeListeners=wN,this.controls=new ZRs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||wN}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 t7e=s=>(t,n)=>{s&&Im.update(()=>s(t,n),!1,!0)};class eFs extends jL{constructor(){super(...arguments),this.removePointerDownListener=wN}onPointerDown(t){this.session=new d9t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:c9t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:t7e(t),onStart:t7e(n),onMove:t7e(r),onEnd:(i,l)=>{delete this.session,a&&Im.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=IJ(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 s7e=!1;class tFs extends _.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),s7e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),q4e.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}),s7e=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Im.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(),iet.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;s7e=!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 h9t(s){const[t,n]=e9t(),r=_.useContext($Je);return e.jsx(tFs,{...s,layoutGroup:r,switchLayoutGroup:_.useContext(o9t),isPresent:t,safeToRemove:n})}const sFs={pan:{Feature:eFs},drag:{Feature:JRs,ProjectionNode:J7t,MeasureLayout:h9t}};function Qxt(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&&Im.postRender(()=>i(t,oae(t)))}class nFs extends jL{mount(){const{current:t}=this.node;t&&(this.unmount=k8s(t,(n,r)=>(Qxt(this.node,r,"Start"),a=>Qxt(this.node,a,"End"))))}unmount(){}}class rFs extends jL{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=rae(gte(this.node.current,"focus",()=>this.onFocus()),gte(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Jxt(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&&Im.postRender(()=>i(t,oae(t)))}class aFs extends jL{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=M8s(t,(a,i)=>(Jxt(this.node,i,"Start"),(l,{success:o})=>Jxt(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const UVe=new WeakMap,n7e=new WeakMap,iFs=s=>{const t=UVe.get(s.target);t&&t(s)},oFs=s=>{s.forEach(iFs)};function lFs({root:s,...t}){const n=s||document;n7e.has(n)||n7e.set(n,{});const r=n7e.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(oFs,{root:s,...t})),r[a]}function cFs(s,t,n){const r=lFs(t);return UVe.set(s,n),r.observe(s),()=>{UVe.delete(s),r.unobserve(s)}}const dFs={some:0,all:1};class uFs extends jL{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:dFs[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:m}=this.node.getProps(),p=u?h:m;p&&p(d)};this.stopObserver=cFs(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(hFs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function hFs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const mFs={inView:{Feature:uFs},tap:{Feature:aFs},focus:{Feature:rFs},hover:{Feature:nFs}},pFs={layout:{ProjectionNode:J7t,MeasureLayout:h9t}},fFs={...ORs,...mFs,...sFs,...pFs},Ar=LRs(fFs,IRs),xFs={some:0,all:1};function gFs(s,t,{root:n,margin:r,amount:a="some"}={}){const i=aet(s),l=new WeakMap,o=d=>{d.forEach(u=>{const h=l.get(u.target);if(u.isIntersecting!==!!h)if(u.isIntersecting){const m=t(u.target,u);typeof m=="function"?l.set(u.target,m):c.unobserve(u.target)}else typeof h=="function"&&(h(u),l.delete(u.target))})},c=new IntersectionObserver(o,{root:n,rootMargin:r,threshold:typeof a=="number"?a:xFs[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function yFs(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=_.useState(i);return _.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 gFs(s.current,c,d)},[t,s,n,a,r]),l}function vFs(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 egt(s){return s.visitor_intent==="buying"&&!s.has_agent}function bFs({token:s}={}){var p;const t=Mi(),n=s||t.token,{data:r,isLoading:a,isError:i}=gLs(n);$t();const l=(p=r==null?void 0:r.open_houses)==null?void 0:p.id,{data:o}=rt({queryKey:["cohost-visitors",n,l],queryFn:async()=>{const{data:f,error:g}=await U.rpc("get_cohost_visitors",{_token:n});if(g)throw g;return f||[]},enabled:!!n&&!!l,refetchInterval:15e3});if(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 c=r.open_houses,d=(o==null?void 0:o.length)||0,u=(o==null?void 0:o.filter(f=>f.visitor_intent==="buying").length)||0,h=(o==null?void 0:o.filter(egt).length)||0,m=f=>{if(!f)return"";const[g,v]=f.split(":"),y=parseInt(g);return`${y>12?y-12:y||12}:${v} ${y>=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:c.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(On,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:d})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(vu,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(sa,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:Ys(new Date(c.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),c.start_time&&e.jsxs("span",{children:[m(c.start_time),c.end_time?` – ${m(c.end_time)}`:""]})]}),e.jsx(Ki,{className:"flex-1 p-4 sm:p-6",children:o!=null&&o.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(bW,{children:o.map((f,g)=>{var b;const v=vFs(f.visitor_intent),y=egt(f);return e.jsxs(Ar.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:g*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${y?"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 ${y?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(b=f.first_name[0])==null?void 0:b.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:[f.first_name," ",f.last_name||""]}),y&&e.jsx(ze,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),f.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 ${v.color}`,children:[v.emoji," ",v.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Ys(new Date(f.created_at),"h:mm a")})]})]})]},f.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(Nv,{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 _Fs(){const t=Pd().pathname.slice(1);if(_.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(bFs,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(COt,{slug: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(SOt,{slug:t})}function wFs({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(Ar.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(Ar.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:c})]}),e.jsxs(Ar.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[e.jsx(sa,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Sale":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction",r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(s==null?void 0:s.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[e.jsx(Ha,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{children:i})]}),n&&e.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.05rem"},children:["“",n,"”"]})]})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:e.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(va,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(on,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Bu,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function m9t({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=PN(a,new Date);if(sC(a)&&!b0(a))return null;const o=b0(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(Ar.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(Ar.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 p9t({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(Ar.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 Ou(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 tgt(s){const t=s.trim();if(!t)return;const n=t.split(/[-/]/).filter(Boolean);if(n.length<3)return;const r=n.map(c=>Number(c));if(r.some(c=>Number.isNaN(c)))return;r[0];let a,i,l;if(n[0].length===4)[l,a,i]=r,a=a-1;else if([a,i,l]=r,a=a-1,n[2].length===2)l=l<=49?2e3+l:1900+l;else if(n[2].length!==4)return;const o=new Date(l,a,i);if(!(o.getFullYear()!==l||o.getMonth()!==a||o.getDate()!==i))return o}const jFs=[{key:"contract_date",label:"Contract Accepted",icon:fN},{key:"earnest_money_due_date",label:"Earnest Money",icon:Nd},{key:"inspection_date",label:"Inspection",icon:Rr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:$r},{key:"appraisal_date",label:"Appraisal",icon:sa},{key:"loan_approval_date",label:"Loan Approval",icon:YU},{key:"title_docs_due_date",label:"Title & Disclosures",icon:$r},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:iP},{key:"target_close_date",label:"Target Close",icon:ya}];function NFs(s,t){const n=Ys(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${n}/${n}`,details:"Added from your Client Portal"}).toString()}`}function kFs(s,t){const n=Ys(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function x9t({deal:s,portal:t,targetCloseDate:n,contractDate:r,inspectionDate:a,appraisalDate:i,actualCloseDate:l}){const o={...s||{},contract_date:(s==null?void 0:s.contract_date)??r??null,inspection_date:(s==null?void 0:s.inspection_date)??(t==null?void 0:t.inspection_date)??a??null,appraisal_date:(s==null?void 0:s.appraisal_date)??(t==null?void 0:t.appraisal_date)??i??null,target_close_date:(s==null?void 0:s.target_close_date)??n??null},c=(s==null?void 0:s.actual_close_date)??l??null,d=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],u=jFs.map(p=>p.key==="target_close_date"&&c?{...p,label:"Closed",date:c,done:!0}:{...p,date:o[p.key],done:d.includes(p.key)}).filter(p=>!!p.date);if(u.length===0)return null;const h=(p,f,g)=>{const v=Ou(f);if(g==="google")window.open(NFs(p,v),"_blank");else{const y=kFs(p,v),b=document.createElement("a");b.href=y,b.download=`${p.replace(/\s+/g,"-").toLowerCase()}.ics`,b.click()}},m=u.filter(p=>p.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:p,date:f,done:g,icon:v})=>{const y=Ou(f),b=sC(y)&&!b0(y),w=b0(y),S=!b&&!w,C=g?"Completed":w?"Today":b?"In progress":"Upcoming";return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:g?"hsl(var(--portal-gold))":w?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:w?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:g?e.jsx(Wr,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(v,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:p}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:g?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Ys(y,"MMM d, yyyy")}),e.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:g||w?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${g||w?.5:.18})`},children:C})]}),S&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(p,f,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:E=>{E.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:E=>{E.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(v0,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(p,f,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},p)})]})]})}function g9t({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 U.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($r,{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(Ga,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function y9t({slug:s,wrapper:t}){const n=zn(),[r,a]=_.useState(null),{data:i=[]}=rt({queryKey:["portal-signature-requests",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await U.functions.invoke("forms-portal-public",{body:{action:"list",slug:s}});return h?[]:(u==null?void 0:u.envelopes)||[]}}),l=i.filter(u=>u.my_turn),o=i.filter(u=>!u.my_turn&&u.status!=="completed");if(!l.length&&!o.length)return null;const c=async u=>{a(u);try{const{data:h,error:m}=await U.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:s,envelope_id:u}});if(m||h!=null&&h.error)throw new Error((h==null?void 0:h.error)||"Could not open the document");n(h.path)}catch(h){ne.error((h==null?void 0:h.message)||"Could not open the document")}finally{a(null)}},d=e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),e.jsxs("div",{className:"space-y-2",children:[l.map(u=>e.jsxs("button",{onClick:()=>c(u.id),disabled:r===u.id,className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.4)"},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.14)",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:r===u.id?e.jsx(bt,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Mm,{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:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},u.id)),o.map(u=>e.jsxs("div",{className:"w-full flex items-center gap-3 p-3 rounded-xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid 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.06)"},children:u.my_status==="signed"?e.jsx(Mr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):e.jsx(Zr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),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-muted))",fontSize:"1rem"},children:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:u.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},u.id))]})]});return t?t(d):d}function v9t({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(Og,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx($g,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"portal-serif",style:{fontSize:r===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:n.title}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Ys(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const _W=[{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"}],SFs=[{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 CFs(s){return rt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 AFs(){const s=ha(),{brokerageId:t}=hs();return rt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=U.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}),U.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 EFs(){const s=$t();return mt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await U.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await U.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function b9t(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function TFs(){const s=ha(),t=$t();return mt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await U.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await U.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await U.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function _9t(s){return rt({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 U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=U.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}),U.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(p=>u.set(p.vendor_id,{display_order:p.display_order,is_visible:p.is_visible}));const h=new Map;return(d||[]).forEach(p=>h.set(p.vendor_id,p.is_visible)),(l||[]).filter(p=>{if(h.get(p.id)===!1)return!1;const f=u.get(p.id);return!(f&&f.is_visible===!1&&!p.is_required)}).map(p=>{var f;return{...p,display_order:((f=u.get(p.id))==null?void 0:f.display_order)??p.sort_order??0}}).sort((p,f)=>(p.display_order||0)-(f.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function sgt(s){try{await U.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function w9t(s,t){return rt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await U.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 U.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 j9t({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=_9t({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(b=>!b.stage_filter||b.stage_filter.length===0||!n?!0:b.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(b,w)=>{switch(w){case"book":return b.booking_url;case"website":return b.website;case"call":return b.phone?`tel:${b.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return b.email?`mailto:${b.email}`:null}},u=b=>{const w=d(b,b.action_type);sgt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),w&&window.open(w,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const w=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(Wo,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(on,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(va,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(ya,{className:"w-3.5 h-3.5"})}].filter(C=>C.action!==b.action_type).map(C=>{const E=d(b,C.action);return!E||E===w?null:e.jsxs("button",{onClick:()=>{sgt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:C.action}),window.open(E,C.action==="call"||C.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:C.label,children:[C.icon,e.jsx("span",{className:"text-xs",children:C.label})]},C.action)}).filter(Boolean)},m=b=>{switch(b.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},p=b=>{switch(b.action_type){case"book":return e.jsx(ya,{className:"w-3.5 h-3.5"});case"call":return e.jsx(va,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(on,{className:"w-3.5 h-3.5"});case"website":return e.jsx(Wo,{className:"w-3.5 h-3.5"})}},f=b=>{var w;return((w=_W.find(S=>S.value===b))==null?void 0:w.label)||b},g=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(b=>b.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(b=>b.disclosure_text).map(b=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[b.company||b.name,":"]})," ",b.disclosure_text]},b.id))});if(a==="grid")return e.jsxs(be,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[g,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(b=>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:b.logo_url?e.jsx("img",{src:b.logo_url,alt:b.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(b.company||b.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:b.company||b.name}),b.company&&b.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:b.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:f(b.category)})]})]}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:b.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(z,{size:"sm",onClick:()=>u(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[p(b),e.jsx("span",{className:"ml-1.5 text-xs",children:m(b)})]}),h(b).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(b)})]})]},b.id))}),v]});const y=o.reduce((b,w)=>((b[w.category]=b[w.category]||[]).push(w),b),{});return e.jsxs(be,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[g,e.jsx("div",{className:"space-y-4",children:Object.entries(y).map(([b,w])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:f(b)}),e.jsx("div",{className:"space-y-2",children:w.map(S=>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: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-sm font-semibold text-slate-500",children:S.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:S.company||S.name}),S.company&&S.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:S.description})]}),e.jsxs(z,{size:"sm",onClick:()=>u(S),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[p(S),e.jsx("span",{className:"ml-1.5 text-xs",children:m(S)})]})]},S.id))})]},b))}),v]})}function MFs(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 PFs(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 N9t({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=_.useState(!1),h=_.useRef(!1),m=MFs(t);_.useEffect(()=>{h.current||(h.current=!0,U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const p=async E=>{await U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:E,user_agent:navigator.userAgent.slice(0,500)})},f=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${m}`,g=async()=>{await navigator.clipboard.writeText(m),u(!0),p("copy_link"),setTimeout(()=>u(!1),2e3)},v=()=>{p("share_sms");const E=encodeURIComponent(f());window.location.href=`sms:?&body=${E}`},y=()=>{p("share_email");const E=encodeURIComponent("A referral you'll thank me for"),P=encodeURIComponent(f());window.location.href=`mailto:?subject=${E}&body=${P}`},b=()=>{p("open_form"),window.open(m,"_blank")},w=a||"Know someone buying or selling?",S=c?PFs(c):null,C=S==null?void 0:S.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."})]}),S&&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:C?e.jsx("video",{src:S,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:S,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(Ko,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:w}),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:b,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(Da,{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(Bu,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:y,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(on,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:g,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(Wr,{className:"w-3.5 h-3.5"}):e.jsx(Sa,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>p("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(Da,{className:"w-4 h-4 text-slate-400"})]})})]})}function k9t(s){return rt({queryKey:["portal-messages",s],queryFn:async()=>{const{data:t,error:n}=await U.from("portal_messages").select("*").eq("portal_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s,refetchInterval:3e4})}function S9t(){const s=$t();return mt({mutationFn:async({portalId:t,senderType:n,senderName:r,body:a,deviceFingerprint:i,portalUrl:l})=>{const{data:o,error:c}=await U.from("portal_messages").insert({portal_id:t,sender_type:n,sender_name:r||null,body:a.trim(),device_fingerprint:i||null,...n==="agent"?{read_at:new Date().toISOString()}:{}}).select().single();if(c)throw c;try{await U.functions.invoke("portal-message-notify",{body:{message_id:o.id,portal_url:l}})}catch(d){console.error("portal-message-notify failed",d)}return o},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-messages",n.portalId]}),s.invalidateQueries({queryKey:["portal-unread-messages"]}),s.invalidateQueries({queryKey:["portal-conversations"]})}})}function LFs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("portal_messages").update({read_at:new Date().toISOString()}).eq("portal_id",t).eq("sender_type","client").is("read_at",null);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-messages",n]}),s.invalidateQueries({queryKey:["portal-unread-messages"]}),s.invalidateQueries({queryKey:["portal-conversations"]})}})}function C9t(){const s=ha();return rt({queryKey:["portal-conversations",s],queryFn:async()=>{const{data:t,error:n}=await U.from("client_portals").select("id, slug, client_name, client_email, archived_at").eq("owner_user_id",s).is("archived_at",null);if(n)throw n;if(!t||t.length===0)return[];const r=t.map(c=>c.id),a=[],i=100,l=1e3;for(let c=0;c{const d=o.get(c.id)||[];return{portalId:c.id,slug:c.slug,clientName:c.client_name,clientEmail:c.client_email,lastMessage:d.length?d[d.length-1]:null,unreadCount:d.filter(u=>u.sender_type==="client"&&!u.read_at).length,messageCount:d.length}}).sort((c,d)=>{var m,p;const u=((m=c.lastMessage)==null?void 0:m.created_at)||"",h=((p=d.lastMessage)==null?void 0:p.created_at)||"";return u===h?(c.clientName||"").localeCompare(d.clientName||""):h.localeCompare(u)})},enabled:!!s,refetchInterval:3e4})}function A9t({portalId:s,clientName:t,agentName:n,agentAvatar:r,deviceFingerprint:a}){const{data:i,isLoading:l}=k9t(s),o=S9t(),[c,d]=_.useState(""),u=`portal_msg_name_${s}`,[h,m]=_.useState(()=>localStorage.getItem(u)||t||""),p=_.useRef(null);_.useEffect(()=>{var v;(v=p.current)==null||v.scrollIntoView({block:"nearest"})},[i==null?void 0:i.length]);const f=async()=>{const v=c.trim();if(!v)return;const y=(h||t||"").trim();if(!y){ne.error("Please add your name first");return}try{localStorage.setItem(u,y),await o.mutateAsync({portalId:s,senderType:"client",senderName:y,body:v,deviceFingerprint:a,portalUrl:window.location.href}),d(""),ne.success("Message sent")}catch(b){ne.error((b==null?void 0:b.message)||"Could not send your message")}},g="hsl(var(--portal-gold))";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(qi,{className:"w-4 h-4",style:{color:g}}),e.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),e.jsx("div",{className:"portal-hairline mb-4"}),e.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[l&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(bt,{className:"w-4 h-4 animate-spin",style:{color:g}})}),!l&&(!i||i.length===0)&&e.jsxs("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:["Have a question for ",n||"your agent","? Send a message below — they'll be notified right away."]}),i==null?void 0:i.map(v=>{const y=v.sender_type==="agent";return e.jsx("div",{className:`flex ${y?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:y?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${y?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[y&&r&&e.jsx("img",{src:r,alt:n||"Agent",className:"w-5 h-5 rounded-full object-cover"}),e.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[y?n||"Your agent":v.sender_name||"You"," ·"," ",Ys(new Date(v.created_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:v.body})]})},v.id)}),e.jsx("div",{ref:p})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[!t&&e.jsx("input",{value:h,onChange:v=>m(v.target.value),placeholder:"Your name",className:"w-full rounded-xl px-3 py-2 text-sm outline-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsx("textarea",{value:c,onChange:v=>d(v.target.value),rows:3,placeholder:`Write a message to ${n||"your agent"}...`,className:"w-full rounded-xl px-3 py-2 text-sm outline-none resize-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsxs("button",{onClick:f,disabled:o.isPending||!c.trim(),className:"w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-medium transition-opacity disabled:opacity-50",style:{background:"hsl(var(--portal-gold) / 0.16)",border:"1px solid hsl(var(--portal-gold) / 0.35)",color:g},children:[o.isPending?e.jsx(bt,{className:"w-4 h-4 animate-spin"}):e.jsx(Fr,{className:"w-4 h-4"}),"Send message"]})]})]})}function IFs(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function DFs(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 RFs={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. 🎉"}},E9t=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function JPe(s){return E9t.map(t=>{if(t==="Active")return{key:"Active",label:IFs(s),description:DFs(s)};const n=RFs[t];return{key:t,label:n.label,description:n.description}})}function DAe(s){if(!s)return 0;const t=E9t.indexOf(s);return t>=0?t:0}function FFs({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var H,K,Z;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,p=m==null?void 0:m.deal_pipeline_stages,f=p==null?void 0:p.is_won_stage,g=m==null?void 0:m.deal_type,v=n==null?void 0:n.stage_mapping;let y=JPe(g);v&&v.length>0&&(y=v.map((oe,re)=>{var ae,J;return{key:`custom-${re}`,label:oe.label||((ae=y[re])==null?void 0:ae.label)||`Stage ${re+1}`,description:oe.description||((J=y[re])==null?void 0:J.description)||"",video_url:oe.video_url||void 0}}));const b=v&&v.length>0?Math.min(DAe(p==null?void 0:p.name),y.length-1):DAe(p==null?void 0:p.name),w=y[b],S=w==null?void 0:w.video_url,C=f&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,E=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,P=!!t,M=(H=s==null?void 0:s.deal_pipeline)==null?void 0:H.deal_type,I=(K=t==null?void 0:t.deal_pipeline)==null?void 0:K.deal_type,D=oe=>oe==="listing"?"Your Sale":oe==="buy-side"?"Your Purchase":"Transaction",F=y.length>1?Math.round((b+1)/y.length*100):0,{data:q=[]}=_9t({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),G=q.some(oe=>!oe.stage_filter||oe.stage_filter.length===0||!(p!=null&&p.name)?!0:oe.stage_filter.includes(p.name)),V=()=>{var oe;(oe=document.getElementById("trusted-vendors"))==null||oe.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(Ar.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(Om,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Ar.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[e.jsx(sa,{className:"w-3 h-3"}),g==="listing"?"Sale":g==="buy-side"?"Purchase":"Transaction",f&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),E&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[e.jsx(Ha,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:E})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(OFs,{pct:F}),e.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",b+1," of ",y.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)"}})]}),P&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(oe=>{const re=oe==="primary"?M:I,ae=r===oe;return e.jsx("button",{onClick:()=>a(oe),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:ae?"hsl(var(--portal-surface-3))":"transparent",color:ae?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:ae?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:D(re)},oe)})}),e.jsxs(Ar.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(w5,{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:((Z=i==null?void 0:i.name)==null?void 0:Z.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(r7e,{href:`tel:${i.phone}`,icon:va,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(r7e,{href:`sms:${i.phone}`,icon:Bu,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(r7e,{href:`mailto:${i.email}`,icon:on,label:"Email",sub:i.email})]})]}),e.jsxs(w5,{children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),e.jsxs("div",{className:"space-y-4",children:[(m==null?void 0:m.target_close_date)&&e.jsx(a7e,{icon:ya,label:"Target close",value:ngt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(a7e,{icon:Zr,label:"Under contract",value:ngt(m.contract_date)}),e.jsx(a7e,{icon:cl,label:"Progress",value:`${F}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[C&&e.jsx(N9t,{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(m9t,{targetCloseDate:m==null?void 0:m.target_close_date,actualCloseDate:m==null?void 0:m.actual_close_date,clientName:n.client_name}),w&&e.jsx(w5,{children:e.jsx(f9t,{currentStage:w,nextStepText:n.next_step_text,nextStepVideoUrl:S||n.next_step_video_url})}),e.jsx(w5,{children:e.jsx(p9t,{journeyStages:y,currentIndex:b})}),o&&o.length>0&&e.jsx(w5,{children:e.jsx(v9t,{updates:o})}),(n==null?void 0:n.id)&&e.jsx(w5,{children:e.jsx(A9t,{portalId:n.id,clientName:n.client_name,agentName:i==null?void 0:i.name,agentAvatar:i==null?void 0:i.avatar_url})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(w5,{children:e.jsx(x9t,{deal:m,portal:n})}),(n==null?void 0:n.slug)&&e.jsx(y9t,{slug:n.slug,wrapper:oe=>e.jsx(w5,{children:oe})}),c&&c.length>0&&e.jsx(w5,{children:e.jsx(g9t,{documents:c})}),G&&e.jsx(w5,{children:e.jsxs("button",{onClick:V,className:"w-full flex items-center gap-3 rounded-xl px-3 py-3 transition-all text-left group",style:{background:"hsl(var(--portal-gold) / 0.06)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},onMouseEnter:oe=>{oe.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:oe=>{oe.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(mq,{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(cl,{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(j9t,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:p==null?void 0:p.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function w5({children:s}){return e.jsx(Ar.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 r7e({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 a7e({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 OFs({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),e.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),e.jsx(Ar.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function ngt(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 zFs({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var v,y;const[l,o]=_.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((y=s.client_name)==null?void 0:y.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]=_.useState({}),[u,h]=_.useState(!1),m=mt({mutationFn:async()=>{const{error:b}=await U.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),ne.error("Something went wrong. Please try again.")}}),p=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,f="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",g="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),p&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(Ha,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:p.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(pe,{required:!0,value:l.first_name,onChange:b=>o(w=>({...w,first_name:b.target.value})),className:f,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(pe,{value:l.last_name,onChange:b=>o(w=>({...w,last_name:b.target.value})),className:f,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(pe,{type:"email",value:l.email,onChange:b=>o(w=>({...w,email:b.target.value})),className:f,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(pe,{type:"tel",value:l.phone,onChange:b=>o(w=>({...w,phone:b.target.value})),className:f,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(b=>e.jsx("button",{type:"button",onClick:()=>o(w=>({...w,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(ee,{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(b=>e.jsx("button",{type:"button",onClick:()=>o(w=>({...w,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),r.map(b=>e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(pe,{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:f}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:`${g} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:`${g} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(w=>e.jsx("option",{value:w,children:w},w))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(w=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:w})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===w?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:w},w))})]},b.id)),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(w=>({...w,notes:b.target.value})),className:`${g} 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(ee,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(pe,{value:l.spouse_first_name,onChange:b=>o(w=>({...w,spouse_first_name:b.target.value})),className:f})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(pe,{value:l.spouse_last_name,onChange:b=>o(w=>({...w,spouse_last_name:b.target.value})),className:f})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(pe,{type:"email",value:l.spouse_email,onChange:b=>o(w=>({...w,spouse_email:b.target.value})),className:f})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(pe,{type:"tel",value:l.spouse_phone,onChange:b=>o(w=>({...w,spouse_phone:b.target.value})),className:f})]})]})]}),e.jsx(z,{type:"submit",disabled:m.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:m.isPending?"Submitting...":"Access My Portal"})]})]})})}function BFs(s,t){const n=(r,a)=>a!=null&&a!==""?a:r!=null&&r!==""?r:null;return{logo_url:n(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:n(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:n(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:n(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:n(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:n(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message),portal_theme:n(s==null?void 0:s.portal_theme,t==null?void 0:t.portal_theme)||"noir"}}function T9t(){const s=ha();return rt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function $Fs(s){return rt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function UFs(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 M9t(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 U.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=U.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function qFs(s,t){return rt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await U.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return n},enabled:t})}function VFs(s){return rt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return t},enabled:!!s})}function P9t({slug:s}){var oe,re,ae,J,te,ce;const[t,n]=_.useState(!1),[r,a]=_.useState("primary"),[i]=_.useState(()=>{const ve=`portal_fp_${s}`;let me=localStorage.getItem(ve);return me||(me=localStorage.getItem("portal_fp"),me?localStorage.setItem(ve,me):(me=crypto.randomUUID(),localStorage.setItem(ve,me),localStorage.setItem("portal_fp",me))),me});_.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=qFs(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=VFs(d),h=(oe=l==null?void 0:l.deal_pipeline)==null?void 0:oe.owner_user_id;rt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:ve,error:me}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(me)throw me;return ve},enabled:!!h});const{data:m}=rt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:ve,error:me}=await U.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(me)throw me;return ve},enabled:!!h}),{data:p}=$Fs(h),f=r==="linked"&&u?u:l,g=f==null?void 0:f.id,v=BFs(p,f==null?void 0:f.branding_override),y=v.portal_theme==="azure"?"azure":"noir";_.useEffect(()=>{const ve=`portal-theme-${y}`;return document.body.classList.add(ve),()=>document.body.classList.remove(ve)},[y]);const{data:b}=rt({queryKey:["portal-updates-public",g],queryFn:async()=>{const{data:ve,error:me}=await U.from("portal_updates").select("*").eq("portal_id",g).order("created_at",{ascending:!1});if(me)throw me;return ve},enabled:!!g}),w=(re=f==null?void 0:f.deal_pipeline)==null?void 0:re.id,{data:S}=rt({queryKey:["portal-documents",w],queryFn:async()=>{const{data:ve,error:me}=await U.from("deal_files").select("*").eq("deal_id",w).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(me)throw me;return ve},enabled:!!w}),C=l==null?void 0:l.id,E=C?`portal_onboarded_${C}_${i}`:null,P=E?localStorage.getItem(E)==="1":!1,{data:M,isLoading:I}=rt({queryKey:["portal-onboarding-check",C,i],queryFn:async()=>{const{data:ve,error:me}=await U.from("portal_onboarding_submissions").select("id").eq("portal_id",C).eq("device_fingerprint",i).maybeSingle();if(me)throw me;return ve&&E&&localStorage.setItem(E,"1"),ve},enabled:!!C&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),D=!!(l!=null&&l.require_onboarding)&&!P&&!M&&!t,{data:F}=rt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:ve,error:me}=await U.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(me)throw me;return ve},enabled:!!h&&D}),q=P||!!M||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!P&&I)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(bt,{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(Om,{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(!q){const ve=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(zFs,{portal:l,dealData:ve,agentProfile:m,customQuestions:F||[],deviceFingerprint:i,onComplete:()=>{E&&localStorage.setItem(E,"1"),n(!0)}})})}const G=(ae=l==null?void 0:l.deal_pipeline)==null?void 0:ae.deal_type,V=(J=u==null?void 0:u.deal_pipeline)==null?void 0:J.deal_type,H=!!u,K=ve=>ve==="listing"?"Your Sale":ve==="buy-side"?"Your Purchase":"Transaction",Z=ve=>ve==="listing"?e.jsx(sa,{className:"w-3.5 h-3.5"}):e.jsx(wb,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(FFs,{portal:l,linkedPortal:u,activePortal:f,activeTab:r,onTabChange:a,agentProfile:m,branding:v,updates:b,documents:S})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(wFs,{dealData:f==null?void 0:f.deal_pipeline,agentProfile:m,welcomeMessage:(f==null?void 0:f.welcome_message)||v.welcome_message,isWon:(ce=(te=f==null?void 0:f.deal_pipeline)==null?void 0:te.deal_pipeline_stages)==null?void 0:ce.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[H&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ve=>{const me=r===ve,he=ve==="primary"?G:V;return e.jsxs("button",{onClick:()=>a(ve),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background: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:[Z(he),e.jsx("span",{style:{fontSize:"1rem"},children:K(he)})]},ve)})}),e.jsx(HFs,{portal:f,updates:b,documents:S,agentProfile:m}),g&&e.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:e.jsx(A9t,{portalId:g,clientName:f==null?void 0:f.client_name,agentName:m==null?void 0:m.name,agentAvatar:m==null?void 0:m.avatar_url,deviceFingerprint:i})}),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(Om,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),m&&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:m.name})]})]})]})]})]})}function HFs({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=JPe(c);d&&d.length>0&&(u=d.map((g,v)=>{var y,b;return{key:`custom-${v}`,label:g.label||((y=u[v])==null?void 0:y.label)||`Stage ${v+1}`,description:g.description||((b=u[v])==null?void 0:b.description)||"",video_url:g.video_url||void 0}}));const h=d&&d.length>0?Math.min(DAe(l==null?void 0:l.name),u.length-1):DAe(l==null?void 0:l.name),m=u[h],p=m==null?void 0:m.video_url,f=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[f&&e.jsx(N9t,{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(m9t,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(p9t,{journeyStages:u,currentIndex:h}),m&&e.jsx(f9t,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:p||s.next_step_video_url}),e.jsx(x9t,{deal:i,portal:s}),(s==null?void 0:s.slug)&&e.jsx(y9t,{slug:s.slug}),n&&n.length>0&&e.jsx(g9t,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(j9t,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(v9t,{updates:t})]})}function L9t({slug:s}){const t=Mi(),n=s||t.slug,[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState("buying"),[w,S]=_.useState("");_.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:C,isLoading:E,error:P}=rt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:D,error:F}=await U.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(F)throw F;return D},enabled:!!n}),{data:M}=rt({queryKey:["portal-referral-agent",C==null?void 0:C.owner_user_id],queryFn:async()=>{const{data:D}=await U.from("profiles").select("id, name, avatar_url").eq("id",C.owner_user_id).single();return D},enabled:!!(C!=null&&C.owner_user_id)}),I=async D=>{if(D.preventDefault(),!C||!h.trim()){ne.error("Please enter your friend's name");return}if(!p.trim()&&!g.trim()){ne.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:F}=await U.from("portal_referrals").insert({portal_id:C.id,owner_user_id:C.owner_user_id,referrer_name:o.trim()||C.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:p.trim()||null,friend_phone:g.trim()||null,friend_interest:y,friend_message:w.trim()||null});if(F)throw F;l(!0)}catch(F){ne.error(F.message||"Could not submit referral")}finally{a(!1)}};return E?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(ln,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):P||!C||!C.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(Wr,{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(ka,{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(Ko,{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(Ko,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:C.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."]}),C.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:C.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:I,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(ee,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"friend_name",value:h,onChange:D=>m(D.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(ee,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(pe,{id:"friend_email",type:"email",value:p,onChange:D=>f(D.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(pe,{id:"friend_phone",type:"tel",value:g,onChange:D=>v(D.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(ee,{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(D=>e.jsx("button",{type:"button",onClick:()=>b(D.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${y===D.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:D.l},D.v))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:w,onChange:D=>S(D.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(ee,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(pe,{id:"referrer_name",value:o,onChange:D=>c(D.target.value),placeholder:C.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(pe,{id:"referrer_email",type:"email",value:d,onChange:D=>u(D.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(bt,{className:"w-4 h-4 animate-spin"}):e.jsx(Ko,{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 GFs(){const t=Pd().pathname.slice(1).replace(/\/$/,"");if(_.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(L9t,{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(P9t,{slug:t})}function WFs(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 RAe({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=_.useMemo(()=>WFs(Array.isArray(s)?s:[]),[s]),[l,o]=_.useState(0);return _.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(sa,{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 I9t({comp:s,open:t,onClose:n}){var d;const[r,a]=_.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,m,p]=u.split(/[-/T]/);return h?`${m}/${p}/${h}`:null};return e.jsx(Is,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Ls,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-2",children:[e.jsx(Rs,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Ha,{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(RAe,{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(RAe,{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(sa,{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(Nd,{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(i7e,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(i7e,{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(i7e,{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(Mle,{icon:e.jsx(mj,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Mle,{icon:e.jsx(Ey,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Mle,{icon:e.jsx(Q4,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Mle,{icon:e.jsx(ya,{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(Y1,{label:"MLS #",value:s.mlsNumber}),e.jsx(Y1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Y1,{label:"Lot Size",value:s.lotSize}),e.jsx(Y1,{label:"Garage",value:s.garageSpaces}),e.jsx(Y1,{label:"Stories",value:s.stories}),e.jsx(Y1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Y1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Y1,{label:"Heating",value:s.heating}),e.jsx(Y1,{label:"Cooling",value:s.cooling}),e.jsx(Y1,{label:"Parking",value:s.parking}),e.jsx(Y1,{label:"Elementary",value:s.elementarySchool}),e.jsx(Y1,{label:"Middle",value:s.middleSchool}),e.jsx(Y1,{label:"High",value:s.highSchool}),e.jsx(Y1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Y1,{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 Mle({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 Y1({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 i7e({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 Ple({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=_.useState(0),c=_.useRef(null);return _.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=p=>1-Math.pow(1-p,3),m=setTimeout(()=>{const p=f=>{d||(d=f);const g=f-d,v=Math.min(1,g/t);o(Math.round(u+(s-u)*h(v))),v<1&&(c.current=requestAnimationFrame(p))};c.current=requestAnimationFrame(p)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function KFs({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=_.useState(t),[c,d]=_.useState(r),[u,h]=_.useState(a),[m,p]=_.useState(i),{commission:f,closing:g,net:v}=_.useMemo(()=>{const w=Math.round(l*u/100),S=Math.round(l*m/100);return{commission:w,closing:S,net:Math.max(0,l-w-S-(c||0))}},[l,u,m,c]),y=w=>`$${w.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(be,{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(kl,{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(Le,{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:y(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Mx,{value:[l],min:s,max:n,step:1e3,onValueChange:([w])=>o(w)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:y(s)}),e.jsxs("span",{children:["Suggested ",y(t)]}),e.jsx("span",{children:y(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,b))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(pe,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:w=>d(Number(w.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Commission %"}),e.jsx(pe,{type:"number",step:"0.25",value:u,onChange:w=>h(Number(w.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Closing costs %"}),e.jsx(pe,{type:"number",step:"0.25",value:m,onChange:w=>p(Number(w.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:y(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",y(f)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",y(g)]}),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:["−",y(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(w7,{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:y(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 D9t({tokenOverride:s}={}){var Pe,Oe,ke,Ve,_e,Ae,Se,We,qe,Be,Ze,$e;const t=Mi(),n=s??t.token,[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState([]),[d,u]=_.useState(!0),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=_.useState(null),[P,M]=_.useState(null),[I,D]=_.useState(!1),{toast:F}=_i();_.useEffect(()=>{n&&(async()=>{const{data:Xe}=await U.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!Xe){u(!1);return}a(Xe);const[{data:nt},{data:Ge}]=await Promise.all([U.from("cma_comps").select("*").eq("cma_id",Xe.id).order("position"),U.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Xe.agent_id).maybeSingle()]);c((nt||[]).filter(ut=>ut.selected)),l(Ge);const Je=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",Je),await U.from("cma_views").insert({cma_id:Xe.id,visitor_token:Je,user_agent:navigator.userAgent}),u(!1)})()},[n]);const q=async Xe=>{if(!r)return;const nt=localStorage.getItem("cma_visitor_token")||"";await U.from("cma_views").insert({cma_id:r.id,visitor_token:nt,reactions:{[Xe]:!0}}),U.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:Xe,visitorToken:nt}}).catch(()=>{}),F({title:"Thanks — your agent just got notified ✨"})},G=!(r!=null&&r.contact_id),V=async()=>{if(!r||!h.trim())return;if(G&&(!p.trim()||!g.trim())){F({title:"Please add your name and email",variant:"destructive"});return}b(!0);const Xe=localStorage.getItem("cma_visitor_token")||"",{data:nt,error:Ge}=await U.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:Xe,viewerName:p.trim()||void 0,viewerEmail:g.trim()||void 0}});if(b(!1),Ge||!(nt!=null&&nt.success)){F({title:"Could not send",description:(Ge==null?void 0:Ge.message)||(nt==null?void 0:nt.error),variant:"destructive"});return}m(""),S(!0),F({title:"Message sent to your agent"})},H=_.useMemo(()=>{const Xe=o.map(nt=>{const Ge=nt.snapshot,Je=(Ge==null?void 0:Ge.soldPrice)||(Ge==null?void 0:Ge.price);return Je&&(Ge!=null&&Ge.sqft)?Je/Ge.sqft:null}).filter(nt=>!!nt).sort((nt,Ge)=>nt-Ge);return Xe.length?Math.round(Xe[Math.floor(Xe.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(bt,{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(sa,{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 K=r.subject||{},Z=(Pe=r.settings)==null?void 0:Pe.personalVideo,oe=(Oe=K.photos)==null?void 0:Oe[0],re=r.contact_first_name?r.contact_first_name:null,ae=((i==null?void 0:i.name)||"A").split(" ").map(Xe=>Xe[0]).slice(0,2).join("").toUpperCase(),J=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,te=i!=null&&i.email?`mailto:${i.email}`:null,ce=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ve=r.price_low??null,me=r.price_likely??null,he=r.price_high??null,ge=ve&&me&&he,Ee=me&&K.sqft?Math.round(me/K.sqft):null,Ne=Ee&&H?Math.round((Ee-H)/H*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:ae}),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(oi,{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:[J&&e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(va,{className:"w-4 h-4 mr-1"}),"Call"]})}),te&&e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(on,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[oe?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:oe,alt:K.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:`${Z!=null&&Z.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"}),re?`Prepared for ${re}`: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:K.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(Ha,{className:"w-4 h-4"}),K.city,", ",K.state," ",K.zip]}),ge&&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(Ple,{to:me,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Ple,{to:ve,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(Ple,{to:me,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Ple,{to:he,prefix:"$",delayMs:800})})]})]})]})]}),(Z==null?void 0:Z.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>D(!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:[Z.thumb?e.jsx("img",{src:Z.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:Z.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(su,{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 ",((ke=i==null?void 0:i.name)==null?void 0:ke.split(" ")[0])||"your agent"]})]})]})})]})})]}),I&&(Z==null?void 0:Z.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>D(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:Xe=>Xe.stopPropagation(),children:[e.jsx("video",{src:Z.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(z,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>D(!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:K.bedrooms??"—"},{label:"Baths",value:K.bathrooms??"—"},{label:"Sq Ft",value:((Ve=K.sqft)==null?void 0:Ve.toLocaleString())??"—"},{label:"Year Built",value:K.yearBuilt??"—"}].map((Xe,nt)=>e.jsx(be,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${nt*80}ms`},children:e.jsxs(Le,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:Xe.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Xe.label})]})},nt))}),((Ae=(_e=r.settings)==null?void 0:_e.priceOverride)==null?void 0:Ae.enabled)&&((We=(Se=r.settings)==null?void 0:Se.priceOverride)==null?void 0:We.note)&&e.jsx(be,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Le,{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})]})}),ge&&e.jsx(KFs,{low:ve,likely:me,high:he}),H&&Ee&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(be,{className:"md:col-span-2",children:e.jsxs(Le,{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 ",K.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",H,"/sqft"]}),". Applied to your home's ",(qe=K.sqft)==null?void 0:qe.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(H*(K.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(be,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Le,{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:["$",Ee,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:["$",H,"/sqft"]})]}),Ne!==null&&Ne!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Ne>0?"text-emerald-600":"text-rose-600"}`,children:[Ne>0?"▲":"▼"," ",Math.abs(Ne),"% ",Ne>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((Xe,nt)=>{var ut;const Ge=Xe.snapshot,Je=Ge.soldPrice||Ge.price;return e.jsxs(be,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${P===nt?"ring-2 ring-primary":""}`,style:{animationDelay:`${nt*60}ms`},onClick:()=>E(nt),onMouseEnter:()=>M(nt),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(RAe,{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:["#",nt+1]}),e.jsx(ze,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ge.status})]}),e.jsxs(Le,{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 · ",((ut=Ge.sqft)==null?void 0:ut.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:["$",Je==null?void 0:Je.toLocaleString()]}),Ge.sqft&&Je?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(Je/Ge.sqft),"/sqft"]}):null]})]})]},nt)})})]}),e.jsx(I9t,{comp:C!==null?(Be=o[C])==null?void 0:Be.snapshot:null,open:C!==null,onClose:()=>E(null)}),e.jsx(be,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Le,{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",re?`, ${re}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Ze=i==null?void 0:i.name)==null?void 0:Ze.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:Fo,label:"I love this price"},{kind:"fair",icon:Ug,label:"Seems fair"},{kind:"lower",icon:_S,label:"I'd price lower"},{kind:"higher",icon:kl,label:"I'd price higher"},{kind:"ready_to_list",icon:jv,label:"Ready to list"},{kind:"want_walkthrough",icon:xa,label:"Want a walkthrough"},{kind:"need_time",icon:ya,label:"Need more time"},{kind:"have_questions",icon:v4,label:"I have questions"}].map(({kind:Xe,icon:nt,label:Ge})=>e.jsxs(z,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>q(Xe),children:[e.jsx(nt,{className:"w-4 h-4 mr-2"}),Ge]},Xe))}),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(Bu,{className:"w-4 h-4"}),"Ask your agent a question"]}),w?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! ",(($e=i==null?void 0:i.name)==null?void 0:$e.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[G&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:p,onChange:Xe=>f(Xe.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:g,onChange:Xe=>v(Xe.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:Xe=>m(Xe.target.value)}),e.jsx(z,{onClick:V,disabled:!h.trim()||y,className:"mt-2",children:y?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(be,{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:ae}),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:[J&&e.jsx(z,{asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(va,{className:"w-4 h-4 mr-2"}),i.phone]})}),te&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(on,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Wo,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(J||ce||te)&&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:[J&&e.jsx(z,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(va,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),ce&&e.jsx(z,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ce,children:[e.jsx(Bu,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),te&&e.jsx(z,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(on,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function YFs(){const t=Pd().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(D9t,{tokenOverride:t})}const qVe="levelup_affiliate_ref",ZFs=30,XFs=()=>{const[s]=Gl();_.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(qVe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},QFs=()=>{try{const s=localStorage.getItem(qVe);if(!s)return null;const t=JSON.parse(s),n=ZFs*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(qVe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},FAe="/assets/levelup-logo-header-_ZX7DvlA.png",JFs="/assets/scale-your-team-ku4MPatU.png";function eOs({open:s,onOpenChange:t}){return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Os,{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(oi,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Rs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(_r,{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 lae="/assets/mission_control-BJ-Kz8rX.png",eLe="/assets/crm-CsLftmB2.png",tLe="/assets/deal_pipeline-XYgypvwv.png",sLe="/assets/staging_studio-5iLDjnv0.png",nLe="/assets/coaching-CSQEA81I.png",rLe="/assets/marketing_studio-Brx1ZOnN.png",tOs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:lae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:eLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:tLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:sLe},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:nLe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:rLe}];function sOs({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(un,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label}),e.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const v2={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_over_25:{name:"Brokerage",subtitle:"Unlimited Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Individual, plus:","Unlimited agents","Brokerage manager dashboard","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"],popular:!1}},nOs=[{icon:dm,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:yc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ya,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Bu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:$r,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Ko,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],rOs=[{category:"Marketing Studio",icon:Nh,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:bu,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:k0,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:rg,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:fm,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:oi,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],aOs=[{icon:On,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:va,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Hf,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ha,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:wl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Fo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:cf,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],iOs=[{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."}],oOs=()=>{const{user:s,loading:t}=hs(),n=zn(),[r]=Gl();_.useEffect(()=>{const P=window.location.host==="listings.relevelup.com",M=window.location.pathname==="/";if(P&&M){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(""),[v,y]=_.useState(!1),[b,w]=_.useState(!1),S=(P,M=!1)=>{o({tier:P,skipTrial:M}),d(!0)};XFs(),_.useEffect(()=>{const P=window.location.host==="listings.relevelup.com",M=location.pathname.startsWith("/public/");!t&&s&&!P&&!M&&n("/dashboard")},[s,t,n,location.pathname]),_.useEffect(()=>{r.get("canceled")==="true"&&ne.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const C=async(P,M=!1)=>{if(!u){ne.error("Please enter your email address");return}if(!m.trim()){ne.error("Please enter your full name");return}y(!0),i(P+(M?"_direct":""));const I=QFs();try{const{data:D,error:F}=await U.functions.invoke("create-checkout",{body:{tier:P,email:u,name:m.trim(),couponCode:f.trim()||void 0,skipTrial:M,referralCode:I}});if(F)throw F;if(D!=null&&D.url)window.open(D.url,"_blank","noopener,noreferrer"),ne.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(D){console.error("Checkout error:",D),ne.error(D.message||"Failed to start checkout. Please try again.")}finally{y(!1),i(null),d(!1),o(null)}},E=()=>{l&&C(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:FAe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(z,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var P;return(P=document.getElementById("features"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(z,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(z,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>n("/blog"),children:"Blog"}),e.jsx(z,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-float-slow { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-8px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[e.jsx("div",{className:"flex justify-center animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-7xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["The tools you need",e.jsx("br",{className:"hidden sm:block"})," to get it done.",e.jsx("span",{className:"block mt-3 bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent",children:"The platform to keep it going."})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-2xl mx-auto leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[e.jsxs(z,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("free-trial"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(Da,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(z,{size:"lg",variant:"outline",onClick:()=>{var P;return(P=document.getElementById("features"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white/40 text-white bg-white/5 backdrop-blur-sm hover:bg-white hover:text-[#122c3a] rounded-full",children:"See What's Included"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 pt-2 text-sm text-white/55 animate-fade-in",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(cf,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Om,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),e.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[e.jsx("div",{className:"absolute inset-x-8 top-10 bottom-0 rounded-[40px] bg-gradient-to-b from-[#4aa8a0]/30 to-transparent blur-2xl","aria-hidden":!0}),e.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/15 bg-[#0d1f29]/80 backdrop-blur-md shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),e.jsx("img",{src:lae,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),e.jsxs("div",{className:"hidden md:flex absolute -left-10 top-24 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6s_ease-in-out_infinite]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:e.jsx(kl,{className:"h-5 w-5 text-[#7fd4cc]"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),e.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),e.jsxs("div",{className:"hidden md:flex absolute -right-10 top-1/2 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_7s_ease-in-out_infinite_1s]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:e.jsx(dm,{className:"h-5 w-5 text-[#e6c878]"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),e.jsxs("div",{className:"hidden md:flex absolute left-8 -bottom-6 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6.5s_ease-in-out_infinite_0.5s]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:e.jsx(ya,{className:"h-5 w-5 text-white/80"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),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(z,{size:"lg",variant:"outline",onClick:()=>{var P;return(P=document.getElementById("brokerage"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(oi,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(z,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Oo,{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.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(X4,{className:"w-4 h-4"}),"40+ tools & counting"]}),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:nOs.map((P,M)=>e.jsxs(be,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(_t,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(P.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Nt,{className:"text-xl font-sans",children:P.title})]}),e.jsx(Le,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:P.description})})]},M))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",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:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:rOs.map(P=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:e.jsx(P.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:P.category})]}),e.jsx("ul",{className:"space-y-2.5",children:P.items.map(M=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),M]},M))})]},P.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),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.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:tOs.map(P=>e.jsx(sOs,{slot:P},P.key))})]})]}),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:aOs.map((P,M)=>e.jsxs(be,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(_t,{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(P.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Nt,{className:"text-lg font-semibold text-white",children:P.title})]}),e.jsx(Le,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:P.description})})]},M))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(z,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.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(Da,{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(oi,{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((P,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(Wr,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:P})]},M))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(z,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(yi,{className:"ml-2 w-5 h-5"})]}),e.jsxs(z,{size:"lg",variant:"outline",onClick:()=>w(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(ya,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:JFs,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:iOs.map((P,M)=>e.jsx(be,{className:"bg-muted/30 border-0",children:e.jsxs(Le,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(I=>e.jsx(Ia,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},I))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',P.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:P.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:P.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(z,{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:()=>S("individual_agent"),children:["Start Free Trial",e.jsx(Da,{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-2 gap-8 max-w-4xl mx-auto",children:[e.jsxs(be,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(_t,{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(Oo,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Nt,{className:"text-xl font-sans",children:v2.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:v2.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:v2.individual_agent.period})]}),e.jsx(En,{className:"text-base mt-2",children:v2.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(Zr,{className:"w-4 h-4"}),v2.individual_agent.trial]})]}),e.jsx(Le,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:v2.individual_agent.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Wr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsxs(dAe,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(z,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("individual_agent"),children:"Start Free Trial"}),e.jsx(z,{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:()=>S("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(be,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl 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(_t,{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(oi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-xl font-sans",children:v2.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:v2.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:v2.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:v2.brokerage_over_25.period})]}),e.jsx(En,{className:"text-base mt-2",children:v2.brokerage_over_25.description})]}),e.jsx(Le,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:v2.brokerage_over_25.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Wr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsx(dAe,{className:"pt-4",children:e.jsx(z,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("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(Om,{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(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(oi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(Hl,{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(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(jj,{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(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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($r,{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(z,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.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(Da,{className:"ml-2 w-5 h-5"})]}),e.jsx(z,{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:FAe,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:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),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(eOs,{open:b,onOpenChange:w}),e.jsx(Is,{open:c,onOpenChange:d,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(_r,{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":"Subscribe to Brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:P=>p(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:P=>h(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(pe,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:f,onChange:P=>g(P.target.value),className:"mt-1"})]})]}),e.jsx(z,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:E,disabled:v,children:v?"Loading...":"Continue to Checkout"})]})})]})},rgt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"How LevelUp collects, uses, shares and retains data — including the LevelUp Hub MCP connector for ChatGPT."})]}),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: September 16, 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:'LevelUp ("we," "our," or "us") provides a real estate business platform for agents, teams and brokerages. This policy explains what we collect, why, who receives it, how long we keep it and the controls you have. It covers the LevelUp web app, our public pages, our SMS program and the LevelUp Hub MCP connector that members can connect to ChatGPT and other AI clients.'}),e.jsx("p",{className:"mt-3",children:"Members store information about other people (their contacts, leads and open-house visitors) in LevelUp. For that information the member is the controller and LevelUp processes it on their behalf."})]}),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:"Depending on which features a member uses, we handle:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Account and profile:"})," name, email, phone, password credentials, title, brokerage, license number and state, website, headshot and logo images, brand colors, taglines and any brokerage compliance line."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Billing:"})," subscription status, plan, and transaction records handled by our payment processor (we do not store full card numbers)."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Contacts and relationship data"})," a member enters or imports: names, emails, phones, mailing addresses, lead source, free-text notes, and optional personal fields such as birthday, home and wedding anniversary, spouse name, spouse email and spouse birthday, company and job title."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Deals, tasks and interaction history:"})," pipeline stage, prices, commissions, bonuses, key dates, tasks, and logged calls, texts, emails, pop-bys and notes."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Listings and media:"})," listing details, photos, videos and agent/brokerage attribution, including listings published to the shared Listing Exchange."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Guest Book visitors:"})," the name, contact details and any survey answers a visitor submits at an open house sign-in page."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Landing page and website leads:"})," the fields a visitor submits on a member's published landing page, property website or home-value page."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Generated marketing and campaign data:"})," drafts and records created by our marketing tools (email, social, print, FSBO and Listing Revival), plus the leads and engagement events those campaigns capture."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"MCP audit logs:"})," for each connector tool call we record the member id, tool name, a truncated snapshot of the tool inputs, the outcome, an error label, the duration and the calling client id."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Technical and usage data:"})," log data, device and browser information, and feature usage needed to run and secure the service."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain and improve the platform and the features a member turns on."}),e.jsx("li",{children:"Perform the actions a member asks for, including through a connected AI client."}),e.jsx("li",{children:"Generate marketing copy and assets when a member explicitly requests generation."}),e.jsx("li",{children:"Process payments and send transactional and support messages."}),e.jsx("li",{children:"Secure the service: authentication, rate limiting, audit trails, abuse investigation and support."}),e.jsx("li",{children:"Meet legal, tax and record-keeping obligations."})]}),e.jsx("p",{className:"mt-3",children:"We do not sell personal information, and we do not use member contact data to train AI models."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. LevelUp Hub MCP Connector (ChatGPT and other AI clients)"}),e.jsxs("p",{children:["Members can optionally connect LevelUp Hub to an AI client such as ",e.jsx("strong",{children:"ChatGPT (OpenAI)"})," ","using the Model Context Protocol. The connector is off until a member connects it and signs in through OAuth, and it can be revoked at any time from the AI client."]}),e.jsxs("p",{className:"mt-3",children:["Once connected, the client can call LevelUp tools ",e.jsx("strong",{children:"as that member"})," and receives whatever a called tool returns — which may include profile and branding data, contacts and their relationship fields, deals and tasks, listings and photos, Guest Book visitors, landing-page leads, and campaign records. OpenAI's handling of that data is governed by OpenAI's own terms and privacy policy."]}),e.jsx("p",{className:"mt-3",children:'The connector does not send email, SMS, direct mail or social posts. Tools that "activate" a campaign only change its status inside LevelUp and publish its page; outbound delivery is always a separate action the member takes in the app. Publishing, activating, merging and deleting require an explicit confirmation step, and open houses, landing pages and property sites are created as unpublished drafts unless the member asks otherwise.'}),e.jsxs("p",{className:"mt-3",children:["Full details are on the"," ",e.jsx(or,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," ","page."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. AI Content Generation"}),e.jsxs("p",{children:["When a member asks for generated copy (listing descriptions, emails, social posts, print collateral, campaign letters), the request is sent to the ",e.jsx("strong",{children:"Lovable AI Gateway"})," and the model provider behind it. That request contains the property details supplied for the task and a brand block with the agent's name, brokerage, phone, email, website, license and any compliance line. Contact records, visitor lists and lead lists are not sent for generation. Nothing is sent to a model provider for read-only tools or for ordinary use of the app."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Who Receives Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Infrastructure providers"})," that host our application, database, storage and email/SMS delivery."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Payment processor"})," for subscriptions and purchases."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The AI client a member connects"})," (OpenAI/ChatGPT or another MCP client), as described in section 4."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The Lovable AI Gateway and its model provider"}),", only for generation requests, as described in section 5."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Third-party services a member connects"})," — for example Google (calendar and sign-in), Gmail, Meta/Facebook and Instagram, YouTube, Canva, Stripe, and CRM imports such as BoldTrail or Lofty — and only when that integration is invoked. Each is governed by its own privacy policy."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The public"}),", for pages a member publishes: open house sign-in pages, landing pages, property websites and public listing pages."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Other LevelUp members"}),", for listings a member publishes to the shared Listing Exchange (listing details, photos and agent/brokerage attribution). Contacts, leads and pipeline data are never shared this way."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Brokerage managers, team leaders, assigned assistants and coaches"}),", limited to the data their role is granted."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"LevelUp administrators"}),", who may act on behalf of a member for support and setup; those actions are recorded in the audit log with the target member."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Legal recipients"}),", where disclosure is required by law or needed to protect rights and safety."]})]}),e.jsx("p",{className:"mt-3",children:"We do not sell, rent or trade personal information."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Retention"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account, contact, deal, listing, campaign, visitor and lead records are kept for as long as the account is active, until the member deletes them, or until the account is deleted."}),e.jsx("li",{children:"Canva: disconnecting Canva revokes LevelUp's access and removes the saved Canva connection. Files a member already imported from Canva are kept, because they may be used in saved drafts or posts, until the member deletes them or the account is deleted; account deletion removes those imported files from LevelUp storage."}),e.jsx("li",{children:"MCP audit log entries are kept for security and support purposes. They are not purged automatically on a fixed schedule; they can be removed on request."}),e.jsx("li",{children:"Short-lived rate-limit counters expire within minutes."}),e.jsx("li",{children:"Billing and tax records are kept as long as the law requires."}),e.jsx("li",{children:"Backups are cycled on our provider's schedule, so deleted data can persist in backups for a limited period after deletion."})]}),e.jsxs("p",{className:"mt-3",children:["We do not promise an automatic timed purge that we do not operate; see"," ",e.jsx(or,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," ","for how requests are handled."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Your Choices and Rights"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access, correct or delete records from within the app."}),e.jsx("li",{children:"Connect or disconnect any integration, including the MCP connector, at any time."}),e.jsx("li",{children:"Review connector activity in the MCP activity log."}),e.jsx("li",{children:"Mark a contact as opted out of marketing email, and opt out of SMS by replying STOP."}),e.jsxs("li",{children:["Request access, correction, export or deletion by emailing ",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:"9. Data Security"}),e.jsx("p",{children:"We use access controls, row-level database security scoped to each member, OAuth-based authentication for connectors, per-member rate limiting and audit logging. No method of transmission or storage is completely secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS / Text Messaging Program (LevelUp Account & Lead Alerts)"}),e.jsx("p",{children:"If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates and support messages related to your LevelUp account."}),e.jsx("p",{className:"mt-3",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, except with the vendors and aggregators that deliver the messages on our behalf."}),e.jsx("p",{className:"mt-3",children:"Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. LevelUp SmartSign (Property Information by Text)"}),e.jsxs("p",{children:["LevelUp SmartSign is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program described in section 10, and consent to one is not consent to the other."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"What we collect:"})," your mobile phone number, the property code you text, the content of your messages, and the details of your inquiry (such as the property you asked about, your questions, and any name or showing preference you provide)."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How we use it:"})," to respond to your inquiry with listing information, answer questions about the property, assist with showing requests, provide support, keep records of your messaging preferences and opt-outs, and meet legal and carrier requirements."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Service providers:"})," messaging providers — including ",e.jsx("strong",{children:"Telnyx"})," — and our hosting and database providers process this information solely to deliver and operate the service on our behalf."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Sharing with an agent:"})," we ask for your separate, specific permission before sharing your inquiry or contact details with a named agent. We identify the actual agent and brokerage first. If you agree, we share your name, phone number and property inquiry with that agent so they can respond to your request. This consumer-requested handoff is not a transfer of your SMS consent: the agent does not receive permission to send you marketing texts, and your LevelUp SmartSign consent does not carry over to them. Agreeing to an agent contacting you also does not enroll you in LevelUp marketing."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," requesting property information does not enroll you in promotional or marketing texts. Marketing texts require a separate affirmative opt-in, and you can stop them at any time by replying STOP."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No sale or sharing for third-party marketing:"})," we do not sell your information, and no mobile information, SMS opt-in data or consent is shared with third parties or affiliates for their own promotional or marketing purposes. The only recipients are the service providers that deliver the service on our behalf, and — with your separate permission — the specific agent you asked to hear from."]}),e.jsxs("p",{className:"mt-3",children:["Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. See the"," ",e.jsx(or,{to:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"})," ","and"," ",e.jsx(or,{to:"/terms-of-service",className:"text-primary hover:underline",children:"Terms of Service"})," ","for program details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Children"}),e.jsx("p",{children:"LevelUp is a business tool and is not directed to children under 16."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. Changes to This Policy"}),e.jsx("p",{children:'We will update this page when our practices change and revise the "Last updated" date above.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"14. Contact Us"}),e.jsxs("p",{children:["Questions about this policy:"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),lOs=()=>e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:"Canva Support | LevelUp Hub"}),e.jsx("meta",{name:"description",content:"How to connect or disconnect your Canva account to LevelUp Hub and find the designs you've imported. Public support page for Canva users."})]}),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("div",{className:"mb-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(nc,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground leading-tight",children:"LevelUp Hub — Canva Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"LevelUp Hub is a real estate business platform for agents, teams and brokerages. Members can connect their own Canva account and bring their designs into LevelUp."})]})]})}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-10",children:[e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(_j,{className:"w-5 h-5 text-primary"})," Connect your Canva account"]}),e.jsxs("ol",{className:"list-decimal pl-6 mt-3 space-y-2",children:[e.jsxs("li",{children:["Sign in to LevelUp Hub and open your ",e.jsx("strong",{className:"text-foreground",children:"Integrations"})," page."]}),e.jsxs("li",{children:["Find the ",e.jsx("strong",{className:"text-foreground",children:"Canva"})," tile and click"," ",e.jsx("strong",{className:"text-foreground",children:"Connect Canva"}),"."]}),e.jsx("li",{children:"A Canva window opens asking you to approve the connection. LevelUp requests read-only access to your designs so it can list them and save copies you choose."}),e.jsx("li",{children:"After you approve, the window closes and your Integrations page shows your Canva account as connected."})]}),e.jsx("p",{className:"mt-3 text-sm",children:`You can also start this from inside LevelUp tools — for example the postcard or social post editors have an "Import from Canva" button that will ask you to connect first if you haven't yet.`})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Oc,{className:"w-5 h-5 text-primary"})," Import designs from Canva"]}),e.jsxs("ol",{className:"list-decimal pl-6 mt-3 space-y-2",children:[e.jsx("li",{children:"In the import window, search or browse your Canva designs and select the ones you want."}),e.jsx("li",{children:"Choose which pages or files to bring in and pick a format where the option is shown."}),e.jsx("li",{children:"LevelUp saves a copy of each selected page or file into your LevelUp media, associated with your account and the tool you imported it for."}),e.jsx("li",{children:"You can then use those copies in the feature you imported them into, or open the design in Canva to edit it."})]}),e.jsx("p",{className:"mt-3 text-sm",children:'To open a design in Canva for editing, use the "Design with Canva" action in your Integrations page — it opens your design on canva.com in a new tab.'})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(nc,{className:"w-5 h-5 text-primary"})," Finding your imported designs"]}),e.jsxs("ul",{className:"list-disc pl-6 mt-3 space-y-2",children:[e.jsx("li",{children:"Imported images for social posts appear in your LevelUp media library, alongside files you uploaded directly."}),e.jsx("li",{children:"Imported postcard fronts and letter pages appear inside the mail tool where you imported them, listed with your saved designs."}),e.jsx("li",{children:"Your Canva connection and the design browsing inside LevelUp are per agent — only your signed-in account can connect your Canva account and browse your designs."})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(_7,{className:"w-5 h-5 text-primary"})," Disconnect your Canva account"]}),e.jsxs("ol",{className:"list-decimal pl-6 mt-3 space-y-2",children:[e.jsxs("li",{children:["Open your ",e.jsx("strong",{className:"text-foreground",children:"Integrations"})," page in LevelUp Hub."]}),e.jsxs("li",{children:["On the Canva tile, click ",e.jsx("strong",{className:"text-foreground",children:"Disconnect"})," and confirm."]}),e.jsx("li",{children:"LevelUp tells Canva to revoke its access to your account and removes the saved connection, including the access and refresh tokens, from its records."}),e.jsx("li",{children:"Disconnecting does not delete files you already imported. They stay in the LevelUp tools where you saved them, because they may be used in saved drafts, postcards or social posts. You can delete them yourself from those tools. Nothing new can be imported until you reconnect."}),e.jsx("li",{children:"If your LevelUp account is deleted, the files LevelUp copied from Canva for your account are deleted from LevelUp storage as part of that deletion."})]}),e.jsxs("p",{className:"mt-3 text-sm",children:[e.jsx(Ch,{className:"w-4 h-4 inline mr-1.5 -mt-0.5 text-primary"}),"You can also remove access from the Canva side at any time: in Canva, go to"," ",e.jsx("strong",{className:"text-foreground",children:"Settings → Connected apps"}),", find LevelUp Hub and remove it."]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(on,{className:"w-5 h-5 text-primary"})," Need help?"]}),e.jsxs("p",{className:"mt-3",children:["Contact the LevelUp team at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline font-medium",children:"hello@relevelup.com"})," ","and we'll help you connect, import or disconnect."]})]}),e.jsx("section",{children:e.jsxs("ul",{className:"list-disc pl-6 space-y-1 text-sm",children:[e.jsx("li",{children:e.jsxs(or,{to:"/privacy-policy",className:"text-primary hover:underline inline-flex items-center gap-1",children:["Privacy Policy ",e.jsx(mr,{className:"w-3 h-3"})]})}),e.jsx("li",{children:e.jsxs(or,{to:"/terms-of-service",className:"text-primary hover:underline inline-flex items-center gap-1",children:["Terms of Service ",e.jsx(mr,{className:"w-3 h-3"})]})})]})})]}),e.jsxs("p",{className:"mt-12 text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(Mr,{className:"w-3.5 h-3.5"}),"LevelUp Hub · hello@relevelup.com"]})]})})]}),agt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(dl,{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: September 16, 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 (LevelUp Account & Lead Alerts)"}),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. LevelUp SmartSign SMS Terms"}),e.jsxs("p",{children:[e.jsx("strong",{children:"LevelUp SmartSign"})," is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program in section 11."]}),e.jsxs("ul",{className:"list-disc pl-6 mt-3 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Requested property responses:"})," texting a property code is a request for SMS responses about that property and your inquiry. LevelUp may reply with listing information, answers to your property questions, and help with showing requests."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," promotional texts about property updates and similar homes require a separate affirmative opt-in. Requesting property information does not subscribe you to marketing. ",e.jsx("strong",{children:"Consent is not a condition of purchase."})]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Agent contact is separate:"})," before sharing your contact details with a named agent and brokerage, LevelUp asks your permission separately. That permission does not enroll you in LevelUp marketing and does not transfer your LevelUp SMS consent to the agent."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Message frequency varies."})," Message and data rates may apply."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Opt out:"})," reply ",e.jsx("strong",{children:"STOP"})," to any message to stop further messages. Reply ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Carrier liability:"})," carriers are not liable for delayed or undelivered messages."]})]}),e.jsxs("p",{className:"mt-3",children:["Support: ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),". How we handle SmartSign information is described in our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"}),". Program details and example disclosures are on the"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. 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"})]})]})]})]})})]}),cOs=()=>e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"How to request deletion of your LevelUp data, and what is deleted or retained."})]}),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: August 25, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Delete records yourself"}),e.jsx("p",{children:"Most data can be removed directly in the app: contacts, deals, tasks, listings, open houses, landing pages, campaigns and uploaded media can each be deleted from their page. Disconnecting an integration (including the ChatGPT / MCP connector) immediately stops further access."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Request account or bulk deletion"}),e.jsxs("p",{children:["Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject "Data Deletion Request" and include your full name, the email address on the account and what you want deleted (the whole account, or specific categories such as MCP audit logs or Guest Book sign-ins). We verify the request against the account before acting on it.']})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What account deletion removes"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account and profile data, branding assets and connected-integration tokens."}),e.jsx("li",{children:"Contacts and their relationship fields, notes, tags and interaction logs."}),e.jsx("li",{children:"Deals, tasks, listings, uploaded media and generated marketing/campaign records."}),e.jsx("li",{children:"Guest Book open houses and the visitor sign-ins captured on them."}),e.jsx("li",{children:"Landing pages, property websites and the leads submitted through them, including FSBO and Listing Revival campaign leads."}),e.jsx("li",{children:"MCP audit log entries for your account."})]}),e.jsx("p",{className:"mt-3",children:"These records are deleted when we process the request. There is no automatic scheduled purge running in the background — deletion happens on account deletion or on a verified request."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Category-specific notes"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"MCP audit logs"})," (member id, tool name, truncated tool inputs, outcome, duration, client id) are retained for security and support and are not purged on a timer. They are removed with the account, or earlier on request."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Campaign leads and Guest Book sign-ins"})," are records about other people that the member controls. A visitor or lead who wants their own record removed should ask the agent they signed in with, or email us and we will route it to that member and remove it."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Content already shared"})," — for example a listing published to the Listing Exchange and saved by another member, or a page a third party archived — may persist outside our control after deletion."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What we retain"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Billing and transaction records required for financial and tax reporting."}),e.jsx("li",{children:"Records we must keep to comply with a legal obligation or to resolve a dispute."}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you."}),e.jsx("li",{children:"Backup copies, until the backup cycle rotates them out after deletion."})]})]}),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:"You can also revoke our access from Meta directly:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Open Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Timing"}),e.jsx("p",{children:"We aim to complete verified deletion requests within 30 days and will email you when it is done. If a request needs more time or is partly refused (for example where we must keep billing records), we will tell you why."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Related"}),e.jsxs("p",{children:["See the ",e.jsx(or,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and the"," ",e.jsx(or,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," page, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),igt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:"MCP & ChatGPT Data Use | LevelUp"}),e.jsx("meta",{name:"description",content:"What the LevelUp Hub MCP connector shares with ChatGPT: data categories, purposes, recipients, retention and member controls."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/mcp-data-use"})]}),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-2",children:"LevelUp Hub MCP — data use"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-8",children:"Last updated: August 25, 2026"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What this connector is"}),e.jsxs("p",{children:["LevelUp Hub publishes an MCP (Model Context Protocol) server. When a LevelUp member connects it to an AI client such as ChatGPT, that client can call LevelUp tools ",e.jsx("strong",{children:"as that member"}),", using an OAuth sign-in the member completes and can revoke. The connector is optional and off until the member connects it."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data the tools can reach"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Profile and branding: name, email, phone, title, brokerage, license number and state, website, headshot and logo images, brand colors and any brokerage compliance line."}),e.jsx("li",{children:"Contacts (Agent OS / Inner Circle): names, emails, phones, addresses, lead source, notes, and the optional relationship fields a member chooses to store (birthday, home and wedding anniversary, spouse name/email/birthday, company, job title)."}),e.jsx("li",{children:"Deals, tasks and interaction logs: pipeline stage, prices, commissions, key dates, task text, and logged calls, texts, emails, pop-bys and notes."}),e.jsx("li",{children:"Listings and media: the member's listings plus listings other members published to the shared Listing Exchange, with photos, videos and agent/brokerage attribution."}),e.jsx("li",{children:"Guest Book open houses and their visitor sign-ins."}),e.jsx("li",{children:"Landing pages, property websites and the leads submitted through them."}),e.jsx("li",{children:"Marketing and campaign records generated through the tools (email, social, print, FSBO and Listing Revival drafts)."}),e.jsx("li",{children:"MCP audit logs: for every tool call we record the member id, tool name, a truncated snapshot of the tool inputs, the outcome, an error label, the duration and the calling client id."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Why"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"To answer the member's own questions about their business and to perform the actions they ask for."}),e.jsx("li",{children:"To draft marketing copy and assets when the member explicitly requests generation."}),e.jsx("li",{children:"To secure the connector: authentication, per-member rate limiting, abuse investigation and support."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Who receives data"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"LevelUp"})," and its hosting/database provider — where the data already lives."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The connected AI client (OpenAI / ChatGPT, or another MCP client the member connects)"})," — it receives whatever a called tool returns, and it is governed by that client's own privacy terms."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The Lovable AI Gateway and the model provider behind it"})," — only when a member requests copy generation, and only the property details and brand/contact block needed for that request. Nothing is sent there for read-only tools."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The public"})," — only for pages the member publishes (open house sign-in pages, landing pages, property websites). Drafts are not published."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Other LevelUp members"})," — only for listings a member chose to publish to the Listing Exchange."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"LevelUp administrators"})," — an administrator may act on behalf of a member for support; those calls are recorded in the audit log with the target member."]})]}),e.jsx("p",{className:"mt-3",children:'The connector does not send email, SMS, direct mail or social posts. Tools that "activate" a campaign only change its status inside LevelUp and publish its page; outbound delivery is always a separate, member-initiated action in the app.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Retention"}),e.jsx("p",{children:"Records created or edited through the connector follow the same retention as the rest of the member's LevelUp account: they are kept until the member deletes them or the account is deleted. MCP audit log entries are kept for security and support purposes and are not automatically purged on a fixed schedule; a member or administrator can ask us to remove them. Short-lived rate-limit counters expire on their own within minutes."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Member controls"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Connect or disconnect the connector at any time from the AI client; revoking access stops all tool calls."}),e.jsx("li",{children:"Actions that publish, activate, merge or delete require an explicit confirmation step; without it the tool returns a preview and changes nothing."}),e.jsx("li",{children:"Open houses, landing pages and property sites are created as unpublished drafts unless the member asks for them to be published."}),e.jsx("li",{children:"Review every call in the member's MCP activity log, and edit or delete the underlying records in the app."}),e.jsxs("li",{children:["Request deletion or export by writing to ",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:"More"}),e.jsxs("p",{children:["See the ",e.jsx(or,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and"," ",e.jsx(or,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," pages, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),ogt="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.",dOs="I agree to receive recurring automated promotional texts from LevelUp SmartSign about property updates and similar homes. Consent is not a condition of purchase. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help.",uOs=Gj({name:Jo().trim().max(200).optional().or(jx("")),phone:Jo().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:Jo().trim().email("Enter a valid email").max(320).optional().or(jx(""))}),hOs=Gj({name:Jo().trim().min(1,"Name is required").max(200),phone:Jo().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:Jo().trim().email("Enter a valid email").max(320).optional().or(jx(""))});function mOs(){const[s,t]=_.useState(""),[n,r]=_.useState(""),[a,i]=_.useState(""),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(!1),f=zn(),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),F=async G=>{var Z;if(G.preventDefault(),!C){ne.error("Please check the marketing consent box to enroll.");return}const V=uOs.safeParse({name:g,phone:y,email:w});if(!V.success){ne.error(((Z=V.error.issues[0])==null?void 0:Z.message)??"Please check your inputs.");return}M(!0);const{data:H,error:K}=await U.functions.invoke("smartsign-marketing-optin",{body:{name:V.data.name||null,phone:V.data.phone,email:V.data.email||null,consent:!0,source_url:window.location.href}});if(M(!1),K||!(H!=null&&H.ok)){ne.error("We could not record your opt-in. Please try again.");return}D(!0),ne.success("Your SmartSign marketing opt-in was recorded.")},q=async G=>{var K;if(G.preventDefault(),!l){ne.error("Please check the consent box to opt in.");return}const V=hOs.safeParse({name:s,phone:n,email:a});if(!V.success){ne.error(((K=V.error.issues[0])==null?void 0:K.message)??"Please check your inputs.");return}d(!0);const{error:H}=await U.from("sms_opt_in_consents").insert({name:V.data.name,phone:V.data.phone,email:V.data.email||null,consent_text:ogt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),H){ne.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(dl,{children:[e.jsx("title",{children:"SMS Opt-In & LevelUp SmartSign | LevelUp"}),e.jsx("meta",{name:"description",content:"LevelUp SmartSign: text a property code to 859-413-5013 for property information. Also opt in to LevelUp account and lead alert texts. Message frequency varies, msg & data rates may apply, reply STOP to opt out or HELP for help."}),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(qi,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Programs"}),e.jsxs("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:["LevelUp runs two separate text messaging programs. ",e.jsx("strong",{children:"LevelUp SmartSign"})," ","lets home shoppers text a property code from a real estate sign to get information about that property. ",e.jsx("strong",{children:"LevelUp Account & Lead Alerts"})," sends LevelUp members notifications about their own account. Each has its own number and its own consent."]})]}),e.jsxs(be,{className:"p-6 md:p-8 mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-10 h-10 rounded-xl bg-primary/10 text-primary",children:e.jsx(pJ,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold leading-tight",children:"LevelUp SmartSign"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Property information by text · Operated by LevelUp Consulting Group"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"LevelUp SmartSign lets you request information about a home by texting the property code shown on the real estate sign. LevelUp responds with listing information, answers questions about the property, and can help with showing requests. LevelUp is the sender of these messages — independent real estate agents do not send messages through the LevelUp SmartSign number."}),e.jsxs("div",{className:"mt-5 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:"Text the property code shown on the sign to 859-413-5013 to request information about that property from LevelUp SmartSign."}),e.jsxs("p",{className:"mt-3 text-xs leading-relaxed text-muted-foreground",children:["By texting a property code, you request SMS responses from LevelUp SmartSign about that property and your inquiry. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. Requesting property information does not subscribe you to marketing updates. See our"," ",e.jsx(or,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"})," ","and"," ",e.jsx(or,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"Terms of Service"}),"."]})]}),e.jsxs("div",{className:"mt-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Example sign — illustration only"}),e.jsxs("div",{className:"rounded-xl border-2 border-dashed border-primary/40 bg-background p-5 text-center",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp SmartSign"}),e.jsx("p",{className:"mt-3 text-sm font-medium text-foreground",children:"Text"}),e.jsx("p",{className:"text-3xl font-bold tracking-tight text-foreground",children:"1234"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"to"}),e.jsx("p",{className:"text-2xl font-bold tracking-tight text-primary",children:"859-413-5013"}),e.jsx("p",{className:"mt-3 text-[11px] leading-relaxed text-muted-foreground",children:"Msg frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. Requesting property info does not subscribe you to marketing."})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.jsx("strong",{children:"1234 is an example property code used for illustration only."})," It is not an active listing and texting it will not return property information. Real property codes appear on the physical sign at the property."]})]}),e.jsxs("div",{className:"mt-8 space-y-4",children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:"Three separate choices — each one is its own decision"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"1. Property information you requested"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"When you text a property code, you are asking LevelUp SmartSign to reply about that property and your inquiry. That is all it does. It does not automatically enroll you in promotional or marketing updates. Reply STOP at any time to stop messages, or HELP for help."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"2. Optional LevelUp SmartSign marketing updates"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Marketing texts require a separate, affirmative choice that you make on purpose. They are never bundled with a property inquiry and are never combined with permission for an agent to contact you."}),I?e.jsxs("div",{className:"mt-4 rounded-md border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Your marketing opt-in has been recorded."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"We saved your number, the exact disclosure you agreed to, and the time of your consent. You can reply STOP to any message to opt out, or HELP for help."})]}):e.jsxs("form",{onSubmit:F,className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-name",children:"Full name (optional)"}),e.jsx(pe,{id:"mkt-name",value:g,onChange:G=>v(G.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-phone",children:"Mobile number"}),e.jsx(pe,{id:"mkt-phone",type:"tel",value:y,onChange:G=>b(G.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-email",children:"Email (optional)"}),e.jsx(pe,{id:"mkt-email",type:"email",value:w,onChange:G=>S(G.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-md border bg-background p-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(za,{id:"mkt-consent",checked:C,onCheckedChange:G=>E(G===!0),className:"mt-0.5"}),e.jsx(ee,{htmlFor:"mkt-consent",className:"text-xs leading-relaxed font-normal cursor-pointer",children:dOs})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This box is optional and starts unchecked. Leaving it unchecked changes nothing. This consent is only for LevelUp SmartSign marketing texts — it is not account or lead alerts, and it is not permission for an agent to contact you."}),e.jsx(z,{type:"submit",disabled:!C||P,size:"sm",children:P?"Saving…":"Opt in to SmartSign marketing texts"})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"3. Permission for an agent to contact you"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Before your contact details are shared with anyone, LevelUp identifies the actual agent and brokerage and asks you separately:"}),e.jsx("p",{className:"mt-2 rounded-md border bg-background p-3 text-xs leading-relaxed text-muted-foreground",children:'"Would you like [Agent Name] at [Brokerage] to contact you about [Property]? If you agree, LevelUp will share your name, phone number, and property inquiry with this agent to respond to your request."'}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:'Agreeing to an agent contacting you does not enroll you in LevelUp marketing texts and does not transfer your LevelUp SMS consent to that agent. A single checkbox or an ambiguous "YES" is never used for both purposes.'})]})]})]}),e.jsxs("div",{className:"mb-6 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"A separate program: LevelUp Account & Lead Alerts"}),e.jsx("p",{className:"text-sm mt-1 text-muted-foreground",children:"The form below is for LevelUp members (real estate agents) who want account notifications and lead alerts about their own LevelUp account. It is a different program from LevelUp SmartSign, uses a different number, and consent to one is never consent to the other. SMS notifications are optional — you may use LevelUp without providing a mobile number or consenting to text messages."})]}),m?e.jsxs(be,{className:"p-8 text-center",children:[e.jsx(Mr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"No text messages — you're all set"}),e.jsx("p",{className:"text-muted-foreground",children:"You declined SMS notifications. No mobile number or consent was recorded, and you can continue using LevelUp normally."}),e.jsx(z,{className:"mt-6",onClick:()=>f("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(be,{className:"p-8 text-center",children:[e.jsx(Mr,{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(be,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:q,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(pe,{id:"name",value:s,onChange:G=>t(G.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(pe,{id:"phone",type:"tel",value:n,onChange:G=>r(G.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email (optional)"}),e.jsx(pe,{id:"email",type:"email",value:a,onChange:G=>i(G.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(za,{id:"consent",checked:l,onCheckedChange:G=>o(G===!0),className:"mt-0.5"}),e.jsx(ee,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:ogt})]})}),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(or,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(or,{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(z,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx(z,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>p(!0),children:"Skip SMS / Continue without text alerts"}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Skipping records no consent and does not limit your access to LevelUp."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(Ch,{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 aLe="/assets/levelup-logo-horizontal-DEFNc0ms.png",pOs=Gj({email:Jo().email("Invalid email address"),password:Jo().min(6,"Password must be at least 6 characters")}),R9t="https://dashboard.relevelup.com",Lle="/oauth-connect",fOs=`${R9t}/profile?reset=true`,V4e="levelupOAuthRouteHistory";function lgt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function xOs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(V4e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(V4e,JSON.stringify([{route:s,at:t}])),!1}}function gOs(){sessionStorage.removeItem(V4e)}const yOs=()=>{const{signIn:s,user:t,loading:n}=hs(),r=(t==null?void 0:t.id)??null,a=zn(),[i]=Gl(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=_.useState(!1),[u,h]=_.useState({}),[m,p]=_.useState(""),[f,g]=_.useState(!1),[v,y]=_.useState(!1),[b,w]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,F]=_.useState(()=>{if(i.get("paused")!=="1")return null;let K="";try{K=sessionStorage.getItem("accountPausedReason")||""}catch{}return K?`Your account is paused. ${K}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),q=_.useRef(!1);_.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const K=new URL("/auth",R9t);K.searchParams.set("next",`${Lle}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(K.toString());return}if(l){const K=`${Lle}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",K);return}o&&lgt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),_.useEffect(()=>{if(n||!r||q.current)return;const K=l?`${Lle}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!lgt(K)){sessionStorage.removeItem("redirectAfterLogin"),q.current=!0,a("/dashboard",{replace:!0});return}const Z=K.startsWith(Lle)||K.startsWith("/oauth/consent")||K.startsWith("/.lovable/oauth/consent");if(Z&&xOs("auth")){w("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}q.current=!0,Z||(gOs(),sessionStorage.removeItem("redirectAfterLogin")),a(K,{replace:!0})},[l,n,a,r]);const G=async K=>{K.preventDefault(),h({}),F(null),C(null),P(!1),d(!0);const Z=new FormData(K.currentTarget),oe=Z.get("email"),re=Z.get("password");try{pOs.parse({email:oe,password:re}),await s(oe,re)}catch(ae){if(ae instanceof $4s){const J={};ae.issues.forEach(te=>{te.path[0]&&(J[te.path[0]]=te.message)}),h(J)}else if(ae instanceof Error&&ae.name==="AccountPaused")F(ae.message);else if(oe)try{const{data:J}=await U.functions.invoke("account-activation-status",{body:{email:oe}});J!=null&&J.needsActivation&&C(oe)}catch{}}finally{d(!1)}},V=async()=>{if(S){I(!0);try{const{data:K,error:Z}=await U.functions.invoke("send-password-reset",{body:{email:S,variant:"activation"}});if(Z)throw Z;if((K==null?void 0:K.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");P(!0),ne.success("Activation email sent! Check your inbox.")}catch(K){ne.error(K instanceof Error?K.message:"Failed to send activation email")}finally{I(!1)}}},H=async()=>{if(!m){ne.error("Please enter your email address");return}g(!0);try{const{data:K,error:Z}=await U.functions.invoke("send-password-reset",{body:{email:m.trim().toLowerCase(),redirectTo:fOs}});if(Z)throw Z;if((K==null?void 0:K.sent)===!1){ne.error("We couldn't find a LevelUp account for that email. Double-check the address, or email hello@relevelup.com and we'll help.");return}ne.success("Password reset email sent! Check your inbox."),y(!1),p("")}catch(K){ne.error(K instanceof Error?K.message:"Failed to send reset email")}finally{g(!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(or,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(ka,{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:aLe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(be,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(_t,{className:"space-y-1 text-center pb-4",children:[e.jsx(Nt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(En,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsxs(Le,{children:[D&&e.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),e.jsx("p",{className:"mt-1 text-sm text-amber-800",children:D}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),S&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),e.jsx("p",{className:"mt-1 text-sm text-gray-700",children:E?`We just emailed ${S} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${S} is ready — it just needs a password. We'll email you a link to set one.`}),!E&&e.jsx(z,{type:"button",onClick:V,disabled:M,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:M?"Sending...":"Email me a set-password link"})]}),e.jsxs("form",{onSubmit:G,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(pe,{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(ee,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(pe,{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(z,{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(Is,{open:v,onOpenChange:y,children:[e.jsx(rl,{asChild:!0,children:e.jsx(z,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Ls,{className:"bg-white",children:[e.jsxs(Os,{children:[e.jsx(Rs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(_r,{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(ee,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(pe,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:K=>p(K.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(z,{onClick:H,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:f,children:f?"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(or,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},cgt=()=>U.auth.oauth,vOs="https://dashboard.relevelup.com",bOs="/oauth-connect",H4e="levelupOAuthRouteHistory",_Os="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",wOs="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function jOs(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function NOs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(H4e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(H4e,JSON.stringify([{route:s,at:t}])),!1}}function kOs(){sessionStorage.removeItem(H4e)}async function dgt(s,t,n){const r=await fetch(`${_Os}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:wOs,"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 o7e(){var g;const{user:s,session:t,loading:n}=hs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=Gl(),l=i.get("authorization_id")??"",[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(!1);_.useEffect(()=>{let v=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const y=`${bOs}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${vOs}${y}`;return}if(n)return;if(!r){if(NOs("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}jOs(y)&&sessionStorage.setItem("redirectAfterLogin",y),window.location.replace(`/auth?next=${encodeURIComponent(y)}`);return}if(!a)return;kOs(),sessionStorage.removeItem("redirectAfterLogin");const b=cgt(),{data:w,error:S}=b?await b.getAuthorizationDetails(l):await dgt(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!v)return;if(S){u(S.message);return}const C=(w==null?void 0:w.redirect_url)??(w==null?void 0:w.redirect_to);if(C&&!(w!=null&&w.client)){window.location.href=C;return}c(w)})(),()=>{v=!1}},[a,l,n,r]);async function p(v){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const y=cgt(),{data:b,error:w}=y?v?await y.approveAuthorization(l,{skipBrowserRedirect:!0}):await y.denyAuthorization(l,{skipBrowserRedirect:!0}):await dgt(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:v?"approve":"deny"})});if(w){m(!1),u(w.message);return}const S=(b==null?void 0:b.redirect_url)??(b==null?void 0:b.redirect_to);if(!S){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=S}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(be,{className:"w-full max-w-md",children:e.jsxs(_t,{children:[e.jsx(Nt,{children:"Authorization error"}),e.jsx(En,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-primary"})});const f=((g=o.client)==null?void 0:g.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{children:["Connect ",f," to LevelUp"]}),e.jsxs(En,{children:[f," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Le,{className:"flex gap-3 justify-end",children:[e.jsx(z,{variant:"outline",disabled:h,onClick:()=>p(!1),children:"Deny"}),e.jsx(z,{disabled:h,onClick:()=>p(!0),children:h?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const SOs="https://chatgpt.com/plugins/plugin_asdk_app_6a7b9baf757081918ac4ab6fcbdb2639?q=levelup",ugt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",COs="https://tile-portal.lovable.app/mcp-oauth-bridge.html",AOs=[{label:"Open the ChatGPT Store",description:"Use the button below to open the LevelUp plugin page in the ChatGPT Store."},{label:"Install the plugin",description:"Tap Install. ChatGPT Plus, Pro, or Team is required to use plugins."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my contacts'."}],EOs=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to add custom MCP connectors."},{label:"Add a new connector",description:"Settings → Connectors → Add. Choose 'Custom / MCP Server'."},{label:"Fill in the basics",description:"Name it LevelUp and add a short description like 'Tools for the LevelUp real estate platform.'"},{label:"Paste the server URL",description:"Paste the MCP server URL below into the Server URL field. Do not paste the tile-portal bridge URL."},{label:"Confirm OAuth",description:"Authentication should be OAuth. Check the 'I understand' box, then tap Create."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my contacts'."}];function TOs(){const[s,t]=_.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(ugt),t(!0),ne.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ne.error("Could not copy URL")}};return e.jsx($s,{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(K4,{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:"Install the official LevelUp plugin from the ChatGPT Store."})]})]}),e.jsxs(be,{className:"border-primary/20 bg-primary/5",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Install from the ChatGPT Store"]}),e.jsx(En,{children:"The easiest way to connect. Tap the button below, then install the LevelUp plugin in ChatGPT."})]}),e.jsx(Le,{children:e.jsx(z,{asChild:!0,size:"lg",className:"w-full sm:w-auto",children:e.jsxs("a",{href:SOs,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Open LevelUp in the ChatGPT Store"]})})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Quick steps"}),e.jsx(En,{children:"Share these steps with any agent who wants to connect via the plugin store."})]}),e.jsx(Le,{children:e.jsx("ol",{className:"space-y-4",children:AOs.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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Manual MCP setup"}),e.jsx(En,{children:"Only use this if you are adding LevelUp as a custom MCP server instead of installing the store plugin."})]}),e.jsxs(Le,{className:"space-y-6",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:ugt}),e.jsx(z,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Xl,{className:"h-4 w-4 text-green-600"}):e.jsx(Sa,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(nl,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2",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:COs}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})}),e.jsx("ol",{className:"space-y-4",children:EOs.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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"What ChatGPT can see"}),e.jsx(En,{children:"The connector acts as you. Before connecting, review exactly which data it can reach, who receives it, how long it is kept and how to disconnect."})]}),e.jsxs(Le,{className:"flex flex-wrap gap-4 text-sm",children:[e.jsx("a",{href:"/mcp-data-use",className:"text-primary underline underline-offset-4",children:"MCP data use"}),e.jsx("a",{href:"/privacy-policy",className:"text-primary underline underline-offset-4",children:"Privacy Policy"}),e.jsx("a",{href:"/data-deletion",className:"text-primary underline underline-offset-4",children:"Data deletion"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(mr,{className:"h-4 w-4"}),e.jsx("span",{children:"Publishing, activating, merging and deleting always ask you to confirm first, and new open houses and pages start as unpublished drafts."})]})]})})}const MOs=()=>{const[s]=Gl(),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(be,{className:"max-w-lg w-full",children:[e.jsxs(_t,{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(Xl,{className:"w-10 h-10 text-green-500"})}),e.jsx(Nt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(En,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Le,{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(on,{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."})})]})]})})},POs=()=>{const{user:s}=hs(),[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState(""),o=async u=>{var h;if(!(s!=null&&s.email)){ne.error("Please sign in to upgrade");return}n(!0),a(u);try{const{data:m,error:p}=await U.functions.invoke("create-checkout",{body:{tier:u,email:s.email,name:((h=s.user_metadata)==null?void 0:h.full_name)||s.email,userId:s.id,couponCode:i.trim()||void 0,skipTrial:!0}});if(p)throw p;if(m!=null&&m.url)window.open(m.url,"_blank","noopener,noreferrer"),ne.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(m){console.error("Checkout error:",m),ne.error(m.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, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"];return e.jsx($s,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(ee,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(pe,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:u=>l(u.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 mb-8 max-w-4xl mx-auto",children:[e.jsxs(be,{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(_t,{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(On,{className:"h-7 w-7 text-primary"})}),e.jsx(Nt,{className:"text-xl",children:"Individual Agent"}),e.jsx(En,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Le,{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((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Wr,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs(z,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(be,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(_t,{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(oi,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Nt,{className:"text-xl",children:"Brokerage"}),e.jsx(En,{children:"Unlimited agents — everything in Individual, plus brokerage tools"})]}),e.jsxs(Le,{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:d.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Wr,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs(z,{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(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(be,{className:"bg-muted/50",children:e.jsxs(Le,{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(va,{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(on,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},LOs=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=hs(),a=zn(),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(!1);_.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),_.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){ne.error("Please enter a brokerage name");return}const{data:m}=await U.auth.getSession(),p=m.session;if(!s||!p){ne.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!p,userId:s==null?void 0:s.id});const{data:f,error:g}=await U.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:f,error:g}),g)throw g;if(!(f!=null&&f.ok))throw new Error((f==null?void 0:f.error)||"Failed to create brokerage");c(!1),u(!0),ne.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(f){console.error("Error creating brokerage:",f),ne.error(f.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(be,{className:"max-w-lg w-full",children:[e.jsxs(_t,{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(bt,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Nt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(En,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Xl,{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(bt,{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(be,{className:"max-w-lg w-full",children:[e.jsxs(_t,{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(oi,{className:"w-10 h-10 text-primary"})}),e.jsx(Nt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(En,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(On,{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(Xl,{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(Xl,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Xl,{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(Xl,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(z,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(Da,{className:"w-4 h-4 ml-2"})]})]})]})})},hgt=()=>{const s=zn(),[t,n]=_.useState("verifying"),[r,a]=_.useState("");_.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await U.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await U.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await U.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{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(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{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(Nt,{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(En,{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(Le,{children:e.jsx(z,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},Ile="https://dashboard.relevelup.com",mgt=()=>{const[s,t]=_.useState(!1),n=_.useMemo(()=>new URLSearchParams(window.location.search),[]),r=_.useMemo(()=>n.get("link"),[n]),a=_.useMemo(()=>n.get("type")||"recovery",[n]),i=_.useMemo(()=>{switch(a){case"claim":return{title:"Claim Your Account",cta:"Continue to Claim Account",doc:"Claim Your LevelUp Account"};case"magiclink":return{title:"Sign In to LevelUp",cta:"Continue to Sign In",doc:"Sign In to LevelUp"};case"email_change":return{title:"Confirm Your Email",cta:"Continue to Confirm Email",doc:"Confirm Your Email"};default:return{title:"Reset Your Password",cta:"Continue to Reset Password",doc:"Reset Your Password"}}},[a]),l=_.useMemo(()=>{if(!r)return!1;try{const f=new URL(r);return f.hostname.endsWith(".supabase.co")&&f.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);_.useEffect(()=>{document.title=i.doc},[i]);const[o,c]=_.useState(null),[d,u]=_.useState("idle"),h=_.useMemo(()=>{if(!r)return null;try{return new URL(r).searchParams.get("email")}catch{return null}},[r]),m=async()=>{var f;u("sending");try{const g=h||((f=window.prompt("Enter the email address on your LevelUp account:"))==null?void 0:f.trim());if(!g){u("idle");return}const{error:v}=await U.functions.invoke("send-password-reset",{body:{email:g,variant:a==="recovery"?"reset":"activation"}});u(v?"failed":"sent")}catch{u("failed")}},p=async()=>{if(!(!l||!r)){if(t(!0),c(null),window.location.origin!==Ile&&window.location.hostname!=="localhost"){window.location.href=`${Ile}${window.location.pathname}${window.location.search}`;return}try{const f=new URL(r),g=f.searchParams.get("token")||f.searchParams.get("token_hash"),v=f.searchParams.get("type")||(a==="claim"?"invite":a);if(g){const{error:y}=await U.auth.verifyOtp({token_hash:g,type:v});if(!y){const b=f.searchParams.get("redirect_to");let w=v==="recovery"?"/profile?reset=true":"/dashboard";if(b)try{const S=new URL(b);w=`${S.pathname}${S.search}`}catch{}window.location.replace(`${Ile}${w}`);return}t(!1),c("This link is invalid or has already been used. Please request a new email.");return}}catch{}window.location.href=r}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:aLe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(be,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(_t,{className:"text-center",children:[e.jsx(Nt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:i.title}),e.jsx(En,{className:"text-gray-600 pt-2",children:o||(l?"Click the button below to continue securely.":"This link is invalid or has expired. Please request a new email from the sign-in page.")})]}),e.jsxs(Le,{className:"space-y-4",children:[l&&!o?e.jsx(z,{onClick:p,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…":i.cta}):d==="sent"?e.jsx("div",{className:"rounded-lg bg-emerald-50 border border-emerald-200 p-4 text-center text-sm text-emerald-800",children:"A fresh link is on its way — check your inbox in the next minute or two."}):e.jsxs(e.Fragment,{children:[e.jsx(z,{onClick:m,disabled:d==="sending",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:d==="sending"?"Sending…":"Email me a fresh link"}),d==="failed"&&e.jsx("p",{className:"text-xs text-center text-red-600",children:"We couldn't send that just now. Please try again in a moment."}),e.jsx(z,{variant:"outline",onClick:()=>window.location.href=`${Ile}/auth`,className:"w-full py-6 text-base",children:"Go to Sign In"})]}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, these links expire and can only be used once."})]})]})]})})]})},Dle="https://dashboard.relevelup.com",IOs=()=>{const s=_.useMemo(()=>new URLSearchParams(window.location.search).get("a")||"",[]),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(null);_.useEffect(()=>{document.title="Activate Your LevelUp Account"},[]),_.useEffect(()=>{let h=!1;return(async()=>{if(!s){c("This link is missing information. Please use the button in your LevelUp email."),a(!1);return}const{data:p,error:f}=await U.functions.invoke("activation-link",{body:{action:"info",ref:s}});h||(f||!(p!=null&&p.ok)?c("We could not recognize this link. Please use the button in your latest LevelUp email."):n({email:p.email,name:p.name,brokerage_name:p.brokerage_name}),a(!1))})(),()=>{h=!0}},[s]);const d=async()=>{if(l(!0),c(null),window.location.origin!==Dle&&window.location.hostname!=="localhost"){window.location.href=`${Dle}${window.location.pathname}${window.location.search}`;return}try{const{data:h,error:m}=await U.functions.invoke("activation-link",{body:{action:"start",ref:s}});if(m||!(h!=null&&h.ok)||!h.token_hash)throw new Error("link_failed");const{error:p}=await U.auth.verifyOtp({token_hash:h.token_hash,type:h.type==="invite"?"invite":"recovery"});if(p)throw p;window.location.replace(`${Dle}/profile?reset=true&activation=1`)}catch{l(!1),c("Something went wrong signing you in. Please try again in a moment.")}},u=((t==null?void 0:t.name)||"").trim().split(/\s+/)[0];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:aLe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(be,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(_t,{className:"text-center",children:[e.jsx(Nt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:u?`Welcome, ${u}`:"Activate Your Account"}),e.jsx(En,{className:"text-gray-600 pt-2",children:r?"Loading your account…":o||(t!=null&&t.brokerage_name?`${t.brokerage_name} provides LevelUp for you. Sign in below to set your password.`:"Sign in below to set your password and get started.")})]}),e.jsxs(Le,{className:"space-y-4",children:[t&&e.jsxs("div",{className:"rounded-lg bg-gray-50 border border-gray-200 p-4 text-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500",children:"Your login email"}),e.jsx("p",{className:"text-base font-semibold text-[#2a4347] break-all",children:t.email})]}),t?e.jsx(z,{onClick:d,disabled:i,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:i?"Signing you in…":"Sign me in"}):r?null:e.jsx(z,{onClick:()=>window.location.href=`${Dle}/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:"No password needed — we'll sign you in and let you choose one."})]})]})]})})]})},DOs=()=>{const s=zn(),[t]=Gl(),[n,r]=_.useState(t.get("code")||""),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState(!1),[v,y]=_.useState(!1),[b,w]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(null),[M,I]=_.useState(null);_.useEffect(()=>{const G=t.get("code");G&&(r(G),D(G))},[t]);const D=async G=>{g(!0);const{data:V,error:H}=await U.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",G.toUpperCase().trim()).single();if(H||!V){ne.error("Invalid invite code"),g(!1);return}if(!V.is_active){ne.error("This invite code is no longer active"),g(!1);return}if(V.max_uses&&V.uses_count>=V.max_uses){ne.error("This invite code has reached its maximum uses"),g(!1);return}if(V.expires_at&&new Date(V.expires_at){G.preventDefault(),D(n)},q=async G=>{var V;if(G.preventDefault(),!c.trim()){ne.error("Please enter your name");return}if(l.length<6){ne.error("Password must be at least 6 characters");return}p(!0);try{const H="https://dashboard.relevelup.com/",{data:K,error:Z}=await U.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:H,data:{name:c.trim()}}});if(Z){Z.message.includes("already registered")?ne.error("This email is already registered. Please sign in instead."):ne.error(Z.message);return}if(K.user){await U.rpc("add_default_signup_tag",{user_id:K.user.id});const oe=n.toUpperCase().trim();S?await U.functions.invoke("assign-brokerage",{body:{userId:K.user.id,brokerageId:S,inviteCode:oe}}):M?await U.functions.invoke("assign-brokerage",{body:{userId:K.user.id,trialDays:M,inviteCode:oe}}):await U.functions.invoke("assign-brokerage",{body:{userId:K.user.id,grandfathered:!0,inviteCode:oe}}),b&&await U.from("invite_codes").update({uses_count:((V=(await U.from("invite_codes").select("uses_count").eq("id",b).single()).data)==null?void 0:V.uses_count)+1}).eq("id",b),ne.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(H){console.error("Signup error:",H),ne.error("An unexpected error occurred")}finally{p(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{className:"text-center",children:[e.jsx(Nt,{className:"text-2xl font-bold text-primary",children:E?`Join ${E}`:"Join LevelUp"}),e.jsx(En,{children:v?E?`Create your account to join ${E}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Le,{children:v?e.jsxs("form",{onSubmit:q,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Full Name"}),e.jsx(pe,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:G=>d(G.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:G=>i(G.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:G=>o(G.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>h(!u),children:u?e.jsx(Yf,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})})]})]}),e.jsx(z,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:F,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(pe,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:G=>r(G.target.value),required:!0,autoFocus:!0})]}),e.jsx(z,{type:"submit",className:"w-full",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},cae=()=>{const{user:s,isCoach:t}=hs();return rt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await U.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},ROs=()=>{const{data:s}=cae();return rt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 U.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}))}})},get=()=>{const{user:s}=hs();return rt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 U.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},FOs=s=>rt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),yet=s=>rt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),vet=s=>rt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),OOs=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function zOs(){const s=zn(),{data:t,isLoading:n}=cae(),{data:r=[],isLoading:a}=ROs();if(n)return e.jsx($s,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx($s,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(fm,{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."})]})});OOs.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($s,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(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(l7e,{icon:fm,label:"Active agents",value:i}),e.jsx(l7e,{icon:gc,label:"This month",value:"—"}),e.jsx(l7e,{icon:vu,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(z,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(z,{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(be,{children:e.jsx(Le,{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(be,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Le,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(ja,{className:"h-14 w-14",children:[e.jsx(xi,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(Na,{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(Da,{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 ",Md(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function l7e({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 F9t({assignmentId:s}){const{user:t}=hs(),n=$t(),[r,a]=_.useState(""),[i,l]=_.useState(!1),o=_.useRef(null),{data:c=[]}=rt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await U.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});_.useEffect(()=>{if(!s)return;const u=U.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{U.removeChannel(u)}},[s,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 U.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(be,{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:Ct("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(ja,{className:"h-8 w-8 mt-1",children:e.jsx(Na,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Ct("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:Ct("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:Md(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Le,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ps,{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(z,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(Fr,{className:"h-4 w-4"})})]})})]})}var bet="Progress",_et=100,[BOs,mwr]=uf(bet),[$Os,UOs]=BOs(bet),O9t=_.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=qOs,...l}=s;(a||a===0)&&!pgt(a)&&console.error(VOs(`${a}`,"Progress"));const o=pgt(a)?a:_et;r!==null&&!fgt(r,o)&&console.error(HOs(`${r}`,"Progress"));const c=fgt(r,o)?r:null,d=OAe(c)?i(c,o):void 0;return e.jsx($Os,{scope:n,value:c,max:o,children:e.jsx(ci.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":OAe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":$9t(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});O9t.displayName=bet;var z9t="ProgressIndicator",B9t=_.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=UOs(z9t,n);return e.jsx(ci.div,{"data-state":$9t(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});B9t.displayName=z9t;function qOs(s,t){return`${Math.round(s/t*100)}%`}function $9t(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function OAe(s){return typeof s=="number"}function pgt(s){return OAe(s)&&!isNaN(s)&&s>0}function fgt(s,t){return OAe(s)&&!isNaN(s)&&s<=t&&s>=0}function VOs(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${_et}\`.`}function HOs(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 ${_et} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var U9t=O9t,GOs=B9t;const Di=_.forwardRef(({className:s,value:t,...n},r)=>e.jsx(U9t,{ref:r,className:Ct("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(GOs,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Di.displayName=U9t.displayName;function q9t({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=rt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:g,error:v}=await U.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 g||[]}}),{data:i}=rt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:g}=await U.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return g}}),l=a.filter(g=>g.is_win),o=l.length,c=l.reduce((g,v)=>g+(Number(v.sale_price)||0),0),d=l.reduce((g,v)=>g+(Number(v.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,p=(u==null?void 0:u.gci_goal)||0,f=g=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g);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(kl,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(c7e,{icon:Kh,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(c7e,{icon:kl,label:"Volume",value:f(c),goal:m,current:c,suffix:m?`of ${f(m)}`:""}),e.jsx(c7e,{icon:Nd,label:"GCI",value:f(d),goal:p,current:d,suffix:p?`of ${f(p)}`:""})]}),o===0&&e.jsx(be,{children:e.jsxs(Le,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function c7e({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(be,{children:e.jsxs(Le,{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(Di,{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 V9t({assignmentId:s,canEdit:t}){const n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState(null),{data:o=[]}=rt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>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(bu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(z,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),m=u>0?Math.min(100,h/u*100):0;return e.jsx(be,{children:e.jsxs(Le,{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(z,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})})]}),u>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[h.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[m.toFixed(0),"%"]})]}),e.jsx(Di,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Ys(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(WOs,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function WOs({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var S,C;const[i,l]=_.useState((r==null?void 0:r.title)||""),[o,c]=_.useState((r==null?void 0:r.description)||""),[d,u]=_.useState((r==null?void 0:r.target_metric)||""),[h,m]=_.useState(((S=r==null?void 0:r.target_value)==null?void 0:S.toString())||""),[p,f]=_.useState(((C=r==null?void 0:r.current_value)==null?void 0:C.toString())||"0"),[g,v]=_.useState((r==null?void 0:r.due_date)||""),[y,b]=_.useState(!1);_.useState(()=>{var E,P;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((E=r==null?void 0:r.target_value)==null?void 0:E.toString())||""),f(((P=r==null?void 0:r.current_value)==null?void 0:P.toString())||"0"),v((r==null?void 0:r.due_date)||"")});const w=async()=>{if(!i.trim())return;b(!0);const E={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:p?Number(p):0,due_date:g||null},{error:P}=r!=null&&r.id?await U.from("coaching_goals").update(E).eq("id",r.id):await U.from("coaching_goals").insert(E);if(b(!1),P)return ne.error(P.message);ne.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Title",value:i,onChange:E=>l(E.target.value)}),e.jsx(Ps,{placeholder:"Description (optional)",rows:2,value:o,onChange:E=>c(E.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(pe,{placeholder:"transactions",value:d,onChange:E=>u(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(pe,{type:"number",value:h,onChange:E=>m(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(pe,{type:"number",value:p,onChange:E=>f(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(pe,{type:"date",value:g,onChange:E=>v(E.target.value)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:w,disabled:y,children:r!=null&&r.id?"Save":"Create"})]})]})})}function H9t({assignmentId:s}){const t=$t(),{user:n}=hs(),r=_.useRef(null),[a,i]=_.useState(!1),{data:l=[]}=rt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await U.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var p;const m=(p=h.target.files)==null?void 0:p[0];if(!(!m||!n)){i(!0);try{const f=`${s}/${Date.now()}-${m.name}`,{error:g}=await U.storage.from("coaching-files").upload(f,m);if(g)throw g;const{error:v}=await U.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:f,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(v)throw v;ne.success("File uploaded"),o()}catch(f){ne.error(f.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:p}=await U.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(p||!m)return ne.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await Qi("Delete this file?")&&(await U.storage.from("coaching-files").remove([h.file_url]),await U.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(z,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(Ra,{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(be,{children:e.jsx(Le,{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(be,{children:e.jsxs(Le,{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($r,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.file_size_bytes?`${(h.file_size_bytes/1024).toFixed(0)} KB · `:"",Ys(new Date(h.created_at),"PP")]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(Ga,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(Cn,{className:"h-4 w-4"})})]})},h.id))})]})}function KOs(){var m,p,f,g;const{id:s}=Mi(),t=zn(),n=$t(),{data:r,isLoading:a}=FOs(s),{data:i=[]}=yet(s),{data:l=[]}=vet(s),[o,c]=_.useState(!1),[d,u]=_.useState(!1);if(a)return e.jsx($s,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx($s,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs($s,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Le,{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(ja,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(xi,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(Na,{className:"text-2xl",children:(((p=h.agent)==null?void 0:p.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((f=h.agent)==null?void 0:f.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(g=h.agent)==null?void 0:g.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(ZOs,{value:h.pipeline_stage||"active",onChange:async v=>{await U.from("coaching_assignments").update({pipeline_stage:v}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(YOs,{assignment:h}),e.jsxs(Qr,{defaultValue:"sessions",children:[e.jsxs(Jr,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Wt,{value:"sessions",children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Wt,{value:"actions",children:[e.jsx(k0,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Wt,{value:"goals",children:[e.jsx(bu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Wt,{value:"kpis",children:[e.jsx(kl,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Wt,{value:"messages",children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Wt,{value:"files",children:[e.jsx(wv,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Wt,{value:"notes",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Kt,{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(z,{size:"sm",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(be,{children:e.jsx(Le,{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(be,{children:e.jsx(Le,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:Ys(new Date(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.zoom_join_url&&e.jsx("a",{href:v.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),v.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",v.agenda]}),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(Hl,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:v.private_notes})]})]})})})},v.id))})]}),e.jsxs(Kt,{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(z,{size:"sm",onClick:()=>u(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(be,{children:e.jsx(Le,{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(be,{children:e.jsxs(Le,{className:"p-3 flex items-center gap-3",children:[e.jsx(za,{checked:v.status==="done",onCheckedChange:async y=>{await U.from("coaching_action_items").update({status:y?"done":"open",completed_at:y?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:Ys(new Date(v.due_date),"MMM d")}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))})]}),e.jsx(Kt,{value:"goals",children:e.jsx(V9t,{assignmentId:h.id,canEdit:!0})}),e.jsx(Kt,{value:"kpis",children:h.agent_id&&e.jsx(q9t,{agentUserId:h.agent_id})}),e.jsx(Kt,{value:"messages",children:e.jsx(F9t,{assignmentId:h.id})}),e.jsx(Kt,{value:"files",children:e.jsx(H9t,{assignmentId:h.id})}),e.jsx(Kt,{value:"notes",className:"space-y-4",children:e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(XOs,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(QOs,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function YOs({assignment:s}){const t=$t(),[n,r]=_.useState(s.sessions_per_month==null?"":String(s.sessions_per_month)),[a,i]=_.useState(!1),l=async()=>{i(!0);const o=n.trim()===""?null:Math.max(1,parseInt(n,10)||1),{error:c}=await U.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return ne.error(c.message);ne.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"})," Monthly session allowance"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use your coach default. This agent books these on their My Coach page."})]}),e.jsx(pe,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs(z,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function ZOs({value:s,onChange:t}){return e.jsxs(ls,{value:s,onValueChange:t,children:[e.jsx(rs,{className:"w-40",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"onboarding",children:"Onboarding"}),e.jsx(He,{value:"active",children:"Active"}),e.jsx(He,{value:"thriving",children:"Thriving"}),e.jsx(He,{value:"at_risk",children:"At Risk"}),e.jsx(He,{value:"graduated",children:"Graduated"})]})]})}function XOs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=_.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=_.useState(60),[c,d]=_.useState("weekly_1on1"),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(!1),[v,y]=_.useState(!0),[b,w]=_.useState(null),[S,C]=_.useState(!1),E=async()=>{C(!0);const{data:M,error:I}=await U.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(C(!1),I||M!=null&&M.error)return ne.error((M==null?void 0:M.error)||(I==null?void 0:I.message)||"Failed to generate brief");w(M.brief||"No brief returned.")},P=async()=>{g(!0);const{data:M,error:I}=await U.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:m,status:"completed"}).select("id").maybeSingle();if(I)return g(!1),ne.error(I.message);if(ne.success("Session saved"),v&&u.trim()&&(M!=null&&M.id)){const{error:D}=await U.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});D?ne.error("Saved, but recap email failed: "+D.message):ne.success("Recap emailed to agent")}g(!1),r==null||r(),t(!1),h(""),p(""),w(null)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Rs,{children:"New Session"}),e.jsxs(z,{size:"sm",variant:"outline",onClick:E,disabled:S,children:[S?e.jsx(bt,{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:[b&&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"]}),b]}),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(pe,{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(pe,{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(ls,{value:c,onValueChange:d,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(He,{value:"grow",children:"GROW Model"}),e.jsx(He,{value:"goal_review",children:"Goal Review"}),e.jsx(He,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ps,{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(Hl,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ps,{rows:3,value:m,onChange:M=>p(M.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(za,{checked:v,onCheckedChange:M=>y(!!M)}),e.jsx(Fr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:P,disabled:f,children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function QOs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState("medium"),[m,p]=_.useState(!1),f=async()=>{if(!a.trim())return;p(!0);const{error:g}=await U.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(p(!1),g)return ne.error(g.message);ne.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Title",value:a,onChange:g=>i(g.target.value)}),e.jsx(Ps,{rows:3,placeholder:"Description (optional)",value:l,onChange:g=>o(g.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(pe,{type:"date",value:c,onChange:g=>d(g.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(ls,{value:u,onValueChange:h,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"low",children:"Low"}),e.jsx(He,{value:"medium",children:"Medium"}),e.jsx(He,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:f,disabled:m,children:"Add"})]})]})})}function VVe({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(Ia,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function JOs({coachId:s}){const[t,n]=_.useState([]),[r,a]=_.useState(!0);_.useEffect(()=>{(async()=>{const{data:l}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await U.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(VVe,{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(be,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(xi,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(Na,{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(VVe,{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 e7s({coachId:s,assignmentId:t}){const{user:n}=hs(),[r,a]=_.useState(null),[i,l]=_.useState(0),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(!1);_.useEffect(()=>{n&&(async()=>{const{data:f}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();f&&(a(f),l(f.rating),c(f.title||""),u(f.body||""))})()},[n,s]);const p=async()=>{if(!n)return;if(!i)return ne.error("Pick a rating");m(!0);const f={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:g}=r?await U.from("coaching_reviews").update(f).eq("id",r.id):await U.from("coaching_reviews").insert(f);if(m(!1),g)return ne.error(g.message);ne.success("Thanks for your review!"),a({...f,id:r==null?void 0:r.id})};return e.jsx(be,{children:e.jsxs(Le,{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(VVe,{value:i,size:28,onChange:l}),e.jsx(pe,{placeholder:"Title (optional)",value:o,onChange:f=>c(f.target.value)}),e.jsx(Ps,{rows:4,placeholder:"What was your experience like?",value:d,onChange:f=>u(f.target.value)}),e.jsx(z,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const Rle=async s=>{var r,a;const{data:t,error:n}=await U.functions.invoke("coaching-booking",{body:s});if(n){const i=(r=n==null?void 0:n.context)!=null&&r.text?await n.context.text():n.message;let l=i;try{l=((a=JSON.parse(i))==null?void 0:a.error)||i}catch{}throw new Error(l)}if(t!=null&&t.error)throw new Error(t.error);return t},d7e=s=>Ys(s,"yyyy-MM-dd"),xgt=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function t7s({assignmentId:s,upcoming:t=[]}){const n=$t(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState(!1),{data:p,isLoading:f}=rt({queryKey:["coaching-booking-context",s],queryFn:()=>Rle({action:"context"})});_.useEffect(()=>{var oe;!r&&((oe=p==null?void 0:p.booking_types)!=null&&oe.length)&&a(p.booking_types[0].id)},[p,r]);const g=_.useMemo(()=>new Date,[]),[v,y]=_.useState(()=>om(new Date)),b=(p==null?void 0:p.max_advance_days)||30,w=_.useMemo(()=>Uh(zf(g),b-1),[g,b]),S=_.useMemo(()=>{const oe=om(v);return oe{const oe=b_(v);return oe>w?w:oe},[v,w]),E=Math.max(0,fv(C,S)+1),{data:P={},isFetching:M}=rt({queryKey:["coaching-availability",r,d7e(S),E],enabled:!!r&&E>0,queryFn:async()=>(await Rle({action:"availability",booking_type_id:r,start:d7e(S),days:E})).availability||{}}),I=_.useMemo(()=>{const oe=om(v),re=b_(v).getDate(),ae=oe.getDay(),J=Array.from({length:ae},()=>null);for(let te=0;teObject.entries(P).filter(([,oe])=>oe.length>0),[P]),F=i?P[i]||[]:[],q=M,G=_.useMemo(()=>{const oe=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const re of F){const ae=Number(re.split(":")[0]);ae<12?oe[0].items.push(re):ae<17?oe[1].items.push(re):oe[2].items.push(re)}return oe.filter(re=>re.items.length>0)},[F]),V=(p==null?void 0:p.booking_types.find(oe=>oe.id===r))||null,H=((p==null?void 0:p.sessions_remaining)??0)<=0,K=async()=>{if(!(!r||!i||!o)){m(!0);try{await Rle({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),ne.success("Session booked — check your Zoom link below."),c(null),u(""),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-availability"]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(oe){ne.error(oe.message||"Could not book that session")}finally{m(!1)}}},Z=async oe=>{if(await Qi("Cancel this coaching session?"))try{await Rle({action:"cancel",session_id:oe}),ne.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(re){ne.error(re.message||"Could not cancel")}};return f?e.jsx(be,{children:e.jsxs(Le,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading your coach's calendar…"]})}):p!=null&&p.scheduler_ready?e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(gc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[p.sessions_remaining," of ",p.sessions_limit," sessions left this month"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your allowance resets on the 1st."})]})]}),H&&e.jsx(ze,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(oe=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-3 rounded-lg border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:Ys(new Date(oe.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[oe.duration_minutes||30," minutes"]})]}),oe.zoom_join_url&&e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:oe.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>Z(oe.id),children:[e.jsx(Bd,{className:"h-4 w-4 mr-1"})," Cancel"]})]},oe.id))]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"mb-2 block",children:"Session type"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.booking_types.map(oe=>e.jsxs("button",{onClick:()=>{a(oe.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===oe.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:oe.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," ",oe.duration_minutes," min"]}),oe.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:oe.description})]},oe.id))})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:eae(v,g),onClick:()=>y(A0(v,-1)),"aria-label":"Previous month",children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Ys(v,"MMMM yyyy")}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:om(A0(v,1))>w,onClick:()=>y(A0(v,1)),"aria-label":"Next month",children:e.jsx(yi,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:["S","M","T","W","T","F","S"].map((oe,re)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:oe},re))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:I.map((oe,re)=>{if(!oe)return e.jsx("div",{},`b${re}`);const ae=d7e(oe),J=(P[ae]||[]).length,ce=oe>=zf(g)&&oe<=w&&J>0,ve=i===ae;return e.jsxs("button",{disabled:!ce,onClick:()=>{l(ae),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${ve?"border-primary bg-primary text-primary-foreground":ce?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:ce?`${J} opening${J===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:Ys(oe,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${ve?"bg-primary-foreground":ce?"bg-primary":"bg-transparent"}`})]},ae)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:M?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-3 w-3 text-primary"}),D.length===0?"No openings this month — try the next month.":`${D.length} day${D.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-2 block",children:i?`Available times · ${Ys(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?q?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):F.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No openings on this day — try another date."}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:G.map(oe=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:oe.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:oe.items.map(re=>e.jsx("button",{onClick:()=>c(re),className:`py-2 rounded-lg border text-sm transition-colors ${o===re?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:xgt(re)},re))})]},oe.label))}):e.jsx("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground text-center",children:"Select a highlighted day to see open times."}),!M&&D.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:D.slice(0,3).map(([oe,re])=>e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{l(oe),c(null)},children:[Ys(new Date(`${oe}T12:00:00`),"EEE MMM d")," · ",re.length," open"]},oe))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Ps,{id:"agenda",rows:3,value:d,onChange:oe=>u(oe.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs(z,{onClick:K,disabled:h||H,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Mr,{className:"h-4 w-4 mr-1"}),"Book ",V==null?void 0:V.name," — ",i&&Ys(new Date(`${i}T12:00:00`),"MMM d")," at ",xgt(o)]}),H&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You've used your sessions for this month. Message your coach if you need more."})]})]})})]}):e.jsx(be,{children:e.jsx(Le,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function s7s(){const{user:s}=hs(),{isMember:t,pkg:n}=OS(),{data:r}=rt({queryKey:["coaching-prep-member",s==null?void 0:s.id,n==null?void 0:n.id],enabled:!!(s!=null&&s.id)&&!!(n!=null&&n.id),queryFn:async()=>{const[{data:l},{data:o},{data:c}]=await Promise.all([U.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",s.id).maybeSingle(),U.from("coaching_prep_checklist_items").select("*").eq("package_id",n.id).eq("is_active",!0).order("sort_order"),U.from("coaching_prep_checklist_state").select("item_id").eq("user_id",s.id)]),d=new Set((c||[]).map(u=>u.item_id));return{submitted:!!(l!=null&&l.submitted_at),items:(o||[]).map(u=>({...u,done:d.has(u.id)}))}}});if(!t||!(n!=null&&n.includes_coaching))return null;const a=(r==null?void 0:r.items)||[],i=a.filter(l=>l.done).length;return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Wf,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs(ze,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:"Onboarding questionnaire"}),e.jsx("div",{className:"text-muted-foreground text-xs",children:r!=null&&r.submitted?"Submitted — your coach has it.":"Complete this before session one."})]}),e.jsx(z,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(or,{to:"/coaching/onboarding",children:r!=null&&r.submitted?"Review":"Start"})})]}),a.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"What we're setting up for you"}),a.map(l=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[l.done?e.jsx(Mr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Gf,{className:"h-4 w-4 mt-0.5 text-muted-foreground/50"}),e.jsxs("span",{children:[e.jsx("span",{className:l.done?"text-muted-foreground line-through":"",children:l.title}),l.description&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.description})]})]},l.id))]})]})]})}function n7s(){var m,p,f,g,v,y;const{user:s}=hs(),{data:t,isLoading:n,refetch:r}=get(),a=$t(),i=t==null?void 0:t.id,{data:l=[]}=yet(i),{data:o=[]}=vet(i);if(_.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&U.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx($s,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx($s,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(fm,{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(b=>b.status!=="done"),u=o.length-d.length,h=l.filter(b=>b.status!=="cancelled"&&new Date(b.scheduled_at).getTime()>Date.now());return e.jsx($s,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(be,{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(ja,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(xi,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(Na,{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:[((v=c.coach)==null?void 0:v.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(u7e,{icon:k0,label:"Open action items",value:d.length}),e.jsx(u7e,{icon:bu,label:"Completed",value:u}),e.jsx(u7e,{icon:ya,label:"Sessions",value:l.length})]}),e.jsx(s7s,{}),((y=c.coach)==null?void 0:y.id)&&e.jsx(e7s,{coachId:c.coach.id,assignmentId:i}),e.jsxs(Qr,{defaultValue:"book",children:[e.jsxs(Jr,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Wt,{value:"book",children:[e.jsx(v0,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Wt,{value:"actions",children:[e.jsx(k0,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Wt,{value:"sessions",children:[e.jsx(ya,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Wt,{value:"goals",children:[e.jsx(bu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Wt,{value:"kpis",children:[e.jsx(kl,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Wt,{value:"messages",children:[e.jsx(qi,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Wt,{value:"files",children:[e.jsx(wv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Kt,{value:"book",children:e.jsx(t7s,{assignmentId:i,upcoming:h})}),e.jsx(Kt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(b=>e.jsx(be,{children:e.jsxs(Le,{className:"p-3 flex items-center gap-3",children:[e.jsx(za,{checked:b.status==="done",onCheckedChange:async w=>{await U.from("coaching_action_items").update({status:w?"done":"open",completed_at:w?new Date().toISOString():null}).eq("id",b.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(ze,{variant:"outline",children:Ys(new Date(b.due_date),"MMM d")}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))}),e.jsx(Kt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(b=>e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Ys(new Date(b.scheduled_at),"PPp")}),e.jsx(ze,{variant:"outline",className:"capitalize",children:b.status})]}),b.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:b.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},b.id))}),e.jsx(Kt,{value:"goals",children:e.jsx(V9t,{assignmentId:i,canEdit:!1})}),e.jsx(Kt,{value:"kpis",children:s&&e.jsx(q9t,{agentUserId:s.id})}),e.jsx(Kt,{value:"messages",children:e.jsx(F9t,{assignmentId:i})}),e.jsx(Kt,{value:"files",children:e.jsx(H9t,{assignmentId:i})})]})]})})}function u7e({icon:s,label:t,value:n}){return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}const ggt="coaching_access",h7e=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),m7e=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function r7s(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState([]),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(""),{data:h=[],isLoading:m}=rt({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:D,error:F}=await U.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",ggt).order("enabled_at",{ascending:!1});if(F)throw F;return D||[]}}),{data:p=[]}=rt({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:D,error:F}=await U.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if(F)throw F;return D||[]}}),f=_.useMemo(()=>{const D=new Set;return h.forEach(F=>D.add(F.user_id)),p.forEach(F=>D.add(F.agent_id)),Array.from(D)},[h,p]),{data:g={}}=rt({queryKey:["coaching-access-profiles",f.join(",")],enabled:f.length>0,queryFn:async()=>{const D={};for(let F=0;F{D[G.id]=G})}return D}});_.useEffect(()=>{const D=t.trim();if(D.length<2){a([]),l(!1);return}l(!0);const F=setTimeout(async()=>{const{data:q}=await U.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${D}%,name.ilike.%${D}%`).limit(12);a(q||[]),l(!1)},250);return()=>clearTimeout(F)},[t]);const v=_.useMemo(()=>{const D=new Map;return h.forEach(F=>D.set(F.user_id,F)),D},[h]),y=_.useMemo(()=>new Set(p.map(D=>D.agent_id)),[p]),b=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},w=async(D,F={})=>{var V;const{data:q}=await U.auth.getUser(),{error:G}=await U.from("feature_entitlements").upsert({user_id:D,feature_key:ggt,enabled:F.enabled??!0,expires_at:F.expires_at??null,notes:F.notes??null,tier:F.tier??null,enabled_by:((V=q==null?void 0:q.user)==null?void 0:V.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return G?(ne.error(G.message),!1):(b(),!0)},S=async D=>{await w(D.id)&&ne.success(`Coaching access granted to ${D.name||D.email}`),n(""),a([])},C=async(D,F)=>{const{error:q}=await U.from("feature_entitlements").update({enabled:F,updated_at:new Date().toISOString()}).eq("id",D.id);if(q)return ne.error(q.message);ne.success(F?"Access enabled":"Access paused"),b()},E=async D=>{if(!await Qi({title:"Revoke coaching access?",description:`${D.profile.name||D.profile.email||"This member"} will lose access to the coaching area unless they're assigned to a coach.`,confirmText:"Revoke access",destructive:!0}))return;const{error:q}=await U.from("feature_entitlements").delete().eq("id",D.entitlement.id);if(q)return ne.error(q.message);ne.success("Coaching access revoked"),b()},P=_.useMemo(()=>{const D=d.trim().toLowerCase(),F=h.map(q=>({entitlement:q,profile:g[q.user_id]}));return D?F.filter(({profile:q})=>`${(q==null?void 0:q.name)||""} ${(q==null?void 0:q.email)||""}`.toLowerCase().includes(D)):F},[h,g,d]),M=h.filter(D=>D.enabled&&!m7e(D)).length,I=p.filter(D=>!v.has(D.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(p7e,{icon:Ch,label:"Granted access",value:M,hint:"Standalone entitlements"}),e.jsx(p7e,{icon:On,label:"Coached members",value:y.size,hint:"Active coach assignments"}),e.jsx(p7e,{icon:un,label:"Total with access",value:new Set([...h.filter(D=>D.enabled&&!m7e(D)).map(D=>D.user_id),...y]).size,hint:"Unique members"})]}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(iP,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Grant Coaching Access"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Give any member access to the coaching area — meeting notes, one-on-one scheduling and their coach workspace — even before a coach is assigned."}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:D=>n(D.target.value)})]}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-lg divide-y max-h-80 overflow-auto",children:i?e.jsxs("div",{className:"p-3 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Searching…"]}):r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No members found"}):r.map(D=>{const F=v.get(D.id),q=y.has(D.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:D.avatar_url||void 0}),e.jsx(Na,{className:"text-xs",children:h7e(D)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:D.name||D.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email})]}),F?e.jsx(ze,{variant:"outline",className:"shrink-0",children:"Already granted"}):q?e.jsxs(ze,{variant:"outline",className:"shrink-0",children:[e.jsx(Oc,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx(z,{size:"sm",variant:"outline",onClick:()=>c({profile:D}),children:"Options"}),e.jsxs(z,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>S(D),children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},D.id)})})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Ch,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx(ze,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(pe,{placeholder:"Filter list…",value:d,onChange:D=>u(D.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):P.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground border rounded-lg",children:"No standalone grants yet. Search above to give a member access."}):e.jsx("div",{className:"border rounded-lg divide-y",children:P.map(({entitlement:D,profile:F})=>{const q=m7e(D);return e.jsxs("div",{className:"flex items-center gap-3 p-3 flex-wrap",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(xi,{src:(F==null?void 0:F.avatar_url)||void 0}),e.jsx(Na,{className:"text-xs",children:h7e(F)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:(F==null?void 0:F.name)||(F==null?void 0:F.email)||D.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:F==null?void 0:F.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[q?e.jsx(ze,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):D.enabled?e.jsx(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx(ze,{variant:"outline",children:"Paused"}),y.has(D.user_id)&&e.jsxs(ze,{variant:"outline",children:[e.jsx(Oc,{className:"h-3 w-3 mr-1"}),"Has coach"]}),D.tier&&e.jsx(ze,{variant:"outline",children:D.tier}),D.expires_at&&e.jsxs("span",{className:"text-xs text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3 w-3"}),q?"Expired":"Expires"," ",new Date(D.expires_at).toLocaleDateString()]})]}),D.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:D.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(mn,{checked:D.enabled&&!q,onCheckedChange:G=>C(D,G)}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>c({profile:F||{id:D.user_id,name:null,email:null},entitlement:D}),children:"Edit"}),e.jsx(z,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>E({profile:F||{id:D.user_id,name:null,email:null},entitlement:D}),children:e.jsx(er,{className:"h-4 w-4"})})]})]},D.id)})})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx(ze,{variant:"outline",children:I.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These members already reach coaching because they're assigned to a coach — no entitlement needed."}),I.length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground border rounded-lg",children:"No active assignments."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(D=>{const F=g[D.agent_id];return e.jsxs("div",{className:"flex items-center gap-2 border rounded-full pl-1 pr-3 py-1",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(xi,{src:(F==null?void 0:F.avatar_url)||void 0}),e.jsx(Na,{className:"text-[10px]",children:h7e(F)})]}),e.jsx("span",{className:"text-sm",children:(F==null?void 0:F.name)||(F==null?void 0:F.email)||D.agent_id})]},D.agent_id)})})]})}),e.jsx(a7s,{state:o,onClose:()=>c(null),onSave:async D=>{if(!o)return;await w(o.profile.id,D)&&(ne.success("Coaching access saved"),c(null))}})]})}function p7e({icon:s,label:t,value:n,hint:r}){return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-sm font-medium",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})]})})}function a7s({state:s,onClose:t,onSave:n}){const[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(!0),[h,m]=_.useState(!1);_.useEffect(()=>{if(!s)return;const f=s.entitlement;a(f!=null&&f.expires_at?f.expires_at.slice(0,10):""),l((f==null?void 0:f.notes)||""),c((f==null?void 0:f.tier)||""),u(f?f.enabled:!0)},[s]);const p=async()=>{m(!0),await n({expires_at:r?new Date(`${r}T23:59:59`).toISOString():null,notes:i.trim()||null,tier:o.trim()||null,enabled:d}),m(!1)};return e.jsx(Is,{open:!!s,onOpenChange:f=>!f&&t(),children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:s!=null&&s.entitlement?"Edit coaching access":"Grant coaching access"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:(s==null?void 0:s.profile.name)||(s==null?void 0:s.profile.email)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s==null?void 0:s.profile.email})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(mn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Expires on (optional)"}),e.jsx(pe,{type:"date",value:r,onChange:f=>a(f.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank for ongoing access."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tier / plan label (optional)"}),e.jsx(pe,{value:o,onChange:f=>c(f.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Internal notes"}),e.jsx(Ps,{value:i,onChange:f=>l(f.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(z,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function i7s(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState("active"),{data:i=[]}=rt({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:p,error:f}=await U.from("coaches").select("id, user_id");if(f)throw f;const g=(p||[]).map(b=>b.user_id);if(!g.length)return[];const{data:v}=await U.from("profiles").select("id, name, email").in("id",g),y=new Map((v||[]).map(b=>[b.id,b]));return(p||[]).map(b=>{var w,S;return{id:b.id,label:((w=y.get(b.user_id))==null?void 0:w.name)||((S=y.get(b.user_id))==null?void 0:S.email)||b.user_id}})}}),{data:l=[],isLoading:o}=rt({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:p,error:f}=await U.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(f)throw f;const g=[...new Set((p||[]).map(b=>b.agent_id))],{data:v}=g.length?await U.from("profiles").select("id, name, email").in("id",g):{data:[]},y=new Map((v||[]).map(b=>[b.id,b]));return(p||[]).map(b=>({...b,agent:y.get(b.agent_id)}))}}),c=p=>{var f;return((f=i.find(g=>g.id===p))==null?void 0:f.label)||"—"},d=_.useMemo(()=>{const p=t.trim().toLowerCase();return l.filter(f=>{var g,v;return r!=="all"&&f.status!==r?!1:p?(((g=f.agent)==null?void 0:g.name)||"").toLowerCase().includes(p)||(((v=f.agent)==null?void 0:v.email)||"").toLowerCase().includes(p)||c(f.coach_id).toLowerCase().includes(p):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(p,f)=>{var y,b;if(f===p.coach_id||!await Qi({title:"Switch coach?",description:`${((y=p.agent)==null?void 0:y.name)||((b=p.agent)==null?void 0:b.email)} will move from ${c(p.coach_id)} to ${c(f)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:v}=await U.from("coaching_assignments").update({coach_id:f}).eq("id",p.id);if(v)return ne.error(v.message);ne.success("Coach switched"),u()},m=async(p,f)=>{var v,y;if(f==="ended"&&!await Qi({title:"End assignment?",description:`${((v=p.agent)==null?void 0:v.name)||((y=p.agent)==null?void 0:y.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:g}=await U.from("coaching_assignments").update({status:f,ended_at:f==="ended"?new Date().toISOString():null}).eq("id",p.id);if(g)return ne.error(g.message);ne.success(f==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx(ze,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{placeholder:"Search by agent or coach…",value:t,onChange:p=>n(p.target.value)}),e.jsxs(ls,{value:r,onValueChange:p=>a(p),children:[e.jsx(rs,{className:"sm:w-40",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"active",children:"Active"}),e.jsx(He,{value:"ended",children:"Ended"}),e.jsx(He,{value:"all",children:"All"})]})]})]}),o?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):d.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No assignments found."}):e.jsx("div",{className:"divide-y border rounded-md",children:d.map(p=>{var f,g,v;return e.jsxs("div",{className:"p-3 flex flex-col md:flex-row md:items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:((f=p.agent)==null?void 0:f.name)||((g=p.agent)==null?void 0:g.email)||p.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(v=p.agent)==null?void 0:v.email," · ",p.pipeline_stage||"onboarding",p.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(AQ,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ls,{value:p.coach_id,onValueChange:y=>h(p,y),children:[e.jsx(rs,{className:"w-full md:w-56 h-9",children:e.jsx(cs,{})}),e.jsx(as,{children:i.map(y=>e.jsx(He,{value:y.id,children:y.label},y.id))})]}),p.status==="active"?e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>m(p,"ended"),children:[e.jsx(vq,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>m(p,"active"),children:[e.jsx(Dx,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},p.id)})})]})})}function o7s(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState([]),[i,l]=_.useState(null),{data:o=[],isLoading:c}=rt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await U.from("coaches").select("*").order("created_at",{ascending:!1});if(m)throw m;if(!(h!=null&&h.length))return[];const p=h.map(v=>v.user_id),{data:f}=await U.from("profiles").select("id, name, email, avatar_url").in("id",p),g=new Map((f||[]).map(v=>[v.id,v]));return h.map(v=>({...v,profile:g.get(v.user_id)}))}});_.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:p}=await U.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(p||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await U.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return ne.error(m.message);const{error:p}=await U.from("coaches").insert({user_id:h.id});if(p&&!String(p.message).includes("duplicate"))return ne.error(p.message);ne.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:p}=await U.from("coaches").update({is_certified:m}).eq("id",h);if(p)return ne.error(p.message);ne.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs($s,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fm,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(Qr,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(Jr,{className:"flex-wrap h-auto",children:[e.jsx(Wt,{value:"coaches",children:"Coaches"}),e.jsx(Wt,{value:"assignments",children:"Assignments"}),e.jsx(Wt,{value:"access",children:"Coaching Access"}),e.jsx(Wt,{value:"applications",children:"Applications"}),e.jsx(Wt,{value:"settings",children:"Settings"})]}),e.jsx(Kt,{value:"assignments",className:"space-y-6",children:e.jsx(i7s,{})}),e.jsx(Kt,{value:"access",className:"space-y-6",children:e.jsx(r7s,{})}),e.jsx(Kt,{value:"applications",className:"space-y-6",children:e.jsx(d7s,{})}),e.jsx(Kt,{value:"settings",className:"space-y-6",children:e.jsx(l7s,{})}),e.jsxs(Kt,{value:"coaches",className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsx(pe,{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(z,{size:"sm",onClick:()=>d(h),children:[e.jsx(sn,{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(be,{children:e.jsx(Le,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var m,p,f;return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((m=h.profile)==null?void 0:m.name)||((p=h.profile)==null?void 0:p.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(f=h.profile)==null?void 0:f.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(z,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"})," Assign"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm pt-2 border-t",children:[e.jsx("span",{className:"text-muted-foreground",children:"LevelUp Certified"}),e.jsx(mn,{checked:h.is_certified,onCheckedChange:g=>u(h.id,g)})]})]})},h.id)})})]})]})]})]}),e.jsx(c7s,{coachId:i,onClose:()=>l(null)})]})}function l7s(){const[s,t]=_.useState("1500"),[n,r]=_.useState(!1),[a,i]=_.useState(!1);_.useEffect(()=>{(async()=>{const{data:c}=await U.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return ne.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await U.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ne.error(d.message);ne.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z_,{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(ee,{children:"Fee (bps)"}),e.jsx(pe,{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(z,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function c7s({coachId:s,onClose:t}){const[n,r]=_.useState(""),[a,i]=_.useState([]),[l,o]=_.useState(!1),c=$t();_.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),_.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await U.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(m||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await U.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ne.error(h.message);ne.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(Is,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Assign Agent"})}),e.jsx(pe,{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(hr,{children:e.jsx(z,{variant:"outline",onClick:t,children:"Close"})})]})})}function d7s(){const s=$t(),[t,n]=_.useState("pending"),[r,a]=_.useState(null),{data:i=[],isLoading:l}=rt({queryKey:["coach-applications",t],queryFn:async()=>{let u=U.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:m}=await u;if(m)throw m;return h||[]}}),{data:o=0}=rt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await U.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await U.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return ne.error(m.message);ne.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(Wr,{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(er,{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(Zr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(be,{children:[e.jsxs(Le,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(i7,{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(z,{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(on,{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(Is,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Ls,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Os,{children:e.jsxs(Rs,{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(MB,{icon:on,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(MB,{icon:va,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(MB,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(MB,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(MB,{icon:mr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(MB,{icon:mr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(f7e,{label:"Specialties",children:r.specialties}),e.jsx(f7e,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(f7e,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ps,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await U.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(hr,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs(z,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(er,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(z,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs(z,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function MB({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 f7e({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 u7s(){const s=zn(),{data:t}=cae(),n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(null),{data:d,refetch:u}=rt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await U.functions.invoke("coach-stripe-status");return v}}),{data:h=[]}=rt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await U.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return v||[]}});_.useEffect(()=>{const v=new URLSearchParams(window.location.search);(v.get("onboarded")||v.get("refresh"))&&u()},[u]);const m=async()=>{var w,S;a(!0);const{data:v,error:y}=await U.functions.invoke("coach-stripe-connect");a(!1);let b=v==null?void 0:v.error;if(!b&&y)try{const C=await((S=(w=y==null?void 0:y.context)==null?void 0:w.json)==null?void 0:S.call(w));b=(C==null?void 0:C.error)||y.message}catch{b=y.message}if(b)return ne.error(b,{duration:1e4});v!=null&&v.url&&(window.location.href=v.url)},p=d||{},f=!!(t!=null&&t.use_platform_stripe),g=f||p.connected&&p.charges_enabled;return e.jsx($s,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(be,{children:e.jsxs(Le,{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(j0,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f?"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."})]}),g?e.jsxs(ze,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Mr,{className:"h-3 w-3"})," ",f?"Using LevelUp billing":"Connected"]}):p.connected?e.jsxs(ze,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(ze,{variant:"outline",children:"Not connected"})]}),!f&&e.jsxs(z,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[g?"Update Stripe details":p.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(mr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{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(z,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!g,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!g&&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(z,{variant:"ghost",size:"icon",onClick:()=>{c(v),l(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi("Delete this package?")&&(await U.from("coaching_packages").delete().eq("id",v.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Cn,{className:"h-4 w-4"})})]},v.id))})]})}),e.jsx(h7s,{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 h7s({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState("month"),[p,f]=_.useState(!0),[g,v]=_.useState(!0),[y,b]=_.useState(!1);_.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),f((r==null?void 0:r.is_active)??!0),v((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const w=async()=>{if(!i.trim()||!d)return ne.error("Name and price required");b(!0);const S={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:p,accepting_clients:g},{error:C}=r!=null&&r.id?await U.from("coaching_packages").update(S).eq("id",r.id):await U.from("coaching_packages").insert(S);if(b(!1),C)return ne.error(C.message);ne.success("Saved"),a==null||a(),t(!1)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:S=>l(S.target.value)}),e.jsx(Ps,{rows:3,placeholder:"What's included",value:o,onChange:S=>c(S.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(pe,{type:"number",value:d,onChange:S=>u(S.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(ls,{value:h,onValueChange:m,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"month",children:"Monthly"}),e.jsx(He,{value:"year",children:"Yearly"}),e.jsx(He,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:S=>f(S.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:g,onChange:S=>v(S.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(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:w,disabled:y,children:r!=null&&r.id?"Save":"Create"})]})]})})}function ygt({kind:s,value:t,onChange:n}){const r=_.useRef(null),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(null),m=_.useRef(null),p=_.useRef([]),[f,g]=_.useState(!1),v=s==="photo"?"image/*":"video/*",y=s==="photo"?10*1024*1024:200*1024*1024,b=async(M,I)=>{var H;const{data:D}=await U.auth.getUser(),F=(H=D.user)==null?void 0:H.id;if(!F)return ne.error("Not signed in");if(M.size>y)return ne.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const q=`${F}/${s}-${Date.now()}.${I}`,{error:G}=await U.storage.from("coach-media").upload(q,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(G)return i(!1),ne.error(G.message);const{data:V}=await U.storage.from("coach-media").createSignedUrl(q,60*60*24*365*10);i(!1),V!=null&&V.signedUrl&&(n(V.signedUrl),ne.success("Uploaded"),d(null))},w=async M=>{const I=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(M,I)},S=async()=>{try{const M=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=M,g(!0),setTimeout(()=>{u.current&&(u.current.srcObject=M,u.current.play())},50);const I=new MediaRecorder(M,{mimeType:"video/webm"});p.current=[],I.ondataavailable=D=>D.data.size>0&&p.current.push(D.data),I.onstop=()=>{const D=new Blob(p.current,{type:"video/webm"});d(D),M.getTracks().forEach(F=>F.stop())},m.current=I,I.start(),o(!0)}catch(M){ne.error(M.message||"Could not access camera")}},C=()=>{var M;(M=m.current)==null||M.stop(),o(!1)},E=()=>{var M;(M=h.current)==null||M.getTracks().forEach(I=>I.stop()),g(!1),o(!1),d(null)},P=async()=>{c&&(await b(c,"webm"),E())};return _.useEffect(()=>()=>{var M;return(M=h.current)==null?void 0:M.getTracks().forEach(I=>I.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 D;const I=(D=M.target.files)==null?void 0:D[0];I&&w(I),M.target.value=""}}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var M;return(M=r.current)==null?void 0:M.click()},children:[a?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:a||f,children:[e.jsx(Lx,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Cn,{className:"h-4 w-4 mr-1"})," Remove"]})]}),f&&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(z,{type:"button",size:"sm",onClick:C,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(jb,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(z,{type:"button",size:"sm",onClick:()=>{var M;return(M=m.current)==null?void 0:M.start()},children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{type:"button",size:"sm",onClick:P,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(z,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),S()},children:"Re-record"})]}),e.jsx(z,{type:"button",size:"sm",variant:"ghost",onClick:E,children:"Cancel"})]})]})]})}function G9t(){const{user:s}=hs(),t=$t(),n=rt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await U.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(y)throw y;return v},enabled:!!s}),r=rt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await U.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(y)throw y;return v},enabled:!!s}),a=rt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await U.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(y)throw y;return v},enabled:!!s}),i=rt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await U.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(y)throw y;return v},enabled:!!s}),l=rt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await U.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(y)throw y;return v},enabled:!!s}),o=mt({mutationFn:async()=>{const{data:v,error:y}=await U.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(y)throw y;const b=[{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:w}=await U.from("agent_booking_types").insert(b.map(E=>({...E,user_id:s.id})));if(w)throw w;const S=[1,2,3,4,5].map(E=>({user_id:s.id,day_of_week:E,start_time:"09:00",end_time:"17:00"})),{error:C}=await U.from("agent_availability_slots").insert(S);if(C)throw C;return v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ne.success("Scheduler set up successfully!")},onError:v=>ne.error(v.message)}),c=mt({mutationFn:async v=>{const{error:y}=await U.from("agent_booking_settings").update(v).eq("user_id",s.id);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ne.success("Settings updated")},onError:v=>ne.error(v.message)}),d=mt({mutationFn:async v=>{const y={...v,user_id:s.id};if(v.id){const{error:b}=await U.from("agent_booking_types").update(y).eq("id",v.id);if(b)throw b}else{const{error:b}=await U.from("agent_booking_types").insert(y);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ne.success("Booking type saved")},onError:v=>ne.error(v.message)}),u=mt({mutationFn:async v=>{const{error:y}=await U.from("agent_booking_types").delete().eq("id",v);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ne.success("Booking type deleted")},onError:v=>ne.error(v.message)}),h=mt({mutationFn:async v=>{const y={...v,user_id:s.id};if(v.id){const{error:b}=await U.from("agent_availability_slots").update(y).eq("id",v.id);if(b)throw b}else{const{error:b}=await U.from("agent_availability_slots").insert(y);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ne.error(v.message)}),m=mt({mutationFn:async v=>{const{error:y}=await U.from("agent_availability_slots").delete().eq("id",v);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ne.error(v.message)}),p=mt({mutationFn:async v=>{const{blocked_date:y,end_date:b,reason:w}=v,S=D=>{const[F,q,G]=D.split("-").map(Number);return new Date(F,q-1,G)},C=D=>`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,E=S(y),P=b?S(b):E;if(P366)throw new Error("Range too large (max 1 year)");const{error:I}=await U.from("agent_blocked_dates").upsert(M,{onConflict:"user_id,blocked_date",ignoreDuplicates:!0});if(I)throw I;return M.length},onSuccess:v=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ne.success(v&&v>1?`${v} dates blocked`:"Date blocked")},onError:v=>ne.error(v.message)}),f=mt({mutationFn:async v=>{const{error:y}=await U.from("agent_blocked_dates").delete().eq("id",v);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:v=>ne.error(v.message)}),g=mt({mutationFn:async({id:v,reason:y})=>{const{error:b}=await U.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:y}).eq("id",v);if(b)throw b;await U.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:v}}).catch(w=>console.error("Google calendar cleanup failed:",w))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ne.success("Booking cancelled")},onError:v=>ne.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:m,addBlockedDate:p,removeBlockedDate:f,cancelBooking:g}}const vgt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function W9t({slots:s,onSave:t,onDelete:n}){const[r,a]=_.useState(null),[i,l]=_.useState("09:00"),[o,c]=_.useState("17:00"),d=vgt.map((h,m)=>s.filter(p=>p.day_of_week===m)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(En,{children:"Set your available hours for each day"})]}),e.jsx(Le,{className:"space-y-2",children:vgt.map((h,m)=>{const p=d[m];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):p.map(f=>{var g,v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(g=f.start_time)==null?void 0:g.slice(0,5),onBlur:y=>t({id:f.id,start_time:y.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(v=f.end_time)==null?void 0:v.slice(0,5),onBlur:y=>t({id:f.id,end_time:y.target.value})}),e.jsx(mn,{checked:f.is_active,onCheckedChange:y=>t({id:f.id,is_active:y})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(f.id),children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},f.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:f=>l(f.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:f=>c(f.target.value)}),e.jsx(z,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(z,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function bgt(s){const[t,n,r]=s.split("-").map(Number);return Ys(new Date(t,n-1,r),"MMM d, yyyy")}function m7s(s){const t=[...s].sort((a,i)=>a.blocked_date.localeCompare(i.blocked_date)),n=[],r=a=>{const[i,l,o]=a.split("-").map(Number),c=new Date(i,l-1,o+1);return`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")}`};for(const a of t){const i=n[n.length-1];i&&r(i.end)===a.blocked_date&&(i.reason??"")===(a.reason??"")?(i.end=a.blocked_date,i.ids.push(a.id)):n.push({start:a.blocked_date,end:a.blocked_date,reason:a.reason,ids:[a.id]})}return n}function K9t({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),h=()=>{i&&(t({blocked_date:i,end_date:o||void 0,reason:d||void 0}),a(!1),l(""),c(""),u(""))};return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(RU,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(En,{children:"Block a single day or a full date range (vacations, holidays, etc.)"})]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Block Dates"]})]}),e.jsxs(Le,{children:[r&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"date",value:i,onChange:m=>l(m.target.value),className:"w-40"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"date",value:o,min:i||void 0,onChange:m=>c(m.target.value),className:"w-40",placeholder:"Optional"})]}),e.jsx(pe,{placeholder:"Reason (optional)",value:d,onChange:m=>u(m.target.value),className:"flex-1 min-w-[180px]"}),e.jsx(z,{size:"sm",onClick:h,children:"Add"}),e.jsx(z,{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:m7s(s).map(m=>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.jsxs("span",{children:[bgt(m.start),m.end!==m.start&&` – ${bgt(m.end)}`]}),m.ids.length>1&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",m.ids.length," days)"]}),m.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",m.reason,")"]}),e.jsx("button",{onClick:()=>m.ids.forEach(n),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(er,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function p7s(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,isLoading:a,initializeSettings:i,updateSettings:l,upsertBookingType:o,deleteBookingType:c,upsertAvailability:d,deleteAvailability:u,addBlockedDate:h,removeBlockedDate:m}=G9t(),[p,f]=_.useState("1-on-1 Coaching Session"),[g,v]=_.useState(45),y=_.useMemo(()=>t.filter(w=>w.is_coaching_only),[t]);if(a)return e.jsx(be,{children:e.jsxs(Le,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Ud,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(En,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Le,{children:e.jsxs(z,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const b=()=>{p.trim()&&(o.mutate({name:p.trim(),description:"Private coaching session",duration_minutes:g,color:"#406E71",icon:"Video",is_active:!0,qualification_enabled:!1,is_coaching_only:!0,sort_order:99}),f("1-on-1 Coaching Session"),v(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(En,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Le,{className:"space-y-3",children:[y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No coaching session type yet — add one below so members can book you."}):y.map(w=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(pe,{className:"h-9 max-w-[240px]",defaultValue:w.name,onBlur:S=>S.target.value!==w.name&&o.mutate({id:w.id,name:S.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:w.duration_minutes,onBlur:S=>o.mutate({id:w.id,duration_minutes:parseInt(S.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:w.is_active,onCheckedChange:S=>o.mutate({id:w.id,is_active:S})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:w.is_active?"Bookable":"Paused"})]}),e.jsx(ze,{variant:"secondary",children:"Coaching only"}),e.jsx(z,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await Qi({title:"Delete session type?",description:`"${w.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(w.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},w.id)),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx(ee,{className:"text-xs",children:"New session type"}),e.jsx(pe,{value:p,onChange:w=>f(w.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Minutes"}),e.jsx(pe,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:g,onChange:w=>v(parseInt(w.target.value)||30)})]}),e.jsxs(z,{onClick:b,disabled:o.isPending,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(W9t,{slots:n,onSave:w=>d.mutate(w),onDelete:w=>u.mutate(w)}),e.jsx(K9t,{blockedDates:r,onAdd:w=>h.mutate(w),onRemove:w=>m.mutate(w)}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Scheduling rules"}),e.jsx(En,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Le,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(pe,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:w=>l.mutate({buffer_minutes:parseInt(w.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(pe,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:w=>l.mutate({min_notice_hours:parseInt(w.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(pe,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:w=>l.mutate({max_advance_days:parseInt(w.target.value)||30})})]})]})]})]})}async function YY(s,t){const n=s==="agent"?"agent-google-calendar":"coach-google-calendar",{data:r,error:a}=await U.functions.invoke(n,{body:t});if(a){let i=a.message;try{const l=a.context;if(l!=null&&l.json){const o=await l.json();o!=null&&o.error&&(i=o.error)}}catch{}throw new Error(i)}if(r!=null&&r.error)throw new Error(r.error);return r}function Y9t(s=!0,t="coach"){const n=$t(),r=rt({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await YY(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=mt({mutationFn:async()=>{const d=await YY(t,{action:"start",origin:window.location.origin}),u=d==null?void 0:d.authorizationUrl;if(!u)throw new Error("Google did not return an authorization link.");try{sessionStorage.setItem("googleCalendarReturnTo",window.location.pathname),sessionStorage.setItem("googleCalendarScope",t)}catch{}window.location.assign(u),await new Promise(h=>setTimeout(h,4e3))},onSuccess:a}),l=mt({mutationFn:()=>YY(t,{action:"disconnect"}),onSuccess:a}),o=mt({mutationFn:d=>YY(t,{action:"settings",...d}),onSuccess:a}),c=mt({mutationFn:()=>YY(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function Z9t({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=Y9t(!0,s),l=s==="agent";_.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(ne.success("Google Calendar connected"),t.refetch()):ne.error(d.get("google_calendar_error")||"Google connection failed."),d.delete("google_calendar"),d.delete("google_calendar_error");const h=d.toString();window.history.replaceState({},"",window.location.pathname+(h?`?${h}`:""))},[]);const o=t.data,c=t.error;return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(_v,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(En,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs(ze,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(Mr,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(Le,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Checking your connection…"]}),c&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsx("span",{children:c.message})]}),o&&!o.configured&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-400/50 bg-amber-50 dark:bg-amber-950/20 p-3 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"Google Calendar isn't switched on for LevelUp yet. Once an admin finishes the one-time Google setup, you'll be able to connect right here."})]}),(o==null?void 0:o.configured)&&!o.connected&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not connected. Your availability comes only from the hours you set in LevelUp."}),e.jsxs(z,{onClick:()=>n.mutate(void 0,{onSuccess:()=>ne.success("Google Calendar connected"),onError:d=>ne.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_v,{className:"h-4 w-4 mr-2"}),n.isPending?"Connecting…":"Connect Google Calendar"]}),n.isError&&e.jsx("p",{className:"text-sm text-destructive",children:n.error.message})]}),(o==null?void 0:o.connected)&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:o.account_email||"Google account"}),o.connected_at&&e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Connected ",new Date(o.connected_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Block busy times and add new bookings to Google.":"Block busy times and add booked sessions to Google."})]}),e.jsx(mn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>ne.error(u.message)})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Invite the guest"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send a Google invite when they leave an email address."})]}),e.jsx(mn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>ne.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>ne.error(u.message)}),children:[e.jsx(rs,{className:"h-9",children:e.jsx(cs,{placeholder:"Primary calendar"})}),e.jsxs(as,{children:[e.jsx(He,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(He,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx(z,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>ne.success("Calendars refreshed"),onError:d=>ne.error(d.message)}),disabled:i.isPending,children:e.jsx(Gi,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>ne.success("Google Calendar reconnected"),onError:d=>ne.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await Qi({title:"Disconnect Google Calendar?",description:"Busy times will stop hiding and new sessions won't be added to Google.",confirmText:"Disconnect",destructive:!0})&&r.mutate(void 0,{onSuccess:()=>ne.success("Google Calendar disconnected"),onError:u=>ne.error(u.message)})},children:[e.jsx(_7,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function f7s(){const s=zn(),{data:t,isLoading:n}=cae(),r=$t(),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(!1),[v,y]=_.useState([]),[b,w]=_.useState(""),[S,C]=_.useState(2),[E,P]=_.useState(!1);_.useEffect(()=>{if(!t)return;const q=t;i(q.slug||""),o(q.headline||""),d(q.bio||""),h(q.photo_url||""),p(q.intro_video_url||""),g(!!q.accepting_clients),y(q.specialties||[]),C(q.default_sessions_per_month??2)},[t]);const M=async()=>{if(!t)return;P(!0);const{error:q}=await U.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:f,specialties:v,default_sessions_per_month:S}).eq("id",t.id);if(P(!1),q)return ne.error(q.message);ne.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},I=()=>{const q=b.trim();if(q){if(v.includes(q))return w("");y([...v,q]),w("")}};if(n)return e.jsx($s,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx($s,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const D=t,F=D.slug?`${window.location.origin}/coaches/${D.slug}`:null;return e.jsx($s,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(ka,{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(z,{variant:"outline",size:"sm",onClick:()=>window.open(F,"_blank"),children:[e.jsx(mr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(z,{onClick:M,disabled:E,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"})," ",E?"Saving…":"Save"]})]})]}),D.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(be,{children:e.jsxs(Le,{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(mn,{checked:f,onCheckedChange:g})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:a,onChange:q=>i(q.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:l,onChange:q=>o(q.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Bio"}),e.jsx(Ps,{rows:6,value:c,onChange:q=>d(q.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(ee,{children:"Profile photo"}),e.jsx(ygt,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Intro video"}),e.jsx(ygt,{kind:"video",value:m,onChange:p})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:v.map(q=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[q,e.jsx("button",{onClick:()=>y(v.filter(G=>G!==q)),children:e.jsx(er,{className:"h-3 w-3"})})]},q))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:b,onChange:q=>w(q.target.value),placeholder:"Add a specialty…",onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),I())}}),e.jsx(z,{type:"button",variant:"outline",onClick:I,children:e.jsx(sn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Coaching calendar"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Open availability right here — assigned members book you from their ",e.jsx("strong",{children:"My Coach → Book"})," tab. These session types never show on your public booking page."]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{children:"Sessions each agent can book per month"}),e.jsx(pe,{type:"number",min:1,max:31,value:S,onChange:q=>C(Math.max(1,parseInt(q.target.value)||1)),className:"max-w-[140px]"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"You can override this for individual agents on their workspace page."})]}),e.jsx(z,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(Z9t,{}),e.jsx(p7s,{}),e.jsx(be,{children:e.jsx(Le,{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(z,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(x7s,{coachId:D.id})]})})}function x7s({coachId:s}){const[t,n]=_.useState("");$t();const{data:r=[],refetch:a}=rt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await U.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return ne.error("Email required");const{error:d}=await U.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ne.error(d.message);n(""),ne.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ne.success("Link copied")},o=async c=>{await Qi("Revoke this invite?")&&(await U.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(be,{children:e.jsxs(Le,{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(Kc,{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(pe,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(z,{onClick:i,children:[e.jsx(sn,{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(z,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Cn,{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 g7s="google_calendar";function y7s(){const[s,t]=_.useState("Finishing your Google Calendar connection…"),n=_.useRef(!1);return _.useEffect(()=>{if(n.current)return;n.current=!0;const r=new URLSearchParams(window.location.search),a=(()=>{try{return!!window.opener&&!window.opener.closed}catch{return!1}})(),i=(()=>{try{return sessionStorage.getItem("googleCalendarReturnTo")||"/coaching/settings"}catch{return"/coaching/settings"}})(),l=(u,h)=>{try{sessionStorage.removeItem("googleCalendarReturnTo")}catch{}const m=new URL(i,window.location.origin);m.searchParams.set("google_calendar",u),h&&m.searchParams.set("google_calendar_error",h),window.location.replace(m.toString())},o=(u,h)=>{var m;if(a){(m=window.opener)==null||m.postMessage({type:u,connectorId:g7s,reason:h},window.location.origin),u==="appUserConnectorOAuthComplete"&&window.close();return}l(u==="appUserConnectorOAuthComplete"?"connected":"failed",h)};if(r.get("success")!=="true"){const u=r.get("error")||"Google did not complete the connection.";t(u),o("appUserConnectorOAuthFailed",u);return}const c=r.get("code");if(!c){const u=r.get("offline_access_allowed")==="false"?"This connection cannot be used yet: a workspace admin must enable offline access on the Google Calendar App User Connector client.":"Google finished, but no exchange code was returned.";t(u),o("appUserConnectorOAuthFailed",u);return}const d=(()=>{try{return sessionStorage.getItem("googleCalendarScope")==="agent"?"agent":"coach"}catch{return"coach"}})();U.functions.invoke(d==="agent"?"agent-google-calendar":"coach-google-calendar",{body:{action:"complete",code:c}}).then(({data:u,error:h})=>{if(h)throw h;if(u!=null&&u.error)throw new Error(u.error);t("Connected! You can close this window."),o("appUserConnectorOAuthComplete")}).catch(u=>{const h=(u==null?void 0:u.message)||"Could not finish the connection.";t(h),o("appUserConnectorOAuthFailed",h)})},[]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-center",children:e.jsxs("div",{className:"space-y-3 max-w-sm",children:[e.jsx(bt,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Fle=[{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 v7s(){const s=zn(),t=$t(),{data:n,isLoading:r}=cae(),[a,i]=_.useState("pending"),[l,o]=_.useState(""),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,g]=_.useState(!1),[v,y]=_.useState(""),{data:b=[],isLoading:w}=rt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:D,error:F}=await U.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(F)throw F;return D||[]}}),S=_.useMemo(()=>b.filter(D=>{if(a!=="all"&&D.status!==a)return!1;if(l){const F=l.toLowerCase();return(D.name||"").toLowerCase().includes(F)||(D.email||"").toLowerCase().includes(F)||(D.brokerage||"").toLowerCase().includes(F)}return!0}),[b,a,l]),C=_.useMemo(()=>{const D={all:b.length};for(const F of Fle)D[F.value]=0;for(const F of b)D[F.status]=(D[F.status]||0)+1;return D},[b]),E=async(D,F)=>{const{error:q}=await U.from("coaching_waitlist").update(F).eq("id",D);if(q)return ne.error(q.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===D&&d(G=>({...G,...F}))},P=async D=>{if(!await Qi("Remove this person from the waitlist?"))return;const{error:F}=await U.from("coaching_waitlist").delete().eq("id",D);if(F)return ne.error(F.message);ne.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:D,error:F}=await U.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(F||D!=null&&D.error)return ne.error((D==null?void 0:D.error)||(F==null?void 0:F.message)||"Could not send invite");ne.success(`Invite sent to ${c.name}`),h(!1),p(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},I=async()=>{if(!n)return;const{data:D,error:F}=await U.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:v}});if(F||D!=null&&D.error)return ne.error((D==null?void 0:D.error)||(F==null?void 0:F.message)||"Could not notify");ne.success(`Notified ${(D==null?void 0:D.count)||0} agents`),g(!1),y(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx($s,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs($s,{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(z,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(ka,{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(Wf,{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(z,{variant:"outline",onClick:()=>g(!0),disabled:!C.pending,title:C.pending?"":"No pending applicants",children:[e.jsx(l7,{className:"h-4 w-4 mr-2"}),"Notify all pending (",C.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 (",C.all,")"]}),Fle.map(D=>e.jsxs("button",{onClick:()=>i(D.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===D.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[D.label," (",C[D.value]||0,")"]},D.value))]}),e.jsx(pe,{placeholder:"Search by name, email, brokerage…",value:l,onChange:D=>o(D.target.value),className:"max-w-md"}),w?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):S.length===0?e.jsx(be,{children:e.jsx(Le,{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:S.map(D=>{const F=Fle.find(q=>q.value===D.status);return e.jsx(be,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(D),children:e.jsxs(Le,{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:D.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email}),D.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.brokerage})]}),e.jsx(ze,{className:(F==null?void 0:F.tone)||"",children:(F==null?void 0:F.label)||D.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Md(new Date(D.created_at),{addSuffix:!0})]}),D.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",D.preferred_package]})]})]})},D.id)})})]}),e.jsx(Is,{open:!!c,onOpenChange:D=>!D&&d(null),children:e.jsx(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:c.name}),e.jsxs(_r,{children:["Joined ",Md(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(ZY,{label:"Email",value:c.email}),e.jsx(ZY,{label:"Phone",value:c.phone}),e.jsx(ZY,{label:"Brokerage",value:c.brokerage}),e.jsx(ZY,{label:"Years",value:c.years_in_business}),e.jsx(ZY,{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 ",Md(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(ls,{value:c.status,onValueChange:D=>E(c.id,{status:D}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Fle.map(D=>e.jsx(He,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Ps,{rows:3,defaultValue:c.coach_notes||"",onBlur:D=>{D.target.value!==(c.coach_notes||"")&&E(c.id,{coach_notes:D.target.value})}})]})]}),e.jsxs(hr,{className:"flex-wrap gap-2",children:[e.jsxs(z,{variant:"outline",className:"text-destructive",onClick:()=>P(c.id),children:[e.jsx(Cn,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(on,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(z,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{p(""),h(!0)},children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(Is,{open:u,onOpenChange:h,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Invite to subscribe"}),e.jsxs(_r,{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(Ps,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:D=>p(D.target.value)})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(z,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:M,children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(Is,{open:f,onOpenChange:g,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Notify all pending applicants"}),e.jsx(_r,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ps,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:v,onChange:D=>y(D.target.value)}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsxs(z,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:I,children:[e.jsx(l7,{className:"h-4 w-4 mr-1"})," Send to ",C.pending||0," agents"]})]})]})})]}):e.jsx($s,{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 ZY({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 b7s(){const{data:s=[],isLoading:t}=rt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await U.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 U.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(Mr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{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(or,{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(Da,{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(Mr,{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(Mr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Mr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(or,{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(Da,{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 _7s=Gj({name:Jo().trim().min(1,"Name required").max(120),email:Jo().trim().email("Invalid email").max(255),phone:Jo().trim().max(40).optional().or(jx("")),brokerage:Jo().trim().max(160).optional().or(jx("")),years_in_business:Jo().max(40).optional().or(jx("")),biggest_challenge:Jo().trim().max(1e3).optional().or(jx("")),preferred_package:Jo().max(120).optional().or(jx("")),message:Jo().trim().max(1500).optional().or(jx(""))});function w7s({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=hs(),[l,o]=_.useState(!1),[c,d]=_.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,p)=>d(f=>({...f,[m]:p})),h=async()=>{var f;const m=_7s.safeParse(c);if(!m.success){ne.error(((f=m.error.issues[0])==null?void 0:f.message)||"Please check your entries");return}o(!0);const{error:p}=await U.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),p){ne.error(p.message||"Could not join waitlist");return}ne.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(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(_r,{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(ee,{children:"Name *"}),e.jsx(pe,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email *"}),e.jsx(pe,{type:"email",value:c.email,onChange:m=>u("email",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:c.brokerage,onChange:m=>u("brokerage",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Years in business"}),e.jsxs(ls,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select…"})}),e.jsxs(as,{children:[e.jsx(He,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(He,{value:"1-3 years",children:"1-3 years"}),e.jsx(He,{value:"4-7 years",children:"4-7 years"}),e.jsx(He,{value:"8-15 years",children:"8-15 years"}),e.jsx(He,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(ee,{children:"Preferred package"}),e.jsxs(ls,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any"})}),e.jsx(as,{children:a.map(m=>e.jsx(He,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Biggest challenge right now"}),e.jsx(Ps,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Anything else?"}),e.jsx(Ps,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx(z,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function j7s(){var g;const{slug:s}=Mi(),t=zn(),{user:n}=hs(),[r,a]=_.useState(null),[i,l]=_.useState(!1),{data:o,isLoading:c}=rt({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||""),y=U.from("coaches").select("*"),{data:b}=v?await y.eq("id",s).maybeSingle():await y.eq("slug",s).maybeSingle();if(!b)return null;const[{data:w},{data:S}]=await Promise.all([U.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),U.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:w,packages:S||[]}}}),d=async v=>{if(!n){ne.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:y,error:b}=await U.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),b||y!=null&&y.error){ne.error((y==null?void 0:y.error)||(b==null?void 0:b.message)||"Checkout failed");return}y!=null&&y.url&&(window.location.href=y.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,p=u,f=(v,y)=>{const b=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return y==="one_time"?b:`${b} / ${y}`};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(z,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(ka,{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(ja,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(xi,{src:p.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(Na,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[p.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(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"}),p.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:p.headline}),((g=p.specialties)==null?void 0:g.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:p.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:[p.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:p.intro_video_url,controls:!0,className:"w-full h-full"})}),p.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:p.bio})]}),e.jsx(JOs,{coachId:p.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),m.length===0?e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(v=>{const y=v.accepting_clients===!1;return e.jsx(be,{className:`border-2 transition-colors ${y?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Le,{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}),y&&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:f(v.price_cents,v.billing_interval)}),y?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(z,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(Wf,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(z,{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(Wr,{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(z,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(Wf,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(w7s,{open:i,onOpenChange:l,coachId:p.id,coachName:h==null?void 0:h.name,packages:m.map(v=>({id:v.id,name:v.name}))})]})}const N7s=Gj({full_name:Jo().trim().min(2,"Please enter your full name").max(100),email:Jo().trim().email("Enter a valid email").max(255),phone:Jo().trim().max(40).optional().or(jx("")),brokerage:Jo().trim().max(150).optional().or(jx("")),years_experience:Jo().trim().max(40).optional().or(jx("")),specialties:Jo().trim().max(500).optional().or(jx("")),why_coach:Jo().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:Jo().trim().max(2e3).optional().or(jx("")),website_url:Jo().trim().max(300).optional().or(jx("")),linkedin_url:Jo().trim().max(300).optional().or(jx(""))});function k7s(){const s=zn(),[t,n]=_.useState(!1),[r,a]=_.useState(!1),[i,l]=_.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var m;d.preventDefault();const u=N7s.safeParse(i);if(!u.success){const p=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return ne.error(p||"Please check the form and try again")}n(!0);const{error:h}=await U.from("coach_applications").insert(u.data);if(n(!1),h)return ne.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(Mr,{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(z,{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(or,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(ka,{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(On,{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(kl,{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(Kh,{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(Mr,{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(jl,{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(Ia,{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(j5,{label:"Full name *",children:e.jsx(pe,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(j5,{label:"Email *",children:e.jsx(pe,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(j5,{label:"Phone",children:e.jsx(pe,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(j5,{label:"Current brokerage",children:e.jsx(pe,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(j5,{label:"Years in real estate",children:e.jsx(pe,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(j5,{label:"Coaching specialties",children:e.jsx(pe,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(j5,{label:"Website",children:e.jsx(pe,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(j5,{label:"LinkedIn",children:e.jsx(pe,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(j5,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ps,{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(j5,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ps,{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(z,{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 j5({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const wet="/assets/testimonial-avatar-1-BsCQFauB.jpg",jet="/assets/testimonial-avatar-2-B6VPVc2t.jpg",Net="/assets/testimonial-avatar-3-GuEFwYUE.jpg",ket="/assets/testimonial-avatar-4-98iKMtkB.jpg",Cet="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",S7s=[wet,jet,Net,ket,Cet],C7s=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:lae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:eLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:tLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:sLe},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:nLe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:rLe}];function A7s({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(un,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const E7s=Gj({name:Jo().trim().min(2,"Name must be at least 2 characters").max(100),email:Jo().trim().email("Please enter a valid email address").max(255),phone:Jo().trim().min(10,"Please enter a valid phone number").max(20).optional().or(jx("")),brokerage:Jo().trim().max(200).optional().or(jx(""))}),T7s=[{icon:dm,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:yc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ya,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Bu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:$r,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Ko,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],M7s=[{category:"Marketing Studio",icon:Nh,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:bu,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:k0,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:rg,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:fm,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:oi,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],P7s=[{icon:On,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:va,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Hf,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ha,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:wl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Fo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:cf,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],L7s=[{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."}],Ole="bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]",I7s=()=>{const s=zn(),[t,n]=_.useState(!1),[r,a]=_.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=_.useState({}),o=async d=>{var h,m;d.preventDefault(),l({});const u=E7s.safeParse(r);if(!u.success){const p={};u.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 U.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((h=r.phone)==null?void 0:h.trim())||void 0,brokerage:((m=r.brokerage)==null?void 0:m.trim())||void 0,referral_code:p}});if(g){console.error("Trial signup error:",g),ne.error(g.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){ne.error(f.error);return}ne.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),ne.error("Something went wrong. Please try again.")}finally{n(!1)}},c=()=>{var d;(d=document.getElementById("trial-form"))==null||d.scrollIntoView({behavior:"smooth",block:"center"})};return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:"LevelUp — Start Your Free Trial | Real Growth. Real Tools. Real Results."}),e.jsx("meta",{name:"description",content:"Try LevelUp free — the all-in-one platform for real estate agents: coaching, done-for-you marketing, CRM, lead sites, social studio, and 40+ tools built to help you scale."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/trial"}),e.jsx("meta",{property:"og:title",content:"LevelUp — Start Your Free Trial | Real Growth. Real Tools. Real Results."}),e.jsx("meta",{property:"og:description",content:"Try LevelUp free — coaching, done-for-you marketing, CRM, lead sites, social studio, and 40+ tools built to help you scale."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://dashboard.relevelup.com/trial"}),e.jsx("meta",{property:"og:image",content:"https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/trial-og.png"}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:image",content:"https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/trial-og.png"}),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("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),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:FAe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(z,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var d;return(d=document.getElementById("features"))==null?void 0:d.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(z,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center pt-28 md:pt-36 pb-20 md:pb-28",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"7-Day Free Trial • No Credit Card Required"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-6xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["Take LevelUp for a"," ",e.jsx("span",{className:"bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent italic",children:"Free Test Drive"})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-xl mx-auto lg:mx-0 leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Mr,{className:"h-5 w-5 text-[#7fd4cc]"}),e.jsx("span",{children:"No credit card required"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Mr,{className:"h-5 w-5 text-[#7fd4cc]"}),e.jsx("span",{children:"Full access to all features"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 justify-center lg:justify-start pt-2 animate-fade-in",children:[e.jsx("div",{className:"flex -space-x-3",children:S7s.map((d,u)=>e.jsx("img",{src:d,alt:`Agent ${u+1}`,className:"w-10 h-10 rounded-full border-2 border-white/20 object-cover"},u))}),e.jsxs("div",{children:[e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(d=>e.jsx(Ia,{className:"h-4 w-4 fill-[#e6c878] text-[#e6c878]"},d))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center lg:justify-start gap-x-6 gap-y-2 text-sm text-white/50 animate-fade-in",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Om,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(cf,{className:"h-4 w-4 text-[#7fd4cc]"})," Set up in 2 minutes"]})]})]}),e.jsxs("div",{id:"trial-form",className:"lg:pl-8 relative",children:[e.jsx("div",{className:"absolute -inset-6 rounded-[32px] bg-[#4aa8a0]/20 blur-2xl","aria-hidden":!0}),e.jsx(be,{className:"relative bg-white shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)] border-0 animate-[hero-float_7s_ease-in-out_infinite]",children:e.jsxs(Le,{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(Xf,{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(ee,{htmlFor:"name",children:"Full Name *"}),e.jsx(pe,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:d=>a({...r,name:d.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(ee,{htmlFor:"email",children:"Email Address *"}),e.jsx(pe,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:d=>a({...r,email:d.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(ee,{htmlFor:"phone",children:"Phone Number"}),e.jsx(pe,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:d=>a({...r,phone:d.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(ee,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:d=>a({...r,brokerage:d.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(z,{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(bt,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Da,{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.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 ${Ole}`})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what you'll open on day one of your trial."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:C7s.map(d=>e.jsx(A7s,{slot:d},d.key))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(z,{size:"lg",onClick:c,className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Try It Free for 7 Days",e.jsx(Da,{className:"ml-2 w-5 h-5"})]})})]})]}),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.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(X4,{className:"w-4 h-4"}),"40+ tools & counting"]}),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:T7s.map((d,u)=>e.jsxs(be,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(_t,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(d.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Nt,{className:"text-xl font-sans",children:d.title})]}),e.jsx(Le,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:d.description})})]},u))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Ole}`})}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools — all included in your free trial."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:M7s.map(d=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:e.jsx(d.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:d.category})]}),e.jsx("ul",{className:"space-y-2.5",children:d.items.map(u=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),u]},u))})]},d.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),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 ${Ole}`})}),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:P7s.map((d,u)=>e.jsxs(be,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(d.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Nt,{className:"text-lg font-semibold text-white",children:d.title})]}),e.jsx(Le,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:d.description})})]},u))})]})]}),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:L7s.map((d,u)=>e.jsx(be,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Le,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(Ia,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},h))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',d.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:d.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d.role})]})]})},u))})]})}),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(Om,{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(cf,{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(On,{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(be,{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 ${Ole}`})}),e.jsxs(Le,{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(z,{onClick:c,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(Da,{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:FH,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:"© 2026 LevelUp Consulting Group. All rights reserved."})]})})})]})]})},D7s=()=>{const s=zn();return e.jsxs(e.Fragment,{children:[e.jsx(dl,{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:FAe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(z,{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(be,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Le,{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(Mr,{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(Ix,{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(on,{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(z,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(Da,{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:FH,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},R7s="https://us06web.zoom.us/meeting/register/7Ybq3ZIkRn2_RLkkv_uY8A",zle="ld-open-house-invite-dismissed";function X9t({pageKey:s,headline:t="Not ready to join the LevelUp family yet?",delayMs:n=15e3}){const[r,a]=_.useState(!1);_.useEffect(()=>{if(localStorage.getItem(`${zle}-${s}`))return;let o=null;const c=d=>{d.clientY<=0&&!localStorage.getItem(`${zle}-${s}`)&&a(!0)};return o=setTimeout(()=>{localStorage.getItem(`${zle}-${s}`)||a(!0)},n),document.addEventListener("mouseleave",c),()=>{o&&clearTimeout(o),document.removeEventListener("mouseleave",c)}},[s,n]);const i=()=>{a(!1),localStorage.setItem(`${zle}-${s}`,"1")};return e.jsx(Is,{open:r,onOpenChange:l=>!l&&i(),children:e.jsx(Ls,{className:"laborday-theme max-w-md border-0 p-0 overflow-hidden bg-transparent",overlayClassName:"bg-black/70 backdrop-blur-sm",children:e.jsxs("div",{className:"relative text-white",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)) 0%, hsl(var(--ld-navy-deep)) 100%)"},children:[e.jsx("div",{className:"h-2 w-full",style:{background:"repeating-linear-gradient(90deg, hsl(var(--ld-red)) 0px, hsl(var(--ld-red)) 24px, hsl(var(--ld-cream)) 24px, hsl(var(--ld-cream)) 48px, hsl(var(--ld-navy)) 48px, hsl(var(--ld-navy)) 72px)"}}),e.jsx("button",{onClick:i,className:"absolute right-3 top-5 rounded-full p-1.5 text-white/70 hover:bg-white/10 hover:text-white transition-colors","aria-label":"Close",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsxs("div",{className:"p-6 pt-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-white/10 ring-1 ring-white/20",children:e.jsx(Xr,{className:"h-6 w-6 ld-gold-text"})}),e.jsxs(Os,{children:[e.jsx(Rs,{className:"text-xl font-bold leading-tight text-white",children:t}),e.jsxs(_r,{className:"text-white/80 mt-3 text-sm leading-relaxed",children:["Join us for our next"," ",e.jsx("span",{className:"font-semibold ld-gold-text",children:"LevelUp Live Open House"})," ","and get an inside look at our agent growth platform."]})]}),e.jsxs("div",{className:"mt-5 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm font-medium text-white ring-1 ring-white/15",children:[e.jsx(ya,{className:"h-4 w-4 ld-gold-text"}),"Every Friday at 1:00 PM ET"]}),e.jsxs("div",{className:"mt-6 flex flex-col gap-3",children:[e.jsx(z,{asChild:!0,size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsxs("a",{href:R7s,target:"_blank",rel:"noreferrer",className:"gap-2",children:["Register for the Open House",e.jsx(mr,{className:"h-4 w-4"})]})}),e.jsx(z,{variant:"ghost",onClick:i,className:"w-full text-white/70 hover:bg-white/10 hover:text-white",children:"Maybe later"})]}),e.jsx("p",{className:"mt-4 text-xs text-white/50",children:"No pressure — you can always come back to this offer."})]})]})})})}const Q9t=Date.UTC(2026,8,12,3,59,59),x7e="Friday, September 11 at 11:59 PM ET",g7e=300,Ble=39*12,F7s=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:lae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:eLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:tLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:sLe},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:nLe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:rLe}],O7s=[{name:"Valerie Harp",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"Level Up has been an absolute game changer for my real estate business. The platform is incredibly easy to use and by far one of the most user-friendly systems I've worked with. Everything is streamlined, intuitive, and designed with agents in mind."},{name:"Robert Larente",meta:"Real Estate Agent",when:"5 months ago",text:"I'm fortunate that my Broker started providing LevelUp membership a few years ago. Originally I used it for kvCore/Bold CRM training. But with the amazing amount of resources that Jeremy and his crew keep adding, I'm quickly canceling my subscriptions to other service providers."},{name:"Tom Lois",meta:"Real Estate Agent",when:"5 months ago",text:"Jeremy and his team at LevelUp continue to upgrade, update, and uplift agents with their meaningful content and insight. Whether you're a newbie or a seasoned agent, this program is for you! Try it — you'll REALLY like it!"},{name:"Michael Smith",meta:"Local Guide · Real Estate Agent",when:"7 months ago",text:"Great value in the material, ideas, etc. shared by the LevelUp team. They consistently provide implementable examples of ways to impact your real estate business. Not just theory, but real ideas/tasks that can be quickly implemented."},{name:"Pamela Nichols",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"I'm loving this platform and all the excellent quick and easy information to use! It has been the easiest thing I've ever used to care for my database! I love the quick videos — quick and to the point!"},{name:"Tracy VanderWall",meta:"Local Guide · Broker/Owner",when:"7 months ago",text:"Best investment my brokerage has made! The value of this platform is AMAZING! The entire LEVELUP Team is wonderful!"},{name:"Bill Burns",meta:"Local Guide · Broker",when:"5 months ago",text:"Jeremy and his team are amazing! Level Up can next level your brokerage!"},{name:"Anissa, REMAX Executives",meta:"Real Estate Agent",when:"6 months ago",text:"So far this has helped me tremendously! Keeps me more organized and motivated to stay on top of these leads that get lost in the daily mix."}],z7s="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",J9t=[{icon:On,title:"1:1 & Group Coaching",desc:"Book live coaching sessions with Jeremy and the LevelUp team — Google Meet created automatically, tracked on your calendar.",value:1200},{icon:j7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — your database finally organized.",value:600},{icon:jv,title:"Deal Pipeline",desc:"Track every transaction from offer to closing with tasks, forms and commission math built in.",value:480},{icon:Lx,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos — no photographer or stager needed.",value:1200},{icon:yc,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine.",value:720},{icon:Wo,title:"Lead Sites",desc:"SEO-optimized neighborhood and listing websites that rank on Google and capture leads 24/7.",value:960},{icon:fm,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech — live weekly sessions too.",value:588},{icon:cb,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place.",value:300},{icon:Xr,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts delivered every Monday, plus screen recording and virtual backgrounds.",value:468},{icon:qi,title:"Reviews Engine",desc:"Collect Google and video reviews with a single link — your reputation on autopilot.",value:240},{icon:un,title:"ChatGPT App + 30 AI Tools",desc:"Your entire business controllable from ChatGPT — create contacts, open houses, marketing assets and more.",value:500},{icon:ya,title:"My Calendar & Booking",desc:"Agent-first calendar with time zones, Google Calendar sync and self-serve booking links.",value:144}],_gt=J9t.reduce((s,t)=>s+t.value,0),B7s=[{q:"What happens after the first year?",a:"Your rate is locked in. As long as your subscription stays active, you renew at $300/year — forever. No surprises, no bump to the regular price."},{q:"Is this the full platform or a stripped-down version?",a:"The full platform. Everything an Individual Agent member gets: coaching, CRM, deal pipeline, Staging Studio, Marketing Studio, lead sites, Academy, forms with e-signature, reviews, Weekly Reels, Listing Exchange and the ChatGPT app."},{q:"How do I manage or cancel my subscription?",a:"Right from your profile. Your billing lives in your LevelUp account settings with a Stripe customer portal — change cards, see invoices or cancel anytime without calling anyone."},{q:"Is there a free trial with this offer?",a:"No trial on this one — you're charged $300 today and get a full 12 months. That's how we're able to offer the lowest rate we've ever run."},{q:"I'm already a monthly member. Can I switch?",a:"Yes — use the button with the same email on your account and Stripe will match you. If anything looks off after checkout, reach out and we'll sort it immediately."},{q:"Who is LevelUp for?",a:"Solo agents and team agents who want one system for their database, marketing, deals and growth coaching — whether you're brand new or a seasoned producer."}];function ezt(s){const[t,n]=_.useState(()=>Date.now());_.useEffect(()=>{const i=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(i)},[]);const r=Math.max(0,s-t),a=Math.floor(r/1e3);return{expired:r<=0,d:Math.floor(a/86400),h:Math.floor(a%86400/3600),m:Math.floor(a%3600/60),sec:a%60}}function wgt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=ezt(Q9t);if(i)return null;const l=[{v:t,l:"Days"},{v:n,l:"Hours"},{v:r,l:"Min"},{v:a,l:"Sec"}];return e.jsx("div",{className:"flex items-center gap-2 sm:gap-3",children:l.map(o=>e.jsxs("div",{className:`${s?"ld-glass":"bg-card border"} rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-center min-w-[60px] sm:min-w-[72px]`,children:[e.jsx("div",{className:`text-2xl sm:text-3xl font-bold tabular-nums ${s?"text-white":"text-foreground"}`,children:String(o.v).padStart(2,"0")}),e.jsx("div",{className:`text-[10px] uppercase tracking-widest ${s?"text-white/60":"text-muted-foreground"}`,children:o.l})]},o.l))})}function jgt(){return e.jsx("div",{className:"flex gap-0.5","aria-label":"5 out of 5 stars",children:Array.from({length:5}).map((s,t)=>e.jsx(Ia,{className:"h-4 w-4 fill-accent text-accent"},t))})}function $7s({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(un,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label}),e.jsx("p",{className:`text-xs px-6 text-center ${t?"text-white/40":"text-muted-foreground/70"}`,children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function U7s(){const{expired:s}=ezt(Q9t),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),d=_.useMemo(()=>[wet,jet,Net,ket,Cet],[]),u=Ble-g7e,h=async()=>{if(!r.trim()||!r.includes("@")){ne.error("Enter your email to claim the offer.");return}l(!0);try{const{data:m,error:p}=await U.functions.invoke("create-checkout",{body:{tier:"individual_annual",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(p){const f=p instanceof Bre?await p.context.text():p.message;throw new Error(f||"Checkout failed to start")}if(m!=null&&m.url){window.location.href=m.url;return}throw new Error("No checkout URL returned")}catch(m){console.error("Labor Day checkout error:",m),ne.error(m.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(dl,{children:[e.jsx("title",{children:"Labor Day Sale — LevelUp for $300/Year (Save $168) | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:`Labor Day only: get the full LevelUp agent growth platform — coaching, CRM, deal pipeline, Staging Studio, marketing and more — for $300/year instead of $39/month. Locked in for as long as you stay a member. Ends ${x7e}.`}),e.jsx("meta",{property:"og:title",content:"Labor Day Sale — LevelUp for $300/Year"}),e.jsx("meta",{property:"og:description",content:"Coaching, CRM, deal pipeline, Staging Studio, marketing studio and more. $300/year, locked in. Ends Sept 11 at midnight."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Archivo+Black&display=swap",rel:"stylesheet"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"Offer",name:"LevelUp Individual Agent — Labor Day Annual",price:"300.00",priceCurrency:"USD",availabilityEnds:"2026-09-11T23:59:59-04:00",seller:{"@type":"Organization",name:"LevelUp Consulting Group"}})})]}),!s&&e.jsxs("div",{className:"fixed bottom-0 inset-x-0 z-50 md:hidden bg-foreground/95 backdrop-blur border-t border-white/10 px-4 py-3 flex items-center justify-between gap-3",style:{backgroundColor:"hsl(var(--ld-navy-deep) / 0.96)"},children:[e.jsxs("div",{className:"text-white",children:[e.jsx("div",{className:"text-xs text-white/60 uppercase tracking-wider",children:"Labor Day"}),e.jsxs("div",{className:"font-bold",children:["$300",e.jsx("span",{className:"text-sm font-normal text-white/70",children:"/year"})," ",e.jsxs("span",{className:"text-xs line-through text-white/50 ml-1",children:["$",Ble]})]})]}),e.jsx(z,{asChild:!0,className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold",children:e.jsx("a",{href:"#claim",children:"Claim Offer"})})]}),e.jsxs("header",{className:"ld-dark relative overflow-hidden",children:[e.jsx("div",{className:"ld-flagbar absolute top-0 inset-x-0 z-10"}),e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.10] pointer-events-none"}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-6 pt-12 pb-20 md:pb-28",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:FH,alt:"LevelUp Consulting Group",className:"h-9 md:h-11 w-auto"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-white/70 text-sm",children:[e.jsx("div",{className:"flex -space-x-2",children:d.map((m,p)=>e.jsx("img",{src:m,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},p))}),e.jsx("span",{children:"3,000+ agents"})]})]}),e.jsxs("div",{className:"mt-16 md:mt-24 text-center max-w-4xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("span",{className:"ld-stamp text-xs sm:text-sm",children:"★ Labor Day Sale ★"}),e.jsxs("p",{className:"mt-4 text-white/60 text-xs sm:text-sm uppercase tracking-[0.2em] font-semibold",children:["Ends ",x7e]})]}),e.jsxs("h1",{className:"ld-display text-4xl sm:text-6xl lg:text-7xl text-white leading-[1.05] uppercase",children:["Everything you need to grow your business.",e.jsx("span",{className:"block mt-4 ld-gold-text",children:"One payment of $300."})]}),e.jsx("div",{className:"mt-6 flex items-center justify-center gap-2 text-accent","aria-hidden":!0,children:Array.from({length:5}).map((m,p)=>e.jsx(Ia,{className:"h-4 w-4 fill-accent text-accent"},p))}),e.jsxs("p",{className:"mt-6 text-lg md:text-xl text-white/75 max-w-2xl mx-auto leading-relaxed",children:["Coaching, a full agent growth platform, CRM, deal pipeline, Staging Studio, marketing studio and more —"," ",e.jsxs("span",{className:"text-white font-semibold",children:["normally $39/month ($",Ble,"/year)"]}),". This week only, get a full year for"," ",e.jsx("span",{className:"text-white font-semibold",children:"$300"}),", locked in for as long as you're a member."]}),e.jsxs("div",{className:"mt-10 flex flex-col items-center gap-4",children:[e.jsx(wgt,{dark:!0}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/50",children:"Offer disappears when the clock hits zero"})]}),e.jsxs("form",{id:"claim",onSubmit:m=>{m.preventDefault(),h()},className:"mt-8 mx-auto max-w-xl ld-glass rounded-2xl p-4 sm:p-5",children:[s?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("p",{className:"text-white font-semibold text-lg",children:"This Labor Day offer has ended."}),e.jsx("p",{className:"text-white/60 text-sm mt-1 mb-4",children:"You can still join LevelUp with a free 7-day trial."}),e.jsx(z,{asChild:!0,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold w-full sm:w-auto",children:e.jsxs("a",{href:"/trial",children:["Start a Free Trial ",e.jsx(Da,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(pe,{value:t,onChange:m=>n(m.target.value),placeholder:"Your name",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"name"}),e.jsx(pe,{value:r,onChange:m=>a(m.target.value),type:"email",placeholder:"Your email",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"email",required:!0}),e.jsx(z,{type:"submit",disabled:i,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-bold h-12 px-6 whitespace-nowrap",children:i?e.jsx(bt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Lock in $300/yr ",e.jsx(Da,{className:"ml-2 h-5 w-5"})]})})]}),!s&&e.jsxs("p",{className:"text-white/50 text-xs mt-3 flex items-center justify-center gap-1.5",children:[e.jsx(Hl,{className:"h-3 w-3"})," Secure Stripe checkout · Manage or cancel anytime from your profile"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," to run and grow their business"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"Everything included"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"One membership. The entire platform."}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["This isn't a teaser tier. You get every tool LevelUp members use daily — worth $",_gt.toLocaleString(),"/year at market rates."]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:[J9t.map(m=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 flex flex-col gap-3 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(m.icon,{className:"h-5 w-5 text-primary"})}),e.jsxs("span",{className:"text-xs font-semibold text-muted-foreground bg-muted rounded-full px-2.5 py-1",children:["$",m.value.toLocaleString(),"/yr value"]})]}),e.jsx("h3",{className:"font-bold text-lg",children:m.title}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:m.desc})]},m.title)),e.jsxs("div",{className:"bg-foreground text-background rounded-2xl p-6 flex flex-col justify-center items-center text-center gap-2",style:{backgroundColor:"hsl(var(--ld-navy))",color:"white"},children:[e.jsx("div",{className:"text-sm uppercase tracking-widest text-white/60",children:"Total value"}),e.jsxs("div",{className:"text-4xl font-bold",children:["$",_gt.toLocaleString(),e.jsx("span",{className:"text-lg font-normal text-white/60",children:"/yr"})]}),e.jsxs("div",{className:"text-white/70 text-sm",children:["Your Labor Day price: ",e.jsx("span",{className:"font-bold text-white",children:"$300/yr"})]})]})]})]})}),e.jsx("section",{className:"ld-dark py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-accent",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10",children:F7s.map(m=>e.jsx($7s,{slot:m},m.key))})]})}),e.jsx("div",{className:"ld-divider pb-4","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 bg-card border rounded-full px-5 py-2.5 mb-6",children:[e.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5","aria-hidden":!0,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.1a7.16 7.16 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"})]}),e.jsx("span",{className:"font-semibold",children:"5.0"}),e.jsx(jgt,{}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"on Google"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Why 3,000+ agents trust LevelUp"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Real reviews from real agents, pulled from our Google Business profile."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:O7s.map(m=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(jgt,{}),e.jsxs("p",{className:"text-sm text-foreground/90 leading-relaxed flex-1",children:['"',m.text,'"']}),e.jsxs("footer",{children:[e.jsx("div",{className:"font-semibold text-sm",children:m.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.meta," · ",m.when]})]})]},m.name))}),e.jsx("div",{className:"text-center mt-8",children:e.jsx("a",{href:z7s,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-primary hover:underline",children:"Read all reviews on Google →"})})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("div",{className:"text-center mb-12",children:e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"The math is simple"})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-card border rounded-3xl p-8",children:[e.jsx("h3",{className:"font-bold text-xl text-muted-foreground",children:"Regular Monthly"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-5xl font-bold text-muted-foreground",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(er,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",Ble," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(er,{className:"h-4 w-4 mt-0.5 shrink-0"})," Price can change at renewal"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary"})," Full platform access"]})]})]}),e.jsxs("div",{className:"relative rounded-3xl p-8 text-white overflow-hidden",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)), hsl(var(--ld-navy-deep)))"},children:[e.jsxs("div",{className:"absolute top-4 right-4 bg-accent text-accent-foreground text-xs font-bold uppercase tracking-wider rounded-full px-3 py-1",children:["Save $",u]}),e.jsx("h3",{className:"font-bold text-xl",children:"Labor Day Annual"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold",children:["$",g7e]}),e.jsx("span",{className:"text-white/70",children:"/year"})]}),e.jsx("p",{className:"text-accent font-semibold text-sm mt-1",children:"That's just $25/month"}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-white/85",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",g7e," per year — save $",u," vs monthly"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(KU,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Rate locked in for as long as you're a member"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Full platform access — everything included"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Om,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx(z,{asChild:!0,size:"lg",className:"mt-8 w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsx("a",{href:"#claim",children:"Claim the $300/yr rate"})})]})]})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight text-center mb-10",children:"Questions agents ask"}),e.jsx("div",{className:"space-y-3",children:B7s.map((m,p)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===p?null:p),className:"w-full flex items-center justify-between gap-4 px-6 py-4 text-left font-semibold",children:[m.q,e.jsx("span",{className:`transition-transform ${o===p?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===p&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:m.a})]},p))})]})}),e.jsx("div",{className:"ld-divider pb-14","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsxs("section",{className:"ld-dark relative overflow-hidden py-20 md:py-28 px-6",children:[e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.08] pointer-events-none"}),e.jsx("div",{className:"ld-flagbar absolute bottom-0 inset-x-0"}),e.jsxs("div",{className:"relative max-w-3xl mx-auto text-center",children:[e.jsx("h2",{className:"ld-display text-3xl md:text-5xl text-white uppercase",children:"This is the lowest rate we've ever run."}),e.jsx("p",{className:"text-white/70 mt-5 text-lg",children:"When the timer hits zero, the $300/year rate is gone. Lock it in now and keep it for as long as you're a member."}),e.jsx("div",{className:"mt-8 flex justify-center",children:e.jsx(wgt,{dark:!0})}),e.jsx(z,{asChild:!0,size:"lg",className:"mt-10 bg-accent text-accent-foreground hover:bg-accent/90 font-bold text-lg px-10 py-6",children:e.jsxs("a",{href:"#claim",children:["Get LevelUp for $300/year ",e.jsx(Da,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-white/40 text-xs mt-4 flex items-center justify-center gap-1.5",children:[e.jsx(Hl,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",x7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(X9t,{pageKey:"individual-labor-day-2026",headline:"Not ready to join the LevelUp family yet?"})]})}const tzt=Date.UTC(2026,8,12,3,59,59),y7e="Friday, September 11 at 11:59 PM ET",jX=399,G4e=499,Ngt=(G4e-jX)*12,q7s=[{key:"dashboard",label:"Agent Command Center",caption:"Every agent's day — smart queue, calendar and pipeline in one view.",src:lae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history for every agent.",src:eLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every transaction with tasks, forms and commission tracking built in.",src:tLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:sLe},{key:"coaching",label:"Coaching",caption:"Live coaching sessions your agents book themselves.",src:nLe},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded.",src:rLe}],V7s=[{name:"Tracy VanderWall",meta:"Local Guide · Broker/Owner",when:"7 months ago",text:"Best investment my brokerage has made! The value of this platform is AMAZING! The entire LEVELUP Team is wonderful!"},{name:"Bill Burns",meta:"Local Guide · Broker",when:"5 months ago",text:"Jeremy and his team are amazing! Level Up can next level your brokerage!"},{name:"Robert Larente",meta:"Real Estate Agent",when:"5 months ago",text:"I'm fortunate that my Broker started providing LevelUp membership a few years ago. Originally I used it for kvCore/Bold CRM training. But with the amazing amount of resources that Jeremy and his crew keep adding, I'm quickly canceling my subscriptions to other service providers."},{name:"Valerie Harp",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"Level Up has been an absolute game changer for my real estate business. The platform is incredibly easy to use and by far one of the most user-friendly systems I've worked with. Everything is streamlined, intuitive, and designed with agents in mind."},{name:"Tom Lois",meta:"Real Estate Agent",when:"5 months ago",text:"Jeremy and his team at LevelUp continue to upgrade, update, and uplift agents with their meaningful content and insight. Whether you're a newbie or a seasoned agent, this program is for you! Try it — you'll REALLY like it!"},{name:"Michael Smith",meta:"Local Guide · Real Estate Agent",when:"7 months ago",text:"Great value in the material, ideas, etc. shared by the LevelUp team. They consistently provide implementable examples of ways to impact your real estate business. Not just theory, but real ideas/tasks that can be quickly implemented."},{name:"Pamela Nichols",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"I'm loving this platform and all the excellent quick and easy information to use! It has been the easiest thing I've ever used to care for my database! I love the quick videos — quick and to the point!"},{name:"Anissa, REMAX Executives",meta:"Real Estate Agent",when:"6 months ago",text:"So far this has helped me tremendously! Keeps me more organized and motivated to stay on top of these leads that get lost in the daily mix."}],H7s="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",G7s=[{icon:C0,title:"Live Weekly Trainings",desc:"Every agent joins live weekly training sessions with Jeremy and the LevelUp team — plus the full on-demand Academy."},{icon:j7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — every agent's database finally organized."},{icon:jv,title:"Deal Pipeline",desc:"Transactions from offer to closing with tasks, forms and commission math built in."},{icon:Lx,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos for every listing."},{icon:yc,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine."},{icon:Wo,title:"Lead Sites",desc:"SEO-optimized websites that rank on Google and capture leads 24/7."},{icon:fm,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech."},{icon:cb,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place."},{icon:Xr,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts every Monday, plus screen recording and virtual backgrounds."}],W7s=[{icon:oi,title:"Your Own Brokerage Hub",desc:"Brand profiles, announcements and resources pushed to every agent from one place."},{icon:cb,title:"Brokerage Form Library",desc:"Publish your official forms office-wide — agents use them read-only or copy to customize."},{icon:Pl,title:"Recruiting Pipeline",desc:"Customizable recruiting stages to attract and track your next agents."},{icon:Nh,title:"Office-Wide Communication",desc:"Broadcasts, brokerage content and resource libraries your agents actually use."}],K7s=[{q:"What does 'unlimited agents' actually mean?",a:"Every agent in your brokerage gets a full LevelUp membership — coaching, CRM, deal pipeline, Staging Studio, Marketing Studio, lead sites, Academy, forms with e-signature, reviews, Weekly Reels and the ChatGPT app. No per-seat fees, no caps, no tiers to unlock."},{q:"Is the $399/mo rate really locked in?",a:"Yes. As long as your subscription stays active, you renew at $399/month — even when the standard brokerage rate goes back to $499/month. No surprises, no bump after year one."},{q:"What happens after I pay?",a:"You'll land on a setup screen where you name your brokerage, set your branding, and start inviting agents. Agents accept their invite and have full access within minutes."},{q:"What if we add or lose agents during the year?",a:"Nothing changes on your bill. The rate is flat $399/month for the whole brokerage whether you have 10 agents or 100. Add and remove agents freely from your brokerage dashboard."},{q:"Is there a contract or trial?",a:"No long-term contract and no trial on this one — you're charged $399 today and billed monthly. Manage or cancel anytime from your profile's Stripe customer portal."},{q:"Is this really the last brokerage offer this year?",a:"Yes. This is our final brokerage partnership promotion of 2026. When the clock hits zero on September 11, this rate is gone."}];function szt(s){const[t,n]=_.useState(()=>Date.now());_.useEffect(()=>{const i=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(i)},[]);const r=Math.max(0,s-t),a=Math.floor(r/1e3);return{expired:r<=0,d:Math.floor(a/86400),h:Math.floor(a%86400/3600),m:Math.floor(a%3600/60),sec:a%60}}function kgt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=szt(tzt);if(i)return null;const l=[{v:t,l:"Days"},{v:n,l:"Hours"},{v:r,l:"Min"},{v:a,l:"Sec"}];return e.jsx("div",{className:"flex items-center gap-2 sm:gap-3",children:l.map(o=>e.jsxs("div",{className:`${s?"ld-glass":"bg-card border"} rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-center min-w-[60px] sm:min-w-[72px]`,children:[e.jsx("div",{className:`text-2xl sm:text-3xl font-bold tabular-nums ${s?"text-white":"text-foreground"}`,children:String(o.v).padStart(2,"0")}),e.jsx("div",{className:`text-[10px] uppercase tracking-widest ${s?"text-white/60":"text-muted-foreground"}`,children:o.l})]},o.l))})}function Sgt(){return e.jsx("div",{className:"flex gap-0.5","aria-label":"5 out of 5 stars",children:Array.from({length:5}).map((s,t)=>e.jsx(Ia,{className:"h-4 w-4 fill-accent text-accent"},t))})}function Y7s({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(un,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function Z7s(){const{expired:s}=szt(tzt),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),d=_.useMemo(()=>[wet,jet,Net,ket,Cet],[]),u=async()=>{if(!r.trim()||!r.includes("@")){ne.error("Enter your email to claim the offer.");return}l(!0);try{const{data:h,error:m}=await U.functions.invoke("create-checkout",{body:{tier:"brokerage_labor_day",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(m){const p=m instanceof Bre?await m.context.text():m.message;throw new Error(p||"Checkout failed to start")}if(h!=null&&h.url){window.location.href=h.url;return}throw new Error("No checkout URL returned")}catch(h){console.error("Brokerage Labor Day checkout error:",h),ne.error(h.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(dl,{children:[e.jsx("title",{children:"Labor Day Brokerage Special — LevelUp for $399/mo, Unlimited Agents | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:`Last brokerage offer of 2026: give every agent in your brokerage a full LevelUp membership — live weekly trainings, CRM, marketing and more — for $399/mo instead of $499/mo. Rate locked. Ends ${y7e}.`}),e.jsx("meta",{property:"og:title",content:"Labor Day Brokerage Special — $399/mo for Your Entire Brokerage"}),e.jsx("meta",{property:"og:description",content:"Unlimited agents, full memberships, live weekly trainings. $399/mo instead of $499/mo, locked in. Last brokerage offer of 2026 — ends Sept 11 at midnight."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Archivo+Black&display=swap",rel:"stylesheet"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"Offer",name:"LevelUp Brokerage Partner — Labor Day Offer",price:"399.00",priceCurrency:"USD",availabilityEnds:"2026-09-11T23:59:59-04:00",seller:{"@type":"Organization",name:"LevelUp Consulting Group"}})})]}),!s&&e.jsxs("div",{className:"fixed bottom-0 inset-x-0 z-50 md:hidden bg-foreground/95 backdrop-blur border-t border-white/10 px-4 py-3 flex items-center justify-between gap-3",style:{backgroundColor:"hsl(var(--ld-navy-deep) / 0.96)"},children:[e.jsxs("div",{className:"text-white",children:[e.jsx("div",{className:"text-xs text-white/60 uppercase tracking-wider",children:"Brokerage Labor Day"}),e.jsxs("div",{className:"font-bold",children:["$",jX,e.jsx("span",{className:"text-sm font-normal text-white/70",children:"/mo"})," ",e.jsxs("span",{className:"text-xs line-through text-white/50 ml-1",children:["$",G4e]})]})]}),e.jsx(z,{asChild:!0,className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold",children:e.jsx("a",{href:"#claim",children:"Claim Offer"})})]}),e.jsxs("header",{className:"ld-dark relative overflow-hidden",children:[e.jsx("div",{className:"ld-flagbar absolute top-0 inset-x-0 z-10"}),e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.10] pointer-events-none"}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-6 pt-12 pb-20 md:pb-28",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:FH,alt:"LevelUp Consulting Group",className:"h-9 md:h-11 w-auto"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-white/70 text-sm",children:[e.jsx("div",{className:"flex -space-x-2",children:d.map((h,m)=>e.jsx("img",{src:h,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},m))}),e.jsx("span",{children:"3,000+ agents"})]})]}),e.jsxs("div",{className:"mt-16 md:mt-24 text-center max-w-4xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("span",{className:"ld-stamp text-xs sm:text-sm",children:"★ Labor Day Brokerage Special ★"}),e.jsxs("p",{className:"mt-4 text-white/60 text-xs sm:text-sm uppercase tracking-[0.2em] font-semibold",children:["Last brokerage offer of 2026 · Ends ",y7e]})]}),e.jsxs("h1",{className:"ld-display text-4xl sm:text-6xl lg:text-7xl text-white leading-[1.05] uppercase",children:["Every agent in your brokerage. Full membership.",e.jsx("span",{className:"block mt-4 ld-gold-text",children:"$399/mo — not $499."})]}),e.jsx("div",{className:"mt-6 flex items-center justify-center gap-2 text-accent","aria-hidden":!0,children:Array.from({length:5}).map((h,m)=>e.jsx(Ia,{className:"h-4 w-4 fill-accent text-accent"},m))}),e.jsxs("p",{className:"mt-6 text-lg md:text-xl text-white/75 max-w-2xl mx-auto leading-relaxed",children:["Live weekly trainings, a full agent growth platform, CRM, marketing studio and more —"," ",e.jsx("span",{className:"text-white font-semibold",children:"for every agent in your brokerage"}),". Normally"," ",e.jsx("span",{className:"text-white font-semibold",children:"$499/month"}),". Partner this week for"," ",e.jsx("span",{className:"text-white font-semibold",children:"$399/month"}),", locked in for as long as you're a partner."]}),e.jsxs("div",{className:"mt-10 flex flex-col items-center gap-4",children:[e.jsx(kgt,{dark:!0}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/50",children:"Offer disappears when the clock hits zero"})]}),e.jsxs("form",{id:"claim",onSubmit:h=>{h.preventDefault(),u()},className:"mt-8 mx-auto max-w-xl ld-glass rounded-2xl p-4 sm:p-5",children:[s?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("p",{className:"text-white font-semibold text-lg",children:"This Labor Day brokerage offer has ended."}),e.jsx("p",{className:"text-white/60 text-sm mt-1 mb-4",children:"You can still partner with LevelUp at the standard brokerage rate."}),e.jsx(z,{asChild:!0,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold w-full sm:w-auto",children:e.jsxs("a",{href:"/pricing",children:["See Brokerage Plans ",e.jsx(Da,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(pe,{value:t,onChange:h=>n(h.target.value),placeholder:"Your name",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"name"}),e.jsx(pe,{value:r,onChange:h=>a(h.target.value),type:"email",placeholder:"Your email",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"email",required:!0}),e.jsx(z,{type:"submit",disabled:i,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-bold h-12 px-6 whitespace-nowrap",children:i?e.jsx(bt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Partner at $399/mo ",e.jsx(Da,{className:"ml-2 h-5 w-5"})]})})]}),!s&&e.jsxs("p",{className:"text-white/50 text-xs mt-3 flex items-center justify-center gap-1.5",children:[e.jsx(Hl,{className:"h-3 w-3"})," Secure Stripe checkout · Set up your brokerage right after payment"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," and the brokerages they work for"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"What your agents get"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A full membership for every agent. No per-seat fees."}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Individually, this membership costs $39/month per agent. As a brokerage partner, every agent gets it — all included in one flat rate."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:G7s.map(h=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 flex flex-col gap-3 hover:shadow-lg transition-shadow",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(h.icon,{className:"h-5 w-5 text-primary"})}),e.jsx("h3",{className:"font-bold text-lg",children:h.title}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:h.desc})]},h.title))})]})}),e.jsx("section",{className:"ld-dark py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-accent",children:"For the brokerage"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight",children:"Tools that make your office run itself"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto",children:"You get more than agent seats — you get brokerage-level controls."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:W7s.map(h=>e.jsxs("div",{className:"ld-glass rounded-2xl p-6 flex flex-col gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white/10 flex items-center justify-center",children:e.jsx(h.icon,{className:"h-5 w-5 text-accent"})}),e.jsx("h3",{className:"font-bold text-lg text-white",children:h.title}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed",children:h.desc})]},h.title))})]})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A real platform, not another training course"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"This is what your agents open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10",children:q7s.map(h=>e.jsx(Y7s,{slot:h,dark:!1},h.key))})]})}),e.jsx("div",{className:"ld-divider pb-4","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 bg-card border rounded-full px-5 py-2.5 mb-6",children:[e.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5","aria-hidden":!0,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.1a7.16 7.16 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"})]}),e.jsx("span",{className:"font-semibold",children:"5.0"}),e.jsx(Sgt,{}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"on Google"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Brokers and agents agree"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Real reviews from our Google Business profile — including the brokers who made the call."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:V7s.map(h=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Sgt,{}),e.jsxs("p",{className:"text-sm text-foreground/90 leading-relaxed flex-1",children:['"',h.text,'"']}),e.jsxs("footer",{children:[e.jsx("div",{className:"font-semibold text-sm",children:h.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.meta," · ",h.when]})]})]},h.name))}),e.jsx("div",{className:"text-center mt-8",children:e.jsx("a",{href:H7s,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-primary hover:underline",children:"Read all reviews on Google →"})})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("div",{className:"text-center mb-12",children:e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Live in three steps"})}),e.jsx("div",{className:"grid md:grid-cols-3 gap-6",children:[{n:"1",title:"Partner & pay",desc:"Claim the $399/mo rate with secure Stripe checkout. Charged today, billed monthly."},{n:"2",title:"Set up your brokerage",desc:"Name your brokerage, add your branding and configure your office — minutes, not days."},{n:"3",title:"Invite your agents",desc:"Send invites and every agent gets their full membership. They can start this week."}].map(h=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 text-center",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-xl",children:h.n}),e.jsx("h3",{className:"font-bold text-lg mt-4",children:h.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2 leading-relaxed",children:h.desc})]},h.n))})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Do the math"}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["25 agents × $39/mo memberships = $975/mo of value. You pay a flat $",jX,"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-card border rounded-3xl p-8",children:[e.jsx("h3",{className:"font-bold text-xl text-muted-foreground",children:"Standard Brokerage Plan"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold text-muted-foreground",children:["$",G4e]}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(er,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",(G4e*12).toLocaleString()," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(er,{className:"h-4 w-4 mt-0.5 shrink-0"})," Standard rate — no lock-in"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary"})," Unlimited agents, full memberships"]})]})]}),e.jsxs("div",{className:"relative rounded-3xl p-8 text-white overflow-hidden",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)), hsl(var(--ld-navy-deep)))"},children:[e.jsxs("div",{className:"absolute top-4 right-4 bg-accent text-accent-foreground text-xs font-bold uppercase tracking-wider rounded-full px-3 py-1",children:["Save $",Ngt.toLocaleString(),"/yr"]}),e.jsx("h3",{className:"font-bold text-xl",children:"Labor Day Partner Rate"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold",children:["$",jX]}),e.jsx("span",{className:"text-white/70",children:"/month"})]}),e.jsx("p",{className:"text-accent font-semibold text-sm mt-1",children:"25 agents = under $16/agent/mo"}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-white/85",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",(jX*12).toLocaleString()," per year — save $",Ngt.toLocaleString()," vs standard"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(KU,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Rate locked for as long as you're a partner"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Unlimited agents — every one gets a full membership"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Om,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx(z,{asChild:!0,size:"lg",className:"mt-8 w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsx("a",{href:"#claim",children:"Partner at $399/mo"})})]})]})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight text-center mb-10",children:"Questions brokers ask"}),e.jsx("div",{className:"space-y-3",children:K7s.map((h,m)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===m?null:m),className:"w-full flex items-center justify-between gap-4 px-6 py-4 text-left font-semibold",children:[h.q,e.jsx("span",{className:`transition-transform ${o===m?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===m&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:h.a})]},m))})]})}),e.jsx("div",{className:"ld-divider pb-14","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsxs("section",{className:"ld-dark relative overflow-hidden py-20 md:py-28 px-6",children:[e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.08] pointer-events-none"}),e.jsx("div",{className:"ld-flagbar absolute bottom-0 inset-x-0"}),e.jsxs("div",{className:"relative max-w-3xl mx-auto text-center",children:[e.jsx("h2",{className:"ld-display text-3xl md:text-5xl text-white uppercase",children:"The last brokerage offer of 2026."}),e.jsx("p",{className:"text-white/70 mt-5 text-lg",children:"When the timer hits zero, the $399/mo partner rate is gone. Lock it in now and give every agent in your brokerage a full membership."}),e.jsx("div",{className:"mt-8 flex justify-center",children:e.jsx(kgt,{dark:!0})}),e.jsx(z,{asChild:!0,size:"lg",className:"mt-10 bg-accent text-accent-foreground hover:bg-accent/90 font-bold text-lg px-10 py-6",children:e.jsxs("a",{href:"#claim",children:["Partner with LevelUp — $399/mo ",e.jsx(Da,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-white/40 text-xs mt-4 flex items-center justify-center gap-1.5",children:[e.jsx(Hl,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",y7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(X9t,{pageKey:"brokerage-labor-day-2026",headline:"Not ready to partner with LevelUp yet?"})]})}const X7s=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Lead site & Listing Exchange access","Deal pipeline & scorecard tracking","Community forums and support"],Q7s=["Everything in Individual, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Agent onboarding tools","Priority support"],J7s=()=>{const{user:s,loading:t}=hs(),n=zn(),[r]=Gl(),a=r.get("plan"),i=a==="individual"?"individual_agent":a==="brokerage"?"brokerage_over_25":a,[l,o]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(""),m=g=>{const v=`/upgrade?plan=${g}`;n(`/auth?next=${encodeURIComponent(v)}`)},p=async g=>{var v;if(!(s!=null&&s.email)){m(g);return}o(!0),d(g);try{const{data:y,error:b}=await U.functions.invoke("create-checkout",{body:{tier:g,email:s.email,name:((v=s.user_metadata)==null?void 0:v.full_name)||s.email,userId:s.id,couponCode:u.trim()||void 0,skipTrial:!0}});if(b)throw b;if(y!=null&&y.url)window.location.href=y.url;else throw new Error("No checkout URL returned")}catch(y){console.error("Checkout error:",y),ne.error(y.message||"Failed to start checkout. Please try again."),o(!1),d(null)}},f=(g,v,y,b,w,S,C)=>e.jsxs(be,{className:`relative border-2 transition-colors ${C?"border-primary shadow-lg":"border-amber-500/30"} ${i===g?"ring-2 ring-primary ring-offset-2":""}`,children:[i===g&&e.jsx(ze,{className:"absolute -top-3 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground",children:"Recommended for you"}),e.jsxs(Le,{className:"p-6 text-center space-y-4",children:[e.jsx("div",{className:`mx-auto h-12 w-12 rounded-full flex items-center justify-center ${C?"bg-primary/10":"bg-amber-500/10"}`,children:S}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-xl",children:v}),e.jsxs("p",{className:`text-3xl font-bold mt-1 ${C?"text-primary":"text-amber-600"}`,children:[y,e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:b})]}),e.jsx("ul",{className:"text-sm space-y-1.5 text-left text-muted-foreground",children:w.map(E=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Wr,{className:`h-4 w-4 mt-0.5 shrink-0 ${C?"text-primary":"text-amber-600"}`}),e.jsx("span",{children:E})]},E))}),e.jsx(z,{className:"w-full",variant:C?"default":"outline",disabled:l||t,onClick:()=>p(g),children:l&&c===g?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Opening secure checkout…"]}):s?e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Upgrade to ",v]}):e.jsxs(e.Fragment,{children:[e.jsx(lP,{className:"h-4 w-4 mr-2"}),"Sign in & upgrade to ",v]})})]})]});return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-[#f4f7fa] to-white",children:e.jsxs("div",{className:"container max-w-5xl py-10 px-4",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("img",{src:aLe,alt:"LevelUp",className:"h-10 mx-auto mb-8"}),e.jsx(ze,{variant:"outline",className:"mb-4 border-primary/40 text-primary",children:"Upgrade your membership"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mb-3 text-[#2a4c64]",children:"Keep your momentum going"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-2xl mx-auto",children:s?"Choose your plan below — payment connects to your existing account and everything you set up stays right where you left it.":"Whether you're on a free trial or it just ended, sign in with your existing LevelUp account, choose your plan, and your payment connects right to it — nothing gets lost or duplicated."})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(ee,{htmlFor:"upgrade-coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(pe,{id:"upgrade-coupon",placeholder:"Enter code (optional)",value:u,onChange:g=>h(g.target.value),className:"mt-1.5"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 max-w-4xl mx-auto",children:[f("individual_agent","Individual Agent","$39","Perfect for solo agents ready to level up",X7s,e.jsx(On,{className:"h-6 w-6 text-primary"}),!0),f("brokerage_over_25","Brokerage","$499","For teams and brokerages",Q7s,e.jsx(oi,{className:"h-6 w-6 text-amber-600"}),!1)]}),e.jsxs("div",{className:"mt-10 bg-white/70 border rounded-xl p-5 max-w-2xl mx-auto space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions before you upgrade? We're happy to help:"}),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 text-sm",children:[e.jsx(va,{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 text-sm",children:[e.jsx(on,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground mt-8",children:"Secure checkout powered by Stripe. Your existing account, listings, and settings are preserved."})]})})},e9s=Gj({viewerName:Jo().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:Jo().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:Jo().max(20,"Phone must be less than 20 characters").optional(),message:Jo().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function t9s({shareToken:s,agentName:t,hasContact:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(null),d=gPe({resolver:yPe(e9s),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:p}=await U.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(p)throw new Error(p.message);if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Failed to send reply");l(!0)}catch(m){console.error("Failed to submit reply:",m),c(m.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(be,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Le,{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(Mr,{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(be,{children:[e.jsxs(_t,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Bu,{className:"h-5 w-5 text-primary"}),e.jsx(Nt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(En,{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(Le,{children:e.jsx(wPe,{...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(Mf,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Your Name *"}),e.jsx(sf,{children:e.jsx(pe,{placeholder:"John Smith",...h})}),e.jsx(hb,{})]})}),e.jsx(Mf,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Email *"}),e.jsx(sf,{children:e.jsx(pe,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(hb,{})]})})]}),!n&&e.jsx(Mf,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Phone (optional)"}),e.jsx(sf,{children:e.jsx(pe,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(hb,{})]})}),e.jsx(Mf,{control:d.control,name:"message",render:({field:h})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Message *"}),e.jsx(sf,{children:e.jsx(Ps,{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(hb,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(z,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const s9s=()=>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(Ia,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Ia,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Ia,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Ia,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Ia,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(WA,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),n9s=()=>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(Ia,{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(Ia,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Ia,{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(WA,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),r9s=()=>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(cS,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(cS,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(cS,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(cS,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(Fo,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(Fo,{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(Fo,{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"})]}),a9s=()=>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(Kh,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Ia,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Kh,{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(Ia,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Ia,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),i9s=()=>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(cS,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(cS,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(BU,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),o9s=()=>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(r7,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(r7,{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"}})]}),l9s=()=>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(pP,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(pP,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(pP,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(aj,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(aj,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(aj,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(aj,{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(Ia,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),c9s=()=>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(Fo,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(Fo,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),d9s=()=>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(Ia,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Ia,{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(Ia,{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(Ia,{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(Ix,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(Ix,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),u9s=()=>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(Ia,{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"})]}),h9s=()=>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(FA,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(FA,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(FA,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(FA,{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"})]})]})]}),m9s=()=>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(Ia,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Ia,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Kh,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Kh,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(WA,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),p9s=()=>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(Hf,{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(Ix,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Ko,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),f9s=()=>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(Fo,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(Fo,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(Fo,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(Fo,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(Fo,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(Fo,{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(Fo,{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(Fo,{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"})]}),x9s=()=>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(bN,{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(bN,{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(bN,{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"})]}),g9s=()=>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(sa,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(sa,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(wb,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(wb,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(Fo,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(Fo,{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(Ix,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),y9s=()=>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(Ix,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(Ix,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(wb,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(sa,{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"})]}),v9s=()=>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(wb,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(wb,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(wb,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(sa,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(Ix,{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(Ia,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),b9s=()=>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(sa,{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(wb,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(Fo,{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(fj,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),Cgt=()=>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"})]}),_9s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Fo,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(Fo,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(Fo,{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(Fo,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),w9s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(fj,{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(sa,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),j9s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Y4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(eq,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(Y4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),XY=()=>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(Ix,{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"})]}),Agt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(sa,{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(sa,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),HVe=[{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(Fo,{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(_9s,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(MQ,{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(XY,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(Y4,{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(j9s,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(wl,{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(On,{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(XY,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Kh,{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(Cgt,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Ha,{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(Agt,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(eq,{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(XY,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Hf,{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(p9s,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(Fo,{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(f9s,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(bN,{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(x9s,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Ia,{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(d9s,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(BU,{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(i9s,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(cS,{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(r9s,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Kh,{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(a9s,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(WA,{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(s9s,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(vu,{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(n9s,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Kh,{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(m9s,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(r7,{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(o9s,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(Fo,{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(c9s,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(pP,{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(l9s,{})},{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(u9s,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(FA,{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(h9s,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(sa,{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(g9s,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(Ix,{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(y9s,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(ya,{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(Agt,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Nd,{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(XY,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(_S,{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(fj,{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(w9s,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(wb,{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(v9s,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(sa,{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(b9s,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Ug,{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(XY,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Kh,{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(Cgt,{})}],N9s=[{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 k9s(s){return HVe.filter(t=>t.category===s)}function Lq(s){return HVe.find(t=>t.id===s)||HVe[0]}function Egt(){const{shareToken:s,recipientToken:t}=Mi(),[n,r]=_.useState(null),[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(!0),[u,h]=_.useState(null),[m,p]=_.useState(!0),f=_.useRef(null),g=_.useRef(0),v=_.useRef(0),y=(()=>{const q=new URLSearchParams(window.location.search);return t||q.get("rt")||null})(),b=_.useCallback((q,G=!1)=>{if(!y||q<=0)return;const V=Math.max(1,Math.round(q));if(V<=v.current)return;const K=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(y)}&e=watch&ws=${V}`;G&&navigator.sendBeacon?navigator.sendBeacon(K):fetch(K,{method:"GET",keepalive:G}).catch(()=>{}),v.current=Math.max(v.current,V)},[y]);_.useEffect(()=>{var oe;if(!m||!(n!=null&&n.playback_url)||!y)return;let q=!1;const G=()=>{g.current>0&&b(g.current,!0)},V=()=>{document.visibilityState==="hidden"&&G()},H=()=>{G()},K=()=>{var ae;if(q||!f.current||!((ae=window.playerjs)!=null&&ae.Player))return;const re=new window.playerjs.Player(f.current);re.on("timeupdate",J=>{const te=Math.floor(Number((J==null?void 0:J.seconds)??0));!Number.isFinite(te)||te<=0||(g.current=Math.max(g.current,te))}),re.on("pause",()=>{g.current>0&&b(g.current)}),re.on("ended",()=>{g.current>0&&b(g.current,!0)})},Z=document.querySelector('script[data-bunny-playerjs="true"]');if((oe=window.playerjs)!=null&&oe.Player)K();else if(Z)Z.addEventListener("load",K,{once:!0});else{const re=document.createElement("script");re.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",re.async=!0,re.defer=!0,re.dataset.bunnyPlayerjs="true",re.onload=K,document.body.appendChild(re)}return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",H),()=>{q=!0,document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",H),G()}},[m,n==null?void 0:n.playback_url,y,b]),_.useEffect(()=>{g.current=0,v.current=0},[y,s]),_.useEffect(()=>{const q=()=>{['[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(K=>{document.querySelectorAll(K).forEach(Z=>{Z.style.display="none"})})};q();const G=[setTimeout(q,500),setTimeout(q,1500),setTimeout(q,3e3)],V=new MutationObserver(q);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{G.forEach(clearTimeout),V.disconnect()}},[]),_.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:G,error:V}=await U.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(V||!G){h("Video not found or has been removed"),d(!1);return}r(G);try{await U.rpc("log_video_view",{p_video_id:G.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(H){console.warn("Failed to log video view:",H)}if(G.owner_user_id){const{data:H}=await U.from("profiles").select("id, name, email, phone").eq("id",G.owner_user_id).single();if(H){i(H);try{const{data:K}=await U.storage.from("avatars").list(`${G.owner_user_id}`);if(K&&K.length>0){const{data:Z}=U.storage.from("avatars").getPublicUrl(`${G.owner_user_id}/${K[0].name}`);o(Z.publicUrl)}}catch{}}}d(!1)})()},[s]);const w=q=>{if(!q)return"0:00";const G=Math.floor(q/60),V=q%60;return`${G}:${V.toString().padStart(2,"0")}`},S=q=>q.includes("iframe.mediadelivery.net/play/")?q.replace("/play/","/embed/")+"?autoplay=true&responsive=true":q,C=q=>{if(!q)return"?";const G=q.split(" ");return G.length>=2?`${G[0][0]}${G[1][0]}`.toUpperCase():q.substring(0,2).toUpperCase()},E=Lq((n==null?void 0:n.page_template)||"default"),P=(n==null?void 0:n.recipient_name)||null,M=E.headerText(P),D=`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(bt,{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(be,{className:"max-w-md w-full",children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Xr,{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 F=E.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsx("title",{children:M}),e.jsx("meta",{name:"description",content:E.subText}),e.jsx("meta",{property:"og:title",content:M}),e.jsx("meta",{property:"og:description",content:E.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:D}),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:E.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:Ct("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",E.gradientClasses),children:[F&&E.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[F&&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:Ct("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",E.accentColor==="primary"&&"bg-primary/10 text-primary",E.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",E.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",E.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",E.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",E.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",E.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",E.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",E.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",E.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",E.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",E.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",E.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:E.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:M}),e.jsx("p",{className:"text-muted-foreground",children:E.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(ja,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(xi,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(Na,{className:"bg-primary/10 text-primary font-semibold",children:C(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:F?"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(z,{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(va,{className:"h-4 w-4"})})}),a.email&&e.jsx(z,{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(on,{className:"h-4 w-4"})})})]})]}),e.jsx(be,{className:"overflow-hidden shadow-lg",children:m&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:f,src:S(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>p(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:q=>{var V;q.currentTarget.style.display="none";const G=(V=q.currentTarget.parentElement)==null?void 0:V.querySelector(".video-fallback");G&&(G.style.display="flex")}}):null,e.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:n.preview_url||n.thumbnail_url?"none":"flex"},children:e.jsx(Xr,{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(su,{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:w(n.duration_seconds)})]})}),!F&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:m?"Enjoy the video!":"Click to play the video"})]}),!m&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(z,{size:"lg",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(su,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(t9s,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function S9s(){return _.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(TQe,{})}function C9s(){const{token:s}=Mi();return _.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(bt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const A9s=[{key:"residential",title:"Residential",tagline:"Homes, condos, land & luxury",path:"/mission-control/listings/new/residential",icon:sa,points:["Standard listing details","Listing Exchange & referrals","Single-property site & marketing"]},{key:"commercial",title:"Commercial",tagline:"Investment, office, retail, industrial & land",path:"/mission-control/listings/new/commercial",icon:oi,points:["Pitch Mode to win the assignment","Institutional-grade microsite","Gated OM & investor tracking"],featured:!0}];function E9s(){const s=zn(),{search:t}=Pd();return e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-10",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"mb-6 -ml-2",onClick:()=>s("/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"mb-10",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"New listing"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-tight md:text-4xl",children:"What are you marketing?"}),e.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Choose the workflow that fits. Commercial unlocks Pitch Mode, investment metrics and the Commercial Launch marketing workspace."})]}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2",children:A9s.map(n=>{const r=n.icon;return e.jsxs("button",{onClick:()=>s(`${n.path}${t}`),className:`group relative overflow-hidden rounded-2xl border p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl ${n.featured?"border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent":"bg-card"}`,children:[n.featured&&e.jsxs("span",{className:"absolute right-5 top-5 inline-flex items-center gap-1 rounded-full border border-primary/30 bg-primary/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-primary",children:[e.jsx(un,{className:"h-3 w-3"})," Commercial Launch"]}),e.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-xl border bg-background",children:e.jsx(r,{className:"h-6 w-6"})}),e.jsx("h2",{className:"text-xl font-semibold",children:n.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n.tagline}),e.jsx("ul",{className:"mt-5 space-y-2 text-sm text-muted-foreground",children:n.points.map(a=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-[7px] h-1 w-1 shrink-0 rounded-full bg-foreground/40"}),a]},a))}),e.jsxs("span",{className:"mt-6 inline-flex items-center gap-1 text-sm font-medium text-primary",children:["Continue ",e.jsx(Da,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]},n.key)})})]})})}const Aet=()=>{const{user:s}=hs();return rt({queryKey:["managed-agent-ids",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("team_members").select("team_id").eq("user_id",s.id).eq("role","team_leader");if(n)throw n;const r=(t||[]).map(l=>l.team_id).filter(Boolean);if(!r.length)return[s.id];const{data:a,error:i}=await U.from("team_members").select("user_id").in("team_id",r);if(i)throw i;return Array.from(new Set([s.id,...(a||[]).map(l=>l.user_id).filter(Boolean)]))},enabled:!!s,staleTime:5*60*1e3})},nzt=s=>{const{user:t}=hs(),{data:n}=Aet();return!t||!s?!1:t.id===s?!0:(n||[]).includes(s)},rzt=()=>rt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),azt=s=>{const{user:t,brokerageId:n}=hs();return rt({queryKey:["listings",s,n],queryFn:async()=>{let r=U.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch");s!=null&&s.listingClass&&(r=r.eq("listing_class",s.listingClass)),s!=null&&s.status?r=r.eq("status",s.status):r=r.neq("status","sold"),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 U.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=U.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).eq("site_only",!1).in("agent_id",c).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch");s!=null&&s.listingClass&&(d=d.eq("listing_class",s.listingClass)),s!=null&&s.status?d=d.eq("status",s.status):d=d.neq("status","sold"),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(p=>p.id)),m=u.filter(p=>!h.has(p.id));l=[...l,...m]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l.map(o=>Tet(Eet(o)))}})};function Eet(s){return s&&Array.isArray(s.commercial)&&(s.commercial=s.commercial[0]??null),s}function Tet(s){return Array.isArray(s==null?void 0:s.photos)&&(s.photos=[...s.photos].sort((t,n)=>(t.sort_order??0)-(n.sort_order??0)||(n.is_primary?1:0)-(t.is_primary?1:0))),s}const Met=()=>{const{user:s}=hs(),{data:t,isLoading:n}=Aet(),r=t&&t.length?t:s?[s.id]:[];return rt({queryKey:["my-listings",s==null?void 0:s.id,r.slice().sort().join(",")],queryFn:async()=>{if(!s)return[];const{data:a,error:i}=await U.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*) `).in("agent_id",r).order("created_at",{ascending:!1});if(i)throw i;return a.map(l=>Tet(Eet(l)))},enabled:!!s&&!n})},dae=s=>{const{user:t}=hs();return rt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await U.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), 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 U.from("listing_views").insert({listing_id:s,viewer_id:t.id}),Tet(Eet(n))},enabled:!!s})},izt=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await U.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"]})}})},T9s=()=>{const s=$t();return mt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await U.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"]})}})},ozt=()=>{const s=$t();return mt({mutationFn:async({id:t,...n})=>{const r=n.is_public===!0?{...n,is_approved:!0}:{...n},{data:a,error:i}=await U.from("listings").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},lzt=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},czt=()=>{const s=$t();return mt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await U.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"]})}})},dzt=()=>{const s=$t();return mt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await U.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"]})}})},uzt=()=>{const s=$t();return mt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>U.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(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"]})}})},hzt=()=>{const s=$t();return mt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await U.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await U.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"]})}})},M9s=()=>{const{user:s}=hs();return rt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},mzt=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await U.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await U.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await U.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},pzt=s=>{const{user:t}=hs();return rt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await U.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},P9s=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await U.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await U.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await U.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},L9s=s=>{const{user:t}=hs();return rt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await U.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},I9s=()=>{const{user:s}=hs();return mt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await U.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},D9s=()=>{const{user:s}=hs();return rt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([U.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),U.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},R9s=()=>{const s=$t(),{user:t}=hs();return mt({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 U.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"]})}})},F9s=()=>rt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await U.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await U.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}}}),O9s=()=>{const{user:s,brokerageId:t}=hs();return rt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await U.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 U.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), 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})},v7e=U,wp=s=>s===""||s==null?null:Number(String(s).replace(/[^0-9.\-]/g,"")),z9s={property_address:"",city:"",state:"",submarket:"",opportunity_title:"",description:"",deal_type:"sale",commercial_type:"office",asking_price:"",lease_rate:"",lease_rate_unit:"sf_year",lease_type:"",building_sf:"",available_sf:"",lot_acres:"",units:"",floors:"",year_built:"",parking_spaces:"",zoning:"",occupancy_pct:"",tenancy:"",noi:"",cap_rate:"",gross_income:"",operating_expenses:"",broker_coop_pct:"",call_for_offers_at:"",is_confidential:!1,hide_address:!1,requires_nda:!1,om_gate_mode:"email",opportunity_zone:!1,is_public:!1,allow_sharing:!0,share_with_brokerage:!1,open_to_referrals:!0,open_to_social_promotion:!0,show_on_lead_site:!0,site_only:!1};function Tgt({label:s,placeholder:t,items:n,onChange:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:s}),n.map((a,i)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:a,placeholder:t,onChange:l=>r(n.map((o,c)=>c===i?l.target.value:o))}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>r(n.filter((l,o)=>o!==i)),children:e.jsx(er,{className:"h-4 w-4"})})]},i)),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:()=>r([...n,""]),children:[e.jsx(sn,{className:"mr-1.5 h-3.5 w-3.5"})," Add"]})]})}function b7e({label:s,description:t,columns:n,rows:r,onChange:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:s}),t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]}),r.map((i,l)=>e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-lg border p-3",children:[n.map(o=>e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:o.label}),e.jsx(pe,{value:i[o.key]??"",placeholder:o.placeholder,onChange:c=>a(r.map((d,u)=>u===l?{...d,[o.key]:c.target.value}:d))})]},o.key)),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>a(r.filter((o,c)=>c!==l)),children:e.jsx(er,{className:"h-4 w-4"})})]},l)),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:()=>a([...r,{}]),children:[e.jsx(sn,{className:"mr-1.5 h-3.5 w-3.5"})," Add row"]})]})}const B9s=[{key:"radius_1",label:"1 mile"},{key:"radius_3",label:"3 miles"},{key:"radius_5",label:"5 miles"}],$9s=[{key:"population",label:"Population"},{key:"households",label:"Households"},{key:"avg_income",label:"Avg income"},{key:"daytime_pop",label:"Daytime pop."}];function Mgt(){const{listingId:s}=Mi(),t=zn(),{user:n,loading:r}=hs(),a=!!s,{data:i,isLoading:l}=dae(s||""),{data:o}=sOt(s);izt();const c=ozt(),d=nOt(),u=rOt(),[h,m]=_.useState(null),[p,f]=_.useState(z9s),[g,v]=_.useState([""]),[y,b]=_.useState([]),[w,S]=_.useState([]),[C,E]=_.useState([]),[P,M]=_.useState([]),[I,D]=_.useState({}),[F,q]=_.useState(!1),[G,V]=_.useState([]),[H,K]=_.useState([]),Z=!a||!!(n!=null&&n.id)&&(i==null?void 0:i.agent_id)===n.id;_.useEffect(()=>{!a||r||l||!i||Z||(ne.error("Only the listing agent can edit this commercial listing"),t(`/mission-control/listings/${i.id}/commercial`,{replace:!0}))},[r,i,a,Z,l,t]);const oe=he=>{if(!(he!=null&&he.length))return;const ge=Array.from(he);V(Ee=>[...Ee,...ge]),K(Ee=>[...Ee,...ge.map(Ne=>URL.createObjectURL(Ne))])},re=he=>{URL.revokeObjectURL(H[he]),V(ge=>ge.filter((Ee,Ne)=>Ne!==he)),K(ge=>ge.filter((Ee,Ne)=>Ne!==he))},ae=async he=>{if(!G.length)return;const{count:ge}=await v7e.from("listing_photos").select("id",{count:"exact",head:!0}).eq("listing_id",he),Ee=ge??0;for(let Ne=0;Nef(Ee=>({...Ee,[he]:ge}));_.useEffect(()=>{!a||!i||(m(i.lifecycle_stage==="pitch"?"pitch":"assignment"),f(he=>({...he,property_address:i.property_address??"",city:i.city??"",state:i.state??"",description:i.description??"",year_built:i.year_built?String(i.year_built):"",is_public:!!i.is_public,allow_sharing:i.allow_sharing??!0,share_with_brokerage:i.share_with_brokerage??!1,open_to_referrals:i.open_to_referrals??!0,open_to_social_promotion:i.open_to_social_promotion??!0,show_on_lead_site:i.show_on_lead_site??!0,site_only:!i.is_public&&(i.show_on_lead_site??!1)&&!i.allow_sharing})))},[a,i]),_.useEffect(()=>{var he;o&&(f(ge=>({...ge,submarket:o.submarket??"",opportunity_title:o.opportunity_title??"",deal_type:o.deal_type??"sale",commercial_type:o.commercial_type??"office",asking_price:o.asking_price!=null?String(o.asking_price):"",lease_rate:o.lease_rate!=null?String(o.lease_rate):"",lease_rate_unit:o.lease_rate_unit??"sf_year",lease_type:o.lease_type??"",building_sf:o.building_sf!=null?String(o.building_sf):"",available_sf:o.available_sf!=null?String(o.available_sf):"",lot_acres:o.lot_acres!=null?String(o.lot_acres):"",units:o.units!=null?String(o.units):"",floors:o.floors!=null?String(o.floors):"",parking_spaces:o.parking_spaces!=null?String(o.parking_spaces):"",zoning:o.zoning??"",occupancy_pct:o.occupancy_pct!=null?String(o.occupancy_pct):"",tenancy:o.tenancy??"",noi:o.noi!=null?String(o.noi):"",cap_rate:o.cap_rate!=null?String(o.cap_rate):"",gross_income:o.gross_income!=null?String(o.gross_income):"",operating_expenses:o.operating_expenses!=null?String(o.operating_expenses):"",broker_coop_pct:o.broker_coop_pct!=null?String(o.broker_coop_pct):"",call_for_offers_at:o.call_for_offers_at?o.call_for_offers_at.slice(0,10):"",is_confidential:!!o.is_confidential,hide_address:!!o.hide_address,requires_nda:!!o.requires_nda,om_gate_mode:o.om_gate_mode??"email",opportunity_zone:!!o.opportunity_zone})),v((he=o.investment_highlights)!=null&&he.length?o.investment_highlights:[""]),b(o.property_highlights??[]),S((o.spaces??[]).map(ge=>({...ge,sf:(ge==null?void 0:ge.sf)!=null?String(ge.sf):""}))),E((o.tenants??[]).map(ge=>({...ge,sf:(ge==null?void 0:ge.sf)!=null?String(ge.sf):""}))),M(o.traffic_counts??[]),D(o.demographics??{}))},[o]);const te=p.deal_type==="lease"||p.deal_type==="sale_or_lease",ce=p.deal_type!=="lease",ve=_.useMemo(()=>({deal_type:p.deal_type,commercial_type:p.commercial_type,opportunity_title:p.opportunity_title||null,submarket:p.submarket||null,asking_price:wp(p.asking_price),lease_rate:wp(p.lease_rate),lease_rate_unit:p.lease_rate_unit,lease_type:p.lease_type||null,building_sf:wp(p.building_sf),available_sf:wp(p.available_sf),lot_acres:wp(p.lot_acres),units:wp(p.units),floors:wp(p.floors),parking_spaces:wp(p.parking_spaces),zoning:p.zoning||null,occupancy_pct:wp(p.occupancy_pct),tenancy:p.tenancy||null,noi:wp(p.noi),cap_rate:wp(p.cap_rate),gross_income:wp(p.gross_income),operating_expenses:wp(p.operating_expenses),broker_coop_pct:wp(p.broker_coop_pct),call_for_offers_at:p.call_for_offers_at?new Date(p.call_for_offers_at).toISOString():null,is_confidential:p.is_confidential,hide_address:p.hide_address,requires_nda:p.requires_nda,om_gate_mode:p.om_gate_mode,opportunity_zone:p.opportunity_zone,investment_highlights:g.map(he=>he.trim()).filter(Boolean),spaces:w.filter(he=>Object.values(he).some(ge=>String(ge??"").trim())),tenants:C.filter(he=>Object.values(he).some(ge=>String(ge??"").trim())),traffic_counts:P.filter(he=>String(he.road??"").trim()||String(he.count??"").trim()),demographics:Object.fromEntries(Object.entries(I).filter(([,he])=>Object.values(he??{}).some(ge=>String(ge??"").trim()))),property_highlights:y.map(he=>he.trim()).filter(Boolean),price_per_sf:wp(p.asking_price)&&wp(p.building_sf)?Math.round(wp(p.asking_price)/wp(p.building_sf)*100)/100:null,price_per_unit:wp(p.asking_price)&&wp(p.units)?Math.round(wp(p.asking_price)/wp(p.units)):null}),[p,g,y,w,C,P,I]),me=async()=>{if(a&&!Z){ne.error("Only the listing agent can edit this commercial listing");return}if(!p.city||!p.state){ne.error("City and state are required");return}if(!a&&!h){ne.error("Choose whether you already have the assignment");return}q(!0);try{let he=s;const ge={property_address:p.property_address||null,city:p.city,state:p.state,neighborhood:p.submarket||null,price:wp(p.asking_price)??0,property_type:"commercial",description:p.description||null,year_built:wp(p.year_built),square_footage:wp(p.building_sf)},Ee=h==="pitch",Ne=Ee?{is_public:!1,allow_sharing:!1,share_with_brokerage:!1,open_to_referrals:!1,open_to_social_promotion:!1,show_on_lead_site:!1}:{is_public:p.site_only?!1:p.is_public,allow_sharing:p.site_only?!1:p.allow_sharing,share_with_brokerage:p.site_only?!1:p.share_with_brokerage,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.site_only?!1:p.open_to_social_promotion,show_on_lead_site:p.site_only?!0:p.show_on_lead_site},Pe=!Ee&&(Ne.is_public||Ne.show_on_lead_site||Ne.allow_sharing)?"active":"coming_soon";if(a&&he)await c.mutateAsync({id:he,...ge,...Ne,...Pe==="active"?{status:"active"}:{}});else{const Oe=await v7e.from("listings").insert({...ge,...Ne,agent_id:n.id,listing_class:"commercial",lifecycle_stage:Ee?"pitch":"won",status:Pe}).select().single();if(Oe.error)throw Oe.error;he=Oe.data.id,Ee&&await u.mutateAsync({listingId:he,values:{launch_plan:tOt}})}await d.mutateAsync({listingId:he,values:ve}),await ae(he),ne.success(a?"Commercial listing updated":"Commercial listing created"),t(`/mission-control/listings/${he}/commercial`)}catch(he){console.error(he),ne.error(he.message||"Could not save listing")}finally{q(!1)}};return a&&(r||l||!i||!Z)?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):!a&&!h?e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-10",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t("/mission-control/listings/new"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"Commercial Launch"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-tight md:text-4xl",children:"Where are you in the deal?"}),e.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Pitch Mode keeps everything private while you compete for the assignment. Win it and the same record becomes your live Commercial Launch — nothing gets re-entered."}),e.jsxs("div",{className:"mt-8 grid gap-5 md:grid-cols-2",children:[e.jsxs("button",{onClick:()=>m("assignment"),className:"group rounded-2xl border bg-card p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl",children:[e.jsx(jl,{className:"mb-4 h-6 w-6"}),e.jsx("h2",{className:"text-lg font-semibold",children:"I already have the assignment"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Go straight to building the launch: microsite, OM gating, investor tracking and reporting."})]}),e.jsxs("button",{onClick:()=>m("pitch"),className:"group rounded-2xl border border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl",children:[e.jsx(bu,{className:"mb-4 h-6 w-6 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"I'm pitching this property"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Private Pitch Workspace with owner intel, positioning, a proposed launch plan and a seller-facing preview of exactly what happens the day they hire you."})]})]})]})}):e.jsxs("div",{className:"min-h-screen bg-background pb-28",children:[e.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t(a?`/mission-control/listings/${s}/commercial`:"/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsxs("div",{className:"mb-8 flex items-start gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl border bg-card",children:e.jsx(oi,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:a?"Edit commercial listing":h==="pitch"?"New pitch":"New commercial listing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h==="pitch"?"Private until you win it — never shown in the Exchange or on the public web.":"Only the fields that matter for this deal type are required."})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"The opportunity"}),e.jsx(En,{children:"How this deal is positioned to the market."})]}),e.jsxs(Le,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal type"}),e.jsxs(ls,{value:p.deal_type,onValueChange:he=>J("deal_type",he),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(GP).map(([he,ge])=>e.jsx(He,{value:he,children:ge},he))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property type"}),e.jsxs(ls,{value:p.commercial_type,onValueChange:he=>J("commercial_type",he),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(wL).map(([he,ge])=>e.jsx(He,{value:he,children:ge},he))})]})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsxs(ee,{children:["Opportunity name ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(pe,{value:p.opportunity_title,placeholder:"e.g. Gateway Logistics Center",onChange:he=>J("opportunity_title",he.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used instead of the street address on confidential offerings."})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Property story"}),e.jsx(Ps,{rows:5,value:p.description,placeholder:"The narrative an investor, tenant or owner should read first.",onChange:he=>J("description",he.target.value)})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Location"})}),e.jsxs(Le,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Street address"}),e.jsx(pe,{value:p.property_address,onChange:he=>J("property_address",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City *"}),e.jsx(pe,{value:p.city,onChange:he=>J("city",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State *"}),e.jsx(pe,{value:p.state,maxLength:2,onChange:he=>J("state",he.target.value.toUpperCase())})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Submarket"}),e.jsx(pe,{value:p.submarket,placeholder:"e.g. North Loop",onChange:he=>J("submarket",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Zoning"}),e.jsx(pe,{value:p.zoning,onChange:he=>J("zoning",he.target.value)})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Pricing"})}),e.jsxs(Le,{className:"grid gap-4 md:grid-cols-2",children:[ce&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Asking price"}),e.jsx(pe,{value:p.asking_price,placeholder:"4750000",onChange:he=>J("asking_price",he.target.value)})]}),te&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lease rate"}),e.jsx(pe,{value:p.lease_rate,placeholder:"24.50",onChange:he=>J("lease_rate",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Rate basis"}),e.jsxs(ls,{value:p.lease_rate_unit,onValueChange:he=>J("lease_rate_unit",he),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"sf_year",children:"Per SF / year"}),e.jsx(He,{value:"sf_month",children:"Per SF / month"}),e.jsx(He,{value:"month",children:"Per month"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lease structure"}),e.jsxs(ls,{value:p.lease_type||"none",onValueChange:he=>J("lease_type",he==="none"?"":he),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Not specified"}),CMs.map(he=>e.jsx(He,{value:he,children:he},he))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Broker co-op (%)"}),e.jsx(pe,{value:p.broker_coop_pct,placeholder:"2.5",onChange:he=>J("broker_coop_pct",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Call for offers"}),e.jsx(pe,{type:"date",value:p.call_for_offers_at,onChange:he=>J("call_for_offers_at",he.target.value)})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Building & site"})}),e.jsxs(Le,{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Building SF"}),e.jsx(pe,{value:p.building_sf,onChange:he=>J("building_sf",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Available SF"}),e.jsx(pe,{value:p.available_sf,onChange:he=>J("available_sf",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lot acres"}),e.jsx(pe,{value:p.lot_acres,onChange:he=>J("lot_acres",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Units"}),e.jsx(pe,{value:p.units,onChange:he=>J("units",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Floors"}),e.jsx(pe,{value:p.floors,onChange:he=>J("floors",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Parking spaces"}),e.jsx(pe,{value:p.parking_spaces,onChange:he=>J("parking_spaces",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Year built"}),e.jsx(pe,{value:p.year_built,onChange:he=>J("year_built",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tenancy"}),e.jsxs(ls,{value:p.tenancy||"none",onValueChange:he=>J("tenancy",he==="none"?"":he),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Not specified"}),e.jsx(He,{value:"single",children:"Single tenant"}),e.jsx(He,{value:"multi",children:"Multi-tenant"}),e.jsx(He,{value:"vacant",children:"Vacant"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Occupancy (%)"}),e.jsx(pe,{value:p.occupancy_pct,onChange:he=>J("occupancy_pct",he.target.value)})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Investment metrics"}),e.jsx(En,{children:"Only what you enter is shown on the microsite."})]}),e.jsxs(Le,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"NOI"}),e.jsx(pe,{value:p.noi,onChange:he=>J("noi",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Cap rate (%)"}),e.jsx(pe,{value:p.cap_rate,onChange:he=>J("cap_rate",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Gross income"}),e.jsx(pe,{value:p.gross_income,onChange:he=>J("gross_income",he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Operating expenses"}),e.jsx(pe,{value:p.operating_expenses,onChange:he=>J("operating_expenses",he.target.value)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3 md:col-span-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Opportunity Zone"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight qualified OZ tax treatment."})]}),e.jsx(mn,{checked:p.opportunity_zone,onCheckedChange:he=>J("opportunity_zone",he)})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Highlights"}),e.jsx(En,{children:"3–6 reasons this opportunity matters. These headline the microsite."})]}),e.jsxs(Le,{className:"space-y-6",children:[e.jsx(Tgt,{label:"Investment highlights",placeholder:"e.g. 12-year NNN lease to investment-grade tenant",items:g,onChange:v}),e.jsx(Tgt,{label:"Property highlights",placeholder:"e.g. 32' clear height, 14 dock doors",items:y,onChange:b})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Spaces, tenants & market data"}),e.jsx(En,{children:"Everything here is optional — the microsite only renders the sections you fill in."})]}),e.jsxs(Le,{className:"space-y-8",children:[e.jsx(b7e,{label:"Available spaces",description:"Suites or spaces available for lease.",columns:[{key:"suite",label:"Suite",placeholder:"Suite 200"},{key:"sf",label:"SF",placeholder:"4,200"},{key:"rate",label:"Rate",placeholder:"$28.00 NNN"},{key:"availability",label:"Availability",placeholder:"Immediate"},{key:"use",label:"Use",placeholder:"Office"}],rows:w,onChange:S}),e.jsx(b7e,{label:"Rent roll / tenants",description:"Shown on investment offerings to demonstrate income stability.",columns:[{key:"name",label:"Tenant",placeholder:"Anchor tenant"},{key:"sf",label:"SF",placeholder:"12,000"},{key:"lease_expiry",label:"Lease expiry",placeholder:"2031"},{key:"rent",label:"Rent",placeholder:"$18.50/SF"},{key:"notes",label:"Notes",placeholder:"Two 5-yr options"}],rows:C,onChange:E}),e.jsx(b7e,{label:"Traffic counts",columns:[{key:"road",label:"Road",placeholder:"US-98"},{key:"count",label:"Vehicles / day",placeholder:"42,500 VPD"}],rows:P,onChange:M}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Demographics"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"1 / 3 / 5-mile radius cards on the microsite."})]}),B9s.map(he=>e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-lg border p-3",children:[e.jsx("p",{className:"w-16 text-sm font-medium",children:he.label}),$9s.map(ge=>{var Ee;return e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:ge.label}),e.jsx(pe,{value:((Ee=I[he.key])==null?void 0:Ee[ge.key])??"",onChange:Ne=>D({...I,[he.key]:{...I[he.key]??{},[ge.key]:Ne.target.value}})})]},ge.key)})]},he.key))]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Photography"}),e.jsx(En,{children:"Cinematic exterior, aerial and interior imagery drives the microsite hero and gallery."})]}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("label",{className:"flex cursor-pointer items-center justify-center rounded-lg border border-dashed px-4 py-8 text-sm text-muted-foreground hover:bg-muted/40",children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:he=>oe(he.target.files)})]}),H.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-3 gap-2 sm:grid-cols-4",children:H.map((he,ge)=>e.jsxs("div",{className:"group relative aspect-[4/3] overflow-hidden rounded-md border",children:[e.jsx("img",{src:he,alt:`Commercial photo ${ge+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>re(ge),className:"absolute right-1 top-1 rounded-full bg-background/90 p-1 opacity-0 transition group-hover:opacity-100","aria-label":"Remove photo",children:e.jsx(er,{className:"h-3 w-3"})})]},he))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[H.length," photo",H.length===1?"":"s"," upload when you save."]})]})]})]}),h!=="pitch"&&e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Distribution & sharing"}),e.jsx(En,{children:"Choose where this opportunity appears. You control the Listing Exchange, your own website, and the public commercial marketplace independently."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"My website only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange, other agents and the public marketplace."})]}),e.jsx(mn,{checked:p.site_only,onCheckedChange:he=>f(ge=>({...ge,site_only:he,is_public:he?!1:ge.is_public,show_on_lead_site:he?!0:ge.show_on_lead_site,share_with_brokerage:he?!1:ge.share_with_brokerage}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Publish publicly"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Go live on commercial.relevelup.com to capture leads."})]}),e.jsx(mn,{checked:p.is_public,disabled:p.site_only,onCheckedChange:he=>J("is_public",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Show on my website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature it on your own lead site."})]}),e.jsx(mn,{checked:p.show_on_lead_site,onCheckedChange:he=>J("show_on_lead_site",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Allow sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other LevelUp agents can share it from the Exchange."})]}),e.jsx(mn,{checked:p.allow_sharing,disabled:p.site_only,onCheckedChange:he=>J("allow_sharing",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share with my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents inside your brokerage."})]}),e.jsx(mn,{checked:p.share_with_brokerage,disabled:p.site_only,onCheckedChange:he=>J("share_with_brokerage",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept tenant / buyer referrals from other agents."})]}),e.jsx(mn,{checked:p.open_to_referrals,onCheckedChange:he=>J("open_to_referrals",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Social promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents may promote it on social media."})]}),e.jsx(mn,{checked:p.open_to_social_promotion,disabled:p.site_only,onCheckedChange:he=>J("open_to_social_promotion",he)})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Confidentiality & document gating"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser presentation, no address, search engines blocked."})]}),e.jsx(mn,{checked:p.is_confidential,onCheckedChange:he=>J("is_confidential",he)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(mn,{checked:p.hide_address,onCheckedChange:he=>J("hide_address",he)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Offering Memorandum access"}),e.jsxs(ls,{value:p.om_gate_mode,onValueChange:he=>J("om_gate_mode",he),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"open",children:"Open download"}),e.jsx(He,{value:"email",children:"Require name, email & company"}),e.jsx(He,{value:"nda",children:"Require confidentiality acknowledgement"})]})]})]})]})]})]})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 border-t bg-background/95 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-4xl items-center justify-between gap-3 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:h==="pitch"?"Saved privately — nothing publishes until you win.":"Not published until you launch."}),e.jsxs(z,{onClick:me,disabled:F,children:[F&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Save changes":"Create & continue"]})]})})]})}function iLe(s){return rt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await U.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 fzt(){const{user:s}=hs(),t=$t();return mt({mutationFn:async({listingId:n,file:r,docKind:a,gateLevel:i,title:l})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const o=r.name.split(".").pop(),c=`${s.id}/${n}/${crypto.randomUUID()}.${o}`,{error:d}=await U.storage.from("listing-documents").upload(c,r,{contentType:r.type||void 0});if(d)throw d;const{data:u,error:h}=await U.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:c,...a?{doc_kind:a}:{},...i?{gate_level:i}:{},...l?{title:l}:{}}).select().single();if(h)throw h;return u},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function xzt(){const s=$t();return mt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await U.storage.from("listing-documents").remove([n]);const{error:a}=await U.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function U9s(){const s=$t();return mt({mutationFn:async({id:t,listingId:n,values:r})=>{const{error:a}=await U.from("listing_documents").update(r).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function q9s(){const s=$t();return mt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await U.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 Pet(s){const{data:t,error:n}=await U.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}function V9s(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const oLe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function wW(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function Let(s){return"nodeType"in s}function X_(s){var t,n;return s?wW(s)?s:Let(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Iet(s){const{Document:t}=X_(s);return s instanceof t}function uae(s){return wW(s)?!1:s instanceof X_(s).HTMLElement}function gzt(s){return s instanceof X_(s).SVGElement}function jW(s){return s?wW(s)?s.document:Let(s)?Iet(s)?s:uae(s)||gzt(s)?s.ownerDocument:document:document:document}const fC=oLe?_.useLayoutEffect:_.useEffect;function Det(s){const t=_.useRef(s);return fC(()=>{t.current=s}),_.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=_.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function yte(s,t){t===void 0&&(t=[s]);const n=_.useRef(s);return fC(()=>{n.current!==s&&(n.current=s)},t),n}function hae(s,t){const n=_.useRef();return _.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function zAe(s){const t=Det(s),n=_.useRef(null),r=_.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function GVe(s){const t=_.useRef();return _.useEffect(()=>{t.current=s},[s]),t.current}let _7e={};function mae(s,t){return _.useMemo(()=>{if(t)return t;const n=_7e[s]==null?0:_7e[s]+1;return _7e[s]=n,s+"-"+n},[s,t])}function yzt(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 Iq=yzt(1),vte=yzt(-1);function G9s(s){return"clientX"in s&&"clientY"in s}function Ret(s){if(!s)return!1;const{KeyboardEvent:t}=X_(s.target);return t&&s instanceof t}function W9s(s){if(!s)return!1;const{TouchEvent:t}=X_(s.target);return t&&s instanceof t}function WVe(s){if(W9s(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 G9s(s)?{x:s.clientX,y:s.clientY}:null}const YP=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[YP.Translate.toString(s),YP.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),Pgt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function K9s(s){return s.matches(Pgt)?s:s.querySelector(Pgt)}const Y9s={display:"none"};function Z9s(s){let{id:t,value:n}=s;return Ft.createElement("div",{id:t,style:Y9s},n)}function X9s(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 Ft.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function Q9s(){const[s,t]=_.useState("");return{announce:_.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const vzt=_.createContext(null);function J9s(s){const t=_.useContext(vzt);_.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function ezs(){const[s]=_.useState(()=>new Set),t=_.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[_.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 tzs={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. `},szs={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 nzs(s){let{announcements:t=szs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=tzs}=s;const{announce:i,announcement:l}=Q9s(),o=mae("DndLiveRegion"),[c,d]=_.useState(!1);if(_.useEffect(()=>{d(!0)},[]),J9s(_.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:p}=h;t.onDragMove&&i(t.onDragMove({active:m,over:p}))},onDragOver(h){let{active:m,over:p}=h;i(t.onDragOver({active:m,over:p}))},onDragEnd(h){let{active:m,over:p}=h;i(t.onDragEnd({active:m,over:p}))},onDragCancel(h){let{active:m,over:p}=h;i(t.onDragCancel({active:m,over:p}))}}),[i,t])),!c)return null;const u=Ft.createElement(Ft.Fragment,null,Ft.createElement(Z9s,{id:r,value:a.draggable}),Ft.createElement(X9s,{id:o,announcement:l}));return n?pv.createPortal(u,n):u}var xy;(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"})(xy||(xy={}));function BAe(){}function $H(s,t){return _.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function lLe(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const PS=Object.freeze({x:0,y:0});function bzt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function _zt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function rzs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function Lgt(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 wzt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function Igt(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 cLe=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Igt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=bzt(Igt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(_zt)},azs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Lgt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=Lgt(c),u=a.reduce((m,p,f)=>m+bzt(d[f],p),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(_zt)};function izs(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=izs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(rzs)};function lzs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function jzt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:PS}function czs(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 dzs=czs(1);function uzs(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 hzs(s,t,n){const r=uzs(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 mzs={ignoreTransform:!1};function NW(s,t){t===void 0&&(t=mzs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=X_(s).getComputedStyle(s);d&&(n=hzs(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 Dgt(s){return NW(s,{ignoreTransform:!0})}function pzs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function fzs(s,t){return t===void 0&&(t=X_(s).getComputedStyle(s)),t.position==="fixed"}function xzs(s,t){t===void 0&&(t=X_(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 dLe(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(Iet(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!uae(a)||gzt(a)||n.includes(a))return n;const i=X_(s).getComputedStyle(a);return a!==s&&xzs(a,i)&&n.push(a),fzs(a,i)?n:r(a.parentNode)}return s?r(s):n}function Nzt(s){const[t]=dLe(s,1);return t??null}function w7e(s){return!oLe||!s?null:wW(s)?s:Let(s)?Iet(s)||s===jW(s).scrollingElement?window:uae(s)?s:null:null}function kzt(s){return wW(s)?s.scrollX:s.scrollLeft}function Szt(s){return wW(s)?s.scrollY:s.scrollTop}function KVe(s){return{x:kzt(s),y:Szt(s)}}var m0;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(m0||(m0={}));function Czt(s){return!oLe||!s?!1:s===document.scrollingElement}function Azt(s){const t={x:0,y:0},n=Czt(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 gzs={x:.2,y:.2};function yzs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=gzs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=Azt(s),p={x:0,y:0},f={x:0,y:0},g={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+g.height?(p.y=m0.Backward,f.y=r*Math.abs((t.top+g.height-i)/g.height)):!u&&c>=t.bottom-g.height&&(p.y=m0.Forward,f.y=r*Math.abs((t.bottom-g.height-c)/g.height)),!m&&o>=t.right-g.width?(p.x=m0.Forward,f.x=r*Math.abs((t.right-g.width-o)/g.width)):!h&&l<=t.left+g.width&&(p.x=m0.Backward,f.x=r*Math.abs((t.left+g.width-l)/g.width)),{direction:p,speed:f}}function vzs(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 Ezt(s){return s.reduce((t,n)=>Iq(t,KVe(n)),PS)}function bzs(s){return s.reduce((t,n)=>t+kzt(n),0)}function _zs(s){return s.reduce((t,n)=>t+Szt(n),0)}function wzs(s,t){if(t===void 0&&(t=NW),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);Nzt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const jzs=[["x",["left","right"],bzs],["y",["top","bottom"],_zs]];let Fet=class{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=dLe(n),a=Ezt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of jzs)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 DJ{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 Nzs(s){const{EventTarget:t}=X_(s);return s instanceof t?s:jW(s)}function j7e(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 V2;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(V2||(V2={}));function Rgt(s){s.preventDefault()}function kzs(s){s.stopPropagation()}var mu;(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"})(mu||(mu={}));const Tzt={start:[mu.Space,mu.Enter],cancel:[mu.Esc],end:[mu.Space,mu.Enter,mu.Tab]},Szs=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case mu.Right:return{...n,x:n.x+25};case mu.Left:return{...n,x:n.x-25};case mu.Down:return{...n,y:n.y+25};case mu.Up:return{...n,y:n.y-25}}};class uLe{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 DJ(jW(n)),this.windowListeners=new DJ(X_(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(V2.Resize,this.handleCancel),this.windowListeners.add(V2.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(V2.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&wzs(r),n(PS)}handleKeyDown(t){if(Ret(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=Tzt,coordinateGetter:l=Szs,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}:PS;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=vte(h,u),p={x:0,y:0},{scrollableAncestors:f}=r.current;for(const g of f){const v=t.code,{isTop:y,isRight:b,isLeft:w,isBottom:S,maxScroll:C,minScroll:E}=Azt(g),P=vzs(g),M={x:Math.min(v===mu.Right?P.right-P.width/2:P.right,Math.max(v===mu.Right?P.left:P.left+P.width/2,h.x)),y:Math.min(v===mu.Down?P.bottom-P.height/2:P.bottom,Math.max(v===mu.Down?P.top:P.top+P.height/2,h.y))},I=v===mu.Right&&!b||v===mu.Left&&!w,D=v===mu.Down&&!S||v===mu.Up&&!y;if(I&&M.x!==h.x){const F=g.scrollLeft+m.x,q=v===mu.Right&&F<=C.x||v===mu.Left&&F>=E.x;if(q&&!m.y){g.scrollTo({left:F,behavior:o});return}q?p.x=g.scrollLeft-F:p.x=v===mu.Right?g.scrollLeft-C.x:g.scrollLeft-E.x,p.x&&g.scrollBy({left:-p.x,behavior:o});break}else if(D&&M.y!==h.y){const F=g.scrollTop+m.y,q=v===mu.Down&&F<=C.y||v===mu.Up&&F>=E.y;if(q&&!m.x){g.scrollTo({top:F,behavior:o});return}q?p.y=g.scrollTop-F:p.y=v===mu.Down?g.scrollTop-C.y:g.scrollTop-E.y,p.y&&g.scrollBy({top:-p.y,behavior:o});break}}this.handleMove(t,Iq(vte(h,this.referenceCoordinates),p))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}uLe.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=Tzt,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 Fgt(s){return!!(s&&"distance"in s)}function Ogt(s){return!!(s&&"delay"in s)}class Oet{constructor(t,n,r){var a;r===void 0&&(r=Nzs(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=jW(l),this.documentListeners=new DJ(this.document),this.listeners=new DJ(r),this.windowListeners=new DJ(X_(l)),this.initialCoordinates=(a=WVe(i))!=null?a:PS,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(V2.Resize,this.handleCancel),this.windowListeners.add(V2.DragStart,Rgt),this.windowListeners.add(V2.VisibilityChange,this.handleCancel),this.windowListeners.add(V2.ContextMenu,Rgt),this.documentListeners.add(V2.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ogt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Fgt(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(V2.Click,kzs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(V2.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=WVe(t))!=null?n:PS,d=vte(a,c);if(!r&&o){if(Fgt(o)){if(o.tolerance!=null&&j7e(d,o.tolerance))return this.handleCancel();if(j7e(d,o.distance))return this.handleStart()}if(Ogt(o)&&j7e(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===mu.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Czs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class kW extends Oet{constructor(t){const{event:n}=t,r=jW(n.target);super(t,Czs,r)}}kW.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 Azs={move:{name:"mousemove"},end:{name:"mouseup"}};var YVe;(function(s){s[s.RightClick=2]="RightClick"})(YVe||(YVe={}));class Ezs extends Oet{constructor(t){super(t,Azs,jW(t.event.target))}}Ezs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===YVe.RightClick?!1:(r==null||r({event:n}),!0)}}];const N7e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Tzs extends Oet{constructor(t){super(t,N7e)}static setup(){return window.addEventListener(N7e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(N7e.move.name,t)};function t(){}}}Tzs.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 RJ;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(RJ||(RJ={}));var $Ae;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})($Ae||($Ae={}));function Mzs(s){let{acceleration:t,activator:n=RJ.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=$Ae.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const p=Lzs({delta:h,disabled:!i}),[f,g]=H9s(),v=_.useRef({x:0,y:0}),y=_.useRef({x:0,y:0}),b=_.useMemo(()=>{switch(n){case RJ.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case RJ.DraggableRect:return a}},[n,a,c]),w=_.useRef(null),S=_.useCallback(()=>{const E=w.current;if(!E)return;const P=v.current.x*y.current.x,M=v.current.y*y.current.y;E.scrollBy(P,M)},[]),C=_.useMemo(()=>o===$Ae.TreeOrder?[...d].reverse():d,[o,d]);_.useEffect(()=>{if(!i||!d.length||!b){g();return}for(const E of C){if((r==null?void 0:r(E))===!1)continue;const P=d.indexOf(E),M=u[P];if(!M)continue;const{direction:I,speed:D}=yzs(E,M,b,t,m);for(const F of["x","y"])p[F][I[F]]||(D[F]=0,I[F]=0);if(D.x>0||D.y>0){g(),w.current=E,f(S,l),v.current=D,y.current=I;return}}v.current={x:0,y:0},y.current={x:0,y:0},g()},[t,S,r,g,i,l,JSON.stringify(b),JSON.stringify(p),f,d,C,u,JSON.stringify(m)])}const Pzs={x:{[m0.Backward]:!1,[m0.Forward]:!1},y:{[m0.Backward]:!1,[m0.Forward]:!1}};function Lzs(s){let{delta:t,disabled:n}=s;const r=GVe(t);return hae(a=>{if(n||!r||!a)return Pzs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[m0.Backward]:a.x[m0.Backward]||i.x===-1,[m0.Forward]:a.x[m0.Forward]||i.x===1},y:{[m0.Backward]:a.y[m0.Backward]||i.y===-1,[m0.Forward]:a.y[m0.Forward]||i.y===1}}},[n,t,r])}function Izs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return hae(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function Dzs(s,t){return _.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 bte;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(bte||(bte={}));var ZVe;(function(s){s.Optimized="optimized"})(ZVe||(ZVe={}));const zgt=new Map;function Rzs(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=_.useState(null),{frequency:o,measure:c,strategy:d}=a,u=_.useRef(s),h=v(),m=yte(h),p=_.useCallback(function(y){y===void 0&&(y=[]),!m.current&&l(b=>b===null?y:b.concat(y.filter(w=>!b.includes(w))))},[m]),f=_.useRef(null),g=hae(y=>{if(h&&!n)return zgt;if(!y||y===zgt||u.current!==s||i!=null){const b=new Map;for(let w of s){if(!w)continue;if(i&&i.length>0&&!i.includes(w.id)&&w.rect.current){b.set(w.id,w.rect.current);continue}const S=w.node.current,C=S?new Fet(c(S),S):null;w.rect.current=C,C&&b.set(w.id,C)}return b}return y},[s,i,n,h,c]);return _.useEffect(()=>{u.current=s},[s]),_.useEffect(()=>{h||p()},[n,h]),_.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),_.useEffect(()=>{h||typeof o!="number"||f.current!==null||(f.current=setTimeout(()=>{p(),f.current=null},o))},[o,h,p,...r]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:i!=null};function v(){switch(d){case bte.Always:return!1;case bte.BeforeDragging:return n;default:return!n}}}function Mzt(s,t){return hae(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function Fzs(s,t){return Mzt(s,t)}function Ozs(s){let{callback:t,disabled:n}=s;const r=Det(t),a=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return _.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function hLe(s){let{callback:t,disabled:n}=s;const r=Det(t),a=_.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return _.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function zzs(s){return new Fet(NW(s),s)}function Bgt(s,t,n){t===void 0&&(t=zzs);const[r,a]=_.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=Ozs({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=hLe({callback:i});return fC(()=>{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 Bzs(s){const t=Mzt(s);return jzt(s,t)}const $gt=[];function $zs(s){const t=_.useRef(s),n=hae(r=>s?r&&r!==$gt&&s&&t.current&&s.parentNode===t.current.parentNode?r:dLe(s):$gt,[s]);return _.useEffect(()=>{t.current=s},[s]),n}function Uzs(s){const[t,n]=_.useState(null),r=_.useRef(s),a=_.useCallback(i=>{const l=w7e(i.target);l&&n(o=>o?(o.set(l,KVe(l)),new Map(o)):null)},[]);return _.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=w7e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,KVe(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=w7e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),_.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>Iq(i,l),PS):Ezt(s):PS,[s,t])}function Ugt(s,t){t===void 0&&(t=[]);const n=_.useRef(null);return _.useEffect(()=>{n.current=null},t),_.useEffect(()=>{const r=s!==PS;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?vte(s,n.current):PS}function qzs(s){_.useEffect(()=>{if(!oLe)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 Vzs(s,t){return _.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function Pzt(s){return _.useMemo(()=>s?pzs(s):null,[s])}const qgt=[];function Hzs(s,t){t===void 0&&(t=NW);const[n]=s,r=Pzt(n?X_(n):null),[a,i]=_.useState(qgt);function l(){i(()=>s.length?s.map(c=>Czt(c)?r:new Fet(t(c),c)):qgt)}const o=hLe({callback:l});return fC(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function Gzs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return uae(t)?t:s}function Wzs(s){let{measure:t}=s;const[n,r]=_.useState(null),a=_.useCallback(d=>{for(const{target:u}of d)if(uae(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=hLe({callback:a}),l=_.useCallback(d=>{const u=Gzs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=zAe(l);return _.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const Kzs=[{sensor:kW,options:{}},{sensor:uLe,options:{}}],Yzs={current:{}},W4e={draggable:{measure:Dgt},droppable:{measure:Dgt,strategy:bte.WhileDragging,frequency:ZVe.Optimized},dragOverlay:{measure:NW}};class FJ 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 Zzs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new FJ,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:BAe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:W4e,measureDroppableContainers:BAe,windowRect:null,measuringScheduled:!1},Xzs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:BAe,draggableNodes:new Map,over:null,measureDroppableContainers:BAe},mLe=_.createContext(Xzs),Lzt=_.createContext(Zzs);function Qzs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new FJ}}}function Jzs(s,t){switch(t.type){case xy.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case xy.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 xy.DragEnd:case xy.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case xy.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new FJ(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case xy.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 FJ(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case xy.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new FJ(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function eBs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=_.useContext(mLe),i=GVe(r),l=GVe(n==null?void 0:n.id);return _.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!Ret(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=K9s(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function tBs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function sBs(s){return _.useMemo(()=>({draggable:{...W4e.draggable,...s==null?void 0:s.draggable},droppable:{...W4e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...W4e.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 nBs(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=_.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;fC(()=>{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=jzt(u,r);if(l||(h.x=0),o||(h.y=0),i.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const m=Nzt(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const Izt=_.createContext({...PS,scaleX:1,scaleY:1});var v6;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(v6||(v6={}));const pLe=_.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=Kzs,collisionDetection:h=ozs,measuring:m,modifiers:p,...f}=t;const g=_.useReducer(Jzs,void 0,Qzs),[v,y]=g,[b,w]=ezs(),[S,C]=_.useState(v6.Uninitialized),E=S===v6.Initialized,{draggable:{active:P,nodes:M,translate:I},droppable:{containers:D}}=v,F=P!=null?M.get(P):null,q=_.useRef({initial:null,translated:null}),G=_.useMemo(()=>{var Fs;return P!=null?{id:P,data:(Fs=F==null?void 0:F.data)!=null?Fs:Yzs,rect:q}:null},[P,F]),V=_.useRef(null),[H,K]=_.useState(null),[Z,oe]=_.useState(null),re=yte(f,Object.values(f)),ae=mae("DndDescribedBy",l),J=_.useMemo(()=>D.getEnabled(),[D]),te=sBs(m),{droppableRects:ce,measureDroppableContainers:ve,measuringScheduled:me}=Rzs(J,{dragging:E,dependencies:[I.x,I.y],config:te.droppable}),he=Izs(M,P),ge=_.useMemo(()=>Z?WVe(Z):null,[Z]),Ee=cr(),Ne=Fzs(he,te.draggable.measure);nBs({activeNode:P!=null?M.get(P):null,config:Ee.layoutShiftCompensation,initialRect:Ne,measure:te.draggable.measure});const Pe=Bgt(he,te.draggable.measure,Ne),Oe=Bgt(he?he.parentElement:null),ke=_.useRef({activatorEvent:null,active:null,activeNode:he,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:D,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ve=D.getNodeFor((n=ke.current.over)==null?void 0:n.id),_e=Wzs({measure:te.dragOverlay.measure}),Ae=(r=_e.nodeRef.current)!=null?r:he,Se=E?(a=_e.rect)!=null?a:Pe:null,We=!!(_e.nodeRef.current&&_e.rect),qe=Bzs(We?null:Pe),Be=Pzt(Ae?X_(Ae):null),Ze=$zs(E?Ve??he:null),$e=Hzs(Ze),Xe=tBs(p,{transform:{x:I.x-qe.x,y:I.y-qe.y,scaleX:1,scaleY:1},activatorEvent:Z,active:G,activeNodeRect:Pe,containerNodeRect:Oe,draggingNodeRect:Se,over:ke.current.over,overlayNodeRect:_e.rect,scrollableAncestors:Ze,scrollableAncestorRects:$e,windowRect:Be}),nt=ge?Iq(ge,I):null,Ge=Uzs(Ze),Je=Ugt(Ge),ut=Ugt(Ge,[Pe]),lt=Iq(Xe,Je),qt=Se?dzs(Se,Xe):null,zt=G&&qt?h({active:G,collisionRect:qt,droppableRects:ce,droppableContainers:J,pointerCoordinates:nt}):null,Zt=wzt(zt,"id"),[ms,Dt]=_.useState(null),It=We?Xe:Iq(Xe,ut),qs=lzs(It,(i=ms==null?void 0:ms.rect)!=null?i:null,Pe),wt=_.useRef(null),Us=_.useCallback((Fs,cn)=>{let{sensor:lr,options:Tn}=cn;if(V.current==null)return;const Yn=M.get(V.current);if(!Yn)return;const fs=Fs.nativeEvent,wn=new lr({active:V.current,activeNode:Yn,event:fs,options:Tn,context:ke,onAbort(Ss){if(!M.get(Ss))return;const{onDragAbort:hn}=re.current,Pn={id:Ss};hn==null||hn(Pn),b({type:"onDragAbort",event:Pn})},onPending(Ss,pr,hn,Pn){if(!M.get(Ss))return;const{onDragPending:an}=re.current,tr={id:Ss,constraint:pr,initialCoordinates:hn,offset:Pn};an==null||an(tr),b({type:"onDragPending",event:tr})},onStart(Ss){const pr=V.current;if(pr==null)return;const hn=M.get(pr);if(!hn)return;const{onDragStart:Pn}=re.current,Gs={activatorEvent:fs,active:{id:pr,data:hn.data,rect:q}};pv.unstable_batchedUpdates(()=>{Pn==null||Pn(Gs),C(v6.Initializing),y({type:xy.DragStart,initialCoordinates:Ss,active:pr}),b({type:"onDragStart",event:Gs}),K(wt.current),oe(fs)})},onMove(Ss){y({type:xy.DragMove,coordinates:Ss})},onEnd:As(xy.DragEnd),onCancel:As(xy.DragCancel)});wt.current=wn;function As(Ss){return async function(){const{active:hn,collisions:Pn,over:Gs,scrollAdjustedTranslate:an}=ke.current;let tr=null;if(hn&&an){const{cancelDrop:Lr}=re.current;tr={activatorEvent:fs,active:hn,collisions:Pn,delta:an,over:Gs},Ss===xy.DragEnd&&typeof Lr=="function"&&await Promise.resolve(Lr(tr))&&(Ss=xy.DragCancel)}V.current=null,pv.unstable_batchedUpdates(()=>{y({type:Ss}),C(v6.Uninitialized),Dt(null),K(null),oe(null),wt.current=null;const Lr=Ss===xy.DragEnd?"onDragEnd":"onDragCancel";if(tr){const Yt=re.current[Lr];Yt==null||Yt(tr),b({type:Lr,event:tr})}})}}},[M]),Es=_.useCallback((Fs,cn)=>(lr,Tn)=>{const Yn=lr.nativeEvent,fs=M.get(Tn);if(V.current!==null||!fs||Yn.dndKit||Yn.defaultPrevented)return;const wn={active:fs};Fs(lr,cn.options,wn)===!0&&(Yn.dndKit={capturedBy:cn.sensor},V.current=Tn,Us(lr,cn))},[M,Us]),kn=Dzs(u,Es);qzs(u),fC(()=>{Pe&&S===v6.Initializing&&C(v6.Initialized)},[Pe,S]),_.useEffect(()=>{const{onDragMove:Fs}=re.current,{active:cn,activatorEvent:lr,collisions:Tn,over:Yn}=ke.current;if(!cn||!lr)return;const fs={active:cn,activatorEvent:lr,collisions:Tn,delta:{x:lt.x,y:lt.y},over:Yn};pv.unstable_batchedUpdates(()=>{Fs==null||Fs(fs),b({type:"onDragMove",event:fs})})},[lt.x,lt.y]),_.useEffect(()=>{const{active:Fs,activatorEvent:cn,collisions:lr,droppableContainers:Tn,scrollAdjustedTranslate:Yn}=ke.current;if(!Fs||V.current==null||!cn||!Yn)return;const{onDragOver:fs}=re.current,wn=Tn.get(Zt),As=wn&&wn.rect.current?{id:wn.id,rect:wn.rect.current,data:wn.data,disabled:wn.disabled}:null,Ss={active:Fs,activatorEvent:cn,collisions:lr,delta:{x:Yn.x,y:Yn.y},over:As};pv.unstable_batchedUpdates(()=>{Dt(As),fs==null||fs(Ss),b({type:"onDragOver",event:Ss})})},[Zt]),fC(()=>{ke.current={activatorEvent:Z,active:G,activeNode:he,collisionRect:qt,collisions:zt,droppableRects:ce,draggableNodes:M,draggingNode:Ae,draggingNodeRect:Se,droppableContainers:D,over:ms,scrollableAncestors:Ze,scrollAdjustedTranslate:lt},q.current={initial:Se,translated:qt}},[G,he,zt,qt,M,Ae,Se,ce,D,ms,Ze,lt]),Mzs({...Ee,delta:I,draggingRect:qt,pointerCoordinates:nt,scrollableAncestors:Ze,scrollableAncestorRects:$e});const Sn=_.useMemo(()=>({active:G,activeNode:he,activeNodeRect:Pe,activatorEvent:Z,collisions:zt,containerNodeRect:Oe,dragOverlay:_e,draggableNodes:M,droppableContainers:D,droppableRects:ce,over:ms,measureDroppableContainers:ve,scrollableAncestors:Ze,scrollableAncestorRects:$e,measuringConfiguration:te,measuringScheduled:me,windowRect:Be}),[G,he,Pe,Z,zt,Oe,_e,M,D,ce,ms,ve,Ze,$e,te,me,Be]),bn=_.useMemo(()=>({activatorEvent:Z,activators:kn,active:G,activeNodeRect:Pe,ariaDescribedById:{draggable:ae},dispatch:y,draggableNodes:M,over:ms,measureDroppableContainers:ve}),[Z,kn,G,Pe,y,ae,M,ms,ve]);return Ft.createElement(vzt.Provider,{value:w},Ft.createElement(mLe.Provider,{value:bn},Ft.createElement(Lzt.Provider,{value:Sn},Ft.createElement(Izt.Provider,{value:qs},d)),Ft.createElement(eBs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Ft.createElement(nzs,{...o,hiddenTextDescribedById:ae}));function cr(){const Fs=(H==null?void 0:H.autoScrollEnabled)===!1,cn=typeof c=="object"?c.enabled===!1:c===!1,lr=E&&!Fs&&!cn;return typeof c=="object"?{...c,enabled:lr}:{enabled:lr}}}),rBs=_.createContext(null),Vgt="button",aBs="Draggable";function iBs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=mae(aBs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=_.useContext(mLe),{role:p=Vgt,roleDescription:f="draggable",tabIndex:g=0}=a??{},v=(c==null?void 0:c.id)===t,y=_.useContext(v?Izt:rBs),[b,w]=zAe(),[S,C]=zAe(),E=Vzs(l,t),P=yte(n);fC(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:S,data:P}),()=>{const I=h.get(t);I&&I.key===i&&h.delete(t)}),[h,t]);const M=_.useMemo(()=>({role:p,tabIndex:g,"aria-disabled":r,"aria-pressed":v&&p===Vgt?!0:void 0,"aria-roledescription":f,"aria-describedby":u.draggable}),[r,p,g,v,f,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:v,listeners:r?void 0:E,node:b,over:m,setNodeRef:w,setActivatorNodeRef:C,transform:y}}function oBs(){return _.useContext(Lzt)}const lBs="Droppable",cBs={timeout:25};function dBs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=mae(lBs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=_.useContext(mLe),u=_.useRef({disabled:n}),h=_.useRef(!1),m=_.useRef(null),p=_.useRef(null),{disabled:f,updateMeasurementsFor:g,timeout:v}={...cBs,...a},y=yte(g??r),b=_.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(y.current)?y.current:[y.current]),p.current=null},v)},[v]),w=hLe({callback:b,disabled:f||!l}),S=_.useCallback((M,I)=>{w&&(I&&(w.unobserve(I),h.current=!1),M&&w.observe(M))},[w]),[C,E]=zAe(S),P=yte(t);return _.useEffect(()=>{!w||!C.current||(w.disconnect(),h.current=!1,w.observe(C.current))},[C,w]),_.useEffect(()=>(o({type:xy.RegisterDroppable,element:{id:r,key:i,disabled:n,node:C,rect:m,data:P}}),()=>o({type:xy.UnregisterDroppable,key:i,id:r})),[r]),_.useEffect(()=>{n!==u.current.disabled&&(o({type:xy.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:m,isOver:(c==null?void 0:c.id)===r,node:C,over:c,setNodeRef:E}}function fLe(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function uBs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function $le(s){return s!==null&&s>=0}function hBs(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=pBs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Ule}:l=i?{x:o.width+c,y:0,...Ule}:{x:0,y:0,...Ule}};function pBs(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=fLe(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}},qle={scaleX:1,scaleY:1},fBs=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,...qle}:a=l?{x:0,y:o.height+c,...qle}:{x:0,y:0,...qle}};function xBs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(E=>typeof E=="object"&&"id"in E?E.id:E),[r]),f=l!=null,g=l?p.indexOf(l.id):-1,v=d?p.indexOf(d.id):-1,y=_.useRef(p),b=!hBs(p,y.current),w=v!==-1&&g===-1||b,S=mBs(i);fC(()=>{b&&f&&u(p)},[b,p,f,u]),_.useEffect(()=>{y.current=p},[p]);const C=_.useMemo(()=>({activeIndex:g,containerId:h,disabled:S,disableTransforms:w,items:p,overIndex:v,useDragOverlay:m,sortedRects:uBs(p,c),strategy:a}),[g,h,S.draggable,S.droppable,w,p,v,c,m,a]);return Ft.createElement(Rzt.Provider,{value:C},t)}const gBs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return fLe(n,r,a).indexOf(t)},yBs=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},vBs={duration:200,easing:"ease"},Fzt="transform",bBs=YP.Transition.toString({property:Fzt,duration:0,easing:"linear"}),_Bs={roleDescription:"sortable"};function wBs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=_.useState(null),o=_.useRef(n);return fC(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=NW(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]),_.useEffect(()=>{i&&l(null)},[i]),i}function gLe(s){let{animateLayoutChanges:t=yBs,attributes:n,disabled:r,data:a,getNewIndex:i=gBs,id:l,strategy:o,resizeObserverConfig:c,transition:d=vBs}=s;const{items:u,containerId:h,activeIndex:m,disabled:p,disableTransforms:f,sortedRects:g,overIndex:v,useDragOverlay:y,strategy:b}=_.useContext(Rzt),w=jBs(r,p),S=u.indexOf(l),C=_.useMemo(()=>({sortable:{containerId:h,index:S,items:u},...a}),[h,a,S,u]),E=_.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:P,node:M,isOver:I,setNodeRef:D}=dBs({id:l,data:C,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:E,...c}}),{active:F,activatorEvent:q,activeNodeRect:G,attributes:V,setNodeRef:H,listeners:K,isDragging:Z,over:oe,setActivatorNodeRef:re,transform:ae}=iBs({id:l,data:C,attributes:{..._Bs,...n},disabled:w.draggable}),J=V9s(D,H),te=!!F,ce=te&&!f&&$le(m)&&$le(v),ve=!y&&Z,me=ve&&ce?ae:null,ge=ce?me??(o??b)({rects:g,activeNodeRect:G,activeIndex:m,overIndex:v,index:S}):null,Ee=$le(m)&&$le(v)?i({id:l,items:u,activeIndex:m,overIndex:v}):S,Ne=F==null?void 0:F.id,Pe=_.useRef({activeId:Ne,items:u,newIndex:Ee,containerId:h}),Oe=u!==Pe.current.items,ke=t({active:F,containerId:h,isDragging:Z,isSorting:te,id:l,index:S,items:u,newIndex:Pe.current.newIndex,previousItems:Pe.current.items,previousContainerId:Pe.current.containerId,transition:d,wasDragging:Pe.current.activeId!=null}),Ve=wBs({disabled:!ke,index:S,node:M,rect:P});return _.useEffect(()=>{te&&Pe.current.newIndex!==Ee&&(Pe.current.newIndex=Ee),h!==Pe.current.containerId&&(Pe.current.containerId=h),u!==Pe.current.items&&(Pe.current.items=u)},[te,Ee,h,u]),_.useEffect(()=>{if(Ne===Pe.current.activeId)return;if(Ne!=null&&Pe.current.activeId==null){Pe.current.activeId=Ne;return}const Ae=setTimeout(()=>{Pe.current.activeId=Ne},50);return()=>clearTimeout(Ae)},[Ne]),{active:F,activeIndex:m,attributes:V,data:C,rect:P,index:S,newIndex:Ee,items:u,isOver:I,isSorting:te,isDragging:Z,listeners:K,node:M,overIndex:v,over:oe,setNodeRef:J,setActivatorNodeRef:re,setDroppableNodeRef:D,setDraggableNodeRef:H,transform:Ve??ge,transition:_e()};function _e(){if(Ve||Oe&&Pe.current.newIndex===S)return bBs;if(!(ve&&!Ret(q)||!d)&&(te||ke))return YP.Transition.toString({...d,property:Fzt})}}function jBs(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 UAe(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 NBs=[mu.Down,mu.Right,mu.Up,mu.Left],Ozt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(NBs.includes(s.code)){if(s.preventDefault(),!n||!r)return;const c=[];i.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const m=a.get(h.id);if(m)switch(s.code){case mu.Down:r.topm.top&&c.push(h);break;case mu.Left:r.left>m.left&&c.push(h);break;case mu.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),p=m?a.get(m.id):null,f=m==null?void 0:m.node.current;if(f&&p&&h&&m){const v=dLe(f).some((E,P)=>o[P]!==E),y=zzt(h,m),b=kBs(h,m),w=v||!y?{x:0,y:0}:{x:b?r.width-p.width:0,y:b?r.height-p.height:0},S={x:p.left,y:p.top};return w.x&&w.y?S:vte(S,w)}}}};function zzt(s,t){return!UAe(s)||!UAe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function kBs(s,t){return!UAe(s)||!UAe(t)||!zzt(s,t)?!1:s.data.current.sortable.indexn(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(er,{className:"h-3 w-3"})}),t?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(Ia,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>r(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function Bzt({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var h,m;const l=lLe($H(kW,{activationConstraint:{distance:5}})),o=[...s].sort((p,f)=>(p.sort_order??0)-(f.sort_order??0)),c=((h=o.find(p=>p.is_primary))==null?void 0:h.id)??null,d=c??((m=o[0])==null?void 0:m.id),u=p=>{var E;const{active:f,over:g}=p;if(!g||f.id===g.id)return;const v=o.findIndex(P=>P.id===f.id),y=o.findIndex(P=>P.id===g.id),b=[...o],[w]=b.splice(v,1);b.splice(y,0,w);const S=c??((E=b[0])==null?void 0:E.id),C=b.map((P,M)=>({...P,sort_order:M,is_primary:P.id===S}));a(C)};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(pLe,{sensors:l,collisionDetection:cLe,onDragEnd:u,children:e.jsx(xLe,{items:o.map(p=>p.id),strategy:pae,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(p=>e.jsx(SBs,{photo:p,isPrimary:p.id===d,onRemove:r,onSetPrimary:i},p.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(bt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{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:p=>n(p.target.files),disabled:t})]})]})})})]})}function yLe({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a,isCommercial:i=!1}){const{user:l}=hs(),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1);_.useEffect(()=>{(async()=>{if(!(!s||!l)){u(!0);try{const{data:y,error:b}=await U.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",l.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(y&&y.share_token)c(y);else if(y&&!y.share_token){const{data:w,error:S}=await U.from("listing_shares").update({share_type:"referral_link"}).eq("id",y.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(w)}else{const{data:w,error:S}=await U.from("listing_shares").insert({listing_id:n,sharing_agent_id:l.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(w)}}catch(y){console.error("Error creating share link:",y),ne.error("Failed to generate share link")}finally{u(!1)}}})()},[s,l,n]);const p=o!=null&&o.share_token?`${i?TMs:"https://listings.relevelup.com"}/${r||n}?ref=${o.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(p),m(!0),ne.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{ne.error("Failed to copy link")}},g=v=>{const y=encodeURIComponent(p),b=encodeURIComponent(`Check out this listing: ${a}`);switch(v){case"email":window.open(`mailto:?subject=${b}&body=${y}`);break;case"text":window.open(`sms:?body=${b}%20${y}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${y}`,"_blank");break}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(_r,{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(ee,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:d?"Generating...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(z,{onClick:f,disabled:d||!p,variant:h?"default":"outline",children:h?e.jsx(Wr,{className:"h-4 w-4"}):e.jsx(Sa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",className:"flex-1",onClick:()=>g("email"),disabled:d,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(z,{variant:"outline",className:"flex-1",onClick:()=>g("text"),disabled:d,children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(z,{variant:"outline",className:"flex-1",onClick:()=>g("facebook"),disabled:d,children:[e.jsx(of,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),o&&(o.click_count>0||o.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(ee,{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(xa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.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(On,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:o.lead_count})]})]})]})]})]})})}var CBs=Object.defineProperty,qAe=Object.getOwnPropertySymbols,$zt=Object.prototype.hasOwnProperty,Uzt=Object.prototype.propertyIsEnumerable,Hgt=(s,t,n)=>t in s?CBs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,XVe=(s,t)=>{for(var n in t||(t={}))$zt.call(t,n)&&Hgt(s,n,t[n]);if(qAe)for(var n of qAe(t))Uzt.call(t,n)&&Hgt(s,n,t[n]);return s},QVe=(s,t)=>{var n={};for(var r in s)$zt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&qAe)for(var r of qAe(s))t.indexOf(r)<0&&Uzt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var o9;(s=>{const t=class Fd{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cFd.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let m=[];for(let f=0;f7)throw new RangeError("Invalid value");let f,g;for(f=u;;f++){const w=Fd.getNumDataCodewords(f,d)*8,S=l.getTotalBits(c,f);if(S<=w){g=S;break}if(f>=h)throw new RangeError("Data too long")}for(const w of[Fd.Ecc.MEDIUM,Fd.Ecc.QUARTILE,Fd.Ecc.HIGH])p&&g<=Fd.getNumDataCodewords(f,w)*8&&(d=w);let v=[];for(const w of c){n(w.mode.modeBits,4,v),n(w.numChars,w.mode.numCharCountBits(f),v);for(const S of w.getData())v.push(S)}a(v.length==g);const y=Fd.getNumDataCodewords(f,d)*8;a(v.length<=y),n(0,Math.min(4,y-v.length),v),n(0,(8-v.length%8)%8,v),a(v.length%8==0);for(let w=236;v.lengthb[S>>>3]|=w<<7-(S&7)),new Fd(f,d,b,m)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let m=0;m<=5;m++)this.setFunctionModule(8,m,r(h,m));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let m=9;m<15;m++)this.setFunctionModule(14-m,8,r(h,m));for(let m=0;m<8;m++)this.setFunctionModule(this.size-1-m,8,r(h,m));for(let m=8;m<15;m++)this.setFunctionModule(8,this.size-15+m,r(h,m));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),m=this.size-11+u%3,p=Math.floor(u/3);this.setFunctionModule(m,p,h),this.setFunctionModule(p,m,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const m=Math.max(Math.abs(h),Math.abs(u)),p=c+h,f=d+u;0<=p&&p{(w!=g-m||C>=f)&&b.push(S[w])});return a(b.length==p),b}drawCodewords(c){if(c.length!=Math.floor(Fd.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(f,g),p||(c+=this.finderPenaltyCountPatterns(g)*Fd.PENALTY_N3),p=this.modules[m][v],f=1);c+=this.finderPenaltyTerminateAndCount(p,f,g)*Fd.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(f,g),p||(c+=this.finderPenaltyCountPatterns(g)*Fd.PENALTY_N3),p=this.modules[v][m],f=1);c+=this.finderPenaltyTerminateAndCount(p,f,g)*Fd.PENALTY_N3}for(let m=0;mp+(f?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*Fd.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.lengthFd.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(Fd.getNumRawDataModules(c)/8)-Fd.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Fd.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const m=h^u.shift();u.push(0),d.forEach((p,f)=>u[f]^=Fd.reedSolomonMultiply(p,m))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class xx{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 xx(xx.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!xx.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={}))})(o9||(o9={}));(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={}))})(o9||(o9={}));var oU=o9;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var ABs={L:oU.QrCode.Ecc.LOW,M:oU.QrCode.Ecc.MEDIUM,Q:oU.QrCode.Ecc.QUARTILE,H:oU.QrCode.Ecc.HIGH},qzt=128,Vzt="L",Hzt="#FFFFFF",Gzt="#000000",Wzt=!1,Kzt=1,EBs=4,TBs=0,MBs=.1;function Yzt(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 Zzt(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 PBs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*MBs),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let f=Math.floor(d),g=Math.floor(u),v=Math.ceil(o+d-f),y=Math.ceil(c+u-g);m={x:f,y:g,w:v,h:y}}const p=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:p}}function LBs(s,t){return t!=null?Math.max(Math.floor(t),0):s?EBs:TBs}function Xzt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Ft.useMemo(()=>{const f=(Array.isArray(s)?s:[s]).reduce((g,v)=>(g.push(...oU.QrSegment.makeSegments(v)),g),[]);return oU.QrCode.encodeSegments(f,ABs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Ft.useMemo(()=>{let p=c.getModules();const f=LBs(r,a),g=p.length+f*2,v=PBs(p,l,f,i);return{cells:p,margin:f,numCells:g,calculatedImageSettings:v}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var IBs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),Qzt=Ft.forwardRef(function(t,n){const r=t,{value:a,size:i=qzt,level:l=Vzt,bgColor:o=Hzt,fgColor:c=Gzt,includeMargin:d=Wzt,minVersion:u=Kzt,boostLevel:h,marginSize:m,imageSettings:p}=r,g=QVe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:v}=g,y=QVe(g,["style"]),b=p==null?void 0:p.src,w=Ft.useRef(null),S=Ft.useRef(null),C=Ft.useCallback(V=>{w.current=V,typeof n=="function"?n(V):n&&(n.current=V)},[n]),[E,P]=Ft.useState(!1),{margin:M,cells:I,numCells:D,calculatedImageSettings:F}=Xzt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:p,size:i});Ft.useEffect(()=>{if(w.current!=null){const V=w.current,H=V.getContext("2d");if(!H)return;let K=I;const Z=S.current,oe=F!=null&&Z!==null&&Z.complete&&Z.naturalHeight!==0&&Z.naturalWidth!==0;oe&&F.excavation!=null&&(K=Zzt(I,F.excavation));const re=window.devicePixelRatio||1;V.height=V.width=i*re;const ae=i/D*re;H.scale(ae,ae),H.fillStyle=o,H.fillRect(0,0,D,D),H.fillStyle=c,IBs?H.fill(new Path2D(Yzt(K,M))):I.forEach(function(J,te){J.forEach(function(ce,ve){ce&&H.fillRect(ve+M,te+M,1,1)})}),F&&(H.globalAlpha=F.opacity),oe&&H.drawImage(Z,F.x+M,F.y+M,F.w,F.h)}}),Ft.useEffect(()=>{P(!1)},[b]);const q=XVe({height:i,width:i},v);let G=null;return b!=null&&(G=Ft.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{P(!0)},ref:S,crossOrigin:F==null?void 0:F.crossOrigin})),Ft.createElement(Ft.Fragment,null,Ft.createElement("canvas",XVe({style:q,height:i,width:i,ref:C,role:"img"},y)),G)});Qzt.displayName="QRCodeCanvas";var LN=Ft.forwardRef(function(t,n){const r=t,{value:a,size:i=qzt,level:l=Vzt,bgColor:o=Hzt,fgColor:c=Gzt,includeMargin:d=Wzt,minVersion:u=Kzt,boostLevel:h,title:m,marginSize:p,imageSettings:f}=r,g=QVe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:v,cells:y,numCells:b,calculatedImageSettings:w}=Xzt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:f,size:i});let S=y,C=null;f!=null&&w!=null&&(w.excavation!=null&&(S=Zzt(y,w.excavation)),C=Ft.createElement("image",{href:f.src,height:w.h,width:w.w,x:w.x+v,y:w.y+v,preserveAspectRatio:"none",opacity:w.opacity,crossOrigin:w.crossOrigin}));const E=Yzt(S,v);return Ft.createElement("svg",XVe({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},g),!!m&&Ft.createElement("title",null,m),Ft.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Ft.createElement("path",{fill:c,d:E,shapeRendering:"crispEdges"}),C)});LN.displayName="QRCodeSVG";function Jzt({open:s,onOpenChange:t,url:n,title:r,fileBase:a}){const i=_.useRef(null),o=`${(h=>h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing")(a||r||"listing")}-qr`,c=()=>{var m;const h=(m=i.current)==null?void 0:m.querySelector("svg");return h?new XMLSerializer().serializeToString(h):null},d=()=>{const h=c();if(!h)return;const m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),p=document.createElement("a");p.href=URL.createObjectURL(m),p.download=`${o}.svg`,p.click(),URL.revokeObjectURL(p.href)},u=(h=1024)=>{const m=c();if(!m)return;const p=new Image,f=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),g=URL.createObjectURL(f);p.onload=()=>{const v=document.createElement("canvas");v.width=h,v.height=h;const y=v.getContext("2d");y&&(y.fillStyle="#ffffff",y.fillRect(0,0,h,h),y.drawImage(p,0,0,h,h),URL.revokeObjectURL(g),v.toBlob(b=>{if(!b)return;const w=document.createElement("a");w.href=URL.createObjectURL(b),w.download=`${o}.png`,w.click(),URL.revokeObjectURL(w.href)},"image/png"))},p.src=g};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Listing QR Code"}),e.jsx(_r,{children:"Scans straight to the public listing page — great for flyers, signs, and open houses."})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{ref:i,className:"rounded-xl bg-white p-4 shadow-sm border",children:e.jsx(LN,{value:n,size:220,level:"H",includeMargin:!0})}),e.jsx("p",{className:"text-xs text-muted-foreground break-all text-center",children:n})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 pt-2",children:[e.jsxs(z,{onClick:()=>u(),className:"gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),"PNG"]}),e.jsxs(z,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),"SVG"]}),e.jsxs(z,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),ne.success("Link copied")},className:"gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),"Copy link"]})]})]})})}var DBs="Separator",Ggt="horizontal",RBs=["horizontal","vertical"],eBt=_.forwardRef((s,t)=>{const{decorative:n,orientation:r=Ggt,...a}=s,i=FBs(r)?r:Ggt,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(ci.div,{"data-orientation":i,...o,...a,ref:t})});eBt.displayName=DBs;function FBs(s){return RBs.includes(s)}var tBt=eBt;const fc=_.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(tBt,{ref:a,decorative:n,orientation:t,className:Ct("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));fc.displayName=tBt.displayName;const Q_=()=>rt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),sBt=()=>{const s=ha(),t=1e3;return rt({queryKey:["innercircle-contacts-lite",s],queryFn:async()=>{const n=[];let r=0;for(;;){const{data:a,error:i}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code, birthday, home_anniversary, wedding_anniversary, created_at").eq("owner_user_id",s).order("created_at",{ascending:!1}).range(r,r+t-1);if(i)throw i;const l=a??[];if(n.push(...l),l.length{const t=ha(),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=U.from("innercircle_contacts").select("*").eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");const i=await r(a);if(i.length===0)return i;const l=i.map(p=>p.id),o=Array.from(new Set(i.map(p=>p.lead_source_id).filter(p=>!!p))),c=(p,f=250)=>{const g=[];for(let v=0;v{const{data:f,error:g}=await U.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",p);if(g)throw g;return f??[]})),Promise.all(c(o).map(async p=>{const{data:f,error:g}=await U.from("lead_sources").select("id, name").in("id",p);if(g)throw g;return f??[]}))]),h=new Map;d.flat().forEach(p=>{const f=h.get(p.contact_id)??[];f.push(p),h.set(p.contact_id,f)});const m=new Map(u.flat().map(p=>[p.id,p]));return i.map(p=>({...p,lead_source_ref:p.lead_source_id?m.get(p.lead_source_id)??null:null,tags:h.get(p.id)??[]}))},enabled:!!t,staleTime:10*60*1e3})},OBs=s=>rt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await U.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),nBt=()=>{const s=ha();return rt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await U.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})},vLe=()=>{const s=$t(),t=ha();return mt({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 U.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await U.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"]}),la({title:"Contact created successfully"})},onError:n=>{la({title:"Error creating contact",description:n.message,variant:"destructive"})}})},zet=()=>{const s=$t();return mt({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 U.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await U.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await U.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"]}),la({title:"Contact updated successfully"})},onError:t=>{la({title:"Error updating contact",description:t.message,variant:"destructive"})}})},rBt=()=>{const s=$t();return mt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await U.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await U.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await U.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),la({title:"Spouse link updated"})},onError:t=>{la({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},aBt=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),la({title:"Contact deleted successfully"})},onError:t=>{la({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},zBs=()=>{const s=$t();return mt({mutationFn:async({ids:t,onProgress:n})=>{let a=0;for(let i=0;i{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})},fae=()=>rt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),BBs=s=>rt({queryKey:["action-scripts",s],queryFn:async()=>{let t=U.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),$Bs=()=>rt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await U.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),UBs=()=>{const s=$t(),t=ha();return mt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await U.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"]}),la({title:"Plan created successfully"})},onError:n=>{la({title:"Error creating plan",description:n.message,variant:"destructive"})}})},qBs=()=>{const s=$t(),t=ha();return mt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await U.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 U.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 U.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),la({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{la({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},VBs=()=>{const s=$t();return mt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await U.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"]}),la({title:"Plan updated successfully"})}})},HBs=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),la({title:"Plan deleted successfully"})}})},GBs=()=>{const s=$t();return mt({mutationFn:async({planId:t,items:n})=>{if(await U.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await U.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"]}),la({title:"Plan schedule updated"})}})},WBs=()=>{const s=$t();return mt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await U.auth.getUser(),{data:o,error:c}=await U.from("action_scripts").insert({action_type_id:t,title: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"]}),la({title:"Script created successfully"})},onError:t=>{la({title:"Error creating script",description:t.message,variant:"destructive"})}})},KBs=()=>{const s=ha();return rt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await U.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},YBs=()=>{const s=$t(),t=ha();return mt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await U.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await U.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await U.from("user_plan_enrollments").insert({owner_user_id:t,plan_id: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"]}),la({title:"Plan enrollment updated"})}})},SW=(s=7)=>{const t=ha();return rt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await U.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})},iBt=()=>{const s=ha();return rt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await U.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})},ZBs=(s=90)=>{const{data:t}=Rb(),{data:n}=iBt();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=$t(),t=ha();return mt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await U.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"]}),la({title:"Action completed!"});try{const[l,o]=await Promise.all([U.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),U.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)&&U.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&&U.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{}}})},oBt="agentos_weekly_touch_goal",Wgt=20,lBt=()=>{if(typeof window>"u")return Wgt;const s=localStorage.getItem(oBt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return Wgt},XBs=s=>{localStorage.setItem(oBt,s.toString())},_Le=()=>{const{data:s}=SW(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=lBt();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},QBs=()=>{const s=ha();return rt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},JBs=()=>{const s=$t();return ha(),mt({mutationFn:async()=>{var c;const{data:t}=await U.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await U.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await U.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await U.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(m=>m.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await U.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&la({title:`${t} contact(s) enrolled in plans`})}})},Bet=()=>{const s=ha(),{data:t}=QBs(),{data:n}=SW(30);return rt({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var f;if(!t||t.length===0)return[];const{data:r}=await U.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(g=>g.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(g=>new Date(g.completed_at)>=o).map(g=>`${g.contact_id}-${g.action_type_id}`))||[]);for(const g of t){if(!((f=g.plan)!=null&&f.items)||g.plan.items.length===0||!g.contact||a.has(g.contact_id))continue;const v=new Date(g.cycle_start_date),b=Math.floor((i.getTime()-v.getTime())/(30.44*24*60*60*1e3))%12+1,w=g.plan.items.find(S=>S.month_number===b);if(w&&w.action_type){const S=`${g.contact_id}-${w.action_type_id}`;if(!c.has(S)){const{data:C}=await U.from("relationship_types").select("name").eq("id",g.relationship_type_id).single();l.push({contact:g.contact,actionType:w.action_type,script:w.default_script||void 0,planName:g.plan.name,relationshipTypeName:(C==null?void 0:C.name)||"",monthNumber:b})}}}const d=5,u=i.getDate(),h=l.sort((g,v)=>g.contact.first_name.localeCompare(v.contact.first_name)),m=(u-1)%Math.max(1,h.length);return[...h.slice(m),...h.slice(0,m)].slice(0,d)},enabled:!!s&&!!t})};function e$s(){const{user:s}=hs(),{limitFor:t,isRestricted:n}=OS(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=rt({queryKey:["mass-email-usage",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&!!r,staleTime:60*1e3,queryFn:async()=>{const o=new Date;o.setDate(1),o.setHours(0,0,0,0);const{count:c}=await U.from("bulk_email_sends").select("id",{count:"exact",head:!0}).eq("user_id",s.id).gte("sent_at",o.toISOString());return c||0}}),l=r===null?1/0:Math.max(0,r-a);return{limit:r,used:a,remaining:l,wouldExceed:o=>r!==null&&o>l,refetch:i}}function t$s({onSelect:s}){const{user:t}=hs(),[n,r]=_.useState("root"),[a,i]=_.useState(null),{data:l=[],isLoading:o}=rt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:y,error:b}=await U.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return y}}),{data:c=[],isLoading:d}=rt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:y,error:b}=await U.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(b)throw b;return y}}),{data:u=[],isLoading:h}=rt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y,error:b}=await U.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(b)throw b;return y}}),m=u.filter(y=>y.user_id===(t==null?void 0:t.id)&&!y.is_shared),p=u.filter(y=>y.is_shared),f=l.find(y=>y.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const g=y=>{s({title:y.name,subject:y.subject,body:y.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(Oo,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"My Saved Templates"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.length," template",m.length===1?"":"s"," you've created"]})]})]}),e.jsx(yi,{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(Wo,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.length," team template",p.length===1?"":"s"]})]})]}),e.jsx(yi,{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(y=>e.jsxs("button",{onClick:()=>{i(y.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:y.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:y.name}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:y.description})]})]}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},y.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(Wc,{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(Oo,{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(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):m.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(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(Ki,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(y=>e.jsxs("button",{onClick:()=>g(y),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:y.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.subject||"(no subject)"})]},y.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(Wo,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(Ki,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(y=>e.jsxs("button",{onClick:()=>g(y),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:y.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:y.subject||"(no subject)"})]},y.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:f==null?void 0:f.icon})," ",f==null?void 0:f.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(bt,{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(Ki,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(y=>e.jsxs("button",{onClick:()=>s(y),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:y.title}),y.tone&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:y.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.subject})]},y.id))})})]})}function NL(){var a;const{user:s}=hs(),{data:t,isLoading:n}=rt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,m;const[i,l]=await Promise.all([U.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),U.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((m=c==null?void 0:c.name)==null?void 0:m.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function xae(){const{user:s}=hs();return rt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([U.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),U.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),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 wLe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=zn();return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(Ho,{className:"h-5 w-5"})}),e.jsx(Rs,{children:"Verify your sending email first"})]}),e.jsx(_r,{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(Zr,{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(on,{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(hr,{className:"gap-2 sm:gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs(z,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(mr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function jLe(){const{user:s}=hs(),t=$t(),{data:n,isLoading:r}=rt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await U.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=mt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await U.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"]}),ne.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ne.error("That slug is already taken. Try another."):ne.error("Failed to create page")}}),i=mt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await U.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ne.success("Page updated!")},onError:()=>ne.error("Failed to update page")}),{data:l=[],isLoading:o}=rt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await U.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=mt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await U.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 cBt({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=_.useState(!1),[l,o]=_.useState([]),[c,d]=_.useState(!1),[u,h]=_.useState(0),m=_.useRef(null),p=_.useRef(null);_.useEffect(()=>{const g=v=>{m.current&&!m.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]),_.useEffect(()=>{p.current&&clearTimeout(p.current);const g=s.trim();if(!n||g.length<1||g.includes("@")&&g.indexOf("@")>0&&/\S+@\S+\.\S+/.test(g)){o([]);return}return p.current=setTimeout(async()=>{d(!0);const v=`%${g}%`,y=U,{data:b,error:w}=await y.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),!w&&b&&(o(b),h(0),i(b.length>0))},180),()=>{p.current&&clearTimeout(p.current)}},[s,n]);const f=g=>{g.email&&(t(g.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(pe,{id:"gmail-to",value:s,onChange:g=>t(g.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:g=>{!a||l.length===0||(g.key==="ArrowDown"?(g.preventDefault(),h(v=>Math.min(v+1,l.length-1))):g.key==="ArrowUp"?(g.preventDefault(),h(v=>Math.max(v-1,0))):g.key==="Enter"?(g.preventDefault(),f(l[u])):g.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(bt,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((g,v)=>{const y=[g.first_name,g.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(v),onClick:()=>f(g),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(Oo,{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:y}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:g.email})]})]},g.id)})})]})}function s$s(){const{user:s}=hs(),{data:t,isLoading:n}=rt({queryKey:["email-signature",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("profiles").select("email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(i)throw i;return a}}),r=((t==null?void 0:t.email_signature)||"").trim();return{signatureHtml:r,hasSignature:r.length>0,signatureEnabledByDefault:!!(t!=null&&t.use_email_signature)&&r.length>0,isLoading:n}}function n$s(s,t){if(!t||s.includes(t))return s;const n=`
${t}
`;return/<\/body>/i.test(s)?s.replace(/<\/body>/i,`${n}`):`${s}${n}`}function r$s(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 k7e=25*1024*1024,Kgt=Math.floor(6.5*1024*1024),a$s=750*1024,b2=50,i$s=["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 Vle(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function o$s(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 l$s(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function yw(s,t){const n=l$s(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 HN({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=hs(),h=$t(),{isReady:m,settings:p}=NL(),{data:f}=xae(),[g,v]=_.useState(!1),{intakePage:y}=jLe(),b=y?`https://contacts.relevelup.com/${y.slug}`:null,w=!!r&&r.length>0,S=e$s(),C=m,E=w?r:n?[n]:[],P=E[0],M=w?Math.ceil(E.length/b2):1,I=w&&E.length>b2,[D,F]=_.useState((P==null?void 0:P.email)||""),[q,G]=_.useState(a),[V,H]=_.useState(i),[K,Z]=_.useState(!1),[oe,re]=_.useState(!1),[ae,J]=_.useState([]),te=_.useRef(new Map),[ce,ve]=_.useState(a),[me,he]=_.useState(i),[ge,Ee]=_.useState(!1),[Ne,Pe]=_.useState("composing"),[Oe,ke]=_.useState(0),[Ve,_e]=_.useState(0),[Ae,Se]=_.useState(0),[We,qe]=_.useState(0),Be=_.useRef(!1),Ze=_.useRef(0),[$e,Xe]=_.useState(!0),{signatureHtml:nt,hasSignature:Ge,signatureEnabledByDefault:Je}=s$s(),[ut,lt]=_.useState(!0),[qt,zt]=_.useState(null),Zt=ft=>{let Lt=5381;for(let Mt=0;Mt>>0;return Lt.toString(36)},ms=w?`bulk-${E.length}-${Zt(E.map(ft=>ft.id||ft.email||"").join("|"))}`:(P==null?void 0:P.id)||"adhoc",Dt=Zt(`${a||""}::${(i||"").slice(0,400)}`),It=`levelup:email-draft:${ms}:${Dt}`,[qs,wt]=_.useState(!1),Us=_.useRef(!1),Es=()=>{try{localStorage.removeItem(It)}catch{}wt(!1)};_.useEffect(()=>{s&<(Ge)},[s,Ge]),_.useEffect(()=>{if(s){const ft=/<[a-z][\s\S]*>/i.test(i),Lt=ft?r$s(i):i;Fs.current=ft?{plain:Lt,html:i}:null,F((P==null?void 0:P.email)||""),ve(a),he(Lt),G(yw(a,P||{first_name:""})),H(yw(Lt,P||{first_name:""})),re(!a&&!i),Ee(!1),Yn(Mt=>Mt+1),J([]),te.current=new Map,Pe("composing"),ke(0),_e(0),Se(0),qe(0),Be.current=!1,Ze.current=0,zt(null);try{const Mt=localStorage.getItem(It);if(Mt){const Qt=JSON.parse(Mt),ks=(Qt==null?void 0:Qt.savedAt)&&Date.now()-Qt.savedAt<14*24*60*60*1e3,gs=(Qt==null?void 0:Qt.rawSubject)||(Qt==null?void 0:Qt.rawBody)||(Qt==null?void 0:Qt.html);ks&&gs&&(Qt.to&&F(Qt.to),ve(Qt.rawSubject||""),he(Qt.rawBody||""),G(yw(Qt.rawSubject||"",P||{first_name:""})),H(yw(Qt.rawBody||"",P||{first_name:""})),Qt.html&&(Fs.current={plain:Qt.rawBody||"",html:Qt.html}),re(!1),Yn(Vt=>Vt+1),wt(!0))}}catch{}Us.current=!0}else Us.current=!1},[s,P,a,i]),_.useEffect(()=>{if(!s||!Us.current||Ne!=="composing")return;const ft=Fs.current,Lt={to:D,rawSubject:ce,rawBody:me,html:ft&&me===ft.plain?ft.html:null,savedAt:Date.now()},Mt=()=>{try{if(!ce&&!me)return;localStorage.setItem(It,JSON.stringify({...Lt,savedAt:Date.now(),html:Fs.current&&me===Fs.current.plain?Fs.current.html:null}))}catch{}},Qt=setTimeout(Mt,600);return window.addEventListener("blur",Mt),document.addEventListener("visibilitychange",Mt),()=>{clearTimeout(Qt),window.removeEventListener("blur",Mt),document.removeEventListener("visibilitychange",Mt)}},[s,D,ce,me,Ne,It]);const kn=async ft=>{const Lt=ft.target.files;if(!Lt)return;const Mt=ae.reduce((gs,Vt)=>gs+Vt.size,0),Qt=[];let ks=Mt;for(const gs of Array.from(Lt)){if(!i$s.includes(gs.type)){ne.error(`${gs.name}: Unsupported file type`);continue}if(ks+gs.size>k7e){ne.error(`Total attachments exceed ${Vle(k7e)} limit`);break}try{const Vt=await o$s(gs);Qt.push({name:gs.name,type:gs.type,size:gs.size,data:Vt}),ks+=gs.size}catch{ne.error(`Failed to read ${gs.name}`)}}J(gs=>[...gs,...Qt]),ft.target.value=""},Sn=ft=>{const Lt=ae[ft];Lt&&te.current.delete(`${Lt.name}::${Lt.size}`),J(Mt=>Mt.filter((Qt,ks)=>ks!==ft))},bn=async()=>{if(ae.length===0||!u)return{inline:[],paths:[]};const ft=[],Lt=[];for(const Mt of ae){const Qt=`${Mt.name}::${Mt.size}`,ks=te.current.get(Qt);if(ks){Lt.push(ks);continue}if(Mt.size<=a$s){ft.push(Mt);continue}const gs=Mt.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Vt=`${u.id}/${Date.now()}-${gs}`,Vs=atob(Mt.data),Zs=new Uint8Array(Vs.length);for(let Or=0;Or{if(!/<[a-z][\s\S]*>/i.test(ft)||typeof window>"u")return ft;const Lt=ft.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,""),Mt=document.createElement("div");return Mt.innerHTML=Lt,(Mt.textContent||Mt.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},Fs=_.useRef(null),cn=Fs.current&&me===Fs.current.plain?Fs.current.html:null,lr=_.useRef(null),[Tn,Yn]=_.useState(0),fs=()=>{const ft=lr.current,Lt=Fs.current;!ft||!Lt||(Fs.current={plain:Lt.plain,html:ft.innerHTML})},wn=ft=>{const Lt=/<[a-z][\s\S]*>/i.test(ft.body),Mt=Lt?cr(ft.body):ft.body;Fs.current=Lt?{plain:Mt,html:ft.body}:null,ve(ft.subject),he(Mt),G(yw(ft.subject,P||{first_name:""})),H(yw(Mt,P||{first_name:""})),re(!1),Yn(Qt=>Qt+1)},As=ft=>{let Lt=ft.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+)\)/g,(Mt,Qt,ks)=>`${Qt}`);return Lt=Lt.replace(/(^|[\s(])((?:https?:\/\/|www\.)[^\s<)]+)/g,(Mt,Qt,ks)=>{const gs=ks.startsWith("http")?ks:`https://${ks}`;return`${Qt}${ks}`}),Lt},Ss=ft=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(ft)?ft:ft.split(/\n\n+/).map(Lt=>`

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

`).join(""),pr=(ft,Lt)=>{const Mt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Qt=ft.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(gs,Vt,Vs,Zs,Zn)=>{if(!Zs||/^(mailto:|tel:|#)/i.test(Zs)||Zs.includes("/bulk-email-track")||Zs.includes("/ses-campaign-track"))return gs;const Or=`${Mt}?s=${Lt}&t=click&u=${encodeURIComponent(Zs)}`;return``});const ks=``;return/<\/body>/i.test(Qt)?Qt=Qt.replace(/<\/body>/i,`${ks}`):Qt=`${Qt}${ks}`,Qt},hn=async ft=>{if(!(ft!=null&&ft.email))return ne.error("Please enter a recipient email"),!1;const Lt=ft||{first_name:""},Mt=yw(ce,Lt),Qt=Fs.current,ks=Qt&&me===Qt.plain,gs=yw(ks?Qt.html:me,Lt);let Vt=ks?gs:Ss(gs);ut&&nt&&(Vt=n$s(Vt,yw(nt,Lt)));const Vs=u&&ft.id?crypto.randomUUID():null;Vs&&(Vt=pr(Vt,Vs));try{if(u&&ft.email){const Or=new Date(Date.now()-6e5).toISOString(),{data:oa}=await U.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",ft.email).eq("subject",Mt).gte("sent_at",Or).limit(1);if(oa&&oa.length>0)return console.log(`Skipping duplicate send to ${ft.email} (same subject within 10 min)`),ne.info(`Skipped ${ft.first_name||ft.email} — already sent this in the last 10 min`),!0}const{inline:Zs,paths:Zn}=await bn();if(C){const Or=(p==null?void 0:p.display_name)||"ReLevelUp",oa=`${Or.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,aa=`${Or} <${oa}>`;let Kr=Zn[0];if(!Kr&&Zs.length>0&&u){const Ba=Zs[0],Ja=Ba.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Ro=`${u.id}/${Date.now()}-${Ja}`,ji=atob(Ba.data),Oa=new Uint8Array(ji.length);for(let uo=0;uo({name:aa,type:Kr,data:Tr})),attachment_paths:Zn,skip_signature:!0}});if(oa)throw oa;if(!(Or!=null&&Or.success))throw new Error((Or==null?void 0:Or.error)||"Failed to send")}if(u&&ft.id&&Vs&&(await U.from("bulk_email_sends").insert({id:Vs,user_id:u.id,contact_id:ft.id,contact_email:ft.email,subject:Mt,source:c||(C?"ses_bulk":"sphere_gaps")}),d))try{await U.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:ft.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Mt}`,completed_at:new Date().toISOString()})}catch(Or){console.warn("touch log insert failed",Or)}return!0}catch(Zs){return console.error("Send error:",Zs),ne.error("Failed to send to "+ft.first_name+": "+(Zs instanceof Error?Zs.message:"Unknown error")),!1}},Pn=()=>{const ft=Oe*b2;return E.slice(ft,ft+b2)},Gs=async(ft=0,Lt=$e)=>{if(!q||!V){ne.error("Please fill in subject and message");return}Z(!0),Pe("sending");let Mt=Math.max(0,Math.min(ft,E.length)),Qt=!1;for(;MtZn+1):Se(Zn=>Zn+1),VssetTimeout(Zn,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),Qt||Be.current||Mt>=E.length)break;if(!Lt){Z(!1),Pe("batch_complete");return}if(qe(0),await new Promise(Vs=>setTimeout(Vs,1500)),Be.current){Qt=!0;break}}Z(!1),!Qt&&!Be.current&&Es(),Pe(Qt||Be.current?"batch_complete":"all_done")},an=async()=>{var Lt;if(!q||!V){ne.error("Please fill in subject and message");return}const ft=w?(r==null?void 0:r.length)||0:1;if(S.wouldExceed(ft)){ne.error(`Your package includes ${(Lt=S.limit)==null?void 0:Lt.toLocaleString()} emails per month. You have ${S.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(C&&f&&!f.hasVerifiedSes&&!f.hasGmail){v(!0);return}if(!w){const Mt=P||{id:"",first_name:"",last_name:"",email:D.trim()};if(!Mt.email){ne.error("Please enter a recipient email");return}Z(!0);try{await hn(Mt)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),Es(),ne.success("Email sent successfully!"),t(!1),o==null||o())}finally{Z(!1)}return}Be.current=!1,Ze.current=0,await Gs(0)},tr=async()=>{Be.current=!1,qe(0),await Gs(Ze.current,!1)},Lr=async()=>{Be.current=!1,Xe(!0),qe(0),await Gs(Ze.current,!0)},Yt=()=>{if(K){Be.current=!0;return}t(!1),o==null||o()},it=Oe*b2;Math.min(it+b2,E.length);const gt=w&&E.length>0?Math.round((Ve+Ae)/E.length*100):0;return e.jsxs(Is,{open:s,onOpenChange:Yt,children:[e.jsxs(Ls,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",onPointerDownOutside:ft=>{(ce||me)&&ft.preventDefault()},onInteractOutside:ft=>{(ce||me)&&ft.preventDefault()},onEscapeKeyDown:ft=>{(ce||me)&&ft.preventDefault()},children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:`h-5 w-5 ${C?"text-orange-500":"text-red-500"}`}),w?`Send to ${E.length} Contacts`:"Compose Email"]}),C?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",p==null?void 0:p.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,w&&Ne==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[E.length," contacts"]}),". You'll review each personalized email before sending."]})]}),qs&&Ne==="composing"&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-xs",children:[e.jsx("span",{children:"We brought back the email you were writing."}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>{Es(),ve(""),he(""),G(""),H(""),Fs.current=null,Yn(ft=>ft+1)},children:"Start fresh"})]}),Ne==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(bt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Oe+1," of ",M,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[We," of ",Pn().length," in this batch"]}),$e&&M>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-continuing through all ",M," batches — keep this window open."]})]}),e.jsx(Di,{value:We/Math.max(Pn().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Ve+Ae," / ",E.length]}),e.jsxs("span",{children:[Ve," sent • ",Ae," failed"]})]}),e.jsx(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Be.current=!0},children:"Stop Sending"})]}),Ne==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Mr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Sending paused after batch ",Oe+1]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ve," sent, ",Ae," failed so far"]})]}),e.jsx(Di,{value:gt,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[E.length-Ve-Ae," contacts remaining (",Math.max(M-Oe-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",className:"flex-1",onClick:Yt,children:"Done for Now"}),e.jsxs(z,{className:"flex-1 gap-2",onClick:Lr,children:[e.jsx(Fr,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full",onClick:tr,children:["Send just the next ",Math.min(b2,Math.max(E.length-(Ve+Ae),0))," contacts"]})]}),Ne==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Mr,{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:[Ve," emails sent successfully",Ae>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Ae," failed"]})]})]}),e.jsx(z,{className:"w-full",onClick:Yt,children:"Close"})]}),Ne==="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($r,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>re(!1),className:"h-7 px-2 text-xs",children:[e.jsx(er,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(t$s,{onSelect:wn})]}):e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>re(!0),children:[e.jsx($r,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(fc,{}),!w&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"gmail-to",children:"To"}),e.jsx(cBt,{value:D,onChange:F,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(pe,{id:"gmail-subject",value:q,onChange:ft=>{G(ft.target.value),ve(ft.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(ee,{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:()=>{H(ft=>ft+"{{first_name}}"),he(ft=>ft+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{H(ft=>ft+"{{last_name}}"),he(ft=>ft+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(ze,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const ft=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;H(Lt=>Lt+ft),he(Lt=>Lt+ft)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),cn&&!ge?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border bg-background",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 font-bold",onMouseDown:ft=>ft.preventDefault(),onClick:()=>document.execCommand("bold"),title:"Bold",children:"B"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 italic",onMouseDown:ft=>ft.preventDefault(),onClick:()=>document.execCommand("italic"),title:"Italic",children:"I"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 underline",onMouseDown:ft=>ft.preventDefault(),onClick:()=>document.execCommand("underline"),title:"Underline",children:"U"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onMouseDown:ft=>ft.preventDefault(),onClick:()=>{const ft=window.prompt("Link address (https://...)");ft&&document.execCommand("createLink",!1,ft)},title:"Add link",children:"Link"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Click the email below to edit it"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-[11px] text-muted-foreground",onClick:()=>Ee(!0),children:"Plain text"})]})]}),e.jsx("div",{ref:lr,contentEditable:!0,suppressContentEditableWarning:!0,onInput:fs,onBlur:fs,className:"max-h-[420px] overflow-y-auto p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:cn}},Tn)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit any text right here — ","{{first_name}}"," and ","{{last_name}}"," are swapped in for each person when it sends."]})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const ft=document.getElementById("gmail-body"),Lt=ft?V.slice(ft.selectionStart,ft.selectionEnd):"",Mt=window.prompt("Link text (what the reader sees)",Lt||"Click here");if(!Mt)return;let Qt=window.prompt("Link address (https://...)","https://");if(!Qt)return;Qt=Qt.trim(),/^(https?:\/\/|mailto:)/i.test(Qt)||(Qt=`https://${Qt}`);const ks=`[${Mt}](${Qt})`,gs=ft?ft.selectionStart:V.length,Vt=ft?ft.selectionEnd:V.length,Vs=V.slice(0,gs)+ks+V.slice(Vt);H(Vs),he(Vs)},children:"Insert link"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Web addresses you type become clickable automatically"})]}),e.jsx(Ps,{id:"gmail-body",value:V,onChange:ft=>{H(ft.target.value),he(ft.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"})]}),w&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Include my email signature"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:Ge?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(mn,{checked:ut&&Ge,onCheckedChange:lt,disabled:!Ge})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var ft;return(ft=document.getElementById("gmail-attachments"))==null?void 0:ft.click()},disabled:K,children:[e.jsx(dP,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Vle(k7e)," 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:kn})]}),ae.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map((ft,Lt)=>e.jsxs(ze,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(dP,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:ft.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Vle(ft.size),")"]}),e.jsx("button",{type:"button",onClick:()=>Sn(Lt),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(er,{className:"h-3 w-3"})})]},Lt))}),C&&ae.some(ft=>ft.size>Kgt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Vle(Kgt)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),w?e.jsxs(z,{onClick:()=>{zt(E[0]||null),Pe("reviewing")},disabled:!q||!V,className:"gap-2",children:["Review Emails",e.jsx(Da,{className:"h-4 w-4"})]}):e.jsxs(z,{onClick:an,disabled:K||!q||!V||!D.trim(),className:"gap-2",children:[K?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),K?"Sending...":"Send Email"]})]})]}),Ne==="reviewing"&&w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),I&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 space-y-2",children:[e.jsxs("p",{className:"text-xs text-amber-600",children:["📦 ",E.length," contacts will be sent in ",M," batches of up to ",b2,"."]}),e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5 accent-current",checked:$e,onChange:ft=>Xe(ft.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Send all batches automatically"}),e.jsx("span",{className:"block text-muted-foreground",children:"Runs straight through every batch — no need to click Continue. Keep this window open; you can stop anytime."})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{children:["Recipients (",E.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:E.map(ft=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(qt==null?void 0:qt.id)===ft.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>zt(ft),children:[ft.first_name," ",ft.last_name," — ",ft.email]},ft.id))})]}),qt&&e.jsxs("div",{className:"border rounded-xl p-3 bg-muted/30 space-y-2 animate-in fade-in slide-in-from-top-1",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs font-semibold text-primary flex items-center gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Preview for ",qt.first_name," ",qt.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:"})," ",qt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",yw(ce,qt)]})]}),e.jsx(fc,{}),cn?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:yw(cn,qt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:yw(me,qt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>{Pe("composing"),zt(null)},children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(z,{onClick:an,disabled:K,className:"gap-2",children:[K?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),I?`Send First ${b2}`:`Send to ${E.length}`]})]})]})]}),e.jsx(wLe,{open:g,onOpenChange:v,hasPending:!!(f!=null&&f.hasPendingSes),pendingEmails:f==null?void 0:f.pendingEmails})]})}function c$s(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const d$s={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function dBt({open:s,onOpenChange:t,listing:n}){const{user:r}=hs(),{data:a=[],isLoading:i}=Rb(),{data:l=[]}=Q_(),[o,c]=_.useState(""),[d,u]=_.useState("all"),[h,m]=_.useState(new Set),[p,f]=_.useState(!1),[g,v]=_.useState(null);_.useEffect(()=>{s||(c(""),u("all"),m(new Set),f(!1))},[s]),_.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await U.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();v((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const y=_.useMemo(()=>a.filter(M=>M.email),[a]),b=_.useMemo(()=>{let M=y;if(d!=="all"&&(M=M.filter(I=>{var D;return(D=I.tags)==null?void 0:D.some(F=>F.relationship_type_id===d)})),o.trim()){const I=o.toLowerCase();M=M.filter(D=>`${D.first_name||""} ${D.last_name||""}`.toLowerCase().includes(I)||(D.email||"").toLowerCase().includes(I))}return M},[y,o,d]),w=()=>{h.size===b.length?m(new Set):m(new Set(b.map(M=>M.id)))},S=M=>{const I=new Set(h);I.has(M)?I.delete(M):I.add(M),m(I)},C=_.useMemo(()=>y.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})),[y,h]),{defaultSubject:E,defaultBody:P}=_.useMemo(()=>{var J,te,ce,ve;const M=n.property_address||`${n.city}, ${n.state}`,I=c$s(n.price),D=d$s[n.property_type]||"home",F=n.bedrooms?`${n.bedrooms} bed`:"",q=n.bathrooms?`${n.bathrooms} bath`:"",G=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",V=[F,q,G].filter(Boolean).join(" • "),H=`https://listings.relevelup.com/${n.slug||n.id}`,K=((te=(J=n.photos)==null?void 0:J.find(me=>me.is_primary))==null?void 0:te.photo_url)||((ve=(ce=n.photos)==null?void 0:ce[0])==null?void 0:ve.photo_url)||"",oe={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",re=`${oe}: ${M} — ${I}`,ae=`

Hi {{first_name}},

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

${K?` ${M} `:""}
${oe}

${I}

${M}

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

${V?`

${V} • ${D}

`:""} 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:re,defaultBody:ae}},[n]);return p?e.jsx(HN,{open:p,onOpenChange:M=>{f(M),M||t(!1)},bulkContacts:C,defaultSubject:E,defaultBody:P,gmailEmail:g}):e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{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(_r,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"sm:w-[180px]",children:e.jsx(cs,{placeholder:"Filter by tag"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(He,{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:w,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(za,{checked:b.length>0&&h.size===b.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===b.length&&b.length>0?"Deselect all":`Select all (${b.length})`})]}),e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(On,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(Ki,{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(bt,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):b.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:y.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:b.map(M=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(za,{checked:h.has(M.id),onCheckedChange:()=>S(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(I=>{var D;return e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(D=I.relationship_type)==null?void 0:D.name},I.id)})})]},M.id))})}),e.jsx(fc,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:g?`Sending from ${g}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>f(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}const u$s="#2a4c64",h$s="#B8965A";function NLe(){const{user:s}=hs();return rt({queryKey:["agent-brand",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const t=s.id,[n,r,a,i]=await Promise.all([U.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),U.from("lead_sites").select("brand_color, accent_color, agent_license_number, brokerage_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5),U.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, title, positioning_statement, display_email").eq("user_id",t).maybeSingle(),U.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle()]),l=n.data||{},o=r.data||[],c=o.find(y=>y.is_active)||o[0]||{},d=a.data||{},u=i.data||{};let h=null;if(l.brokerage_id){const{data:y}=await U.from("brokerage_brand_profiles").select("primary_color, accent_color, logo_url, lock_colors, lock_logo").eq("brokerage_id",l.brokerage_id).maybeSingle();h=y||null}const m=!!(h!=null&&h.lock_colors),p=(...y)=>y.map(b=>typeof b=="string"&&b.trim()?b.trim():null).find(Boolean)||null,f=m?p(h==null?void 0:h.primary_color,u.brand_color,c.brand_color):p(u.brand_color,h==null?void 0:h.primary_color,c.brand_color),g=m?p(h==null?void 0:h.accent_color,u.accent_color,c.accent_color):p(u.accent_color,h==null?void 0:h.accent_color,c.accent_color);let v=l.brokerage_name||d.brokerage_display_name||c.brokerage_legal_name||null;if(!v&&l.brokerage_id){const{data:y}=await U.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle();v=(y==null?void 0:y.name)||null}return{name:l.name||s.email||"Your Name",headshotUrl:u.headshot_url||l.avatar_url||null,brokerageName:v,brokerageLogoUrl:(h!=null&&h.lock_logo?h==null?void 0:h.logo_url:u.logo_url)||u.logo_url||d.brokerage_logo_url||d.team_logo_url||c.team_logo_url||(h==null?void 0:h.logo_url)||null,licenseNumber:u.license_number||c.agent_license_number||null,licenseState:u.license_state||c.license_state||null,phone:l.phone||null,email:d.display_email||l.email||s.email||null,website:u.website_url||l.website_url||null,brandColor:f||u$s,accentColor:g||h$s,tagline:u.tagline||d.positioning_statement||l.title||d.title||null}}})}const Ygt=[{key:"just_listed",label:"Just Listed",ribbon:"JUST LISTED"},{key:"price_improvement",label:"Price Drop",ribbon:"PRICE IMPROVEMENT"},{key:"under_contract",label:"Under Contract",ribbon:"UNDER CONTRACT"},{key:"sold",label:"Sold",ribbon:"JUST SOLD"},{key:"open_house",label:"Open House",ribbon:"OPEN HOUSE"}],m$s=[{key:"onyx",label:"Onyx & Gold",base:"#0F172A",accent:"#D4AF37"},{key:"navy",label:"Classic Navy",base:"#2a4c64",accent:"#B8965A"},{key:"noir",label:"Modern Noir",base:"#111111",accent:"#F5F5F5"}],VAe=s=>{switch(s){case"price_improvement":return"price_improvement";case"under_contract":return"under_contract";case"sold":return"sold";default:return"just_listed"}},p$s=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)}`},Hle=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Zgt=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}),Xgt=(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)},NX=(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()}…`},f$s=(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},g$s=s=>{const t=s.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t,r=parseInt(n,16);return Number.isNaN(r)?{r:15,g:23,b:42}:{r:r>>16&255,g:r>>8&255,b:r&255}},ET=(s,t)=>{const{r:n,g:r,b:a}=g$s(s);return`rgba(${n},${r},${a},${t})`};function $et({listingId:s,open:t,onOpenChange:n,initialStatus:r}){var ve,me;const a=zn(),{data:i}=dae(s||""),{data:l}=NLe(),[o,c]=_.useState(null),[d,u]=_.useState({base:null,accent:null}),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[g,v]=_.useState(null),[y,b]=_.useState(null),[w,S]=_.useState(r||"just_listed"),[C,E]=_.useState("brand"),[P,M]=_.useState(""),[I,D]=_.useState(!1),F=_.useMemo(()=>((i==null?void 0:i.photos)||[]).slice().sort((he,ge)=>he.is_primary&&!ge.is_primary?-1:!he.is_primary&&ge.is_primary?1:(he.sort_order??0)-(ge.sort_order??0)),[i==null?void 0:i.photos]),q=_.useMemo(()=>({key:"brand",label:"My Brand Kit",base:d.base||(l==null?void 0:l.brandColor)||"#2a4c64",accent:d.accent||(l==null?void 0:l.accentColor)||"#B8965A"}),[d.base,d.accent,l==null?void 0:l.brandColor,l==null?void 0:l.accentColor]),G=_.useMemo(()=>[q,...m$s],[q]),V=G.find(he=>he.key===C)||q,H=((ve=Ygt.find(he=>he.key===w))==null?void 0:ve.ribbon)||"JUST LISTED",K=y||((me=F[0])==null?void 0:me.photo_url)||null,Z=p$s((o==null?void 0:o.phone)||(l==null?void 0:l.phone)),oe=[i!=null&&i.bedrooms?`${i.bedrooms} BD`:null,i!=null&&i.bathrooms?`${i.bathrooms} BA`:null,i!=null&&i.square_footage?`${i.square_footage.toLocaleString()} SF`:null].filter(Boolean);_.useEffect(()=>{var ge;if(!t)return;S(r||VAe(i==null?void 0:i.status));const he=((ge=F[0])==null?void 0:ge.photo_url)||null;b(Ee=>Ee||he)},[t,i==null?void 0:i.id,F.length]),_.useEffect(()=>{t||(v(null),b(null),D(!1),u({base:null,accent:null}))},[t]),_.useEffect(()=>{let he=!1;if(!(!t||!(i!=null&&i.agent_id)))return(async()=>{var Ae,Se,We,qe;const[ge,Ee,Ne]=await Promise.all([U.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",i.agent_id).maybeSingle(),U.from("agent_brand_profiles").select("brand_color, accent_color").eq("user_id",i.agent_id).maybeSingle(),U.from("lead_sites").select("brand_color, accent_color, is_active, created_at").eq("agent_id",i.agent_id).order("created_at",{ascending:!0}).limit(5)]);if(he)return;const Pe=ge.data;c({name:(Pe==null?void 0:Pe.name)||((Ae=i.agent)==null?void 0:Ae.name)||"Agent",phone:(Pe==null?void 0:Pe.phone)||(Pe==null?void 0:Pe.phone_e164)||null,avatar_url:(Pe==null?void 0:Pe.avatar_url)||null,brokerage:((Se=Pe==null?void 0:Pe.brokerage)==null?void 0:Se.name)||((qe=(We=i.agent)==null?void 0:We.brokerage)==null?void 0:qe.name)||null});const Oe=Ee.data||null,ke=Ne.data||[],Ve=ke.find(Be=>Be.is_active)||ke[0]||{},_e=Be=>typeof Be=="string"&&Be.trim()?Be.trim():null;u({base:_e(Oe==null?void 0:Oe.brand_color)||_e(Ve.brand_color),accent:_e(Oe==null?void 0:Oe.accent_color)||_e(Ve.accent_color)})})(),()=>{he=!0}},[t,i==null?void 0:i.agent_id]),_.useEffect(()=>{if(!t||!i||I)return;const he=[i.city,i.state].filter(Boolean).join(", "),ge=oe.join(" · "),Ee=Hle(i.price),Ne=Z?`call or text ${Z}`:"send me a message",Pe=(i.city||"").replace(/[^a-zA-Z]/g,""),Oe={just_listed:`✨ JUST LISTED in ${he||"town"}!`,price_improvement:`📉 PRICE IMPROVEMENT in ${he||"town"}!`,under_contract:`🤝 UNDER CONTRACT in ${he||"town"}!`,sold:`🎉 JUST SOLD in ${he||"town"}!`,open_house:`🚪 OPEN HOUSE in ${he||"town"}!`},ke={just_listed:`Want a private tour? ${Ne}.`,price_improvement:`This one won't last at the new number — ${Ne}.`,under_contract:`Looking for something similar? ${Ne}.`,sold:`Thinking about making a move? ${Ne}.`,open_house:`Stop by or ${Ne} for details.`},Ve={just_listed:"#JustListed",price_improvement:"#PriceImprovement",under_contract:"#UnderContract",sold:"#JustSold",open_house:"#OpenHouse"},_e=[Oe[w],i.property_address||"",[ge,Ee].filter(Boolean).join(" · "),i.description?i.description.split(/\n+/)[0].slice(0,180):"",ke[w],[Ve[w],Pe?`#${Pe}RealEstate`:"","#RealEstate","#DreamHome"].filter(Boolean).join(" ")].filter(Boolean);M(_e.join(` `))},[t,i==null?void 0:i.id,w,Z,I]);const re=_.useCallback(async()=>{if(!i)return;const he=(o==null?void 0:o.name)||(l==null?void 0:l.name)||"Agent",ge=(o==null?void 0:o.brokerage)||(l==null?void 0:l.brokerageName)||null;m(!0);try{const Ee=document.createElement("canvas");Ee.width=1080,Ee.height=1080;const Ne=Ee.getContext("2d");if(!Ne)throw new Error("Canvas unavailable");if(Ne.fillStyle=V.base,Ne.fillRect(0,0,1080,1080),K)try{const qe=await Zgt(K);Xgt(Ne,qe,0,0,1080,1080)}catch{}const Pe=Ne.createLinearGradient(0,0,0,1080);Pe.addColorStop(0,ET(V.base,.6)),Pe.addColorStop(.34,ET(V.base,.18)),Pe.addColorStop(.62,ET(V.base,.5)),Pe.addColorStop(1,ET(V.base,.98)),Ne.fillStyle=Pe,Ne.fillRect(0,0,1080,1080),Ne.fillStyle=V.accent,Ne.fillRect(56,62,72,3),Ne.font="600 22px Arial, sans-serif",x$s(Ne,H,146,72,8),(w==="sold"||w==="under_contract")&&(Ne.save(),Ne.fillStyle=ET(V.accent,.92),Ne.fillRect(0,430,1080,96),Ne.fillStyle=V.base,Ne.font="700 46px Arial, sans-serif",Ne.textAlign="center",Ne.textBaseline="middle",Ne.fillText(w==="sold"?"SOLD":"UNDER CONTRACT",540,479),Ne.restore(),Ne.textAlign="left"),Ne.save(),Ne.shadowColor="rgba(0,0,0,0.55)",Ne.shadowBlur=24,Ne.shadowOffsetY=4,Ne.fillStyle="#F8FAFC",Ne.font="600 64px Georgia, serif",Ne.textBaseline="top";const Oe=f$s(Ne,i.property_address||`${i.city||""}, ${i.state||""}`.trim(),952,2);let ke=Oe.length>1?590:654;Oe.forEach(qe=>{Ne.fillText(qe,64,ke),ke+=70}),Ne.restore();const Ve=[i.city,i.state].filter(Boolean).join(", ")+(i.neighborhood?` · ${i.neighborhood}`:"");Ne.fillStyle="rgba(248,250,252,0.9)",Ne.font="600 26px Arial, sans-serif",Ne.fillText(NX(Ne,Ve.toUpperCase(),952),64,ke+8),Ne.fillStyle=V.accent,Ne.font="700 56px Arial, sans-serif";const _e=w==="sold"?`SOLD · ${Hle(i.price)}`:w==="price_improvement"?`NOW ${Hle(i.price)}`:Hle(i.price);Ne.fillText(_e,64,ke+58),oe.length>0&&(Ne.fillStyle="rgba(248,250,252,0.86)",Ne.font="600 22px Arial, sans-serif",Ne.fillText(NX(Ne,oe.join(" · "),400),620,ke+78));const Ae=Ne.createLinearGradient(0,880,0,1080);Ae.addColorStop(0,ET(V.base,.96)),Ae.addColorStop(1,V.base),Ne.fillStyle=Ae,Ne.fillRect(0,880,1080,200),Ne.fillStyle=V.accent,Ne.fillRect(0,880,1080,3),Ne.save(),Ne.beginPath(),Ne.arc(124,980,60,0,Math.PI*2),Ne.closePath(),Ne.fillStyle=ET(V.accent,.18),Ne.fill(),Ne.lineWidth=6,Ne.strokeStyle=V.accent,Ne.stroke(),Ne.clip();const Se=(o==null?void 0:o.avatar_url)||(l==null?void 0:l.headshotUrl)||null;let We=!1;if(Se)try{const qe=await Zgt(Se);Xgt(Ne,qe,64,920,120,120),We=!0}catch{We=!1}We||(Ne.fillStyle=V.accent,Ne.font="700 48px Arial, sans-serif",Ne.textAlign="center",Ne.textBaseline="middle",Ne.fillText(he.charAt(0).toUpperCase(),124,982)),Ne.restore(),Ne.textAlign="left",Ne.textBaseline="alphabetic",Ne.fillStyle="#F8FAFC",Ne.font="600 38px Georgia, serif",Ne.fillText(NX(Ne,he,Z?430:820),212,970),ge&&(Ne.fillStyle=V.accent,Ne.font="600 20px Arial, sans-serif",Ne.fillText(NX(Ne,ge.toUpperCase(),Z?430:820),212,1008)),Z&&(Ne.textAlign="right",Ne.fillStyle=ET(V.accent,.9),Ne.font="600 16px Arial, sans-serif",Ne.fillText("CALL · TEXT",1016,958),Ne.fillStyle="#F8FAFC",Ne.font="600 38px Arial, sans-serif",Ne.fillText(Z,1016,1008)),v(Ee.toDataURL("image/png"))}catch(Ee){console.error("Generate graphic error",Ee),ne.error("Could not generate graphic")}finally{m(!1)}},[i,o,l,V,K,H,w,oe,Z]);_.useEffect(()=>{if(!t||!i)return;const he=setTimeout(()=>{re()},300);return()=>clearTimeout(he)},[t,i==null?void 0:i.id,o==null?void 0:o.name,y,w,C,l==null?void 0:l.brandColor]);const ae=async he=>(await fetch(he)).blob(),J=async()=>{if(!g)return;const he=document.createElement("a");he.href=g,he.download=`${w}-${(i==null?void 0:i.slug)||(i==null?void 0:i.id)||"graphic"}.png`,he.click(),ne.success("Downloaded!")},te=async()=>{try{await navigator.clipboard.writeText(P),ne.success("Caption copied")}catch{ne.error("Copy not supported in this browser")}},ce=async()=>{var he;if(g){f(!0);try{const{data:ge}=await U.auth.getUser(),Ee=(he=ge.user)==null?void 0:he.id;if(!Ee)throw new Error("Not signed in");const Ne=await ae(g),Pe=`listing-social/${Ee}/${crypto.randomUUID()}.png`,{error:Oe}=await U.storage.from("agent-uploads").upload(Pe,Ne,{contentType:"image/png",upsert:!0});if(Oe)throw Oe;const{data:ke}=U.storage.from("agent-uploads").getPublicUrl(Pe);sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:ke.publicUrl,mediaType:"image",caption:P,source:"listing",sourceRef:i==null?void 0:i.id})),n(!1),a("/social-studio"),ne.success("Draft ready in Social Studio")}catch(ge){console.error("Push to Social Studio failed",ge),ne.error("Could not send to Social Studio")}finally{f(!1)}}};return e.jsx(Is,{open:t,onOpenChange:n,children:e.jsx(Ls,{className:"!max-w-[900px] !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(Os,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(Rs,{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:"Share this listing"})]}),e.jsx(_r,{className:"text-xs",children:"Square 1080×1080 graphic in your brand colors — ready for Instagram, Facebook and LinkedIn."})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 pb-3 space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ygt.map(he=>e.jsx(z,{type:"button",size:"sm",variant:w===he.key?"default":"outline",className:"h-7 text-xs",onClick:()=>S(he.key),children:he.label},he.key))}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:G.map(he=>e.jsxs("button",{type:"button",onClick:()=>E(he.key),className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs transition ${C===he.key?"border-primary ring-2 ring-primary/25":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("span",{className:"flex",children:[e.jsx("span",{className:"h-3.5 w-3.5 rounded-l-full",style:{background:he.base}}),e.jsx("span",{className:"h-3.5 w-3.5 rounded-r-full",style:{background:he.accent}})]}),he.label]},he.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"relative mx-auto flex aspect-square w-full max-w-[360px] items-center justify-center overflow-hidden rounded-lg",style:{background:V.base},children:[g?e.jsx("img",{src:g,alt:"Social graphic preview",className:"h-full w-full object-cover"}):e.jsx("div",{className:"text-xs text-white/70",children:"Preparing preview…"}),h&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/60 text-white/90",children:[e.jsx(bt,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),F.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:F.map(he=>e.jsx("button",{type:"button",onClick:()=>b(he.photo_url),className:`relative h-14 w-14 shrink-0 overflow-hidden rounded-md border-2 transition ${y===he.photo_url?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:he.photo_url,alt:"",className:"h-full w-full object-cover"})},he.id))})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Post text"}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:te,children:[e.jsx(Sa,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Ps,{value:P,onChange:he=>{M(he.target.value),D(!0)},rows:14,className:"min-h-[260px] text-sm",placeholder:"Your caption…"})]})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-5 pb-5 pt-3",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>n(!1),children:"Not now"}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>void re(),disabled:h||!i,className:"gap-1.5",children:"Regenerate"}),e.jsxs(z,{variant:"outline",size:"sm",onClick:J,disabled:!g,className:"gap-1.5",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Download"]}),e.jsxs(z,{size:"sm",onClick:ce,disabled:!g||p,className:"gap-1.5",children:[p?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Push to Social Studio"]})]})]})})})}function y$s({listing:s,canEdit:t}){const n=zn(),{data:r,isLoading:a}=MMs(s.id),i=rOt(),l=aOt(),[o,c]=_.useState({owner_name:"",owner_company:"",owner_email:"",owner_phone:"",decision_maker_notes:"",pitch_date:"",positioning:"",pricing_strategy:"",pitch_notes:"",competitors:""}),[d,u]=_.useState(tOt),[h,m]=_.useState("");_.useEffect(()=>{r&&(c({owner_name:r.owner_name??"",owner_company:r.owner_company??"",owner_email:r.owner_email??"",owner_phone:r.owner_phone??"",decision_maker_notes:r.decision_maker_notes??"",pitch_date:r.pitch_date?String(r.pitch_date).slice(0,10):"",positioning:r.positioning??"",pricing_strategy:r.pricing_strategy??"",pitch_notes:r.pitch_notes??"",competitors:r.competitors??""}),Array.isArray(r.launch_plan)&&r.launch_plan.length&&u(r.launch_plan))},[r]);const p=r!=null&&r.preview_token?`${window.location.origin}/commercial-pitch/${r.preview_token}`:null,f=async()=>{await i.mutateAsync({listingId:s.id,values:{...o,pitch_date:o.pitch_date||null,launch_plan:d.filter(y=>{var b;return(b=y.label)==null?void 0:b.trim()})}}),ne.success("Pitch saved")},g=async()=>{await l.mutateAsync({listingId:s.id,stage:"won"}),ne.success("Assignment won — welcome to Launch"),n(`/mission-control/listings/${s.id}/commercial`)},v=async()=>{await l.mutateAsync({listingId:s.id,stage:"lost",lostReason:h}),ne("Marked as lost opportunity"),n("/mission-control/listings")};return a?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-6 lg:col-span-2",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Owner & decision makers"}),e.jsx(En,{children:"Who actually signs the listing agreement."})]}),e.jsxs(Le,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Owner name"}),e.jsx(pe,{value:o.owner_name,onChange:y=>c({...o,owner_name:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Entity / company"}),e.jsx(pe,{value:o.owner_company,onChange:y=>c({...o,owner_company:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:o.owner_email,onChange:y=>c({...o,owner_email:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:o.owner_phone,onChange:y=>c({...o,owner_phone:y.target.value})})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Decision-maker intel"}),e.jsx(Ps,{rows:3,value:o.decision_maker_notes,onChange:y=>c({...o,decision_maker_notes:y.target.value}),placeholder:"Motivations, timing, partners, tax position, who influences the decision…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Pitch date"}),e.jsx(pe,{type:"date",value:o.pitch_date,onChange:y=>c({...o,pitch_date:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Competing brokers"}),e.jsx(pe,{value:o.competitors,onChange:y=>c({...o,competitors:y.target.value})})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Positioning & pricing strategy"}),e.jsx(En,{children:"The argument you're making for how this asset goes to market."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Proposed positioning"}),e.jsx(Ps,{rows:4,value:o.positioning,onChange:y=>c({...o,positioning:y.target.value}),placeholder:"Buyer profile, story, comparable trades, why this asset wins attention…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Pricing strategy"}),e.jsx(Ps,{rows:4,value:o.pricing_strategy,onChange:y=>c({...o,pricing_strategy:y.target.value}),placeholder:"Recommended ask, cap-rate rationale, call-for-offers timing…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Private pitch notes"}),e.jsx(Ps,{rows:3,value:o.pitch_notes,onChange:y=>c({...o,pitch_notes:y.target.value}),placeholder:"Never shown to the owner."})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Proposed launch plan"}),e.jsx(En,{children:"Shown on the owner-facing preview — this is what they buy."})]}),e.jsxs(Le,{className:"space-y-3",children:[d.map((y,b)=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:y.label,placeholder:"Milestone",onChange:w=>u(d.map((S,C)=>C===b?{...S,label:w.target.value}:S))}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>u(d.filter((w,S)=>S!==b)),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(Ps,{className:"mt-2",rows:2,value:y.detail??"",placeholder:"What happens in this step",onChange:w=>u(d.map((S,C)=>C===b?{...S,detail:w.target.value}:S))})]},b)),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>u([...d,{label:"",detail:""}]),children:[e.jsx(sn,{className:"mr-1.5 h-3.5 w-3.5"})," Add step"]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{className:"border-primary/30 bg-gradient-to-br from-primary/[0.06] to-transparent",children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Owner preview"}),e.jsx(En,{children:"A private, seller-facing page showing exactly what happens the day they hire you."})]}),e.jsx(Le,{className:"space-y-3",children:p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center gap-2 rounded-lg border bg-background px-3 py-2",children:e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:p})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>{navigator.clipboard.writeText(p),ne.success("Link copied")},children:[e.jsx(Sa,{className:"mr-1.5 h-3.5 w-3.5"})," Copy"]}),e.jsxs(z,{size:"sm",className:"flex-1",onClick:()=>window.open(p,"_blank"),children:[e.jsx(mr,{className:"mr-1.5 h-3.5 w-3.5"})," Open"]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the pitch to generate the private preview link."})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Outcome"})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{className:"w-full",children:[e.jsx(jl,{className:"mr-2 h-4 w-4"})," Won listing"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Convert this pitch into a Commercial Launch?"}),e.jsx(ql,{children:"Everything you've entered carries over. The listing moves into the Launch stage where you can publish the microsite, gate the OM and start tracking investor activity."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:g,children:"Yes — we won it"})]})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"w-full",children:[e.jsx(Bd,{className:"mr-2 h-4 w-4"})," Lost opportunity"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Mark as lost?"}),e.jsx(ql,{children:"Kept private in your archive so you can learn from it."})]}),e.jsx(pe,{placeholder:"Reason (optional)",value:h,onChange:y=>m(y.target.value)}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:v,children:"Mark lost"})]})]})]})]})]})]})]}),e.jsx("div",{className:"sticky bottom-4 flex justify-end",children:e.jsxs(z,{onClick:f,disabled:i.isPending,size:"lg",className:"shadow-lg",children:[i.isPending?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-2 h-4 w-4"}),"Save pitch"]})})]}):e.jsx(be,{children:e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Private pitch workspace"}),e.jsx(En,{children:"Only the listing agent can view or update pitch strategy and owner information."})]})})}function v$s({listingId:s}){const{data:t=[],isLoading:n}=iLe(s),r=fzt(),a=xzt(),i=U9s(),l=_.useRef(null),[o,c]=_.useState("om"),[d,u]=_.useState("email"),h=async p=>{if(p!=null&&p.length)try{for(const f of Array.from(p))await r.mutateAsync({listingId:s,file:f,docKind:o,gateLevel:d});ne.success("Document uploaded")}catch(f){ne.error(f.message||"Upload failed")}finally{l.current&&(l.current.value="")}},m=async p=>{try{window.open(await Pet(p),"_blank")}catch{ne.error("Could not open document")}};return e.jsx("div",{className:"space-y-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Deal room"}),e.jsx(En,{children:"Offering memorandum, financials and diligence files. Everything is stored privately and released through expiring secure links only."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Document type"}),e.jsxs(ls,{value:o,onValueChange:p=>c(p),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(pVe).map(([p,f])=>e.jsx(He,{value:p,children:f},p))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Access"}),e.jsxs(ls,{value:d,onValueChange:p=>u(p),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(kft).map(([p,f])=>e.jsx(He,{value:p,children:f},p))})]})]}),e.jsxs("div",{className:"flex items-end",children:[e.jsxs(z,{className:"w-full",onClick:()=>{var p;return(p=l.current)==null?void 0:p.click()},disabled:r.isPending,children:[r.isPending?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"mr-2 h-4 w-4"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",multiple:!0,className:"hidden",onChange:p=>h(p.target.files)})]})]}),n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-12 text-center",children:[e.jsx($r,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No documents yet. Upload the OM to activate gated requests."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:t.map(p=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg border bg-muted/40",children:e.jsx($r,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:p.title||p.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(p.file_size/1024/1024).toFixed(2)," MB · ",p.download_count??0," downloads"]})]}),e.jsx(ze,{variant:"secondary",children:pVe[p.doc_kind||"other"]}),e.jsxs(ls,{value:p.gate_level||"email",onValueChange:f=>i.mutate({id:p.id,listingId:s,values:{gate_level:f}}),children:[e.jsxs(rs,{className:"w-[190px]",children:[p.gate_level==="public"?e.jsx(Ga,{className:"mr-2 h-3.5 w-3.5"}):p.gate_level==="nda"?e.jsx(Ch,{className:"mr-2 h-3.5 w-3.5"}):e.jsx(Hl,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(cs,{})]}),e.jsx(as,{children:Object.entries(kft).map(([f,g])=>e.jsx(He,{value:f,children:g},f))})]}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>m(p.storage_path),children:"Preview"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>a.mutate({id:p.id,storage_path:p.storage_path,listingId:s}),children:e.jsx(Cn,{className:"h-4 w-4"})})]},p.id))})]})]})})}const b$s={om_request:"OM request",tour_request:"Tour request",investor_inquiry:"Investor inquiry",loi_intent:"LOI intent",inquiry:"Inquiry",showing_request:"Tour request",general:"Inquiry"};function _$s({listingId:s}){const{data:t=[],isLoading:n}=FJe(s),{data:r=[]}=RJe(s),a=_.useMemo(()=>{const o={};for(const c of r)c.lead_id&&(o[c.lead_id]=(o[c.lead_id]??0)+(Cft[c.event_type]??1));return o},[r]),i=_.useMemo(()=>[...t].map(o=>({...o,score:(a[o.id]??0)+(Cft[o.lead_type]??5)})).sort((o,c)=>c.score-o.score),[t,a]),l=i.filter(o=>o.score>=12);return n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[l.length>0&&e.jsxs(be,{className:"border-amber-500/30 bg-amber-500/[0.04]",children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"High-interest prospects"}),e.jsx(En,{children:"Ranked by document access, tour requests and repeat engagement."})]}),e.jsx(Le,{className:"grid gap-3 md:grid-cols-2",children:l.slice(0,6).map(o=>{const c=Aft(o.score);return e.jsxs("div",{className:"rounded-xl border bg-background 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("p",{className:"truncate font-medium",children:[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:o.company||fVe[o.investor_role||"other"]})]}),e.jsx(ze,{variant:"outline",className:c.tone,children:c.label})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(z,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs("a",{href:`mailto:${o.email}`,children:[e.jsx(on,{className:"mr-1.5 h-3.5 w-3.5"})," Email"]})}),o.phone&&e.jsx(z,{asChild:!0,size:"sm",variant:"ghost",children:e.jsxs("a",{href:`tel:${o.phone}`,children:[e.jsx(va,{className:"mr-1.5 h-3.5 w-3.5"})," Call"]})})]})]},o.id)})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Investors & inquiries"}),e.jsx(En,{children:"Every prospect is written into your LevelUp CRM automatically."})]}),e.jsx(Le,{children:i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(On,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No inquiries yet. Publish the microsite and start distribution."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:i.map(o=>{const c=Aft(o.score);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate text-sm font-medium",children:[[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email,o.company&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",o.company]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[o.email,o.phone?` · ${o.phone}`:""," · ",new Date(o.created_at).toLocaleDateString()]}),o.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:['"',o.message,'"']})]}),o.investor_role&&e.jsx(ze,{variant:"secondary",children:fVe[o.investor_role]??o.investor_role}),e.jsx(ze,{variant:"outline",children:b$s[o.lead_type]??o.lead_type}),e.jsx(ze,{variant:"outline",className:c.tone,children:c.label}),e.jsx(z,{asChild:!0,size:"sm",variant:"outline",children:e.jsx("a",{href:`mailto:${o.email}`,children:"Reply"})})]},o.id)})})})]})]})}const w$s={page_view:"Viewed the microsite",gallery_view:"Opened the gallery",om_request:"Requested the Offering Memorandum",om_download:"Downloaded the Offering Memorandum",doc_download:"Downloaded a document",tour_request:"Requested a tour",inquiry:"Submitted an inquiry",contact_click:"Clicked to contact the broker",share_click:"Opened a shared link",map_view:"Explored the location"};function j$s({listing:s}){const{data:t=[],isLoading:n}=RJe(s.id),{data:r=[]}=FJe(s.id),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(!1),u=async p=>{d(!0);try{const{data:f,error:g}=await U.functions.invoke("commercial-seller-report",{body:{action:p?"send":"generate",listingId:s.id,days:7,narrative:l||null,recipients:a.split(/[,\s]+/).map(v=>v.trim()).filter(Boolean)}});if(g)throw g;if(f!=null&&f.error)throw new Error(f.error);ne.success(p?"Activity report sent to your owner":"Weekly report generated")}catch(f){ne.error(f.message||"Could not build the report")}finally{d(!1)}},h=_.useMemo(()=>{const p=v=>{const y=Array.isArray(v)?v:[v];return t.filter(b=>y.includes(b.event_type)).length},f=new Set(t.map(v=>v.session_id).filter(Boolean)),g=new Map;return t.forEach(v=>v.session_id&&g.set(v.session_id,(g.get(v.session_id)??0)+1)),{views:p("page_view")||s.view_count||0,unique:f.size,repeat:[...g.values()].filter(v=>v>3).length,omRequests:p(["om_request","om_download"]),downloads:p(["doc_download","om_download"]),tours:p("tour_request"),inquiries:r.length,shares:s.share_count??0}},[t,r,s]),m=[{label:"Microsite views",value:h.views,icon:xa},{label:"Unique visitors",value:h.unique,icon:On},{label:"Repeat visitors",value:h.repeat,icon:pm},{label:"OM requests",value:h.omRequests,icon:RQ},{label:"Document downloads",value:h.downloads,icon:Ga},{label:"Tour requests",value:h.tours,icon:pm},{label:"Total inquiries",value:h.inquiries,icon:On},{label:"Shares",value:h.shares,icon:sd}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid gap-px overflow-hidden rounded-xl border bg-border sm:grid-cols-2 lg:grid-cols-4",children:m.map(p=>e.jsxs("div",{className:"bg-card px-5 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(p.icon,{className:"h-3.5 w-3.5"}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.16em]",children:p.label})]}),e.jsx("p",{className:"mt-1.5 text-2xl font-semibold tabular-nums",children:p.value})]},p.label))}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Send the weekly owner report"}),e.jsx(En,{children:"Last 7 days of activity, packaged as a branded report the owner can read in their inbox."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Owner email(s)"}),e.jsx(pe,{placeholder:"owner@example.com, asset.manager@example.com",value:a,onChange:p=>i(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Broker note (optional)"}),e.jsx(Ps,{rows:2,placeholder:"What you did this week and what happens next.",value:l,onChange:p=>o(p.target.value)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{onClick:()=>u(!0),disabled:c,children:[c?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(on,{className:"mr-2 h-4 w-4"}),"Send report"]}),e.jsx(z,{variant:"outline",onClick:()=>u(!1),disabled:c,children:"Save without sending"})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Owner activity report"}),e.jsx(En,{children:"Everything below is what your owner sees in the weekly activity report — proof the asset is being worked."})]}),e.jsx(Le,{children:n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(pm,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Activity appears here the moment the microsite goes live and prospects engage."})]}):e.jsx("div",{className:"space-y-1",children:t.slice(0,40).map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg px-3 py-2 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-primary/60"}),e.jsx("p",{className:"truncate text-sm",children:w$s[p.event_type]??p.event_type}),p.lead_id&&e.jsx(ze,{variant:"secondary",className:"shrink-0",children:"Identified"})]}),e.jsx("p",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(p.created_at).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]},p.id))})})]})]})}function N$s({listing:s,details:t,publicUrl:n}){var f,g;const r=zn(),[a,i]=_.useState(!1),l=s.photos??[],[o,c]=_.useState(0),d=(f=l[o])==null?void 0:f.photo_url,u=[...(t==null?void 0:t.investment_highlights)??[],...(t==null?void 0:t.property_highlights)??[]].filter(Boolean),h=(t==null?void 0:t.spaces)??[],m=(t==null?void 0:t.tenants)??[],p=s.agent;return e.jsxs($s,{title:"Commercial Listing",children:[e.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-6",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>r("/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsx("div",{className:"overflow-hidden rounded-2xl border bg-muted",children:d?e.jsx("img",{src:d,alt:vP(s,t),className:"h-[300px] w-full object-cover md:h-[440px]"}):e.jsxs("div",{className:"flex h-[240px] w-full items-center justify-center text-muted-foreground",children:[e.jsx(nc,{className:"mr-2 h-5 w-5"})," No photos yet"]})}),l.length>1&&e.jsx("div",{className:"mt-3 flex gap-2 overflow-x-auto pb-1",children:l.map((v,y)=>e.jsx("button",{onClick:()=>c(y),className:`h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${y===o?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:v.photo_url,alt:"",className:"h-full w-full object-cover"})},v.id??y))}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(oi,{className:"mr-1 h-3 w-3"})," Commercial"]}),(t==null?void 0:t.deal_type)&&e.jsx(ze,{variant:"secondary",children:GP[t.deal_type]}),(t==null?void 0:t.commercial_type)&&e.jsx(ze,{variant:"secondary",children:wL[t.commercial_type]}),(t==null?void 0:t.is_confidential)&&e.jsxs(ze,{variant:"outline",children:[e.jsx(Hl,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:vP(s,t)}),e.jsxs("p",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ha,{className:"h-4 w-4"})," ",nae(s,t)]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold",children:RH(t,s.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.is_public&&e.jsxs(z,{variant:"outline",onClick:()=>window.open(n,"_blank"),children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," View microsite"]}),s.allow_sharing&&e.jsxs(z,{onClick:()=>i(!0),children:[e.jsx(sd,{className:"mr-2 h-4 w-4"})," Share link"]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(oOt,{details:t})}),e.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-6 lg:col-span-2",children:[s.description&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"About this property"})}),e.jsx(Le,{className:"whitespace-pre-line text-sm text-muted-foreground",children:s.description})]}),u.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Highlights"})}),e.jsx(Le,{className:"space-y-2",children:u.map((v,y)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{children:v})]},y))})]}),h.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Available spaces"})}),e.jsx(Le,{className:"space-y-2 text-sm",children:h.map((v,y)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:v.suite||`Space ${y+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[OA(v.sf),v.rate,v.use,v.availability].filter(Boolean).join(" · ")})]},y))})]}),m.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Tenant roster"})}),e.jsx(Le,{className:"space-y-2 text-sm",children:m.map((v,y)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:v.name||`Tenant ${y+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[OA(v.sf),v.rent,v.lease_expiry].filter(Boolean).join(" · ")})]},y))})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Listing agent"})}),e.jsxs(Le,{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(p==null?void 0:p.name)||"LevelUp Member"}),((g=p==null?void 0:p.brokerage)==null?void 0:g.name)&&e.jsx("p",{className:"text-muted-foreground",children:p.brokerage.name})]}),(p==null?void 0:p.email)&&e.jsxs(z,{variant:"outline",className:"w-full",onClick:()=>window.open(`mailto:${p.email}`),children:[e.jsx(on,{className:"mr-2 h-4 w-4"})," Email agent"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the listing agent can update this listing."})]})]}),s.open_to_referrals&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Open to referrals"})}),e.jsx(Le,{className:"text-sm text-muted-foreground",children:"The listing agent welcomes buyer or tenant referrals on this opportunity."})]})]})]})]}),e.jsx(yLe,{open:a,onOpenChange:i,listingId:s.id,listingSlug:s.slug??null,listingTitle:vP(s,t),isCommercial:!0})]})}function k$s(){const{listingId:s=""}=Mi(),t=zn(),{user:n}=hs(),[r,a]=Gl(),{data:i,isLoading:l}=dae(s),{data:o}=sOt(s),{data:c=[]}=iLe(s),{data:d=[]}=RJe(s),{data:u=[]}=FJe(s),h=nOt(),m=aOt(),p=PMs(),f=czt(),g=dzt(),v=uzt(),y=hzt(),[b,w]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,F]=_.useState(!1),q=r.get("tab")||"overview",G=te=>a({tab:te},{replace:!0}),V=i?`${window.location.origin}/public/listing/${i.slug||i.id}`:"",H=_.useMemo(()=>{var te;return EMs(o,{photoCount:((te=i==null?void 0:i.photos)==null?void 0:te.length)??0,hasOm:c.some(ce=>ce.doc_kind==="om"),isPublic:!!(i!=null&&i.is_public)})},[o,i,c]),K=async te=>{var ce;if(!(!te||!i)){w(!0);try{for(const ve of Array.from(te)){const me=ve.name.split(".").pop(),he=`${n==null?void 0:n.id}/${i.id}/${Date.now()}-${Math.random().toString(36).slice(2)}.${me}`,{error:ge}=await U.storage.from("listing-photos").upload(he,ve);if(ge)throw ge;const{data:{publicUrl:Ee}}=U.storage.from("listing-photos").getPublicUrl(he);await f.mutateAsync({listingId:i.id,photoUrl:Ee,isPrimary:!((ce=i.photos)!=null&&ce.length)})}ne.success("Photos uploaded")}catch(ve){ne.error(ve.message||"Upload failed")}finally{w(!1)}}};if(l)return e.jsx($s,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!i)return e.jsx($s,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"Listing not found"})});const Z=i.lifecycle_stage==="pitch",oe=i.lifecycle_stage??"won",re=ROe.findIndex(te=>te.key===oe),ae=vP(i,o),J=!!(n!=null&&n.id)&&i.agent_id===n.id;return J?e.jsx($s,{title:"Commercial Launch",children:e.jsxs("div",{className:"bg-background",children:[e.jsx("div",{className:"border-b bg-gradient-to-b from-muted/40 to-background",children:e.jsxs("div",{className:"mx-auto max-w-7xl px-4 py-6",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>t("/mission-control/listings"),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(oi,{className:"mr-1 h-3 w-3"})," Commercial Launch"]}),(o==null?void 0:o.deal_type)&&e.jsx(ze,{variant:"secondary",children:GP[o.deal_type]}),(o==null?void 0:o.commercial_type)&&e.jsx(ze,{variant:"secondary",children:wL[o.commercial_type]}),Z&&e.jsxs(ze,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:[e.jsx(bu,{className:"mr-1 h-3 w-3"})," Pitch — private"]}),(o==null?void 0:o.is_confidential)&&e.jsxs(ze,{variant:"outline",children:[e.jsx(Hl,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:ae}),e.jsx("p",{className:"text-muted-foreground",children:nae(i,o)}),e.jsx("p",{className:"mt-2 text-xl font-semibold",children:RH(o,i.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!J&&e.jsxs(ze,{variant:"outline",className:"self-center",children:[e.jsx(Hl,{className:"mr-1 h-3 w-3"})," View only — listing agent controls updates"]}),J&&e.jsxs(z,{variant:"outline",onClick:()=>t(`/mission-control/listings/${i.id}/commercial/edit`),children:[e.jsx(Wa,{className:"mr-2 h-4 w-4"})," Edit details"]}),J&&!Z&&!i.is_public&&e.jsxs(z,{onClick:()=>{p.mutate({listingId:i.id,values:{is_public:!0,allow_sharing:!0,status:"active"}}),oe==="won"&&m.mutate({listingId:i.id,stage:"launched"})},children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," Publish & go live"]}),!Z&&i.is_public&&e.jsxs(z,{variant:"outline",onClick:()=>window.open(V,"_blank"),children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," View microsite"]})]})]}),!Z&&e.jsx("div",{className:"mt-6 flex flex-wrap items-center gap-2",children:ROe.filter(te=>te.key!=="pitch").map((te,ce)=>{const ve=ROe.findIndex(ge=>ge.key===te.key),me=ve===re,he=veJ&&m.mutate({listingId:i.id,stage:te.key}),className:`flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-colors ${me?"border-primary bg-primary text-primary-foreground":he?"border-primary/30 bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"} ${J?"":"cursor-default"}`,children:[he&&e.jsx(Wr,{className:"h-3 w-3"})," ",te.label,ce<4&&e.jsx("span",{className:"ml-1 opacity-40",children:"›"})]},te.key)})})]})}),e.jsx("div",{className:"mx-auto max-w-7xl px-4 py-8",children:Z?e.jsx(y$s,{listing:i,canEdit:J}):e.jsxs(Qr,{value:J||["overview","marketing"].includes(q)?q:"overview",onValueChange:G,children:[e.jsxs(Jr,{className:"mb-6 flex w-full flex-wrap justify-start",children:[e.jsx(Wt,{value:"overview",children:"Overview"}),e.jsx(Wt,{value:"marketing",children:"Marketing"}),J&&e.jsx(Wt,{value:"investors",children:"Investors & Leads"}),J&&e.jsx(Wt,{value:"reporting",children:"Reporting"}),J&&e.jsx(Wt,{value:"documents",children:"Documents"}),J&&e.jsx(Wt,{value:"settings",children:"Settings"})]}),e.jsxs(Kt,{value:"overview",className:"space-y-6",children:[e.jsx(oOt,{details:o}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs(be,{className:"lg:col-span-2",children:[e.jsxs(_t,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:"Launch readiness"}),e.jsx(En,{children:"Everything an institutional-quality launch needs."})]}),e.jsxs("span",{className:"text-2xl font-semibold tabular-nums",children:[H.score,"%"]})]}),e.jsx(Di,{value:H.score,className:"mt-3"})]}),e.jsx(Le,{className:"space-y-2",children:I4e.map(te=>{const ce=H.done.includes(te.key);return e.jsxs("button",{disabled:!J,onClick:()=>J&&h.mutate({listingId:i.id,values:{launch_checklist:{...(o==null?void 0:o.launch_checklist)??{},[te.key]:!ce}}}),className:"flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-muted/60",children:[e.jsx("span",{className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${ce?"border-primary bg-primary text-primary-foreground":""}`,children:ce&&e.jsx(Wr,{className:"h-3 w-3"})}),e.jsxs("span",{children:[e.jsx("span",{className:`block text-sm font-medium ${ce?"text-muted-foreground line-through":""}`,children:te.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:te.detail})]})]},te.key)})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Quick actions"})}),e.jsxs(Le,{className:"grid gap-2",children:[e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>C(!0),children:[e.jsx(sd,{className:"mr-2 h-4 w-4"})," Share link"]}),e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>P(!0),children:[e.jsx(lf,{className:"mr-2 h-4 w-4"})," Signage QR code"]}),J&&e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>I(!0),children:[e.jsx(on,{className:"mr-2 h-4 w-4"})," Email brokers & investors"]}),J&&e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>F(!0),children:[e.jsx(un,{className:"mr-2 h-4 w-4"})," Generate social post"]}),J&&e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>G("documents"),children:[e.jsx(Hl,{className:"mr-2 h-4 w-4"})," Manage gated OM"]})]})]}),(o==null?void 0:o.call_for_offers_at)&&e.jsxs(be,{className:"border-amber-500/30 bg-amber-500/[0.05]",children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm",children:"Call for offers"})}),e.jsx(Le,{children:e.jsxs("p",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Ud,{className:"h-4 w-4"}),new Date(o.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Recent engagement"})}),e.jsxs(Le,{className:"space-y-2",children:[d.slice(0,6).map(te=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate capitalize",children:te.event_type.replace(/_/g," ")}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(te.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]},te.id)),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),e.jsxs("p",{className:"pt-2 text-xs text-muted-foreground",children:[u.length," inquiries captured"]})]})]})]})]})]}),e.jsxs(Kt,{value:"marketing",className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Photography"}),e.jsx(En,{children:"The first image becomes the cinematic microsite hero."})]}),e.jsx(Le,{children:J?e.jsx(Bzt,{photos:i.photos??[],uploading:b,onUpload:K,onRemove:te=>g.mutate({photoId:te,listingId:i.id}),onReorder:te=>v.mutate({photos:te.map(ce=>({id:ce.id,sort_order:ce.sort_order,is_primary:ce.is_primary}))}),onSetPrimary:te=>y.mutate({photoId:te,listingId:i.id})}):e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[(i.photos??[]).map(te=>e.jsx("img",{src:te.photo_url,alt:ae,className:"aspect-[4/3] w-full rounded-lg object-cover",loading:"lazy"},te.id)),!(i.photos??[]).length&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No photos yet."})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[{icon:Wo,title:"Property microsite",body:"Institutional-grade public page with gated OM.",action:()=>window.open(V,"_blank"),cta:"Preview"},{icon:lf,title:"Signage QR",body:"On-site sign that routes to the microsite.",action:()=>P(!0),cta:"Create"},...J?[{icon:on,title:"Broker & investor email",body:"Send to targeted segments of your database.",action:()=>I(!0),cta:"Compose"},{icon:un,title:"Social & LinkedIn",body:"Branded launch graphics and copy.",action:()=>F(!0),cta:"Generate"}]:[]].map(te=>e.jsxs(be,{className:"flex flex-col",children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx(te.icon,{className:"mb-2 h-5 w-5"}),e.jsx(Nt,{className:"text-sm",children:te.title}),e.jsx(En,{className:"text-xs",children:te.body})]}),e.jsx(Le,{className:"mt-auto",children:e.jsx(z,{size:"sm",variant:"outline",className:"w-full",onClick:te.action,children:te.cta})})]},te.title))})]}),J&&e.jsx(Kt,{value:"investors",children:e.jsx(_$s,{listingId:i.id})}),J&&e.jsx(Kt,{value:"reporting",children:e.jsx(j$s,{listing:i})}),J&&e.jsx(Kt,{value:"documents",children:e.jsx(v$s,{listingId:i.id})}),J&&e.jsx(Kt,{value:"settings",className:"space-y-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Visibility"}),e.jsx(En,{children:"Control who can see this offering."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Publish public microsite"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Makes the commercial microsite live at a shareable URL."})]}),e.jsx(mn,{checked:!!i.is_public,onCheckedChange:te=>{p.mutate({listingId:i.id,values:{is_public:te,allow_sharing:te?!0:i.allow_sharing}}),te&&oe==="won"&&m.mutate({listingId:i.id,stage:"launched"})}})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share inside my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage on the Exchange."})]}),e.jsx(mn,{checked:!!i.share_with_brokerage,onCheckedChange:te=>p.mutate({listingId:i.id,values:{share_with_brokerage:te}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser mode, address hidden, search engines blocked."})]}),e.jsx(mn,{checked:!!(o!=null&&o.is_confidential),onCheckedChange:te=>h.mutate({listingId:i.id,values:{is_confidential:te}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(mn,{checked:!!(o!=null&&o.hide_address),onCheckedChange:te=>h.mutate({listingId:i.id,values:{hide_address:te}})})]}),V&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-muted/40 px-3 py-2",children:[e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:V}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText(V),ne.success("Copied")},children:e.jsx(Sa,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),e.jsx(yLe,{open:S,onOpenChange:C,listingId:i.id,listingSlug:i.slug,listingTitle:ae,isCommercial:!0}),e.jsx(Jzt,{open:E,onOpenChange:P,url:V,title:ae,fileBase:i.slug||i.id}),e.jsx(dBt,{open:M,onOpenChange:I,listing:i}),e.jsx($et,{open:D,onOpenChange:F,listingId:i.id})]})}):Z?e.jsx($s,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"This opportunity is private to the listing agent."})}):e.jsx(N$s,{listing:i,details:o,publicUrl:V})}function S$s(){var m,p,f;const{token:s=""}=Mi(),{data:t,isLoading:n,error:r}=rt({queryKey:["commercial-pitch-preview",s],queryFn:async()=>{const{data:g,error:v}=await U.functions.invoke("commercial-pitch-preview",{body:{token:s}});if(v)throw v;if(g!=null&&g.error)throw new Error(g.error);return g},enabled:!!s});if(n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!(t!=null&&t.listing))return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This preview link is no longer active."});const{listing:a,details:i,pitch:l}=t,o=a.agent,c=(p=(m=a.photos)==null?void 0:m[0])==null?void 0:p.photo_url,d=OJe(i).slice(0,4),u=l.launch_plan??[],h=[{icon:Wo,label:"Dedicated property microsite",detail:"An institutional-grade page built for this asset alone."},{icon:$r,label:"Offering Memorandum & teaser",detail:"Gated, tracked and released only to qualified prospects."},{icon:on,label:"Targeted broker & investor email",detail:"Direct outreach to buyers, brokers and 1031 capital."},{icon:lf,label:"Signage, QR & social distribution",detail:"On-site and digital presence working together."},{icon:wl,label:"Weekly owner activity reporting",detail:"Views, OM requests, downloads, tours and prospect interest."},{icon:Ch,label:"Confidentiality controls",detail:"Address, financials and documents released on your terms."}];return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(dl,{children:[e.jsxs("title",{children:["Marketing proposal — ",vP(a,i)]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow"})]}),e.jsxs("section",{className:"relative min-h-[70vh] overflow-hidden",children:[c?e.jsx("img",{src:c,alt:"",className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/70 to-[#0b0f14]/40"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[70vh] max-w-6xl flex-col justify-end px-6 pb-14 pt-24 md:px-10",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:["Private marketing proposal",l.owner_name?` prepared for ${l.owner_name}`:""]}),e.jsx("h1",{className:"mt-4 max-w-3xl font-serif text-4xl leading-[1.05] md:text-6xl",children:vP(a,i)}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/55",children:[e.jsx(Ha,{className:"h-4 w-4"})," ",nae(a,i)]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:GP[(i==null?void 0:i.deal_type)??"sale"]}),(i==null?void 0:i.commercial_type)&&e.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:wL[i.commercial_type]})]})]})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-2 gap-px border-y border-white/10 bg-white/10 md:grid-cols-4",children:d.map(g=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:g.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums",children:g.value})]},g.label))}),(l.positioning||l.pricing_strategy)&&e.jsxs("section",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Recommendation"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"How we take this asset to market"}),e.jsxs("div",{className:"mt-10 grid gap-10 md:grid-cols-2",children:[l.positioning&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.16em] text-white/50",children:"Positioning"}),e.jsx("p",{className:"mt-4 whitespace-pre-line text-lg leading-relaxed text-white/75",children:l.positioning})]}),l.pricing_strategy&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.16em] text-white/50",children:"Pricing strategy"}),e.jsx("p",{className:"mt-4 whitespace-pre-line text-lg leading-relaxed text-white/75",children:l.pricing_strategy}),e.jsx("p",{className:"mt-6 text-2xl font-semibold",children:RH(i,a.price)})]})]})]}),u.length>0&&e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"The plan"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"What happens the day you hire us"}),e.jsx("div",{className:"mt-12 space-y-8",children:u.map((g,v)=>e.jsxs("div",{className:"flex gap-6 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(v+1).padStart(2,"0")}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-medium",children:g.label}),g.detail&&e.jsx("p",{className:"mt-1.5 text-white/60",children:g.detail})]})]},v))})]})}),e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Distribution"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"Where your property shows up"}),e.jsx("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:h.map(g=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx(g.icon,{className:"mb-4 h-5 w-5 text-white/70"}),e.jsx("p",{className:"font-medium",children:g.label}),e.jsx("p",{className:"mt-1.5 text-sm text-white/55",children:g.detail})]},g.label))})]})}),o&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col items-start gap-6 px-6 py-16 md:flex-row md:items-center md:justify-between md:px-10",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[o.avatar_url&&e.jsx("img",{src:o.avatar_url,alt:o.name,className:"h-20 w-20 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Prepared by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:o.name}),e.jsx("p",{className:"text-sm text-white/55",children:((f=o.brokerage)==null?void 0:f.name)||o.brokerage_name})]})]}),e.jsxs("div",{className:"flex gap-3 text-sm text-white/70",children:[o.email&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`mailto:${o.email}`,children:"Email"}),o.phone&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`tel:${o.phone}`,children:"Call"})]})]})}),e.jsx("footer",{className:"py-10 text-center text-xs text-white/35",children:"Confidential — prepared exclusively for the property owner."})]})}const C$s={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},A$s=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function E$s(){var te;const[s]=Gl(),t=s.get("r"),n=s.get("m"),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!0),[d,u]=_.useState(0),[h,m]=_.useState(!1),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState("tour"),[P,M]=_.useState(!1),[I,D]=_.useState(!1),F=async()=>{if(!p.trim()||!g.trim()){ne.error("Please enter your name and email");return}M(!0);try{const ve=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:p.trim(),email:g.trim(),phone:y.trim()||null,message:w.trim()||null,intent:C})}),me=await ve.json();if(!ve.ok||!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Could not send");D(!0),ne.success("Sent! The agent will be in touch shortly.")}catch(ce){ne.error((ce==null?void 0:ce.message)||"Could not send")}finally{M(!1)}};if(_.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const ce=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(ce).then(ve=>ve.json()).then(ve=>{ve.error?l("This private listing link is no longer valid."):a({listing:ve.listing,agent:ve.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(dl,{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(Hl,{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:q,agent:G}=r,V=(te=q.photos)!=null&&te.length?q.photos:[],H=V[0],K=C$s[q.status]||q.status,Z=(G==null?void 0:G.sender_name)||(G==null?void 0:G.name)||"Your Agent",oe=(G==null?void 0:G.sender_email)||null,re=encodeURIComponent(`Interested in ${q.address}`),ae=encodeURIComponent(`Hi ${Z}, I'd love to learn more about ${q.address}, ${q.city}. Thanks!`),J=G!=null&&G.booking_slug?`https://dashboard.relevelup.com/book/${G.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(dl,{children:[e.jsxs("title",{children:["Private Listing · ",q.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(Hl,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",Z]})]}),e.jsxs("div",{className:"relative",children:[H?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:H,alt:q.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:K})}),V.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:[V.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(be,{className:"shadow-xl border-slate-200",children:e.jsxs(Le,{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:q.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(Ha,{className:"h-4 w-4"}),q.city,", ",q.state," ",q.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:A$s(q.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[q.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(mj,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,q.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(Ey,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,q.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(jb,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),q.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:q.description})]}),V.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:V.slice(0,9).map((ce,ve)=>e.jsx("button",{type:"button",onClick:()=>{u(ve),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:ce,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},ve))})]})]})}),e.jsxs(be,{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:[Z," will get back to you personally."]})]}),e.jsx(Le,{className:"p-6 sm:p-8",children:I?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Mr,{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:[Z," 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(ce=>e.jsx("button",{type:"button",onClick:()=>E(ce.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${C===ce.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:ce.label},ce.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(pe,{id:"pl-name",value:p,onChange:ce=>f(ce.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-email",children:"Email *"}),e.jsx(pe,{id:"pl-email",type:"email",value:g,onChange:ce=>v(ce.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(pe,{id:"pl-phone",value:y,onChange:ce=>b(ce.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ps,{id:"pl-msg",value:w,onChange:ce=>S(ce.target.value),placeholder:`I'd love to see ${q.address}…`,rows:4,maxLength:2e3})]}),e.jsx(z,{onClick:F,disabled:P,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:P?"Sending…":"Send to "+Z.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(be,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Le,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[G!=null&&G.avatar_url?e.jsx("img",{src:G.avatar_url,alt:Z,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:Z.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:Z}),(G==null?void 0:G.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:G.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[oe&&e.jsx(z,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${oe}?subject=${re}&body=${ae}`,children:[e.jsx(on,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(G==null?void 0:G.phone)&&e.jsx(z,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${G.phone}`,children:[e.jsx(va,{className:"h-4 w-4 mr-1.5"}),G.phone]})}),J&&e.jsx(z,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:J,target:"_blank",rel:"noreferrer",children:[e.jsx(Ud,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&V.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",children:[e.jsx("button",{className:"absolute top-4 right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>m(!1),"aria-label":"Close",children:e.jsx(er,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(ce=>(ce-1+V.length)%V.length),"aria-label":"Previous",children:e.jsx(Wc,{className:"h-8 w-8"})}),e.jsx("img",{src:V[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(ce=>(ce+1)%V.length),"aria-label":"Next",children:e.jsx(yi,{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," / ",V.length]})]})]})]})}function T$s(){var i;const{slug:s}=Mi(),{data:t,isLoading:n,error:r}=uOt(s);if(_.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),_.useEffect(()=>{t!=null&&t.id&&zd(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(ln,{className:"h-28 w-28 rounded-full"}),e.jsx(ln,{className:"h-6 w-48"}),e.jsx(ln,{className:"h-4 w-36"})]}),e.jsx(ln,{className:"h-12 w-full"}),e.jsx(ln,{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(dl,{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(BJe,{card:t})]})}const M$s="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",P$s="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",L$s="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",I$s="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",D$s="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",R$s="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",K4e={"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:R$s},"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:M$s},"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:P$s},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:L$s},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:I$s},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:D$s}},F$s=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function uBt(s){return s&&s in K4e?K4e[s]:K4e["minimal-mono"]}function O$s(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 hBt({slugOverride:s}={}){var Sn;const{slug:t}=Mi(),n=s||t,[r]=Gl(),a=r.get("t"),[i,l]=_.useState(!0),[o,c]=_.useState(null),[d,u]=_.useState(null),h=_.useRef(null),m=_.useRef(null),[p,f]=_.useState(null),[g,v]=_.useState(null),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=_.useState(0),[P,M]=_.useState(!1),[I,D]=_.useState(""),[F,q]=_.useState(""),[G,V]=_.useState(""),[H,K]=_.useState(""),[Z,oe]=_.useState(""),[re,ae]=_.useState(""),[J,te]=_.useState(""),[ce,ve]=_.useState(""),[me,he]=_.useState(""),[ge,Ee]=_.useState(""),[Ne,Pe]=_.useState(""),[Oe,ke]=_.useState(""),[Ve,_e]=_.useState(""),[Ae,Se]=_.useState([]),[We,qe]=_.useState([]),[Be,Ze]=_.useState(""),[$e,Xe]=_.useState(""),[nt,Ge]=_.useState(""),[Je,ut]=_.useState([]);_.useEffect(()=>{lt()},[n,a]);const lt=async()=>{if(!n)return;l(!0);const{data:bn,error:cr}=await U.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(cr||!bn){M(!0),l(!1);return}u(bn),m.current=bn;const{data:Fs}=await U.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",bn.user_id).single();if(Fs){let cn;if(Fs.brokerage_id){const{data:Yn}=await U.from("brokerages").select("name").eq("id",Fs.brokerage_id).single();cn=(Yn==null?void 0:Yn.name)||void 0}let lr=Fs.avatar_url||null;if(!lr){const{data:Yn}=U.storage.from("avatars").getPublicUrl(`${bn.user_id}/avatar.jpg`);Yn!=null&&Yn.publicUrl&&(lr=`${Yn.publicUrl}?t=${Date.now()}`)}const Tn={...Fs,avatar_url:lr,brokerage_name:cn};c(Tn),h.current=Tn}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",bn.id);const{data:cn,error:lr}=await U.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:bn.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:cn,resolveErr:lr}),!lr&&(cn!=null&&cn.contact_id)){v(cn.contact_id);const Tn=cn.contact;Tn&&(f(Tn),D(Tn.first_name||""),q(Tn.last_name||""),V(Tn.email||""),K(Tn.phone||""),oe(Tn.address||""),ae(Tn.city||""),te(Tn.state||""),ve(Tn.zip||""),he(Tn.birthday||""),Ee(Tn.home_anniversary||""))}}catch(cn){console.error("Failed to resolve token:",cn)}l(!1)},qt=async()=>{var bn,cr;if(!I.trim()){ne.error("Please enter your first name");return}if(!n){ne.error("Invalid page. Please refresh.");return}S(!0);try{let Fs=(bn=m.current)==null?void 0:bn.id,cn=(cr=m.current)==null?void 0:cr.user_id;if(!Fs||!cn){const{data:Yn}=await U.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Yn){ne.error("This page is no longer active. Please contact the agent directly."),S(!1);return}Fs=Yn.id,cn=Yn.user_id}const lr={intake_page_id:Fs,agent_user_id:cn,existing_contact_id:g,first_name:I.trim(),last_name:F.trim()||null,email:G.trim()||null,phone:H.trim()||null,address:Z.trim()||null,city:re.trim()||null,state:J.trim()||null,zip:ce.trim()||null,birthday:me||null,home_anniversary:ge||null,real_estate_interest:Ne||null,message:Oe.trim()||null,life_events:{spouse_name:Ve.trim()||null,kids:Ae.filter(Yn=>Yn.name.trim()),pets:We.filter(Yn=>Yn.name.trim()),favorite_spots:Be.trim()||null,dream_neighborhood:$e.trim()||null,wedding_anniversary:nt||null},referrals:Je.filter(Yn=>Yn.name.trim()&&Yn.contact.trim())},{error:Tn}=await U.from("contact_intake_submissions").insert(lr);if(console.log("[ConnectPage] Insert result:",{error:Tn}),Tn)throw Tn;a&&await U.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Yn=[I.trim(),F.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:cn,contactName:Yn,contactEmail:G.trim()||null,contactPhone:H.trim()||null,slug:n})})}catch(Yn){console.warn("Connect page notification failed (non-blocking):",Yn)}b(!0)}catch(Fs){console.error(Fs),ne.error("Something went wrong. Please try again.")}finally{S(!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(bt,{className:"h-8 w-8 animate-spin text-slate-400"})});if(P)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(y)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(dl,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Ar.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(Ar.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(Mr,{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(Fo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const zt=!!a&&!!p,Zt=(d==null?void 0:d.show_little_things)??!0,ms=[{title:zt?"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:I,onChange:bn=>D(bn.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:F,onChange:bn=>q(bn.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:G,onChange:bn=>V(bn.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:H,onChange:bn=>K(bn.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:Z,onChange:bn=>oe(bn.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:re,onChange:bn=>ae(bn.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:J,onChange:bn=>te(bn.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:ce,onChange:bn=>ve(bn.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:me,onChange:bn=>he(bn.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:ge,onChange:bn=>Ee(bn.target.value),className:"connect-input"})]})]})]})},...Zt?[{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:Ve,onChange:bn=>_e(bn.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:nt,onChange:bn=>Ge(bn.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>Se(bn=>[...bn,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(sn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ae.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ae.map((bn,cr)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:bn.name,onChange:Fs=>Se(cn=>cn.map((lr,Tn)=>Tn===cr?{...lr,name:Fs.target.value}:lr)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:bn.age,onChange:Fs=>Se(cn=>cn.map((lr,Tn)=>Tn===cr?{...lr,age:Fs.target.value}:lr)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Se(Fs=>Fs.filter((cn,lr)=>lr!==cr)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(er,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},cr))]})]}),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:()=>qe(bn=>[...bn,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(sn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[We.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),We.map((bn,cr)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:bn.name,onChange:Fs=>qe(cn=>cn.map((lr,Tn)=>Tn===cr?{...lr,name:Fs.target.value}:lr)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:bn.kind,onChange:Fs=>qe(cn=>cn.map((lr,Tn)=>Tn===cr?{...lr,kind:Fs.target.value}:lr)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>qe(Fs=>Fs.filter((cn,lr)=>lr!==cr)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(er,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},cr))]})]}),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:Be,onChange:bn=>Ze(bn.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:$e,onChange:bn=>Xe(bn.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."})]}),Je.length<3&&e.jsxs("button",{type:"button",onClick:()=>ut(bn=>[...bn,{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(sn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:Je.map((bn,cr)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:bn.name,onChange:Fs=>ut(cn=>cn.map((lr,Tn)=>Tn===cr?{...lr,name:Fs.target.value}:lr)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:bn.contact,onChange:Fs=>ut(cn=>cn.map((lr,Tn)=>Tn===cr?{...lr,contact:Fs.target.value}:lr)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>ut(Fs=>Fs.filter((cn,lr)=>lr!==cr)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(er,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},cr))})]})]})}]:[],{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(bn=>e.jsxs("button",{type:"button",onClick:()=>Pe(Ne===bn.value?"":bn.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ne===bn.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:bn.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:bn.desc})]},bn.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:Oe,onChange:bn=>ke(bn.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Dt=ms.length,It=uBt(d==null?void 0:d.theme),qs=O$s(It,(d==null?void 0:d.accent_color)||null),wt=(d==null?void 0:d.cover_image_url)||It.defaultCover,Us=(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)||""),kn=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:qs,children:[e.jsxs(dl,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Us} — ${(o==null?void 0:o.name)||"your agent"}`}),wt&&e.jsx("meta",{property:"og:image",content:wt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Us}),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(Ar.img,{src:wt,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(Ar.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:It.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Us}),Es&&e.jsx(Ar.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(Ar.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:It.accent,color:It.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Sn=o==null?void 0:o.name)==null?void 0:Sn.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(va,{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(on,{className:"h-4 w-4"})})]})]}),e.jsx(Ar.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((bn,cr)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:cr<=C?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},cr))}),e.jsxs(Ar.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:kn?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(bW,{mode:"wait",children:e.jsxs(Ar.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:ms[C].title})]}),ms[C].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:ms[C].subtitle})]}),ms[C].fields]},C)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[C>0?e.jsx("button",{type:"button",onClick:()=>E(bn=>bn-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",{}),C{if(C===0&&!I.trim()){ne.error("Please enter your first name");return}E(bn=>bn+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:w,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:w?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),C>0&&CE(bn=>bn+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(Fo,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const CW=()=>({trackEngagement:_.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await U.auth.getUser();if(!i)return;await U.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function QY({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=_.useState(0),[i,l]=_.useState(!1),{trackEngagement:o}=CW(),c=_.useCallback(p=>{o("newsletter",p.id,p.title,"click_link")},[o]),d=_.useCallback(()=>{a(p=>(p+1)%s.length)},[s.length]),u=_.useCallback(()=>{a(p=>(p-1+s.length)%s.length)},[s.length]),h=_.useCallback(p=>{a(p)},[]);if(_.useEffect(()=>{if(s.length<=1||i)return;const p=setInterval(d,t);return()=>clearInterval(p)},[s.length,i,t,d]),!s||s.length===0)return null;const m=s[r];return e.jsxs("div",{className:Ct("relative w-full overflow-hidden rounded-xl",n),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"icon",className:Ct("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(Wc,{className:"h-6 w-6"})}),e.jsx(z,{variant:"ghost",size:"icon",className:Ct("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(yi,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((p,f)=>e.jsx("button",{onClick:()=>h(f),className:Ct("w-2 h-2 rounded-full transition-all duration-300",f===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${f+1}`},f))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx(z,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:m.link_text||"Learn More"})})]})]})}const z$s=["reserved","scheduled_for_charge","paid","payment_failed","completed"],UH=s=>!!s&&(s.access_override||z$s.includes(s.status)),Df=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),_te=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`},JVe=(s,t="usd",n)=>`One-time payment: ${Df(s,t)} for the ${_te(n)}`,Uet=[{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}],wte=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:[]}},B$s=(s,t)=>!s.hidden.includes(t),Qgt=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),yu=(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,kLe=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&&rrt({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await U.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),qet=s=>rt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),pBt=s=>rt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await U.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),Vet=()=>{const{user:s}=hs();return rt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await U.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},Het=s=>{const{data:t=[],...n}=Vet();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},$$s=()=>{const{user:s}=hs(),t=$t();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.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=>ne.error(n.message||"Could not save your answers")})},fBt=s=>{const{user:t}=hs();return rt({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await U.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},U$s=()=>{const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},q$s=(s,t)=>{const{user:n}=hs(),r=t||(n==null?void 0:n.id);return rt({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,p,f,g]=await Promise.all([U.from("program_weeks").select("*").eq("program_id",s).order("week_number"),U.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),U.from("program_resources").select("*").eq("program_id",s).order("sort_order"),U.from("program_events").select("*").eq("program_id",s).order("starts_at"),U.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),U.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),U.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),U.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),U.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),U.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),U.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",a).order("sort_order")]);return{weeks:i.data||[],lessons:l.data||[],resources:o.data||[],myResources:g.data||[],events:c.data||[],announcements:d.data||[],completions:u.data||[],progress:h.data||[],videoLogs:m.data||[],badges:p.data||[],analysis:f.data||null}}})},V$s=s=>{const{user:t}=hs(),n=$t();return mt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await U.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 U.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=>ne.error(r.message||"Could not update progress")})},H$s=s=>{const{user:t}=hs(),n=$t();return mt({mutationFn:async r=>{const{error:a}=await U.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ne.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ne.error(r.message||"Could not log the video")})},G$s=s=>{const{user:t}=hs(),n=$t();return mt({mutationFn:async r=>{const{error:a}=await U.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:()=>{ne.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ne.error(r.message||"Could not save your check-in")})},W$s=s=>{const{user:t}=hs(),n=$t();return mt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await U.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=>ne.error(r.message||"Could not update your RSVP")})},K$s=s=>rt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),Y$s=s=>{const t=$t();return mt({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 U.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ne.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ne.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},Z$s=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ne.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ne.error(t.message||"Could not delete the code")})},X$s=()=>mt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await U.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}}),Q$s=()=>mt({mutationFn:async s=>{const{error:t}=await U.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),J$s=s=>rt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),eUs=s=>{const t=$t();return mt({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 U.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ne.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ne.error(n.message||"Could not save the session")})},tUs=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ne.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the session")})},sUs=s=>rt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([U.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),U.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||[]}}}),nUs=s=>{const t=$t();return mt({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 U.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ne.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ne.error(n.message||"Could not save the video")})},rUs=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ne.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the video")})},xBt=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},OJ=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),gBt=[{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"}],AW="event-images",gae=s=>{if(s.file_path){const{data:t}=U.storage.from(AW).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},zJ=async(s,t="open")=>{if(!s.file_path){const c=s.url;c&&window.open(c,"_blank","noopener,noreferrer");return}const{data:n,error:r}=await U.storage.from(AW).download(s.file_path);if(r||!n){const c=gae(s);c&&window.open(c,"_blank","noopener,noreferrer");return}const a=s.file_path.split("/").pop()||s.title||"resource",i=a.toLowerCase().endsWith(".pdf")||n.type==="application/pdf",l=i?new Blob([n],{type:"application/pdf"}):n,o=URL.createObjectURL(l);if(t==="open"&&i){if(!window.open(o,"_blank","noopener,noreferrer")){const d=document.createElement("a");d.href=o,d.download=a,d.click()}}else{const c=document.createElement("a");c.href=o,c.download=a,document.body.appendChild(c),c.click(),c.remove()}setTimeout(()=>URL.revokeObjectURL(o),6e4)},yBt=s=>rt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),aUs=s=>{const t=$t();return mt({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 U.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ne.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ne.error(n.message||"Could not save the resource")})},iUs=()=>{const s=$t();return mt({mutationFn:async t=>{t.file_path&&await U.storage.from(AW).remove([t.file_path]);const{error:n}=await U.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ne.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the resource")})},oUs=(s,t)=>rt({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),lUs=(s,t)=>{const n=$t(),{user:r}=hs();return mt({mutationFn:async a=>{const i={program_id:s,user_id:t,uploaded_by:(r==null?void 0:r.id)??null,title:(a.title||"").trim(),description:a.description||null,category:(a.category||"Personal").trim()||"Personal",resource_kind:a.resource_kind||"pdf",url:a.url||null,file_path:a.file_path||null,status:a.status||"published",sort_order:a.sort_order??0};if(a.id){const{error:l}=await U.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await U.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{ne.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>ne.error(a.message||"Could not save the resource")})},cUs=()=>{const s=$t();return mt({mutationFn:async t=>{t.file_path&&await U.storage.from(AW).remove([t.file_path]);const{error:n}=await U.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ne.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the resource")})},dUs=s=>{const{user:t}=hs();return rt({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await U.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},uUs=s=>{const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await U.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 U.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ne.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=>ne.error(r.message||"Could not update your notify preference")})},hUs=s=>rt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 U.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}})}}),mUs=s=>{if(!s)return null;const t=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}),n=r=>{const[a,i,l]=t.format(r).split(/[-/T]/).map(Number);return Date.UTC(a,i-1,l)};return Math.round((n(new Date(s))-n(new Date))/864e5)},pUs=()=>{const{data:s=[]}=mBt(),{data:t=[]}=Vet(),n=new Set(t.filter(UH).map(a=>a.program_id)),r=s.filter(a=>n.has(a.id));return r.length===0?null:e.jsx("div",{className:"mb-6 space-y-3",children:r.map(a=>{const i=mUs(a.kickoff_at),l=i===null?null:i>1?`Kicks off in ${i} days`:i===1?"Kicks off tomorrow":i===0?"Kicks off today":"In progress";return e.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-primary/30 bg-gradient-to-r from-primary/12 via-primary/5 to-background p-5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/15",children:e.jsx(Xf,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold leading-tight",children:a.name}),l&&e.jsx(ze,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${yu(a.kickoff_at)} · `:"","Your program dashboard is live — lessons, resources and sessions inside."]})]})]}),e.jsx(z,{asChild:!0,size:"lg",className:"shrink-0",children:e.jsxs(or,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(Da,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},fUs={url:"/exp-agent-advantage.webp"};function xUs({className:s}){const{isMember:t,program:n,packageName:r}=OS();return!t||!((n==null?void 0:n.name)||"").toLowerCase().includes("exp")?null:e.jsxs(be,{className:Ct("relative overflow-hidden border border-border/60 bg-gradient-to-r from-card via-card to-muted/40 p-6 mb-6",s),children:[e.jsx("div",{className:"pointer-events-none absolute -right-10 -top-10 h-40 w-40 rounded-full bg-primary/5 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-accent/5 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col items-center gap-4 text-center sm:flex-row sm:gap-6 sm:text-left",children:[e.jsx("div",{className:"flex shrink-0 items-center justify-center rounded-xl border border-border bg-background p-4 shadow-sm",children:e.jsx("img",{src:fUs.url,alt:"eXp Agent Advantage — powered by LevelUp",className:"h-14 w-auto object-contain dark:invert dark:brightness-95 sm:h-16"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 sm:justify-start",children:[e.jsx(un,{className:"h-4 w-4 text-primary","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:"Partnership Benefit"})]}),e.jsx("h2",{className:"mt-1 text-lg font-semibold text-foreground sm:text-xl",children:"Welcome to your eXp Agent Advantage dashboard"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:["You are enrolled in the ",r||"eXp"," partnership. Everything below is included with your membership — coaching, tools, and resources built exclusively for eXp Luxury agents."]})]})]})]})}function gUs({className:s}){var E,P,M;const{user:t}=hs(),{isMember:n,program:r,pkg:a,packageName:i}=OS(),l=_.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=get(),c=o==null?void 0:o.id,{data:d=[]}=yet(c),{data:u=[]}=vet(c),{data:h}=rt({queryKey:["exp-coaching-prep",t==null?void 0:t.id,a==null?void 0:a.id],enabled:!!(t!=null&&t.id)&&!!(a!=null&&a.id)&&l,queryFn:async()=>{const[{data:I},{data:D},{data:F}]=await Promise.all([U.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",t.id).maybeSingle(),U.from("coaching_prep_checklist_items").select("id, title, sort_order").eq("package_id",a.id).eq("is_active",!0).order("sort_order"),U.from("coaching_prep_checklist_state").select("item_id").eq("user_id",t.id)]),q=new Set((F||[]).map(G=>G.item_id));return{submitted:!!(I!=null&&I.submitted_at),items:(D||[]).map(G=>({...G,done:q.has(G.id)}))}}});if(!l)return null;const m=((E=o==null?void 0:o.coachProfile)==null?void 0:E.name)||"Your LevelUp Coach",p=((P=o==null?void 0:o.coachProfile)==null?void 0:P.avatar_url)||void 0,f=(M=o==null?void 0:o.coach)==null?void 0:M.headline,v=d.filter(I=>I.status!=="cancelled"&&new Date(I.scheduled_at).getTime()>Date.now()).sort((I,D)=>new Date(I.scheduled_at).getTime()-new Date(D.scheduled_at).getTime())[0],y=u.filter(I=>I.status!=="done"),b=u.length-y.length,w=(h==null?void 0:h.items)||[],S=w.filter(I=>I.done).length,C=w.length?Math.round(S/w.length*100):0;return e.jsxs(be,{className:Ct("overflow-hidden border-border/60 mb-6",s),children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#33586f] to-[#406E71] p-6 text-white",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-24 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-24 -left-10 h-56 w-56 rounded-full bg-[#c8a24a]/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col gap-5 md:flex-row md:items-center",children:[e.jsxs(ja,{className:"h-16 w-16 ring-4 ring-white/20 md:h-20 md:w-20",children:[e.jsx(xi,{src:p,alt:m}),e.jsx(Na,{className:"bg-white/20 text-xl text-white",children:m.charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/75",children:[e.jsx(un,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em]",children:i?`${i} Coaching`:"Included Coaching"})]}),e.jsx("h2",{className:"mt-1 text-2xl font-bold leading-tight",children:m}),e.jsx("p",{className:"mt-1 max-w-xl text-sm text-white/80",children:f||"1:1 accountability coaching included with your eXp Agent Advantage membership."})]}),e.jsxs("div",{className:"flex flex-col gap-2 md:items-end",children:[e.jsx(z,{asChild:!0,className:"bg-white text-[#2a4c64] hover:bg-white/90",children:e.jsxs(or,{to:"/my-coach",children:[e.jsx(v0,{className:"mr-2 h-4 w-4"})," Book a session"]})}),e.jsx(z,{asChild:!0,variant:"outline",className:"border-white/40 bg-white/10 text-white hover:bg-white/20 hover:text-white",children:e.jsxs(or,{to:"/my-coach",children:[e.jsx(qi,{className:"mr-2 h-4 w-4"})," Message coach"]})})]})]})]}),e.jsxs("div",{className:"grid gap-4 p-5 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Next session"]}),v?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-lg font-semibold text-foreground",children:Ys(new Date(v.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ys(new Date(v.scheduled_at),"h:mm a"),v.title?` · ${v.title}`:""]}),v.meeting_url&&e.jsx(z,{asChild:!0,size:"sm",variant:"outline",className:"mt-3",children:e.jsx("a",{href:v.meeting_url,target:"_blank",rel:"noreferrer",children:"Join meeting"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Nothing on the calendar yet — grab a time with ",m.split(" ")[0],"."]}),e.jsx(z,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(or,{to:"/my-coach",children:"Schedule now"})})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(k0,{className:"h-3.5 w-3.5"})," Action items"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-foreground",children:y.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),b>0&&e.jsxs(ze,{variant:"secondary",className:"ml-auto",children:[b," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[y.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Gf,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:I.title||I.description})]},I.id)),y.length===0&&e.jsx("li",{className:"text-sm text-muted-foreground",children:"You're all caught up."})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(Wf,{className:"h-3.5 w-3.5"})," Coaching prep"]}),h!=null&&h.submitted?w.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-2 flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"font-semibold text-foreground",children:[S,"/",w.length," complete"]}),e.jsxs("span",{className:"text-muted-foreground",children:[C,"%"]})]}),e.jsx(Di,{value:C,className:"mt-2 h-2"}),e.jsx("ul",{className:"mt-3 space-y-1",children:w.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[I.done?e.jsx(Mr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}):e.jsx(Gf,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),e.jsx("span",{className:Ct("line-clamp-1",I.done?"text-muted-foreground line-through":"text-foreground"),children:I.title})]},I.id))})]}):e.jsxs("p",{className:"mt-2 flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(fm,{className:"mt-0.5 h-4 w-4 shrink-0"})," Questionnaire submitted — your coach is building your plan."]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Complete your onboarding questionnaire before session one."}),e.jsx(z,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(or,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function yUs(s){return"EST"}function jte(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=yUs();return`${n} ${r}`}function NF(s){const t=new Date,n=new Date(s),r=ift(n,-15),a=ift(n,30);return t>a?"ended":Qk(t,{start:n,end:a})?"live":Qk(t,{start:r,end:n})?"starting_soon":"upcoming"}function Get(s){const t=NF(s);return t==="starting_soon"||t==="live"}const vUs=Get,bUs=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=_.useState(new Date);_.useEffect(()=>{const p=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(p)},[]);const i=s.filter(p=>Get(p.event_date));if(i.length===0)return null;const l=i[0],o=NF(l.event_date),c=t.find(p=>p.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",m=h?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${m.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${m.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${m.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${m.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${m.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Nv,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{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 ${jte(new Date(l.event_date))}`:`Starts at ${jte(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs(z,{onClick:()=>window.open(d,"_blank"),className:`${m.button} text-white gap-2`,children:[e.jsx(mr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs(z,{variant:"outline",onClick:n,className:`${m.outlineButton} gap-2`,children:[e.jsx(On,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function bg(){const{user:s}=hs(),{data:t,isLoading:n}=rt({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:m,error:p}=await U.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(p)throw p;return m}}),{data:r,isLoading:a}=rt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:m}=await U.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return m}}),i=!!(t!=null&&t.is_active),l=!!t&&!t.is_active,o=(t==null?void 0:t.gmail_email)||null,c=!!(r!=null&&r.email),d=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailNeedsReconnect:l,gmailEmail:o,hasVerifiedSes:c,sesEmail:d,canSendEmail:i||c,sendMethod:i?"gmail":c?"mass_email":"none",isLoading:n||a}}function _Us(){var C;const{user:s}=hs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=bg(),a=OS(),i=a.isMember&&!!((C=a.pkg)!=null&&C.includes_coaching),l=a.isMember&&!i,[o,c]=_.useState(!1),[d,u]=_.useState(!1);_.useEffect(()=>{s!=null&&s.id&&U.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:E})=>{c(!!E),u(!0)})},[s==null?void 0:s.id]);const{data:h,isLoading:m}=rt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[E,P,M,I,D,F]=await Promise.all([U.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),U.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),U.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle(),U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1)]),q=(F.data||[]).map(re=>re.id);let G=!1;if(q.length){const{count:re}=await U.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",q);G=(re||0)>0}const V=E.data,H=!!(V!=null&&V.avatar_url&&(V!=null&&V.phone)&&(V!=null&&V.bio)),K=P.count||0,Z=(M.count||0)>0,oe=I.count||0;return{profile:V,profileComplete:H,contactsCount:K,contactsComplete:K>=5,eventsRegistered:Z,communityComplete:oe>0,nextOnboardingEvent:D.data||null,coachingBooked:G}}}),p=t||n,f=[{id:"profile",complete:!!(h!=null&&h.profileComplete)},{id:"email",complete:p},{id:"contacts",complete:!!(h!=null&&h.contactsComplete)},{id:"event",complete:!!(h!=null&&h.eventsRegistered)},{id:"community",complete:!!(h!=null&&h.communityComplete)}],g=l?f.filter(E=>E.id!=="community"&&E.id!=="event"):f;i&&g.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const v=g.filter(E=>E.complete).length,y=g.length;return{steps:g,completedCount:v,totalCount:y,allComplete:v===y,dismissed:o,dismiss:async()=>{s!=null&&s.id&&(c(!0),await U.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(c(!1),await U.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:h,isGmailConnected:t,hasVerifiedSes:n,loading:m||r||!d||a.isLoading}}const wUs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Oo,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:on,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:On,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:ya,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:qi,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"},coaching:{title:"Schedule Your Coaching Session",description:"Book your first 1:1 session with your LevelUp coach.",icon:fm,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function jUs(){var g,v;const s=zn(),{user:t}=hs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=_Us(),[u,h]=_.useState(!0);if(d||l||i)return null;const m=(((g=c==null?void 0:c.profile)==null?void 0:g.name)||((v=t==null?void 0:t.user_metadata)==null?void 0:v.name)||"there").split(" ")[0],p=r/a*100,f=async y=>{switch(y){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const b=c==null?void 0:c.nextOnboardingEvent;if(!b){s("/events");return}if(!(t!=null&&t.id))return;const{error:w}=await U.from("event_registrations").insert({user_id:t.id,event_id:b.id});w&&!String(w.message).toLowerCase().includes("duplicate")?(ne.error("Could not register — opening events page."),s("/events")):ne.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(be,{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(er,{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, ",m,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(Di,{value:p,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs(z,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(Da,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(y=>!y),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(h1,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(cl,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Le,{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(y=>{const b=wUs[y.id],w=b.icon;return e.jsx("div",{className:Ct("relative rounded-xl border p-4 transition-all group",y.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!y.complete&&f(y.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ct("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",y.complete?"from-emerald-500 to-emerald-600":b.accent),children:y.complete?e.jsx(Mr,{className:"h-5 w-5"}):e.jsx(w,{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:Ct("font-semibold text-sm",y.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Ct("text-xs text-muted-foreground mt-1 leading-relaxed",y.complete&&"line-through"),children:b.description}),y.id==="event"&&!y.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"]}),!y.complete&&e.jsxs(z,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:S=>{S.stopPropagation(),f(y.id)},children:[b.cta," ",e.jsx(Da,{className:"h-3 w-3 ml-1"})]})]}),y.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},y.id)})})})]})}function NUs(s){return rt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function kUs(s,t){return rt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=U.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 SUs(s,t=4){return rt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await U.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 CUs(s){const t=$t();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.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 AUs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function EUs(s){const t=$t();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.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 TUs(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function MUs(s){const t=$t();return mt({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 U.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const PUs={video:su,pdf:$r,link:Oc,event:ya,graphic:yc},LUs={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 IUs(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 DUs(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 RUs({item:s}){const t=zn(),n=PUs[s.content_type]||Oc,r=LUs[s.content_type]||"",[a,i]=_.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?IUs(s.url):null);_.useEffect(()=>{l||!s.url||s.content_type!=="video"||!DUs(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(be,{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(Le,{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:Ys(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function FUs(){const{brokerageId:s}=hs(),t=zn(),{data:n=[],isLoading:r}=SUs(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(oi,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Da,{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(RUs,{item:a},a.id))})]})}const vBt=({className:s,variant:t="default"})=>e.jsx(ze,{variant:"outline",className:Ct("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"}),OUs={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"},zUs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function BUs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function $Us(){const s=zn(),{data:t,isLoading:n}=rzt(),{data:r,isLoading:a}=azt({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(be,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Le,{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(vBt,{})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Da,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Le,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(sa,{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(z,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var m,p;const h=((m=u.photos)==null?void 0:m.find(f=>f.is_primary))||((p=u.photos)==null?void 0:p[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(sa,{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(Ia,{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 ${OUs[u.status]}`,children:zUs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:BUs(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 bBt(s=10,t){return rt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await U.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(m=>m.user_id))||[]);let a=null;if(t){const{data:m}=await U.from("profiles").select("id").eq("brokerage_id",t);a=new Set((m==null?void 0:m.map(p=>p.id))||[])}const{data:i,error:l}=await U.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(m=>!r.has(m.user_id));a&&(o=o.filter(m=>a.has(m.user_id)));const c=o.slice(0,s),d=c.map(m=>m.user_id),{data:u}=await U.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(m=>[m.id,{name:m.name}]))||[]);return c.map(m=>({user_id:m.user_id,total_points:m.total_points,total_events_attended:m.total_events_attended,current_streak:m.current_streak,profile:h.get(m.user_id)||null}))}})}function _Bt(s){return rt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function wBt(s){return rt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function jBt(s,t){return rt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await U.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await U.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 U.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 U.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function UUs(){const{user:s,brokerageId:t,isAdmin:n}=hs();zn();const r=!!t,[a,i]=_.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=bBt(5,l()),{data:d}=_Bt(s==null?void 0:s.id),{data:u}=jBt(s==null?void 0:s.id,l()),{data:h}=wBt(s==null?void 0:s.id),m=n||r,p=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(jl,{className:"h-4 w-4 text-yellow-500"}),p()]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((g,v)=>e.jsx(ln,{className:"h-10 w-full"},v))})})]});const f=g=>g===0?e.jsx(jl,{className:"h-4 w-4 text-yellow-500 mx-auto"}):g===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):g===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:g+1});if(m){const g=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-2",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(jl,{className:"h-4 w-4 text-yellow-500"}),p()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(z,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(z,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Le,{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:[g.map((v,y)=>{var b,w,S;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":y===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:f(y)}),e.jsx(ja,{className:"h-6 w-6",children:e.jsx(Na,{className:"text-xs",children:((w=(b=v.profile)==null?void 0:b.name)==null?void 0:w.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((S=v.profile)==null?void 0:S.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:v.total_points})]},v.user_id)}),g.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(or,{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(Ko,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(yi,{className:"h-4 w-4"})]})]})]})}return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(jl,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Le,{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(vu,{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(Kh,{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(g=>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:g.badge_name},g.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(or,{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(Ko,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(yi,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Ia,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(or,{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(Ko,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(yi,{className:"h-4 w-4"})]})]})})]})}const Q9=()=>rt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await U.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),Wet=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r}=await U.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 U.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"]}),ne.success("Lead source added")},onError:n=>{ne.error("Failed to add lead source"),console.error(n)}})},qUs=()=>{const s=$t();return mt({mutationFn:async({id:t,name:n})=>{const{error:r}=await U.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ne.success("Lead source updated")},onError:t=>{ne.error(t.message||"Failed to update lead source")}})},VUs=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ne.success("Lead source removed")},onError:t=>{ne.error(t.message||"Failed to remove lead source")}})},Ket=(s,t)=>{const{user:n,isAdmin:r}=hs(),a=r&&t?t:n==null?void 0:n.id;return rt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},Yet=s=>{const{user:t,isAdmin:n}=hs(),r=n&&s?s:t==null?void 0:t.id;return rt({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},SLe=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.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"]}),ne.success("Transaction added")},onError:n=>{ne.error("Failed to add transaction"),console.error(n)}})},HUs=()=>{const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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"]}),ne.success("Transaction updated")},onError:t=>{ne.error("Failed to update transaction"),console.error(t)}})},GUs=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ne.success("Transaction deleted")},onError:t=>{ne.error("Failed to delete transaction"),console.error(t)}})},NBt=(s,t)=>{const{user:n,isAdmin:r}=hs(),a=r&&t?t:n==null?void 0:n.id;return rt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await U.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},WUs=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.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]}),ne.success("Goals saved")},onError:n=>{ne.error("Failed to save goals"),console.error(n)}})},CLe=()=>{const{user:s}=hs();return rt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},KUs=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{data:r,error:a}=await U.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"]}),ne.success("Settings saved")},onError:n=>{ne.error("Failed to save settings"),console.error(n)}})},kBt=(s,t)=>{const{data:n,isLoading:r}=Ket(s,t),{data:a,isLoading:i}=Yet(t),{data:l}=CLe(),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(C=>C.transaction_type==="buyer").length,h=d.filter(C=>C.transaction_type==="seller").length,m=d.reduce((C,E)=>C+Number(E.sale_price),0),p=d.reduce((C,E)=>C+(Number(E.commission_amount)||0),0),f=d.reduce((C,E)=>{const P=Number(E.commission_amount)||0;if(!P)return C;let M=P;return E.brokerage_split_pct&&(M-=P*(E.brokerage_split_pct/100)),E.team_split_pct&&(M-=P*(E.team_split_pct/100)),E.franchise_fee_pct&&(M-=P*(E.franchise_fee_pct/100)),E.referral_fee_pct&&(M-=P*(E.referral_fee_pct/100)),E.transaction_fee&&(M-=E.transaction_fee),C+Math.max(0,M)},0),g={};d.forEach(C=>{var P;const E=((P=C.lead_source)==null?void 0:P.name)||"Unknown";g[E]=(g[E]||0)+1});const v=Object.entries(g).map(([C,E])=>({name:C,count:E})).sort((C,E)=>E.count-C.count),y=v[0]||null,b={};d.forEach(C=>{const E=Ou(C.close_date).toLocaleString("default",{month:"short"});b[E]=(b[E]||0)+1});const S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(C=>({month:C,count:b[C]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:m,averagePrice:d.length>0?m/d.length:0,totalCommission:o?p:0,totalNetToAgent:o?f:0,topLeadSource:y,transactionsByMonth:S,leadSourceBreakdown:v}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},YUs=()=>{const{isAdmin:s}=hs();return rt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await U.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 U.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},b6={recency:40,touchpoints:30,transactions:20,referrals:10},Jgt={warm:70,cooling:40};function ZUs(s){return s===null?0:s<=14?b6.recency:s<=30?b6.recency*.85:s<=60?b6.recency*.65:s<=90?b6.recency*.4:s<=180?b6.recency*.2:b6.recency*.05}function XUs(s){const t=Math.min(s/12,1);return Math.round(b6.touchpoints*t)}function QUs(s){return s?b6.transactions:0}function JUs(){return 0}function eqs(s){return s>=Jgt.warm?"warm":s>=Jgt.cooling?"cooling":"at-risk"}function yae(){const{data:s,isLoading:t}=Rb(),{data:n}=iBt(),{data:r}=SW(365),{data:a}=Yet(),i=_.useMemo(()=>{if(!s)return[];const o=new Date,c=_F(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const m=(n==null?void 0:n[h.id])||null,p=m?PN(o,new Date(m)):null,f=d[h.id]||0,g=u.has(h.id),v=ZUs(p),y=XUs(f),b=QUs(g),w=JUs(),S=Math.round(v+y+b+w),C={score:S,status:eqs(S),breakdown:{recency:Math.round(v),touchpoints:Math.round(y),transactions:Math.round(b),referrals:Math.round(w)},lastTouchDate:m,daysSinceTouch:p,touchCountLast12Months:f,hasTransaction:g};return{...h,relationshipScore:C}})},[s,n,r,a]),l=_.useMemo(()=>{const o=i.filter(m=>m.relationshipScore.status==="warm").length,c=i.filter(m=>m.relationshipScore.status==="cooling").length,d=i.filter(m=>m.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((m,p)=>m+p.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function tqs(s){const{contactsWithScores:t,isLoading:n}=yae(),r=_.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function SBt(){const s=zn(),{stats:t,contactsWithScores:n,isLoading:r}=yae();if(r)return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(ln,{className:"h-5 w-40"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(ln,{className:"h-20 w-full"}),e.jsx(ln,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Le,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(z,{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(be,{children:[e.jsxs(_t,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:[e.jsx(kl,{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(Le,{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(Di,{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(Di,{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(Di,{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(_S,{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(yi,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(yi,{className:"h-4 w-4 ml-1"})]})]})]})}const sqs=()=>{const s=Number(new Intl.DateTimeFormat("en-US",{hour:"numeric",hour12:!1,timeZone:"America/New_York"}).format(new Date));return s<12?"Good morning":s<17?"Good afternoon":"Good evening"},nqs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function rqs({value:s,goal:t}){const n=Math.min(t>0?s/t*100:0,100),r=30,a=2*Math.PI*r;return e.jsxs("div",{className:"relative h-[86px] w-[86px] shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 72 72",className:"h-full w-full -rotate-90",children:[e.jsx("circle",{cx:"36",cy:"36",r,fill:"none",strokeWidth:"7",className:"stroke-current opacity-20"}),e.jsx("circle",{cx:"36",cy:"36",r,fill:"none",strokeWidth:"7",strokeLinecap:"round",stroke:"hsl(var(--hub-glow))",strokeDasharray:a,strokeDashoffset:a-a*n/100,style:{transition:"stroke-dashoffset .6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center leading-none",children:[e.jsx("span",{className:"text-lg font-bold",children:s}),e.jsxs("span",{className:"text-[10px] hub-ink-muted",children:["of ",t]})]})]})}function aqs({name:s,eventsThisWeek:t=0}){const n=zn(),{user:r}=hs(),{data:a}=Bet(),{data:i}=sBt(),l=_Le(),{hasAccess:o,hasAssignment:c}=URt(),{hasFeature:d}=OS(),{data:u}=rt({queryKey:["hub-active-listings",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{count:w,error:S}=await U.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",r.id);return S?0:w||0}}),h=_.useMemo(()=>{if(!i)return 0;const w=Date.now()-7*24*60*60*1e3;return i.filter(S=>S.created_at&&new Date(S.created_at).getTime()>=w).length},[i]),m=(a==null?void 0:a.length)||0,p=(l==null?void 0:l.streak)||0,f=(l==null?void 0:l.actionsThisWeek)||0,g=(l==null?void 0:l.weeklyGoal)||20,v=[m>0?`${m} ${m===1?"person":"people"} to reach out to`:"no follow-ups queued",t>0?`${t} ${t===1?"event":"events"} coming up`:null].filter(Boolean).join(" • "),y=[{label:"New leads (7d)",value:h,to:"/mission-control/contacts"},{label:"Follow-ups due",value:m,to:"/mission-control"},...d("listing_exchange")?[{label:"My listings",value:u??0,to:"/mission-control/listings"}]:[],{label:"Day streak",value:p,to:"/mission-control",icon:vu}],b=[{label:"Add Contact",icon:Pl,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:sd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:C0,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:Ud,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:un,to:"/ask-ai"}];return e.jsxs("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-7 mb-6",children:[e.jsxs("div",{className:"relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:nqs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[sqs(),", ",s]}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:v?`Today: ${v}.`:"You're all clear today — go create some momentum."}),e.jsx("div",{className:"mt-5 grid grid-cols-2 gap-2 sm:grid-cols-4",children:y.map(w=>e.jsxs("button",{onClick:()=>n(w.to),className:"hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[w.icon&&e.jsx(w.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),e.jsx("span",{className:"text-xl font-bold",children:w.value})]}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:w.label})]},w.label))})]}),e.jsxs("div",{className:"hub-glass flex items-center gap-4 rounded-2xl px-4 py-3 lg:self-center",children:[e.jsx(rqs,{value:f,goal:g}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Weekly touches"}),e.jsx("p",{className:"text-xs hub-ink-muted",children:f>=g?"Goal crushed 🎉":`${g-f} to hit your goal`}),e.jsxs("button",{onClick:()=>n("/mission-control"),className:"mt-2 inline-flex items-center gap-1 text-xs font-medium underline-offset-2 hover:underline",children:["Open Agent OS ",e.jsx(Da,{className:"h-3 w-3"})]})]})]})]}),e.jsx("div",{className:"hub-scroll relative mt-5 flex gap-2 overflow-x-auto pb-1",children:b.map(w=>e.jsxs("button",{onClick:()=>n(w.to),className:"hub-glass flex shrink-0 items-center gap-2 rounded-full px-3.5 py-2 text-sm font-medium transition-colors",children:[e.jsx(w.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),w.label]},w.label))})]})}const lU=24*60*60*1e3,iqs=s=>{if(!s)return null;const t=String(s).split(/[-/T]/);if(t.length<3)return null;const n=parseInt(t[1],10)-1,r=parseInt(t[2],10);return isNaN(n)||isNaN(r)?null:{month:n,day:r}},Gle=s=>{const t=iqs(s);if(!t)return null;const n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate());let a=new Date(n.getFullYear(),t.month,t.day);return a.getTime()s!==null&&s>=0&&s<=t,lqs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,cqs={hot_lead_listings:{reason:"Viewing your listings repeatedly",action:"Call now",priority:20},listing_email_click:{reason:"Clicked a listing in your email",action:"Call",priority:21},listing_email_open:{reason:"Opened your listing email",action:"Text",priority:24},open_house_visitor:{reason:"Visited your open house",action:"Follow up",priority:22},email_clicked:{reason:"Clicked a link in your email",action:"Call",priority:23},active_email_thread:{reason:"Active email conversation",action:"Reply",priority:23},email_opened:{reason:"Opened your recent email",action:"Text",priority:26},long_term_homeowner:{reason:"Owned their home 7+ years",action:"Send equity check-in",priority:28},birthday_soon:{reason:"Birthday coming up",action:"Send wishes",priority:12},home_anniversary_soon:{reason:"Home anniversary coming up",action:"Send wishes",priority:13}},dqs=(s=5)=>{const t=ha(),{data:n,isLoading:r}=Bet(),{data:a,isLoading:i}=Rb(),l=rt({queryKey:["smart-queue",t,n==null?void 0:n.length,a==null?void 0:a.length],queryFn:async()=>{var P;const o=[],c=new Set,d=M=>{var I;!((I=M.contact)!=null&&I.id)||c.has(M.contact.id)||(c.add(M.contact.id),o.push(M))};if((n||[]).forEach((M,I)=>{var D;d({key:`plan-${M.contact.id}-${I}`,contact:M.contact,kind:"plan",actionLabel:((D=M.actionType)==null?void 0:D.name)||"Touch",reason:M.planName?`${M.planName}${M.relationshipTypeName?` · ${M.relationshipTypeName}`:""}`:"Scheduled touch",priority:0,planAction:M})}),o.length>=s)return o.slice(0,s);const u=a||[],h=new Map(u.map(M=>[M.id,M])),[{data:m},{data:p},{data:f}]=await Promise.all([U.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),U.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-14*lU).toISOString()),U.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*lU).toISOString())]),g=new Set([...(m||[]).map(M=>M.contact_id),...(p||[]).map(M=>M.contact_id)]),v=new Set((f||[]).map(M=>M.contact_id)),y=M=>!g.has(M)&&!c.has(M);for(const M of u){if(!y(M.id))continue;const D=[{days:Gle(M.birthday),label:"Birthday"},{days:Gle(M.home_anniversary),label:"Home anniversary"},{days:Gle(M.wedding_anniversary),label:"Wedding anniversary"},{days:Gle(M.spouse_birthday),label:`${M.spouse_name||"Spouse"}'s birthday`}].find(F=>oqs(F.days,7));D&&d({key:`milestone-${M.id}`,contact:M,kind:"milestone",actionLabel:"Send wishes",reason:`${D.label} ${lqs(D.days)}`,priority:D.days===0?1:5+D.days})}const{data:b}=await U.from("contact_signals").select("contact_id, signal_type, title, weight, detected_at").eq("owner_user_id",t).or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`).order("weight",{ascending:!1}).order("detected_at",{ascending:!1}).limit(200);for(const M of b||[]){const I=h.get(M.contact_id);if(!I||!y(M.contact_id))continue;const D=cqs[M.signal_type]||{reason:M.title||"Recent activity",action:"Follow up",priority:27};d({key:`signal-${M.contact_id}`,contact:I,kind:"signal",actionLabel:D.action,reason:D.reason,priority:D.priority})}const{data:w}=await U.from("deal_pipeline").select("contact_id, deal_name, property_address, updated_at").eq("owner_user_id",t).is("actual_close_date",null).not("contact_id","is",null).order("updated_at",{ascending:!0}).limit(50);for(const M of w||[]){const I=h.get(M.contact_id);!I||!y(M.contact_id)||d({key:`deal-${M.contact_id}`,contact:I,kind:"deal",actionLabel:"Check in",reason:`Open deal with no contact in 2 weeks${M.property_address?` · ${M.property_address}`:""}`,priority:30})}const S=Date.now()-3*lU;for(const M of u)y(M.id)&&(v.has(M.id)||new Date(M.created_at).getTime()y(M.id)&&!v.has(M.id)&&new Date(M.created_at).getTime()M.id.localeCompare(I.id));if(E.length>0){const M=new Date().getDate()*7%E.length;for(let I=0;IM.priority-I.priority).slice(0,s)},enabled:!!t&&!r&&!i});return{...l,isLoading:l.isLoading||r||i}},uqs=()=>{const s=ha(),t=$t();return mt({mutationFn:async n=>{const r=new Date(Date.now()+14*lU).toISOString(),{error:a}=await U.from("contact_snoozes").insert({contact_id:n,owner_user_id:s,snoozed_until:r});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-queue"]}),t.invalidateQueries({queryKey:["today-actions"]}),la({title:"Snoozed for 14 days"})},onError:n=>la({title:"Could not snooze",description:n.message,variant:"destructive"})})},hqs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),mqs={plan:{icon:_v,tint:"var(--nav-crm)"},milestone:{icon:Hf,tint:"var(--nav-events)"},signal:{icon:vu,tint:"var(--nav-marketing)"},deal:{icon:Px,tint:"var(--nav-listings)"},new:{icon:un,tint:"var(--nav-apps)"},cold:{icon:aj,tint:"var(--nav-more)"}};function pqs(){const s=zn(),{data:t,isLoading:n}=dqs(5),r=uqs(),a=_Le(),i=(a==null?void 0:a.actionsThisWeek)||0,l=(a==null?void 0:a.weeklyGoal)||20,o=t||[];return e.jsxs("section",{className:"hub-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-crm) / 0.12)"},children:e.jsx(bu,{className:"h-4 w-4",style:{color:"hsl(var(--nav-crm))"}})}),"Today's Top 5"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:o.length>0?"Picked for you from your plans, milestones and live activity.":"Your queue is clear."})]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control"),children:["Agent OS ",e.jsx(yi,{className:"h-4 w-4"})]})]}),n?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(c=>e.jsx(ln,{className:"h-16 w-full rounded-xl"},c))}):o.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/30 p-6 text-center",children:[e.jsx(Mr,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due today. Add a new contact to your database to keep the pipeline full."}),e.jsxs(z,{size:"sm",variant:"outline",className:"mt-3 gap-1.5",onClick:()=>s("/mission-control/contacts?new=true"),children:[e.jsx(Pl,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(UN,{delayDuration:200,children:e.jsx("div",{className:"space-y-2",children:o.map(c=>{const d=c.contact,u=d.first_name?`${d.first_name} ${d.last_name||""}`.trim():d.name||"Contact",h=mqs[c.kind],m=h.icon;return e.jsxs("div",{className:"group flex items-center gap-3 rounded-xl border border-border p-3 transition-colors hover:bg-muted/40",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-semibold",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:hqs(u)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:u}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs(ze,{variant:"secondary",className:"gap-1 text-[10px]",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:[e.jsx(m,{className:"h-3 w-3"}),c.actionLabel]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:c.reason})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(fqs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100","aria-label":"Not now",disabled:r.isPending,onClick:()=>r.mutate(d.id),children:e.jsx(er,{className:"h-4 w-4"})})}),e.jsx(Tx,{children:"Not now — hide for 14 days"})]})]})]},c.key)})})}),e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Weekly goal"}),e.jsxs("span",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-primary",children:i})," / ",l," touches"]})]}),e.jsx(Di,{value:Math.min(i/l*100,100),className:"h-2"})]})]})}function fqs({contact:s,onOpen:t}){const n=(s==null?void 0:s.phone)||(s==null?void 0:s.mobile_phone),r=s==null?void 0:s.email;return e.jsxs(e.Fragment,{children:[n&&e.jsx(z,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Call",children:e.jsx("a",{href:`tel:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(va,{className:"h-4 w-4"})})}),n&&e.jsx(z,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Text",children:e.jsx("a",{href:`sms:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(qi,{className:"h-4 w-4"})})}),r&&e.jsx(z,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Email",children:e.jsx("a",{href:`mailto:${r}`,onClick:a=>a.stopPropagation(),children:e.jsx(on,{className:"h-4 w-4"})})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(yi,{className:"h-4 w-4"})})]})}const xqs=s=>{const t=i=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(i),n=t(new Date),r=t(new Date(Date.now()+864e5)),a=t(s);return a===n?"Today":a===r?"Tomorrow":a};function gqs({events:s,registrations:t}){const n=zn(),{data:r}=get(),{data:a}=rt({queryKey:["hub-upcoming-sessions",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:l,error:o}=await U.from("coaching_sessions").select("id, scheduled_at, zoom_join_url, status, agenda").eq("assignment_id",r.id).gte("scheduled_at",new Date().toISOString()).neq("status","cancelled").order("scheduled_at",{ascending:!0}).limit(3);return o?[]:l||[]}}),i=_.useMemo(()=>{const l=(s||[]).map(c=>{const d=t==null?void 0:t.find(u=>u.event_id===c.id);return{id:`event-${c.id}`,title:c.title,subtitle:"LevelUp Event",date:new Date(c.event_date),kind:"event",live:vUs(c.event_date),joinUrl:d?d.zoom_join_url||c.zoom_link:null,onClick:()=>n("/events")}}),o=(a||[]).map(c=>({id:`session-${c.id}`,title:"Coaching Session",subtitle:"Coaching",date:new Date(c.scheduled_at),kind:"coaching",joinUrl:c.zoom_join_url||null,onClick:()=>n("/coaching")}));return[...l,...o].sort((c,d)=>c.date.getTime()-d.date.getTime()).slice(0,5)},[s,t,a,n]);return e.jsxs("section",{className:"hub-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-events) / 0.14)"},children:e.jsx(gc,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),"Up Next"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n("/events"),children:["All ",e.jsx(yi,{className:"h-4 w-4"})]})]}),i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/30 p-6 text-center",children:[e.jsx(gc,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled yet."}),e.jsx(z,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>n("/events"),children:"Browse Events"})]}):e.jsx("ol",{className:"relative space-y-1",children:i.map(l=>e.jsx("li",{children:e.jsxs("button",{onClick:l.onClick,className:"group flex w-full items-start gap-3 rounded-xl p-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{background:l.kind==="coaching"?"hsl(var(--nav-academy) / 0.14)":"hsl(var(--nav-events) / 0.14)"},children:l.live?e.jsx(Nv,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(fm,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(Xr,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:l.title}),e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[l.live?"Live now":`${xqs(l.date)} · ${jte(l.date)}`," ·"," ",l.subtitle]})]}),l.joinUrl&&e.jsxs(z,{size:"sm",variant:l.live?"destructive":"secondary",className:"h-7 shrink-0 gap-1 px-2 text-xs",onClick:o=>{o.stopPropagation(),window.open(l.joinUrl,"_blank")},children:[e.jsx(mr,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const eyt=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function yqs(){const s=zn(),{data:t,isLoading:n}=rt({queryKey:["hub-pipeline-snapshot"],queryFn:async()=>{const{data:r,error:a}=await U.from("deal_pipeline").select("id, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage)");if(a)throw a;const i=(r||[]).filter(u=>{var h,m;return!((h=u.stage)!=null&&h.is_won_stage)&&!((m=u.stage)!=null&&m.is_lost_stage)}),l=(r||[]).filter(u=>{var h;return(h=u.stage)==null?void 0:h.is_won_stage}),o=i.reduce((u,h)=>u+Number(h.expected_price||0),0),c=l.reduce((u,h)=>u+Number(h.sale_price||h.expected_price||0),0),d={};return i.forEach(u=>{var m,p,f;const h=((m=u.stage)==null?void 0:m.id)||"none";d[h]||(d[h]={name:((p=u.stage)==null?void 0:p.name)||"Unassigned",color:((f=u.stage)==null?void 0:f.color)||null,count:0}),d[h].count+=1}),{openCount:i.length,wonCount:l.length,volume:o,wonVolume:c,stages:Object.values(d).sort((u,h)=>h.count-u.count).slice(0,4)}}});return e.jsxs("section",{className:"hub-card flex flex-col p-5",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-listings) / 0.14)"},children:e.jsx(gj,{className:"h-4 w-4",style:{color:"hsl(var(--nav-listings))"}})}),"Pipeline"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control/pipeline"),children:["Open ",e.jsx(yi,{className:"h-4 w-4"})]})]}),n?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ln,{className:"h-12 w-full"}),e.jsx(ln,{className:"h-16 w-full"})]}):!t||t.openCount+t.wonCount===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center rounded-xl border border-dashed border-border bg-muted/30 p-5 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No deals yet. Start tracking your buyers and sellers."}),e.jsx(z,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>s("/mission-control/pipeline"),children:"Create a Deal"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:t.openCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Open deals"})]}),e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:eyt(t.volume)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pipeline volume"})]})]}),e.jsx("div",{className:"mt-4 space-y-2",children:t.stages.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{background:r.color||"hsl(var(--primary))"}}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-muted-foreground",children:r.name}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:r.count})]},r.name))}),t.wonCount>0&&e.jsxs("p",{className:"mt-4 border-t border-border pt-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:t.wonCount})," closed ·"," ",e.jsx("span",{className:"font-semibold text-foreground",children:eyt(t.wonVolume)})," volume"]})]})]})}function vqs(){const s=zn(),{user:t}=hs(),{hasFeature:n}=OS(),{data:r}=rt({queryKey:["hub-jump-back-in",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const i=[],l=U,o=async u=>{try{const h=await u();return(h==null?void 0:h.data)||[]}catch{return[]}},[c,d]=await Promise.all([o(()=>l.from("listing_presentations").select("id, title, updated_at").eq("owner_user_id",t.id).order("updated_at",{ascending:!1}).limit(2)),o(()=>l.from("listings").select("id, property_address, updated_at").eq("agent_id",t.id).order("updated_at",{ascending:!1}).limit(2))]);return c.forEach(u=>i.push({id:`preso-${u.id}`,label:u.title||"Listing Presentation",sub:"Presentation Studio",icon:C0,hue:"--nav-listings",to:`/apps/listing-presentation-studio/${u.id}`})),d.forEach(u=>i.push({id:`listing-${u.id}`,label:u.property_address||"Listing",sub:"My Listings",icon:sa,hue:"--nav-websites",to:`/mission-control/listings/${u.id}`})),i.push({id:"marketing",label:"Create a post",sub:"Marketing Studio",icon:Nh,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=P8t(i.to);return!l||n(l)});return a.length<=1?null:e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Jump back in"})]}),e.jsx("div",{className:"hub-scroll flex gap-3 overflow-x-auto pb-1",children:a.map(i=>e.jsxs("button",{onClick:()=>s(i.to),className:"hub-card group flex w-[230px] shrink-0 items-center gap-3 p-3 text-left",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl",style:{background:`hsl(var(${i.hue}) / 0.14)`},children:e.jsx(i.icon,{className:"h-5 w-5",style:{color:`hsl(var(${i.hue}))`}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:i.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:i.sub})]}),e.jsx(Da,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function bqs({videos:s,kits:t,templates:n,services:r}){const a=zn(),i=[{id:"videos",label:"Academy",icon:dm,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:wv,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:rP,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:un,hue:"--nav-crm",items:r,viewAll:"/additional-services",emptyText:"No additional services yet."}],[l,o]=_.useState(i[0].id),c=i.find(d=>d.id===l)||i[0];return e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Fresh for you"}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(Da,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"hub-scroll mb-4 flex gap-2 overflow-x-auto pb-1",children:i.map(d=>{const u=d.id===c.id;return e.jsxs("button",{onClick:()=>o(d.id),className:`flex shrink-0 items-center gap-2 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors ${u?"border-transparent text-foreground":"border-border text-muted-foreground hover:text-foreground"}`,style:u?{background:`hsl(var(${d.hue}) / 0.14)`}:void 0,children:[e.jsx(d.icon,{className:"h-4 w-4",style:{color:`hsl(var(${d.hue}))`}}),d.label,d.items.length>0&&e.jsx("span",{className:"rounded-full bg-muted px-1.5 text-[11px] text-muted-foreground",children:d.items.length})]},d.id)})}),c.items.length===0?e.jsxs("div",{className:"rounded-2xl border border-dashed border-border bg-muted/30 p-8 text-center",children:[e.jsx(c.icon,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.emptyText})]}):e.jsx("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:c.items.map(d=>e.jsxs("button",{onClick:d.onOpen,className:"hub-card group overflow-hidden text-left",children:[e.jsxs("div",{className:"relative aspect-[3/2] overflow-hidden bg-muted/50",children:[d.image?e.jsx("img",{src:d.image,alt:d.title,loading:"lazy",className:`h-full w-full ${c.fit==="contain"?"object-contain":"object-cover"} transition-transform duration-300 group-hover:scale-105`}):e.jsx("div",{className:"flex h-full w-full items-center justify-center",children:e.jsx(c.icon,{className:"h-8 w-8 text-muted-foreground/40"})}),d.meta&&e.jsx("span",{className:"absolute bottom-2 right-2 rounded bg-foreground/75 px-1.5 py-0.5 text-xs text-background",children:d.meta})]}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"line-clamp-2 text-sm font-medium text-foreground group-hover:text-primary",children:d.title})})]},d.id))})]})}const _qs=()=>{var ae;const{user:s,isAdmin:t}=hs(),n=zn(),{hasFeature:r}=OS(),[a,i]=_.useState([]),[l,o]=_.useState([]),[c,d]=_.useState([]),[u,h]=_.useState([]),[m,p]=_.useState([]),[f,g]=_.useState([]),[v,y]=_.useState(new Set),[b,w]=_.useState([]),[S,C]=_.useState([]),[E,P]=_.useState([]),[M,I]=_.useState(null),[D,F]=_.useState(!0);_.useEffect(()=>{q()},[s]);const q=async()=>{var J,te,ce,ve,me;try{const[he,ge,Ee,Ne,Pe,Oe,ke,Ve,_e,Ae,Se]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),U.from("events").select("*").order("event_date",{ascending:!0}),U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),U.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),U.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),U.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(J=Se.data)!=null&&J.name&&I(Se.data.name);const We=((te=he.data)==null?void 0:te.map(nt=>nt.tag))||[],qe=new Set(((ce=Ee.data)==null?void 0:ce.map(nt=>nt.app_id))||[]);y(qe);const Ze=(((ve=ge.data)==null?void 0:ve.filter(nt=>!nt.required_tags||nt.required_tags.length===0?!0:nt.required_tags.some(Ge=>We.includes(Ge))))||[]).sort((nt,Ge)=>nt.name==="LevelUp Members Portal"?-1:Ge.name==="LevelUp Members Portal"?1:0);i(Ze.slice(0,6));const $e=((me=Ne.data)==null?void 0:me.filter(nt=>NF(nt.event_date)!=="ended"))||[];o($e.slice(0,4)),w(Pe.data||[]),d(Oe.data||[]),h(ke.data||[]),p(Ve.data||[]),g(_e.data||[]);const Xe=Ae.data||[];C(Xe.filter(nt=>nt.placement==="top")),P(Xe.filter(nt=>nt.placement==="between"))}catch(he){console.error("Error loading dashboard:",he),ne.error("Failed to load dashboard data")}finally{F(!1)}},G=async J=>{var ce,ve,me;if(J.target_url.startsWith("/")){U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:J.app_id,app_name:J.name,user_agent:navigator.userAgent}).then(()=>{}),n(J.target_url);return}const te=window.open("about:blank","_blank");try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:J.app_id,app_name:J.name,user_agent:navigator.userAgent});let{data:he}=await U.auth.getSession();(ce=he.session)!=null&&ce.access_token||(he=(await U.auth.refreshSession()).data);const ge=(ve=he==null?void 0:he.session)==null?void 0:ve.access_token;if(!ge){te==null||te.close(),ne.error("Your session expired — please sign in again to launch this app.");return}const{data:Ee,error:Ne}=await U.functions.invoke("sso-launch",{body:{app_id:J.app_id},headers:{Authorization:`Bearer ${ge}`}});if(Ne)throw Ne;Ee!=null&&Ee.redirect_url?te&&!te.closed?(te.location.href=Ee.redirect_url,(me=te.focus)==null||me.call(te)):window.location.assign(Ee.redirect_url):(te==null||te.close(),ne.error("Launch link unavailable"))}catch(he){te==null||te.close(),console.error("Error launching app:",he),ne.error("Failed to launch app")}},V={"Newsletter Pro":"newsletter","Social AutoPilot":"social","Staging Studio":"marketing_studio",SigFlow:"marketing_studio","Agent Review":"marketing_studio",AgentReview:"marketing_studio"},H=a.filter(J=>{const te=V[J.name]||V[J.app_id];return!te||r(te)}),K=J=>E.filter(te=>te.section_after===J),Z=(M||((ae=s==null?void 0:s.user_metadata)==null?void 0:ae.name)||"there").split(" ")[0],oe=Date.now()+7*24*60*60*1e3,re=l.filter(J=>new Date(J.event_date).getTime()<=oe).length;return e.jsxs($s,{title:"Dashboard",children:[r("learn")&&e.jsx(bUs,{events:l,registrations:b,onNavigateToEvents:()=>n("/events")}),e.jsx(pUs,{}),e.jsx(xUs,{}),e.jsx(gUs,{}),e.jsx(aqs,{name:Z,eventsThisWeek:re}),e.jsx(jUs,{}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-6 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsx(pqs,{})}),r("learn")&&e.jsx(gqs,{events:l,registrations:b})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(SBt,{}),r("deals")&&e.jsx(yqs,{}),r("learn")&&e.jsx(UUs,{})]}),e.jsx(vqs,{}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(QY,{banners:S})}),e.jsx(FUs,{}),D?e.jsx("div",{className:"mb-10 grid grid-cols-2 gap-4 md:grid-cols-4",children:[0,1,2,3].map(J=>e.jsx("div",{className:"h-44 rounded-2xl bg-muted/40 animate-pulse"},J))}):e.jsx(bqs,{videos:(r("learn")?m:[]).map(J=>({id:J.id,title:J.title,image:J.thumbnail_url,meta:J.duration,onOpen:()=>n(`/academy/${J.id}`)})),kits:(r("learn")?u:[]).map(J=>({id:J.id,title:J.name,image:J.featured_image_url,onOpen:()=>n(`/toolbox/${J.id}`)})),templates:(r("marketing_studio")?c:[]).map(J=>({id:J.id,title:J.name,image:J.preview_image_url,onOpen:()=>n("/templates")})),services:f.map(J=>({id:J.id,title:J.name,image:J.preview_image_url,onOpen:()=>window.open(J.signup_link_url,"_blank")}))}),K("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(QY,{banners:K("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx($Us,{})}),H.length>0&&e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Apps"}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Da,{className:"h-4 w-4"})]})]}),H.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Le,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Ty,{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:H.map(J=>{const te=v.has(J.id);return e.jsxs("div",{onClick:()=>G(J),className:"hub-card group flex items-start gap-4 p-5 cursor-pointer",children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:J.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:J.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:J.description})]}),te&&e.jsx(Ty,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},J.id)})})]}),K("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(QY,{banners:K("templates")})}),K("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(QY,{banners:K("events")})}),K("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(QY,{banners:K("toolbox")})})]})},wqs=[{key:"contacts",label:"Contacts",icon:va,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:oP,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:wv,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:Xr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:sa,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Wf,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Ha,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:j0,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:ip,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:C0,description:"Create and manage smart presentations"}];function jqs(){var P;const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState({email:"",name:"",password:""}),[p,f]=_.useState("create"),[g,v]=_.useState(!1),[y,b]=_.useState(null);_.useEffect(()=>{s&&w()},[s]);const w=async()=>{if(s){a(!0);try{const{data:M,error:I}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(I)throw I;if(M&&M.length>0){const D=M.map(G=>G.assistant_id),{data:F}=await U.from("profiles").select("id, name, email").in("id",D),q=M.map(G=>{const V=F==null?void 0:F.find(H=>H.id===G.assistant_id);return{...G,permissions:G.permissions,assistant_profile:V?{name:V.name||"",email:V.email||""}:void 0}});n(q)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},S=async()=>{if(s){if(p==="link"){if(!h.email.trim()){ne.error("Please enter the assistant's email");return}v(!0);try{const{data:{session:M}}=await U.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:I,error:D}=await U.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(D||!I){ne.error("No account found with that email. Try creating a new assistant instead.");return}const{data:F}=await U.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",I.id);if(F&&F.length>0){ne.error("This assistant is already assigned to you");return}const q=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:I.id,role:"assistant",action:"add",agentId:s.id})}),G=await q.json();if(!q.ok)throw new Error(G.error||"Failed to assign assistant role");const{error:V}=await U.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:I.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(V)throw V;ne.success(`${I.name||I.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),w()}catch(M){console.error("Error linking assistant:",M),ne.error(M.message||"Failed to link assistant")}finally{v(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ne.error("Please fill in all fields");return}if(h.password.length<6){ne.error("Password must be at least 6 characters");return}v(!0);try{const{data:{session:M}}=await U.auth.getSession();if(!M)throw new Error("Not authenticated");const I=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"})}),D=await I.json();if(!I.ok)throw new Error(D.error||"Failed to create assistant account");const F=D.userId||D.id;if(!F)throw new Error("No user ID returned");const q=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,role:"assistant",action:"add",agentId:s.id})}),G=await q.json();if(!q.ok)throw new Error(G.error||"Failed to assign assistant role");const{error:V}=await U.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:F,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(V)throw V;ne.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),w()}catch(M){console.error("Error adding assistant:",M),ne.error(M.message||"Failed to add assistant")}finally{v(!1)}}},C=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await U.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:I}=await U.from("agent_assistant_assignments").delete().eq("id",d.id);if(I)throw I;const{data:D}=await U.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!D||D.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"})}),ne.success("Assistant removed"),c(!1),u(null),w()}catch(M){console.error("Error removing assistant:",M),ne.error(M.message||"Failed to remove assistant")}},E=async(M,I,D)=>{b(M);try{const F=t.find(V=>V.id===M);if(!F)return;const q={...F.permissions,[I]:D},{error:G}=await U.from("agent_assistant_assignments").update({permissions:q}).eq("id",M);if(G)throw G;n(V=>V.map(H=>H.id===M?{...H,permissions:q}:H))}catch(F){console.error("Error updating permissions:",F),ne.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Le,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(En,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(z,{size:"sm",onClick:()=>{f("create"),l(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Le,{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 I,D,F,q;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(ja,{className:"h-10 w-10",children:e.jsx(Na,{children:((D=(I=M.assistant_profile)==null?void 0:I.name)==null?void 0:D.split(" ").map(G=>G[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((F=M.assistant_profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((q=M.assistant_profile)==null?void 0:q.email)||""})]}),e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[e.jsx(Om,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(z,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(M),c(!0)},children:e.jsx(Cn,{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:wqs.map(G=>{const V=G.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(V,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:G.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:G.description})]})]}),e.jsx(mn,{checked:M.permissions[G.key]||!1,onCheckedChange:H=>E(M.id,G.key,H),disabled:y===M.id})]},G.key)})})]})]},M.id)})})})]}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add Assistant"}),e.jsx(_r,{children:p==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(z,{variant:p==="create"?"default":"outline",size:"sm",onClick:()=>f("create"),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(z,{variant:p==="link"?"default":"outline",size:"sm",onClick:()=>f("link"),children:[e.jsx(Kc,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"assistant-name",children:"Name"}),e.jsx(pe,{id:"assistant-name",value:h.name,onChange:M=>m({...h,name:M.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"assistant-email",children:"Email"}),e.jsx(pe,{id:"assistant-email",type:"email",value:h.email,onChange:M=>m({...h,email:M.target.value}),placeholder:"assistant@email.com"})]}),p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(pe,{id:"assistant-password",type:"password",value:h.password,onChange:M=>m({...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(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(z,{onClick:S,disabled:g,children:[g&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),p==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Ql,{open:o,onOpenChange:c,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Remove Assistant?"}),e.jsxs(ql,{children:["This will remove ",(P=d==null?void 0:d.assistant_profile)==null?void 0:P.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:C,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function av(s){this.content=s}av.prototype={constructor:av,find:function(s){for(var t=0;t>1}};av.from=function(s){if(s instanceof av)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new av(t)};function CBt(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=CBt(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function ABt(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 X1(r,a)}cutByIndex(t,n){return t==n?X1.empty:t==0&&n==this.content.length?this:new X1(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 X1(a,i)}addToStart(t){return new X1([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new X1(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?Wle(n+1,i):Wle(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 X1.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new X1(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return X1.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}};Lm.none=[];class GAe extends Error{}class Ii{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=TBt(this.content,t+this.openStart,n);return r&&new Ii(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Ii(EBt(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return Ii.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Ii(Ya.fromJSON(t,n.content),r,a)}static maxOpen(t,n=!0){let r=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=t.lastChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.lastChild)a++;return new Ii(t,r,a)}}Ii.empty=new Ii(Ya.empty,0,0);function EBt(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(EBt(i.content,t-a-1,n-a-1)))}function TBt(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=TBt(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function Nqs(s,t,n){if(n.openStart>s.depth)throw new GAe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new GAe("Inconsistent open depths");return MBt(s,t,n,0)}function MBt(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 BJ(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&&(S7(s.nodeAfter,r),i++));for(let o=i;oa&&tHe(s,t,a+1),l=r.depth>a&&tHe(n,r,a+1),o=[];return BJ(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(PBt(i,l),S7(C7(i,LBt(s,t,n,r,a+1)),o)):(i&&S7(C7(i,WAe(s,t,a+1)),o),BJ(t,n,a,o),l&&S7(C7(l,WAe(n,r,a+1)),o)),BJ(r,null,a,o),new Ya(o)}function WAe(s,t,n){let r=[];if(BJ(null,s,n,r),s.depth>n){let a=tHe(s,t,n+1);S7(C7(a,WAe(s,t,n+1)),r)}return BJ(t,null,n,r),new Ya(r)}function kqs(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(Ya.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class Nte{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 KAe(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 Nte(n,r,i)}static resolveCached(t,n){let r=tyt.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()+")"),IBt(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=Ya.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=Ya.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};bP.prototype.text=void 0;class YAe extends bP{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):IBt(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 YAe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new YAe(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 IBt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class l9{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new Eqs(t,n);if(r.next==null)return l9.empty;let a=DBt(r);r.next&&r.err("Unexpected trailing text");let i=Rqs(Dqs(a));return Fqs(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(` `)}}l9.empty=new l9(!0);class Eqs{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 DBt(s){let t=[];do t.push(Tqs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function Tqs(s){let t=[];do t.push(Mqs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function Mqs(s){let t=Iqs(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=Pqs(s,t);else break;return t}function syt(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function Pqs(s,t){let n=syt(s),r=n;return s.eat(",")&&(s.next!="}"?r=syt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function Lqs(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 Iqs(s){if(s.eat("(")){let t=DBt(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=Lqs(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 Dqs(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 l9(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:OBt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new bP(this,this.computeAttrs(t),Ya.from(n),Lm.setFrom(r))}createChecked(t=null,n,r){return n=Ya.from(n),this.checkContent(n),new bP(this,this.computeAttrs(t),n,Lm.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Ya.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(Ya.empty,!0);return i?new bP(this,t,n.append(i),Lm.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 $Bt(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 Oqs(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 zqs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Oqs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class ALe{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=BBt(t,a.attrs),this.excluded=null;let i=FBt(this.attrs);this.instance=i?new Lm(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Lm(this,OBt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new ALe(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let UBt=class{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in t)n[a]=t[a];n.nodes=av.from(t.nodes),n.marks=av.from(t.marks||{}),this.nodes=ryt.compile(this.spec.nodes,this),this.marks=ALe.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]=l9.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?ayt(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==""?[]:ayt(this,l.split(" "))}this.nodeFromJSON=a=>bP.fromJSON(this,a),this.markFromJSON=a=>Lm.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 ryt){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 YAe(r,r.defaultAttrs,t,Lm.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 ayt(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 Bqs(s){return s.tag!=null}function $qs(s){return s.style!=null}let $J=class nHe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(Bqs(a))this.tags.push(a);else if($qs(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 oyt(this,n,!1);return r.addAll(t,Lm.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new oyt(this,n,!0);return r.addAll(t,Lm.none,n.from,n.to),Ii.maxOpen(r.finish())}matchTag(t,n,r){for(let a=r?this.tags.indexOf(r)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let n=[];function r(a){let i=a.priority==null?50:a.priority,l=0;for(;l{r(l=lyt(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=lyt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new nHe(t,nHe.schemaRules(t)))}};const qBt={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},Uqs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},VBt={ol:!0,ul:!0},kte=1,rHe=2,UJ=4;function iyt(s,t,n){return t!=null?(t?kte:0)|(t==="full"?rHe:0):s&&s.whitespace=="pre"?kte|rHe:n&~UJ}class Kle{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=Lm.none,this.match=i||(l&UJ?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ya.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&kte)){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=Ya.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Ya.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&&!qBt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class oyt{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=iyt(null,n.preserveWhitespace,0)|(r?UJ:0);a?i=new Kle(a.type,a.attrs,Lm.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new Kle(null,null,Lm.none,!0,null,l):i=new Kle(t.schema.topNodeType,null,Lm.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&rHe?"full":this.localPreserveWS||(a.options&kte)>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):cyt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Kle(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|=kte)}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 qqs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&VBt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Vqs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function lyt(s){let t={};for(let n in s)t[n]=s[n];return t}function cyt(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&&Y4e(C7e(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return Y4e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new J9(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=dyt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return dyt(t.marks)}}function dyt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function C7e(s){return s.document||window.document}const uyt=new WeakMap;function Hqs(s){let t=uyt.get(s);return t===void 0&&uyt.set(s,t=Gqs(s)),t}function Gqs(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let m=h.indexOf(" ");m>0?c.setAttributeNS(h.slice(0,m),h.slice(m+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:p,contentDOM:f}=Y4e(s,m,n,r);if(c.appendChild(p),f){if(o)throw new RangeError("Multiple content holes");o=f}}}return{dom:c,contentDOM:o}}const HBt=65535,GBt=Math.pow(2,16);function Wqs(s,t){return s+t*GBt}function hyt(s){return s&HBt}function Kqs(s){return(s-(s&HBt))/GBt}const WBt=1,KBt=2,Z4e=4,YBt=8;class aHe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&YBt)>0}get deletedBefore(){return(this.delInfo&(WBt|Z4e))>0}get deletedAfter(){return(this.delInfo&(KBt|Z4e))>0}get deletedAcross(){return(this.delInfo&Z4e)>0}}class ej{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&ej.empty)return ej.empty}recover(t){let n=0,r=hyt(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let m=d?t==c?-1:t==h?1:n:n,p=c+a+(m<0?0:u);if(r)return p;let f=t==(n<0?c:h)?null:Wqs(o/3,t-c),g=t==c?KBt:t==h?WBt:Z4e;return(n<0?t!=c:t!=h)&&(g|=YBt),new aHe(p,g,f)}a+=u-d}return r?t+a:new aHe(t+a,0,null)}touches(t,n){let r=0,a=hyt(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 Ste;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 zg.fromReplace(t,this.from,this.to,i)}invert(){return new R4(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 TM(n.pos,r.pos,this.mark)}merge(t){return t instanceof TM&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new TM(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 TM(n.from,n.to,t.markFromJSON(n.mark))}}N1.jsonID("addMark",TM);class R4 extends N1{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new Ii(Zet(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return zg.fromReplace(t,this.from,this.to,r)}invert(){return new TM(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 R4(n.pos,r.pos,this.mark)}merge(t){return t instanceof R4&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new R4(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 R4(n.from,n.to,t.markFromJSON(n.mark))}}N1.jsonID("removeMark",R4);class MM extends N1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return zg.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return zg.fromReplace(t,this.pos,this.pos+1,new Ii(Ya.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 E0(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 E0(n.from,n.to,n.gapFrom,n.gapTo,Ii.fromJSON(t,n.slice),n.insert,!!n.structure)}}N1.jsonID("replaceAround",E0);function iHe(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 Yqs(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let m=Math.max(d,t),p=Math.min(d+c.nodeSize,n),f=r.addToSet(h);for(let g=0;gs.step(c)),i.forEach(c=>s.step(c))}function Zqs(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 ALe){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 R4(l.from,l.to,l.style)))}function Xet(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 Xqs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function EW(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;f--)g||r.index(f)>0?(g=!0,u=Ya.from(r.node(f).copy(u)),h++):c--;let m=Ya.empty,p=0;for(let f=i,g=!1;f>n;f--)g||a.after(f+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=Ya.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new E0(a,i,a,i,new Ii(r,0,0),n.length,!0))}function sVs(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)&&nVs(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",f=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!f?d=!1:!p&&f&&(d=!0)}d===!1&&XBt(s,l,o,i),Xet(s,s.mapping.slice(i).map(o,1),r,void 0,d===null);let u=s.mapping.slice(i),h=u.map(o,1),m=u.map(o+l.nodeSize,1);return s.step(new E0(h,m,h+1,m-1,new Ii(Ya.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&ZBt(s,l,o,i),!1}})}function ZBt(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 XBt(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 nVs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function rVs(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 E0(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Ii(Ya.from(l),0,0),1,!0))}function Dq(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),m=a.index(d);if(h.type.spec.isolating)return!1;let p=h.content.cutByIndex(m,h.childCount),f=r&&r[u+1];f&&(p=p.replaceChild(0,f.type.create(f.attrs)));let g=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!g.type.validContent(p))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function aVs(s,t,n=1,r){let a=s.doc.resolve(t),i=Ya.empty,l=Ya.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Ya.from(a.node(o).copy(i));let u=r&&r[d];l=Ya.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Ig(t,t,new Ii(i.append(l),n,n),!0))}function kL(s,t){let n=s.resolve(t),r=n.index();return QBt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function iVs(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&&QBt(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 oVs(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);XBt(s,u.node(),u.before(),o)}l.inlineContent&&Xet(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 Ig(d,c.map(t+n,-1),Ii.empty,!0)),r===!0){let u=s.doc.resolve(d);ZBt(s,u.node(),u.before(),s.steps.length)}return s}function lVs(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 TLe(s,t,n=t,r=Ii.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return e$t(a,i,r)?new Ig(t,n,r):new cVs(a,i,r).fit()}function e$t(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class cVs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Ya.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=Ya.from(t.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,a=this.close(t<0?this.$to:r.doc.resolve(t));if(!a)return null;let i=this.placed,l=r.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new Ii(i,l,o);return t>-1?new E0(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Ig(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=E7e(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(Ya.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=E7e(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Ii(t,n+1,Math.max(r,a.size+n>=t.size-r?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=E7e(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Ii(kX(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Ii(kX(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 g=0;g1||c==0||g.content.size)&&(h=v,u.push(t$t(g.mark(m.allowedMarks(g.marks)),d==1?c:0,d==o.childCount?p:-1)))}let f=d==o.childCount;f||(p=-1),this.placed=SX(this.placed,n,Ya.from(u)),this.frontier[n].match=h,f&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,v=o;g1&&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=T7e(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=SX(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=SX(this.placed,this.depth,Ya.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Ya.empty,!0);n.childCount&&(this.placed=SX(this.placed,this.frontier.length,n))}}function kX(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(kX(s.firstChild.content,t-1,n)))}function SX(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(SX(s.lastChild.content,t-1,n)))}function E7e(s,t){for(let n=0;n1&&(r=r.replaceChild(0,t$t(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(Ya.empty,!0)))),s.copy(r)}function T7e(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&&!dVs(n,i.content,l)?o:null}function dVs(s,t,n){for(let r=n;r0;m--,p--){let f=a.node(m).type.spec;if(f.defining||f.definingAsContext||f.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==p&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,p=0;;p++){let f=m.firstChild;if(d.push(f),p==r.openStart)break;m=f.content}for(let m=u-1;m>=0;m--){let p=d[m],f=uVs(p.type);if(f&&!p.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(f||!p.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let p=(m+u+1)%(r.openStart+1),f=d[p];if(f)for(let g=0;g=0&&(s.replace(t,n,r),!(s.steps.length>h));m--){let p=l[m];p<0||(t=a.before(p),n=i.after(p))}}function s$t(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(Ya.empty,!0))}return s}function mVs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=lVs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Ii(Ya.from(r),0,0))}function pVs(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=n$t(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 n$t(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 Rq extends N1{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 zg.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 zg.fromReplace(t,this.pos,this.pos+1,new Ii(Ya.from(a),0,n.isLeaf?0:1))}getMap(){return ej.empty}invert(t){return new Rq(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 Rq(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 Rq(n.pos,n.attr,n.value)}}N1.jsonID("attr",Rq);class Cte extends N1{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 zg.ok(r)}getMap(){return ej.empty}invert(t){return new Cte(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 Cte(n.attr,n.value)}}N1.jsonID("docAttr",Cte);let qH=class extends Error{};qH=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};qH.prototype=Object.create(Error.prototype);qH.prototype.constructor=qH;qH.prototype.name="TransformError";let Jet=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new Ste}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new qH(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let r=0;r{t=Math.min(t,o),n=Math.max(n,c)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,r=Ii.empty){let a=TLe(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Ii(Ya.from(r),0,0))}delete(t,n){return this.replace(t,n,Ii.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return hVs(this,t,n,r),this}replaceRangeWith(t,n,r){return mVs(this,t,n,r),this}deleteRange(t,n){return pVs(this,t,n),this}lift(t,n){return Qqs(this,t,n),this}join(t,n=1){return oVs(this,t,n),this}wrap(t,n){return tVs(this,t,n),this}setBlockType(t,n=t,r,a=null){return sVs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return rVs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new Rq(t,n,r)),this}setDocAttribute(t,n){return this.step(new Cte(t,n)),this}addNodeMark(t,n){return this.step(new MM(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 Lm)n.isInSet(r.marks)&&this.step(new c9(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new c9(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 aVs(this,t,n,r),this}addMark(t,n,r){return Yqs(this,t,n,r),this}removeMark(t,n,r){return Zqs(this,t,n,r),this}clearIncompatible(t,n,r){return Xet(this,t,n,r),this}};const M7e=Object.create(null);class Zl{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new r$t(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?S$(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):S$(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 jN(t.node(0))}static atStart(t){return S$(t,t,0,0,1)||new jN(t)}static atEnd(t){return S$(t,t,t.content.size,t.childCount,-1)||new jN(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=M7e[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 M7e)throw new RangeError("Duplicate use of selection JSON ID "+t);return M7e[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Nl.between(this.$anchor,this.$head).getBookmark()}}Zl.prototype.visible=!0;class r$t{constructor(t,n){this.$from=t,this.$to=n}}let pyt=!1;function fyt(s){!pyt&&!s.parent.inlineContent&&(pyt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Nl extends Zl{constructor(t,n=t){fyt(t),fyt(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 Zl.near(r);let a=t.resolve(n.map(this.anchor));return new Nl(a.parent.inlineContent?a:r,r)}replace(t,n=Ii.empty){if(super.replace(t,n),n==Ii.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Nl&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new MLe(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 Nl(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=Zl.findFrom(n,r,!0)||Zl.findFrom(n,-r,!0);if(i)n=i.$head;else return Zl.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(Zl.findFrom(t,-r,!0)||Zl.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&&pl.isSelectable(o))return pl.create(s,n-(a<0?o.nodeSize:0))}else{let c=S$(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function xyt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(Zl.near(s.doc.resolve(l),n))}const gyt=1,Yle=2,yyt=4;class xVs extends Jet{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|=Yle,this}ensureMarks(t){return Lm.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&Yle)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~Yle,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)||Lm.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(Zl.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|=yyt,this}get scrolledIntoView(){return(this.updated&yyt)>0}}function vyt(s,t){return!t||!s?s:s.bind(t)}class CX{constructor(t,n,r){this.name=t,this.init=vyt(n.init,r),this.apply=vyt(n.apply,r)}}const gVs=[new CX("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new CX("selection",{init(s,t){return s.selection||Zl.atStart(t.doc)},apply(s){return s.selection}}),new CX("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new CX("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class P7e{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=gVs.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 CX(r.key,r.spec.state,r))})}}class cU{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 P7e(t.schema,t.plugins),i=new cU(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=bP.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=Zl.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 a$t(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=a$t(a,t,{})),n[r]=a}return n}class By{constructor(t){this.spec=t,this.props={},t.props&&a$t(t.props,this,this.props),this.key=t.key?t.key.key:i$t("plugin")}getState(t){return t[this.key]}}const L7e=Object.create(null);function i$t(s){return s in L7e?s+"$"+ ++L7e[s]:(L7e[s]=0,s+"$")}class k1{constructor(t="key"){this.key=i$t(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const dv=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},VH=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let oHe=null;const G3=function(s,t,n){let r=oHe||(oHe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},yVs=function(){oHe=null},d9=function(s,t,n,r){return n&&(byt(s,t,n,r,-1)||byt(s,t,n,r,1))},vVs=/^(img|br|input|textarea|hr)$/i;function byt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:eN(s))){let l=s.parentNode;if(!l||l.nodeType!=1||vae(s)||vVs.test(s.nodeName)||s.contentEditable=="false")return!1;t=dv(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?eN(s):0}else return!1}}function eN(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function bVs(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=eN(s)}else if(s.parentNode&&!vae(s))t=dv(s),s=s.parentNode;else return null}}function _Vs(s,t){for(;;){if(s.nodeType==3&&t2),H2=HH||(xC?/Mac/.test(xC.platform):!1),c$t=xC?/Win/.test(xC.platform):!1,zA=/Android \d/.test(SL),bae=!!_yt&&"webkitFontSmoothing"in _yt.documentElement.style,kVs=bae?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function SVs(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 v3(s,t){return typeof s=="number"?s:s[t]}function CVs(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 wyt(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=VH(l);continue}let o=l,c=o==i.body,d=c?SVs(i):CVs(o),u=0,h=0;if(t.topd.bottom-v3(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+v3(a,"top")-d.top:t.bottom-d.bottom+v3(a,"bottom")),t.leftd.right-v3(r,"right")&&(u=t.right-d.right+v3(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let p=o.scrollLeft,f=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let g=o.scrollLeft-p,v=o.scrollTop-f;t={left:t.left-g,top:t.top-v,right:t.right-g,bottom:t.bottom-v}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:VH(l)}}function AVs(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:d$t(s.dom)}}function d$t(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=VH(r));return t}function EVs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;u$t(n,r==0?0:r-t)}function u$t(s,t){for(let n=0;n=o){l=Math.max(f.bottom,l),o=Math.min(f.top,o);let g=f.left>t.left?f.left-t.left:f.right=(f.left+f.right)/2?1:0));continue}}else f.top>t.top&&!c&&f.left<=t.left&&f.right>=t.left&&(c=u,d={left:Math.max(f.left,Math.min(f.right,t.left)),top:f.top});!n&&(t.left>=f.right&&t.top>=f.top||t.left>=f.left&&t.top>=f.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?MVs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:h$t(n,a)}function MVs(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 ttt(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function PVs(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 IVs(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 m$t(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;bae&&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=IVs(s,r,a,t))}o==null&&(o=LVs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function jyt(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,JY(t6(G3(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==eN(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return I7e(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==eN(r))){let c=r.childNodes[a-1],d=c.nodeType==3?G3(c,eN(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return JY(t6(d,1),!1)}if(i==null&&a=0)}function JY(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 I7e(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 f$t(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 FVs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return f$t(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=p$t(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=G3(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 OVs=/[\u0590-\u08ac]/;function zVs(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?!OVs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:f$t(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let p=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:f,focusOffset:g}=s.domSelectionRange(),v=f&&!p.contains(f.nodeType==1?f:f.parentNode)||c==f&&d==g;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return m!=null&&(o.caretBidiLevel=m),v}):r.pos==r.start()||r.pos==r.end()}let Nyt=null,kyt=null,Syt=!1;function BVs(s,t,n){return Nyt==t&&kyt==n?Syt:(Nyt=t,kyt=n,Syt=n=="up"||n=="down"?FVs(s,t,n):zVs(s,t,n))}const kN=0,Cyt=1,kF=2,gC=3;class _ae{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=kN,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;ndv(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 g$t){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 x$t&&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?dv(i.dom)+1:0}}else{let i,l=!0;for(;i=r=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,n,u);t=l;for(let h=o;h>0;h--){let m=this.children[h-1];if(m.size&&m.dom.parentNode==this.contentDOM&&!m.emptyChildAt(1)){a=dv(m.dom)+1;break}t-=m.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;uf&&ln){let f=o;o=c,c=f}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(p)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?kF:Cyt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=gC:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?kF:gC}r=l}this.dirty=kF}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?kF:Cyt;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==kN&&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 $Vs extends _ae{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 u9 extends _ae{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=J9.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new u9(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&gC||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=gC&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=kN){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=hHe(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}=J9.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let m=u;return u=b$t(u,r,n),d?c=new UVs(t,n,r,a,u,h||null,m,d,i,l+1):n.isText?new LLe(t,n,r,a,u,m,i):new wP(t,n,r,a,u,h||null,m,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=()=>Ya.empty)}return t}matchesNode(t,n,r){return this.dirty==kN&&t.eq(this.node)&&ZAe(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 VVs(this,l&&l.node,t);WVs(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?Lm.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,m)=>{c.syncToMarks(d.marks,r,t,m);let p;c.findNodeMatch(d,u,h,m)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,p,t)||c.updateNextNode(d,u,h,t,m,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==kF)&&(l&&this.protectLocalComposition(t,l),y$t(this.contentDOM,this.children,t),HH&&KVs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Nl)||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=YVs(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 $Vs(this,i,n,a);t.input.compositionNodes.push(l),this.children=hHe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==gC||!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=kN}updateOuterDeco(t){if(ZAe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=v$t(this.dom,this.nodeDOM,uHe(this.outerDeco,this.node,n),uHe(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 Ayt(s,t,n,r,a){b$t(r,t,s);let i=new wP(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class LLe extends wP{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==gC||this.dirty!=kN&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=kN||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=kN,!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 LLe(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=gC)}get domAtom(){return!1}isText(t){return this.node.text==t}}class g$t extends _ae{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==kN&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class UVs extends wP{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==gC)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 y$t(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=u9.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 u9)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 GVs(s,t){return s.type.side-t.type.side}function WVs(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 f=i+m.nodeSize;if(m.isText){let v=f;l!v.inline):o.slice();r(m,g,t.forChild(i,m),p),i=f}}function KVs(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 YVs(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 hHe(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 stt(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(PLe(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&pl.isSelectable(h)&&a.parent&&!(h.isInline&&wVs(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new pl(l==m?o:r.resolve(m))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,m=l;for(let p=0;p{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!_$t(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function XVs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,dv(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&$_&&_P<=11&&(n.disabled=!0,n.disabled=!1)}function w$t(s,t){if(t instanceof pl){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Lyt(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Lyt(s)}function Lyt(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function ntt(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Nl.between(t,n,r)}function Iyt(s){return s.editable&&!s.hasFocus()?!1:j$t(s)}function j$t(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 QVs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return d9(t.node,t.offset,n.anchorNode,n.anchorOffset)}function mHe(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&&Zl.findFrom(i,t)}function _6(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Dyt(s,t,n){let r=s.state.selection;if(r instanceof Nl)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 _6(s,new Nl(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=mHe(s.state,t);return a&&a instanceof pl?_6(s,a):!1}else if(!(H2&&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?pl.isSelectable(i)?_6(s,new pl(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):bae?_6(s,new Nl(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof pl&&r.node.isInline)return _6(s,new Nl(t>0?r.$to:r.$from));{let a=mHe(s.state,t);return a?_6(s,a):!1}}}function XAe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function VJ(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function LB(s,t){return t<0?JVs(s):eHs(s)}function JVs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(NN&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(VJ(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(N$t(n))break;{let o=n.previousSibling;for(;o&&VJ(o,-1);)a=n.parentNode,i=dv(o),o=o.previousSibling;if(o)n=o,r=XAe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?pHe(s,n,r):a&&pHe(s,a,i)}function eHs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=XAe(n),i,l;for(;;)if(r{s.state==a&&aE(s)},50)}function Ryt(s,t){let n=s.state.doc.resolve(t);if(!(gv||c$t)&&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 Fyt(s,t,n){let r=s.state.selection;if(r instanceof Nl&&!r.empty||n.indexOf("s")>-1||H2&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=mHe(s.state,t);if(l&&l instanceof pl)return _6(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof jN?Zl.near(l,t):Zl.findFrom(l,t);return o?_6(s,o):!1}return!1}function Oyt(s,t){if(!(s.state.selection instanceof Nl))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 zyt(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function nHs(s){if(!b1||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;zyt(s,r,"true"),setTimeout(()=>zyt(s,r,"false"),20)}return!1}function rHs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function aHs(s,t){let n=t.keyCode,r=rHs(t);if(n==8||H2&&n==72&&r=="c")return Oyt(s,-1)||LB(s,-1);if(n==46&&!t.shiftKey||H2&&n==68&&r=="c")return Oyt(s,1)||LB(s,1);if(n==13||n==27)return!0;if(n==37||H2&&n==66&&r=="c"){let a=n==37?Ryt(s,s.state.selection.from)=="ltr"?-1:1:-1;return Dyt(s,a,r)||LB(s,a)}else if(n==39||H2&&n==70&&r=="c"){let a=n==39?Ryt(s,s.state.selection.from)=="ltr"?1:-1:1;return Dyt(s,a,r)||LB(s,a)}else{if(n==38||H2&&n==80&&r=="c")return Fyt(s,-1,r)||LB(s,-1);if(n==40||H2&&n==78&&r=="c")return nHs(s)||Fyt(s,1,r)||LB(s,1);if(r==(H2?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function rtt(s,t){s.someProp("transformCopied",p=>{t=p(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let l=s.someProp("clipboardSerializer")||J9.fromSchema(s.state.schema),o=T$t(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=E$t[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let f=o.createElement(u[p]);for(;c.firstChild;)f.appendChild(c.firstChild);c.appendChild(f),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=s.someProp("clipboardTextSerializer",p=>p(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function k$t(s,t,n,r,a){let i=a.parent.type.spec.code,l,o;if(!n&&!t)return null;let c=!!t&&(r||i||!n);if(c){if(s.someProp("transformPastedText",m=>{t=m(t,i||r,s)}),i)return o=new Ii(Ya.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",m=>{o=m(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",m=>m(t,a,r,s));if(h)o=h;else{let m=a.marks(),{schema:p}=s.state,f=J9.fromSchema(p);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(g=>{let v=l.appendChild(document.createElement("p"));g&&v.appendChild(f.serializeNode(p.text(g,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=cHs(n),bae&&dHs(l);let d=l&&l.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let m=l.firstChild;for(;m&&m.nodeType!=1;)m=m.nextSibling;if(!m)break;l=m}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||$J.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!iHs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=uHs(Byt(o,+u[1],+u[2]),u[4]);else if(o=Ii.maxOpen(oHs(o.content,a),!0),o.openStart||o.openEnd){let h=0,m=0;for(let p=o.content.firstChild;h{o=h(o,s,c)}),o}const iHs=/^(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 oHs(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&&C$t(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=A$t(l[l.length-1],i.length));let u=S$t(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Ya.from(l)}return s}function S$t(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Ya.from(s));return s}function C$t(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(Ya.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Byt(s,t,n){return tn})),R7e.createHTML(s)):s}function cHs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=T$t().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&E$t[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=lHs(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Ya.from(c.create(r[o+1],a)),i++,l++}return new Ii(a,i,l)}const Mb={},Pb={},hHs={touchstart:!0,touchmove:!0};class mHs{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 pHs(s){for(let t in Mb){let n=Mb[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{xHs(s,r)&&!att(s,r)&&(s.editable||!(r.type in Pb))&&n(s,r)},hHs[t]?{passive:!0}:void 0)}b1&&s.dom.addEventListener("input",()=>null),xHe(s)}function PM(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function fHs(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 xHe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>att(s,r))})}function att(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function xHs(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 gHs(s,t){!att(s,t)&&Mb[t.type]&&(s.editable||!(t.type in Pb))&&Mb[t.type](s,t)}Pb.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!P$t(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(zA&&gv&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),HH&&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,lF(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||aHs(s,n)?n.preventDefault():PM(s,"key")};Pb.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};Pb.keypress=(s,t)=>{let n=t;if(P$t(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||H2&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Nl)||!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 ILe(s){return{left:s.clientX,top:s.clientY}}function yHs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function itt(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 Fq(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 vHs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&pl.isSelectable(r)?(Fq(s,new pl(n)),!0):!1}function bHs(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof pl&&(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(pl.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?(Fq(s,pl.create(s.state.doc,a)),!0):!1}function _Hs(s,t,n,r,a){return itt(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?bHs(s,n):vHs(s,n))}function wHs(s,t,n,r){return itt(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function jHs(s,t,n,r){return itt(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||NHs(s,n,r)}function NHs(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(Fq(s,Nl.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)Fq(s,Nl.create(r,o+1,o+1+l.content.size));else if(pl.isSelectable(l))Fq(s,pl.create(r,o));else continue;return!0}}function ott(s){return QAe(s)}const M$t=H2?"metaKey":"ctrlKey";Mb.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=ott(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&yHs(n,s.input.lastClick)&&!n[M$t]&&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(ILe(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new kHs(s,l,n,!!r)):(i=="doubleClick"?wHs:jHs)(s,l.pos,l.inside,n)?n.preventDefault():PM(s,"pointer"))};class kHs{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[M$t],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 pl&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&NN&&!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)),PM(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(()=>aE(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(ILe(t))),this.updateAllowDefault(t),this.allowDefault||!n?PM(this.view,"pointer"):_Hs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||b1&&this.mightDrag&&!this.mightDrag.node.isAtom||gv&&!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)?(Fq(this.view,Zl.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):PM(this.view,"pointer")}move(t){this.updateAllowDefault(t),PM(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)}}Mb.touchstart=s=>{s.input.lastTouch=Date.now(),ott(s),PM(s,"pointer")};Mb.touchmove=s=>{s.input.lastTouch=Date.now(),PM(s,"pointer")};Mb.contextmenu=s=>ott(s);function P$t(s,t){return s.composing?!0:b1&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const SHs=zA?5e3:-1;Pb.compositionstart=Pb.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Nl&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||gv&&c$t&&CHs(s)))s.markCursor=s.state.storedMarks||n.marks(),QAe(s,!0),s.markCursor=null;else if(QAe(s,!t.selection.empty),NN&&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}L$t(s,SHs)};function CHs(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"}Pb.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++,L$t(s,20))};function L$t(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>QAe(s),t))}function I$t(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=EHs());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function AHs(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=bVs(t.focusNode,t.focusOffset),r=_Vs(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 EHs(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function QAe(s,t=!1){if(!(zA&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),I$t(s),t||s.docView&&s.docView.dirty){let n=stt(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 THs(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 Ate=$_&&_P<15||HH&&kVs<604;Mb.copy=Pb.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=Ate?null:n.clipboardData,l=r.content(),{dom:o,text:c}=rtt(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):THs(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function MHs(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function PHs(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?Ete(s,r.value,null,a,t):Ete(s,r.textContent,r.innerHTML,a,t)},50)}function Ete(s,t,n,r,a){let i=k$t(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Ii.empty)))return!0;if(!i)return!1;let l=MHs(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 D$t(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," "):""}Pb.paste=(s,t)=>{let n=t;if(s.composing&&!zA)return;let r=Ate?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&Ete(s,D$t(r),r.getData("text/html"),a,n)?n.preventDefault():PHs(s,n)};class R$t{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const LHs=H2?"altKey":"ctrlKey";function F$t(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[LHs]}Mb.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(ILe(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof pl?a.to-1:a.to))){if(r&&r.mightDrag)l=pl.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=pl.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=rtt(s,o);(!n.dataTransfer.files.length||!gv||l$t>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Ate?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",Ate||n.dataTransfer.setData("text/plain",d),s.dragging=new R$t(u,F$t(s,n),l)};Mb.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};Pb.dragover=Pb.dragenter=(s,t)=>t.preventDefault();Pb.drop=(s,t)=>{try{IHs(s,t,s.dragging)}finally{s.dragging=null}};function IHs(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(ILe(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",p=>{i=p(i,s,!1)}):i=k$t(s,D$t(t.dataTransfer),Ate?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&F$t(s,t));if(s.someProp("handleDrop",p=>p(s,t,i||Ii.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?JBt(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:p}=n;p?p.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let m=c.doc.resolve(d);if(u&&pl.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new pl(m));else{let p=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((f,g,v,y)=>p=y),c.setSelection(ntt(s,m,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}Mb.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())&&aE(s)},20))};Mb.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)};Mb.beforeinput=(s,t)=>{if(gv&&zA&&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,lF(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 Pb)Mb[s]=Pb[s];function Tte(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 JAe{constructor(t,n){this.toDOM=t,this.spec=n||A7,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 fb(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof JAe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&Tte(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class jP{constructor(t,n){this.attrs=t,this.spec=n||A7}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 fb(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==r1||t.maps.length==0?this:this.mapInner(t,n,0,0,r||A7)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=z$t(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 jP){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,A7));return I6.from(r)}forChild(t,n){if(n.isLeaf)return Nx.empty;let r=[];for(let a=0;an instanceof Nx)?t:t.reduce((n,r)=>n.concat(r instanceof Nx?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let v=g-f-(p-m);for(let y=0;yb+u-h)continue;let w=o[y]+u-h;p>=w?o[y+1]=m<=w?-2:-1:m>=u&&v&&(o[y]+=v,o[y+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 m=n.map(s[d+1]+i,-1),p=m-a,{index:f,offset:g}=r.content.findIndex(h),v=r.maybeChild(f);if(v&&g==h&&g+v.nodeSize==p){let y=o[d+2].mapInner(n,v,u+1,s[d]+i+1,l);y!=r1?(o[d]=h,o[d+1]=p,o[d+2]=y):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=RHs(o,s,t,n,a,i,l),u=eEe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=z$t(s,o,c+n);if(d){i=!0;let u=eEe(d,o,n+c+1,r);u!=r1&&a.push(c,c+o.nodeSize,u)}});let l=O$t(i?B$t(s):s,-n).sort(E7);for(let o=0;o0;)t++;s.splice(t,0,n)}function F7e(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=r1&&t.push(r)}),s.cursorWrapper&&t.push(Nx.create(s.state.doc,[s.cursorWrapper.deco])),I6.from(t)}const FHs={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},OHs=$_&&_P<=11;class zHs{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 BHs{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new zHs,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():b1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),OHs&&(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,FHs)),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(Iyt(this.view)){if(this.suppressingSelectionUpdates)return aE(this.view);if($_&&_P<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&d9(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=VH(i))n.add(i);for(let i=t.anchorNode;i;i=VH(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)&&Iyt(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(NN&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,m]=u;h.parentNode&&h.parentNode.parentNode==m.parentNode?m.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let m of u){let p=m.parentNode;p&&p.nodeName=="LI"&&(!h||qHs(t,h)!=p)&&m.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),$Hs(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,VHs(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||aE(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 y=r.childNodes[v-1],b=y.pmViewDesc;if(y.nodeName=="BR"&&!b){i=v;break}if(!b||b.size)break}let h=s.state.doc,m=s.someProp("domParser")||$J.fromSchema(s.state.schema),p=h.resolve(l),f=null,g=m.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:a,to:i,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:GHs,context:p});if(d&&d[0].pos!=null){let v=d[0].pos,y=d[1]&&d[1].pos;y==null&&(y=v),f={anchor:v+l,head:y+l}}return{doc:g,sel:f,from:l,to:o}}function GHs(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(b1&&/^(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||b1&&/^(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 WHs=/^(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 KHs(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let P=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,M=stt(s,P);if(M&&!s.state.selection.eq(M)){if(gv&&zA&&s.input.lastKeyCode===13&&Date.now()-100D(s,lF(13,"Enter"))))return;let I=s.state.tr.setSelection(M);P=="pointer"?I.setMeta("pointer",!0):P=="key"&&I.scrollIntoView(),i&&I.setMeta("composition",i),s.dispatch(I)}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=HHs(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),m,p;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||zA)&&a.some(P=>P.nodeType==1&&!WHs.test(P.nodeName))&&(!f||f.endA>=f.endB)&&s.someProp("handleKeyDown",P=>P(s,lF(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!f)if(r&&c instanceof Nl&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))f={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let P=Gyt(s,s.state.doc,d.sel);if(P&&!P.eq(s.state.selection)){let M=s.state.tr.setSelection(P);i&&M.setMeta("composition",i),s.dispatch(M)}}return}s.state.selection.froms.state.selection.from&&f.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?f.start=s.state.selection.from:f.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(f.endB+=s.state.selection.to-f.endA,f.endA=s.state.selection.to)),$_&&_P<=11&&f.endB==f.start+1&&f.endA==f.start&&f.start>d.from&&d.doc.textBetween(f.start-d.from-1,f.start-d.from+1)=="  "&&(f.start--,f.endA--,f.endB--);let g=d.doc.resolveNoCache(f.start-d.from),v=d.doc.resolveNoCache(f.endB-d.from),y=u.resolve(f.start),b=g.sameParent(v)&&g.parent.inlineContent&&y.end()>=f.endA;if((HH&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(P=>P.nodeName=="DIV"||P.nodeName=="P"))||!b&&g.posP(s,lF(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>f.start&&ZHs(u,f.start,f.endA,g,v)&&s.someProp("handleKeyDown",P=>P(s,lF(8,"Backspace")))){zA&&gv&&s.domObserver.suppressSelectionUpdates();return}gv&&f.endB==f.start&&(s.input.lastChromeDelete=Date.now()),zA&&!b&&g.start()!=v.start()&&v.parentOffset==0&&g.depth==v.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==f.endA&&(f.endB-=2,v=d.doc.resolveNoCache(f.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(P){return P(s,lF(13,"Enter"))})},20));let w=f.start,S=f.endA,C=P=>{let M=P||s.state.tr.replace(w,S,d.doc.slice(f.start-d.from,f.endB-d.from));if(d.sel){let I=Gyt(s,M.doc,d.sel);I&&!(gv&&s.composing&&I.empty&&(f.start!=f.endB||s.input.lastChromeDeleteaE(s),20));let P=C(s.state.tr.delete(w,S)),M=u.resolve(f.start).marksAcross(u.resolve(f.endA));M&&P.ensureMarks(M),s.dispatch(P)}else if(f.endA==f.endB&&(E=YHs(g.parent.content.cut(g.parentOffset,v.parentOffset),y.parent.content.cut(y.parentOffset,f.endA-y.start())))){let P=C(s.state.tr);E.type=="add"?P.addMark(w,S,E.mark):P.removeMark(w,S,E.mark),s.dispatch(P)}else if(g.parent.child(g.index()).isText&&g.index()==v.index()-(v.textOffset?0:1)){let P=g.parent.textBetween(g.parentOffset,v.parentOffset),M=()=>C(s.state.tr.insertText(P,w,S));s.someProp("handleTextInput",I=>I(s,w,S,P,M))||s.dispatch(M())}else s.dispatch(C());else s.dispatch(C())}function Gyt(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:ntt(s,t.resolve(n.anchor),t.resolve(n.head))}function YHs(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||O7e(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 XHs(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 $$t{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 mHs,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Qyt),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=Zyt(this),Yyt(this),this.nodeViews=Xyt(this),this.docView=Ayt(this.state.doc,Kyt(this),F7e(this),this.dom,this),this.domObserver=new BHs(this,(r,a,i,l)=>KHs(this,r,a,i,l)),this.domObserver.start(),pHs(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&&xHe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(Qyt),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&&(I$t(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=Xyt(this);JHs(p,this.nodeViews)&&(this.nodeViews=p,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&xHe(this),this.editable=Zyt(this),Yyt(this);let c=F7e(this),d=Kyt(this),u=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",h=i||!this.docView.matchesNode(t.doc,d,c);(h||!t.selection.eq(a.selection))&&(l=!0);let m=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&AVs(this);if(l){this.domObserver.stop();let p=h&&($_||gv)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&QHs(a.selection,t.selection);if(h){let f=gv?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=AHs(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Ayt(t.doc,d,c,this.dom,this)),f&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&QVs(this))?aE(this,p):(w$t(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():m&&EVs(m)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof pl){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&wyt(this,n.getBoundingClientRect(),t)}else wyt(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 DVs(this,t)}coordsAtPos(t,n=1){return p$t(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 BVs(this,n||this.state,t)}pasteHTML(t,n){return Ete(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return Ete(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return rtt(this,t)}destroy(){this.docView&&(fHs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],F7e(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,yVs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return gHs(this,t)}domSelectionRange(){let t=this.domSelection();return t?b1&&this.root.nodeType===11&&jVs(this.dom.ownerDocument)==this.dom&&UHs(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}$$t.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function Kyt(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"),[fb.node(0,s.state.doc.content.size,t)]}function Yyt(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:fb.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function Zyt(s){return!s.someProp("editable",t=>t(s.state)===!1)}function QHs(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 Xyt(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 JHs(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 Qyt(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 ZP={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:"'"},tEe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},eGs=typeof navigator<"u"&&/Mac/.test(navigator.platform),tGs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var uv=0;uv<10;uv++)ZP[48+uv]=ZP[96+uv]=String(uv);for(var uv=1;uv<=24;uv++)ZP[uv+111]="F"+uv;for(var uv=65;uv<=90;uv++)ZP[uv]=String.fromCharCode(uv+32),tEe[uv]=String.fromCharCode(uv);for(var z7e in ZP)tEe.hasOwnProperty(z7e)||(tEe[z7e]=ZP[z7e]);function sGs(s){var t=eGs&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||tGs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?tEe:ZP)[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 nGs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),rGs=typeof navigator<"u"&&/Win/.test(navigator.platform);function aGs(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 U$t(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const cGs=(s,t,n)=>{let r=U$t(s,n);if(!r)return!1;let a=utt(r);if(!a){let l=r.blockRange(),o=l&&EW(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(G$t(s,a,t,-1))return!0;if(r.parent.content.size==0&&(GH(i,"end")||pl.isSelectable(i)))for(let l=r.depth;;l--){let o=TLe(s.doc,r.before(l),r.after(l),Ii.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==r.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},dGs=(s,t,n)=>{let r=U$t(s,n);if(!r)return!1;let a=utt(r);return a?q$t(s,a,t):!1},uGs=(s,t,n)=>{let r=V$t(s,n);if(!r)return!1;let a=htt(r);return a?q$t(s,a,t):!1};function q$t(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=TLe(s.doc,i,c,Ii.empty);if(!d||d.from!=i||d instanceof Ig&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Nl.create(u.doc,i)),n(u.scrollIntoView())}return!0}function GH(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 hGs=(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=utt(r)}let l=i&&i.nodeBefore;return!l||!pl.isSelectable(l)?!1:(t&&t(s.tr.setSelection(pl.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function utt(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 V$t(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=V$t(s,n);if(!r)return!1;let a=htt(r);if(!a)return!1;let i=a.nodeAfter;if(G$t(s,a,t,1))return!0;if(r.parent.content.size==0&&(GH(i,"start")||pl.isSelectable(i))){let l=TLe(s.doc,r.before(),r.after(),Ii.empty);if(l&&l.slice.size{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",s):r.parentOffset=0;t--){let n=s.node(t);if(s.index(t)+1{let n=s.selection,r=n instanceof pl,a;if(r){if(n.node.isTextblock||!kL(s.doc,n.from))return!1;a=n.from}else if(a=ELe(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(pl.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},xGs=(s,t)=>{let n=s.selection,r;if(n instanceof pl){if(n.node.isTextblock||!kL(s.doc,n.to))return!1;r=n.to}else if(r=ELe(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},gGs=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&EW(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},yGs=(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 H$t(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=H$t(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(Zl.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},bGs=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof jN||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=H$t(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(Dq(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&EW(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},wGs=(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(pl.create(s.doc,a))),!0)};function jGs(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||kL(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function G$t(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&jGs(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let p=t.pos+i.nodeSize,f=Ya.empty;for(let y=l.length-1;y>=0;y--)f=Ya.from(l[y].create(null,f));f=Ya.from(a.copy(f));let g=s.tr.step(new E0(t.pos-1,p,t.pos,p,new Ii(f,1,0),l.length,!0)),v=g.doc.resolve(p+2*l.length);v.nodeAfter&&v.nodeAfter.type==a.type&&kL(g.doc,v.pos)&&g.join(v.pos),n(g.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:Zl.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&EW(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&GH(i,"start",!0)&&GH(a,"end")){let p=a,f=[];for(;f.push(p),!p.isTextblock;)p=p.lastChild;let g=i,v=1;for(;!g.isTextblock;g=g.firstChild)v++;if(p.canReplace(p.childCount,p.childCount,g.content)){if(n){let y=Ya.empty;for(let w=f.length-1;w>=0;w--)y=Ya.from(f[w].copy(y));let b=s.tr.step(new E0(t.pos-f.length,t.pos+i.nodeSize,t.pos+v,t.pos+i.nodeSize-v,new Ii(y,f.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function W$t(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(Nl.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const NGs=W$t(-1),kGs=W$t(1);function SGs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&Qet(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function Jyt(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 KAe(c,c,t.depth),t.endIndex=0;u--)i=Ya.from(n[u].type.create(n[u].attrs,i));s.step(new E0(t.start-(r?2:0),t.end,t.start,t.end,new Ii(i,0,0),n.length,!0));let l=0;for(let u=0;ul.childCount>0&&l.firstChild.type==s);return i?n?r.node(i.depth-1).type==s?MGs(t,n,s,i):PGs(t,n,i):!0:!1}}function MGs(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);ig;f--)p-=a.child(f).nodeSize,r.delete(p-1,p+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Ya.empty:Ya.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new E0(h-(o?1:0),m+(c?1:0),h+1,m-1,new Ii((o?Ya.empty:Ya.from(a.copy(Ya.empty))).append(c?Ya.empty:Ya.from(a.copy(Ya.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function LGs(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=Ya.from(d?s.create():null),h=new Ii(Ya.from(s.create(null,Ya.from(o.type.create(null,u)))),d?3:1,0),m=i.start,p=i.end;n(t.tr.step(new E0(m-(d?3:1),p,m,p,h,1,!0)).scrollIntoView())}return!0}}function DLe(s){const{state:t,transaction:n}=s;let{selection:r}=n,{doc:a}=n,{storedMarks:i}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,i=n.storedMarks,n}}}let RLe=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(m=>m===!0)),h={...Object.fromEntries(Object.entries(r).map(([m,p])=>[m,(...g)=>{const v=this.buildProps(d,n),y=p(...g)(v);return o.push(y),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:DLe({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}},IGs=class{constructor(){this.callbacks={}}on(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),this}emit(t,...n){const r=this.callbacks[t];return r&&r.forEach(a=>a.apply(this,n)),this}off(t,n){const r=this.callbacks[t];return r&&(n?this.callbacks[t]=r.filter(a=>a!==n):delete this.callbacks[t]),this}once(t,n){const r=(...a)=>{this.off(t,r),n.apply(this,a)};return this.on(t,r)}removeAllListeners(){this.callbacks={}}};function So(s,t,n){return s.config[t]===void 0&&s.parent?So(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?So(s.parent,t,n):null}):s.config[t]}function FLe(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 K$t(s){const t=[],{nodeExtensions:n,markExtensions:r}=FLe(s),a=[...n,...r],i={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return s.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage,extensions:a},c=So(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,p])=>{t.push({type:h,name:m,attribute:{...i,...p}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=So(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const m={...i,...h};typeof(m==null?void 0:m.default)=="function"&&(m.default=m.default()),m!=null&&m.isRequired&&(m==null?void 0:m.default)===void 0&&delete m.default,t.push({type:l.name,name:u,attribute:m})})}),t}function M0(s,t){if(typeof s=="string"){if(!t.nodes[s])throw Error(`There is no node type named '${s}'. Maybe you forgot to add the extension?`);return t.nodes[s]}return s}function cp(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function gHe(s,t){return t.filter(n=>n.type===s.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(s.attrs)||{}:{[n.name]:s.attrs[n.name]}).reduce((n,r)=>cp(n,r),{})}function Y$t(s){return typeof s=="function"}function Vc(s,t=void 0,...n){return Y$t(s)?t?s.bind(t)(...n):s(...n):s}function DGs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function RGs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function e0t(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):RGs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function t0t(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&DGs(n)?!1:n!=null))}function FGs(s,t){var n;const r=K$t(s),{nodeExtensions:a,markExtensions:i}=FLe(s),l=(n=a.find(d=>So(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(y=>y.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((y,b)=>{const w=So(b,"extendNodeSchema",h);return{...y,...w?w(d):{}}},{}),p=t0t({...m,content:Vc(So(d,"content",h)),marks:Vc(So(d,"marks",h)),group:Vc(So(d,"group",h)),inline:Vc(So(d,"inline",h)),atom:Vc(So(d,"atom",h)),selectable:Vc(So(d,"selectable",h)),draggable:Vc(So(d,"draggable",h)),code:Vc(So(d,"code",h)),whitespace:Vc(So(d,"whitespace",h)),linebreakReplacement:Vc(So(d,"linebreakReplacement",h)),defining:Vc(So(d,"defining",h)),isolating:Vc(So(d,"isolating",h)),attrs:Object.fromEntries(u.map(y=>{var b;return[y.name,{default:(b=y==null?void 0:y.attribute)===null||b===void 0?void 0:b.default}]}))}),f=Vc(So(d,"parseHTML",h));f&&(p.parseDOM=f.map(y=>e0t(y,u)));const g=So(d,"renderHTML",h);g&&(p.toDOM=y=>g({node:y,HTMLAttributes:gHe(y,u)}));const v=So(d,"renderText",h);return v&&(p.toText=v),[d.name,p]})),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},m=s.reduce((v,y)=>{const b=So(y,"extendMarkSchema",h);return{...v,...b?b(d):{}}},{}),p=t0t({...m,inclusive:Vc(So(d,"inclusive",h)),excludes:Vc(So(d,"excludes",h)),group:Vc(So(d,"group",h)),spanning:Vc(So(d,"spanning",h)),code:Vc(So(d,"code",h)),attrs:Object.fromEntries(u.map(v=>{var y;return[v.name,{default:(y=v==null?void 0:v.attribute)===null||y===void 0?void 0:y.default}]}))}),f=Vc(So(d,"parseHTML",h));f&&(p.parseDOM=f.map(v=>e0t(v,u)));const g=So(d,"renderHTML",h);return g&&(p.toDOM=v=>g({mark:v,HTMLAttributes:gHe(v,u)})),[d.name,p]}));return new UBt({topNode:l,nodes:o,marks:c})}function $7e(s,t){return t.nodes[s]||t.marks[s]||null}function s0t(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function mtt(s,t){const n=J9.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const OGs=(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 ptt(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class OLe{constructor(t){this.find=t.find,this.handler=t.handler}}const zGs=(s,t)=>{if(ptt(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 Zle(s){var t;const{editor:n,from:r,to:a,text:i,rules:l,plugin:o}=s,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(m=>m.type.spec.code))return!1;let u=!1;const h=OGs(d)+i;return l.forEach(m=>{if(u)return;const p=zGs(h,m.find);if(!p)return;const f=c.state.tr,g=DLe({state:c.state,transaction:f}),v={from:r-(p[0].length-i.length),to:a},{commands:y,chain:b,can:w}=new RLe({editor:n,state:g});m.handler({state:g,range:v,match:p,commands:y,chain:b,can:w})===null||!f.steps.length||(f.setMeta(o,{transform:f,from:r,to:a,text:i}),c.dispatch(f),u=!0)}),u}function BGs(s){const{editor:t,rules:n}=s,r=new By({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=mtt(Ya.from(u),l.schema);const{from:h}=c,m=h+u.length;Zle({editor:t,from:h,to:m,text:u,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return Zle({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&Zle({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?Zle({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function $Gs(s){return Object.prototype.toString.call(s).slice(8,-1)}function Xle(s){return $Gs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function zLe(s,t){const n={...s};return Xle(s)&&Xle(t)&&Object.keys(t).forEach(r=>{Xle(t[r])&&Xle(s[r])?n[r]=zLe(s[r],t[r]):n[r]=t[r]}),n}class LS{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=Vc(So(this,"addOptions",{name:this.name}))),this.storage=Vc(So(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new LS(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>zLe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new LS(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=Vc(So(n,"addOptions",{name:n.name})),n.storage=Vc(So(n,"addStorage",{name:n.name,options:n.options})),n}static handleExit({editor:t,mark:n}){const{tr:r}=t.state,a=t.state.selection.$from;if(a.pos===a.end()){const l=a.marks();if(!!!l.find(d=>(d==null?void 0:d.type.name)===n.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",a.pos),t.view.dispatch(r),!0}return!1}}function UGs(s){return typeof s=="number"}class Z$t{constructor(t){this.find=t.find,this.handler=t.handler}}const qGs=(s,t,n)=>{if(ptt(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 VGs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new RLe({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,f)=>{if(!p.isTextblock||p.type.spec.code)return;const g=Math.max(r,f),v=Math.min(a,f+p.content.size),y=p.textBetween(g-f,v-f,void 0,"");qGs(y,i.find,l).forEach(w=>{if(w.index===void 0)return;const S=g+w.index+1,C=S+w[0].length,E={from:n.tr.mapping.map(S),to:n.tr.mapping.map(C)},P=i.handler({state:n,range:E,match:w,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(P)})}),h.every(p=>p!==null)}let Qle=null;const HGs=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 GGs(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:p,pasteEvt:f})=>{const g=u.tr,v=DLe({state:u,transaction:g});if(!(!VGs({editor:t,state:v,from:Math.max(h-1,0),to:m.b-1,rule:p,pasteEvent:f,dropEvent:o})||!g.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,g}};return n.map(u=>new By({view(h){const m=f=>{var g;r=!((g=h.dom.parentElement)===null||g===void 0)&&g.contains(f.target)?h.dom.parentElement:null,r&&(Qle=t)},p=()=>{Qle&&(Qle=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(i=r===h.dom.parentElement,o=m,!i){const p=Qle;p!=null&&p.isEditable&&setTimeout(()=>{const f=p.state.selection;f&&p.commands.deleteRange({from:f.from,to:f.to})},10)}return!1},paste:(h,m)=>{var p;const f=(p=m.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return l=m,a=!!(f!=null&&f.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,p)=>{const f=h[0],g=f.getMeta("uiEvent")==="paste"&&!a,v=f.getMeta("uiEvent")==="drop"&&!i,y=f.getMeta("applyPasteRules"),b=!!y;if(!g&&!v&&!b)return;if(b){let{text:C}=y;typeof C=="string"?C=C:C=mtt(Ya.from(C),p.schema);const{from:E}=y,P=E+C.length,M=HGs(C);return c({rule:u,state:p,from:E,to:{b:P},pasteEvt:M})}const w=m.doc.content.findDiffStart(p.doc.content),S=m.doc.content.findDiffEnd(p.doc.content);if(!(!UGs(w)||!S||w===S.b))return c({rule:u,state:p,from:w,to:S,pasteEvt:l})}}))}function WGs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class dU{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=dU.resolve(t),this.schema=FGs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=dU.sort(dU.flatten(t)),r=WGs(n.map(a=>a.name));return r.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${r.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),n}static flatten(t){return t.map(n=>{const r={name:n.name,options:n.options,storage:n.storage},a=So(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=So(r,"priority")||100,l=So(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:$7e(n.name,this.schema)},a=So(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=dU.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:$7e(l.name,this.schema)},c=[],d=So(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&So(l,"exitable",o)&&(u.ArrowRight=()=>LS.handleExit({editor:t,mark:l})),d){const g=Object.fromEntries(Object.entries(d()).map(([v,y])=>[v,()=>y({editor:t})]));u={...u,...g}}const h=oGs(u);c.push(h);const m=So(l,"addInputRules",o);s0t(l,t.options.enableInputRules)&&m&&r.push(...m());const p=So(l,"addPasteRules",o);s0t(l,t.options.enablePasteRules)&&p&&a.push(...p());const f=So(l,"addProseMirrorPlugins",o);if(f){const g=f();c.push(...g)}return c}).flat();return[BGs({editor:t,rules:r}),...GGs({editor:t,rules:a}),...i]}get attributes(){return K$t(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=FLe(this.extensions);return Object.fromEntries(n.filter(r=>!!So(r,"addNodeView")).map(r=>{const a=this.attributes.filter(c=>c.type===r.name),i={name:r.name,options:r.options,storage:r.storage,editor:t,type:M0(r.name,this.schema)},l=So(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const p=gHe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:r,HTMLAttributes:p})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:$7e(t.name,this.schema)};t.type==="mark"&&(!((n=Vc(So(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=So(t,"onBeforeCreate",r),i=So(t,"onCreate",r),l=So(t,"onUpdate",r),o=So(t,"onSelectionUpdate",r),c=So(t,"onTransaction",r),d=So(t,"onFocus",r),u=So(t,"onBlur",r),h=So(t,"onDestroy",r);a&&this.editor.on("beforeCreate",a),i&&this.editor.on("create",i),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),h&&this.editor.on("destroy",h)})}}class Tv{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=Vc(So(this,"addOptions",{name:this.name}))),this.storage=Vc(So(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Tv(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>zLe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Tv({...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=Vc(So(n,"addOptions",{name:n.name})),n.storage=Vc(So(n,"addStorage",{name:n.name,options:n.options})),n}}function X$t(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var m;c.isBlock&&d>r&&(o+=i);const p=l==null?void 0:l[c.type.name];if(p)return u&&(o+=p({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(m=c==null?void 0:c.text)===null||m===void 0?void 0:m.slice(Math.max(r,d)-d,a-d))}),o}function Q$t(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const KGs=Tv.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new By({key:new k1("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=Q$t(n);return X$t(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),YGs=()=>({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),ZGs=(s=!1)=>({commands:t})=>t.setContent("",s),XGs=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),p=h.blockRange(m);if(!p)return;const f=EW(p);if(o.type.isTextblock){const{defaultType:g}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(p.start,g)}(f||f===0)&&t.lift(p,f)})}),!0},QGs=s=>t=>s(t),JGs=()=>({state:s,dispatch:t})=>bGs(s,t),eWs=(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 Nl(r.doc.resolve(Math.max(l-1,0)))),!0},tWs=()=>({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},sWs=s=>({tr:t,state:n,dispatch:r})=>{const a=M0(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},nWs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},rWs=()=>({state:s,dispatch:t})=>lGs(s,t),aWs=()=>({commands:s})=>s.keyboardShortcut("Enter"),iWs=()=>({state:s,dispatch:t})=>vGs(s,t);function sEe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:ptt(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function J$t(s,t,n={}){return s.find(r=>r.type===t&&sEe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function n0t(s,t,n={}){return!!J$t(s,t,n)}function ftt(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),!J$t([...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&&n0t([...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=CL(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=ftt(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=Nl.create(l,h.from,h.to);n.setSelection(m)}}return!0},lWs=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=()=>{(nEe()||r0t())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),cWs()&&!nEe()&&!r0t()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!eUt(n.state.selection))return l(),!0;const o=tUt(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},uWs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),hWs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),sUt=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&&sUt(r)}return s};function Jle(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return sUt(n)}function Mte(s,t,n){if(s instanceof bP||s instanceof Ya)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 Ya.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),Mte("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new UBt({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?$J.fromSchema(c).parseSlice(Jle(s),n.parseOptions):$J.fromSchema(c).parse(Jle(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=$J.fromSchema(t);return n.slice?i.parseSlice(Jle(s),n.parseOptions).content:i.parse(Jle(s),n.parseOptions)}return Mte("",t,n)}function mWs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(Zl.near(s.doc.resolve(l),n))}const pWs=s=>!("type"in s),fWs=(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{Mte(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(v){c(v)}try{o=Mte(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},m=!0,p=!0;if((pWs(o)?o:[o]).forEach(v=>{v.check(),m=m?v.isText&&v.marks.length===0:!1,p=p?v.isBlock:!1}),u===h&&p){const{parent:v}=r.doc.resolve(u);v.isTextblock&&!v.type.spec.code&&!v.childCount&&(u-=1,h+=1)}let g;if(m){if(Array.isArray(t))g=t.map(v=>v.text||"").join("");else if(t instanceof Ya){let v="";t.forEach(y=>{y.text&&(v+=y.text)}),g=v}else typeof t=="object"&&t&&t.text?g=t.text:g=t;r.insertText(g,u,h)}else g=o,r.replaceWith(u,h,g);n.updateSelection&&mWs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:g}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:g})}return!0},xWs=()=>({state:s,dispatch:t})=>fGs(s,t),gWs=()=>({state:s,dispatch:t})=>xGs(s,t),yWs=()=>({state:s,dispatch:t})=>cGs(s,t),vWs=()=>({state:s,dispatch:t})=>mGs(s,t),bWs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=ELe(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},_Ws=()=>({state:s,dispatch:t,tr:n})=>{try{const r=ELe(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},wWs=()=>({state:s,dispatch:t})=>dGs(s,t),jWs=()=>({state:s,dispatch:t})=>uGs(s,t);function nUt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function NWs(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=NWs(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 Pte(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?M0(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const p=Math.max(r,m),f=Math.min(a,m+h.nodeSize);o.push({node:h,from:p,to:f})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>sEe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const SWs=(s,t={})=>({state:n,dispatch:r})=>{const a=M0(s,n.schema);return Pte(n,a,t)?gGs(n,r):!1},CWs=()=>({state:s,dispatch:t})=>_Gs(s,t),AWs=s=>({state:t,dispatch:n})=>{const r=M0(s,t.schema);return TGs(r)(t,n)},EWs=()=>({state:s,dispatch:t})=>yGs(s,t);function BLe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function a0t(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 TWs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=BLe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=M0(s,r.schema)),o==="mark"&&(l=CL(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,a0t(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(a0t(h.attrs,t)))})})}),!0):!1},MWs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),PWs=()=>({tr:s,dispatch:t})=>{if(t){const n=new jN(s.doc);s.setSelection(n)}return!0},LWs=()=>({state:s,dispatch:t})=>hGs(s,t),IWs=()=>({state:s,dispatch:t})=>pGs(s,t),DWs=()=>({state:s,dispatch:t})=>wGs(s,t),RWs=()=>({state:s,dispatch:t})=>kGs(s,t),FWs=()=>({state:s,dispatch:t})=>NGs(s,t);function yHe(s,t,n={},r={}){return Mte(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const OWs=(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=yHe(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 rUt(s,t){const n=CL(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 zWs(s,t){const n=new Jet(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function BWs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function aUt(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 xtt(s){return t=>aUt(t.$from,s)}function UWs(s,t){const n={from:0,to:s.content.size};return X$t(s,n,t)}function qWs(s,t){const n=M0(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 iUt(s,t){const n=BLe(typeof t=="string"?t:t.name,s.schema);return n==="node"?qWs(s,t):n==="mark"?rUt(s,t):{}}function VWs(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 HWs(s){const t=VWs(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 GWs(s){const{mapping:t,steps:n}=s,r=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=n[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),u=t.slice(i).map(c),h=t.invert().map(d,-1),m=t.invert().map(u);r.push({oldRange:{from:h,to:m},newRange:{from:d,to:u}})})}),HWs(r)}function gtt(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=ftt(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 X4e(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 vHe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?CL(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>sEe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const p=h.pos,f=m.pos;s.doc.nodesBetween(p,f,(g,v)=>{if(!g.isText&&!g.marks.length)return;const y=Math.max(p,v),b=Math.min(f,v+g.nodeSize),w=b-y;l+=w,o.push(...g.marks.map(S=>({mark:S,from:y,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>sEe(h.mark.attrs,n,{strict:!1})).reduce((h,m)=>h+m.to-m.from,0),d=o.filter(h=>i?h.mark.type!==i&&h.mark.type.excludes(i):!0).reduce((h,m)=>h+m.to-m.from,0);return(c>0?c+d:c)>=l}function WWs(s,t,n={}){if(!t)return Pte(s,null,n)||vHe(s,null,n);const r=BLe(t,s.schema);return r==="node"?Pte(s,t,n):r==="mark"?vHe(s,t,n):!1}function i0t(s,t){const{nodeExtensions:n}=FLe(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=Vc(So(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function ytt(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&&(ytt(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function KWs(s){return s instanceof pl}function YWs(s,t,n){var r;const{selection:a}=t;let i=null;if(eUt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const p=!m||m.type.allowsMarkType(n),f=!!n.isInSet(u.marks)||!u.marks.some(g=>g.type.excludes(n));d=p&&f}return!d}),d})}const ZWs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=CL(s,r.schema);if(a)if(l){const d=rUt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,p)=>{const f=Math.max(p,u),g=Math.min(p+m.nodeSize,h);m.marks.find(y=>y.type===c)?m.marks.forEach(y=>{c===y.type&&n.addMark(f,g,c.create({...y.attrs,...t}))}):n.addMark(f,g,c.create(t))})});return YWs(r,n,c)},XWs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),QWs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=M0(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})=>Jyt(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>Jyt(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},JWs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=CF(s,0,r.content.size),i=pl.create(r,a);t.setSelection(i)}return!0},eKs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Nl.atStart(r).from,o=Nl.atEnd(r).to,c=CF(a,l,o),d=CF(i,l,o),u=Nl.create(r,c,d);t.setSelection(u)}return!0},tKs=s=>({state:t,dispatch:n})=>{const r=M0(s,t.schema);return LGs(r)(t,n)};function o0t(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 sKs=({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=X4e(d,o.node().type.name,o.node().attrs);if(i instanceof pl&&i.node.isBlock)return!o.parentOffset||!Dq(l,o.pos)?!1:(r&&(s&&o0t(n,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,m=o.depth===0?void 0:BWs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let p=h&&m?[{type:m,attrs:u}]:void 0,f=Dq(t.doc,t.mapping.map(o.pos),1,p);if(!p&&!f&&Dq(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(f=!0,p=m?[{type:m,attrs:u}]:void 0),r){if(f&&(i instanceof Nl&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,p),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const g=t.mapping.map(o.before()),v=t.doc.resolve(g);o.node(-1).canReplaceWith(v.index(),v.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&o0t(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return f},nKs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=M0(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const m=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let y=Ya.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-b;M>=c.depth-3;M-=1)y=Ya.from(c.node(M).copy(y));const w=c.indexAfter(-1){if(P>-1)return!1;M.isTextblock&&M.content.size===0&&(P=I+1)}),P>-1&&n.setSelection(Nl.near(n.doc.resolve(P))),n.scrollIntoView()}return!0}const p=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,f={...X4e(m,h.type.name,h.attrs),...t},g={...X4e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const v=p?[{type:o,attrs:f},{type:p,attrs:g}]:[{type:o,attrs:f}];if(!Dq(n.doc,c.pos,2))return!1;if(a){const{selection:y,storedMarks:b}=r,{splittableMarks:w}=i.extensionManager,S=b||y.$to.parentOffset&&y.$from.marks();if(n.split(c.pos,2,v).scrollIntoView(),!S||!a)return!0;const C=S.filter(E=>w.includes(E.type.name));n.ensureMarks(C)}return!0},U7e=(s,t)=>{const n=xtt(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)&&kL(s.doc,n.pos)&&s.join(n.pos),!0},q7e=(s,t)=>{const n=xtt(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)&&kL(s.doc,r)&&s.join(r),!0},rKs=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:m}=a.extensionManager,p=M0(s,l.schema),f=M0(t,l.schema),{selection:g,storedMarks:v}=l,{$from:y,$to:b}=g,w=y.blockRange(b),S=v||g.$to.parentOffset&&g.$from.marks();if(!w)return!1;const C=xtt(E=>i0t(E.type.name,h))(g);if(w.depth>=1&&C&&w.depth-C.depth<=1){if(C.node.type===p)return d.liftListItem(f);if(i0t(C.node.type.name,h)&&p.validContent(C.node.content)&&o)return c().command(()=>(i.setNodeMarkup(C.pos,p),!0)).command(()=>U7e(i,p)).command(()=>q7e(i,p)).run()}return!n||!S||!o?c().command(()=>u().wrapInList(p,r)?!0:d.clearNodes()).wrapInList(p,r).command(()=>U7e(i,p)).command(()=>q7e(i,p)).run():c().command(()=>{const E=u().wrapInList(p,r),P=S.filter(M=>m.includes(M.type.name));return i.ensureMarks(P),E?!0:d.clearNodes()}).wrapInList(p,r).command(()=>U7e(i,p)).command(()=>q7e(i,p)).run()},aKs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=CL(s,r.schema);return vHe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},iKs=(s,t,n={})=>({state:r,commands:a})=>{const i=M0(s,r.schema),l=M0(t,r.schema),o=Pte(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})},oKs=(s,t={})=>({state:n,commands:r})=>{const a=M0(s,n.schema);return Pte(n,a,t)?r.lift(a):r.wrapIn(a,t)},lKs=()=>({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},cKs=()=>({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},dKs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=CL(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:p}=o;const f=(i=d.marks().find(v=>v.type===c))===null||i===void 0?void 0:i.attrs,g=ftt(d,c,f);g&&(m=g.from,p=g.to),n.removeMark(m,p,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},uKs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=BLe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=M0(s,r.schema)),o==="mark"&&(l=CL(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,p,f;n.selection.empty?r.doc.nodesBetween(d,u,(g,v)=>{i&&i===g.type&&(p=Math.max(v,d),f=Math.min(v+g.nodeSize,u),h=v,m=g)}):r.doc.nodesBetween(d,u,(g,v)=>{v=d&&v<=u&&(i&&i===g.type&&n.setNodeMarkup(v,void 0,{...g.attrs,...t}),l&&g.marks.length&&g.marks.forEach(y=>{if(l===y.type){const b=Math.max(v,d),w=Math.min(v+g.nodeSize,u);n.addMark(b,w,l.create({...y.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(g=>{l===g.type&&n.addMark(p,f,l.create({...g.attrs,...t}))}))}),!0):!1},hKs=(s,t={})=>({state:n,dispatch:r})=>{const a=M0(s,n.schema);return SGs(a,t)(n,r)},mKs=(s,t={})=>({state:n,dispatch:r})=>{const a=M0(s,n.schema);return CGs(a,t)(n,r)};var pKs=Object.freeze({__proto__:null,blur:YGs,clearContent:ZGs,clearNodes:XGs,command:QGs,createParagraphNear:JGs,cut:eWs,deleteCurrentNode:tWs,deleteNode:sWs,deleteRange:nWs,deleteSelection:rWs,enter:aWs,exitCode:iWs,extendMarkRange:oWs,first:lWs,focus:dWs,forEach:uWs,insertContent:hWs,insertContentAt:fWs,joinBackward:yWs,joinDown:gWs,joinForward:vWs,joinItemBackward:bWs,joinItemForward:_Ws,joinTextblockBackward:wWs,joinTextblockForward:jWs,joinUp:xWs,keyboardShortcut:kWs,lift:SWs,liftEmptyBlock:CWs,liftListItem:AWs,newlineInCode:EWs,resetAttributes:TWs,scrollIntoView:MWs,selectAll:PWs,selectNodeBackward:LWs,selectNodeForward:IWs,selectParentNode:DWs,selectTextblockEnd:RWs,selectTextblockStart:FWs,setContent:OWs,setMark:ZWs,setMeta:XWs,setNode:QWs,setNodeSelection:JWs,setTextSelection:eKs,sinkListItem:tKs,splitBlock:sKs,splitListItem:nKs,toggleList:rKs,toggleMark:aKs,toggleNode:iKs,toggleWrap:oKs,undoInputRule:lKs,unsetAllMarks:cKs,unsetMark:dKs,updateAttributes:uKs,wrapIn:hKs,wrapInList:mKs});const fKs=Tv.create({name:"commands",addCommands(){return{...pKs}}}),xKs=Tv.create({name:"drop",addProseMirrorPlugins(){return[new By({key:new k1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),gKs=Tv.create({name:"editable",addProseMirrorPlugins(){return[new By({key:new k1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),yKs=new k1("focusEvents"),vKs=Tv.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new By({key:yKs,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}}}})]}}),bKs=Tv.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:p}=h,f=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,g=f.parent.type.spec.isolating,v=h.pos-h.parentOffset,y=g&&f.parent.childCount===1?v===h.pos:Zl.atStart(d).from===m;return!u||!p.type.isTextblock||p.textContent.length||!y||y&&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 nEe()||nUt()?i:a},addProseMirrorPlugins(){return[new By({key:new k1("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(g=>g.getMeta("composition")))return;const r=s.some(g=>g.docChanged)&&!t.doc.eq(n.doc),a=s.some(g=>g.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=Zl.atStart(t.doc).from,d=Zl.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!ytt(n.doc))return;const m=n.tr,p=DLe({state:n,transaction:m}),{commands:f}=new RLe({editor:this.editor,state:p});if(f.clearNodes(),!!m.steps.length)return m}})]}}),_Ks=Tv.create({name:"paste",addProseMirrorPlugins(){return[new By({key:new k1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),wKs=Tv.create({name:"tabindex",addProseMirrorPlugins(){return[new By({key:new k1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class cF{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 cF(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 cF(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 cF(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 cF(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new cF(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 jKs=`.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 NKs(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 kKs extends IGs{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=NKs(jKs,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=Y$t(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?[gKs,KGs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),fKs,vKs,bKs,wKs,xKs,_Ks].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 dU(a,this)}createCommandManager(){this.commandManager=new RLe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=yHe(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=yHe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=tUt(n,this.options.autofocus);this.view=new $$t(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:cU.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 iUt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return WWs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return mtt(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return UWs(this.state.doc,{blockSeparator:n,textSerializers:{...Q$t(this.schema),...r}})}get isEmpty(){return ytt(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 cF(n,this)}get $doc(){return this.$pos(0)}}function WH(s){return new OLe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Vc(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(gtt(n.from,n.to,t.doc).filter(p=>p.mark.type.excluded.find(g=>g===s.type&&g!==p.mark.type)).filter(p=>p.to>d).length)return null;un.from&&i.delete(n.from+c,d);const m=n.from+c+l.length;i.addMark(n.from+c,m,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function oUt(s){return new OLe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Vc(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 bHe(s){return new OLe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=Vc(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 Lte(s){return new OLe({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=Vc(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&Qet(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:p}=s.editor.extensionManager,f=m||h.$to.parentOffset&&h.$from.marks();if(f){const g=f.filter(v=>p.includes(v.type.name));l.ensureMarks(g)}}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&&kL(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let P0=class _He{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=Vc(So(this,"addOptions",{name:this.name}))),this.storage=Vc(So(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new _He(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>zLe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new _He(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=Vc(So(n,"addOptions",{name:n.name})),n.storage=Vc(So(n,"addStorage",{name:n.name,options:n.options})),n}};function h9(s){return new Z$t({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=Vc(s.getAttributes,void 0,r,a);if(i===!1||i===null)return null;const{tr:l}=t,o=r[r.length-1],c=r[0];let d=n.to;if(o){const u=c.search(/\S/),h=n.from+c.indexOf(o),m=h+o.length;if(gtt(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(v=>v===s.type&&v!==f.mark.type)).filter(f=>f.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function SKs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof pl){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 CKs(s){return new Z$t({find:s.find,handler({match:t,chain:n,range:r,pasteEvent:a}){const i=Vc(s.getAttributes,void 0,t,a),l=Vc(s.getContent,void 0,i);if(i===!1||i===null)return null;const o={type:s.type.name,attrs:i};l&&(o.content=l),t.input&&n().deleteRange(r).insertContentAt(r.from,o)}})}function AKs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var lUt={exports:{}},V7e={};/** * @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 l0t;function EKs(){if(l0t)return V7e;l0t=1;var s=Ft;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var p=m(),f=r({inst:{value:p,getSnapshot:m}}),g=f[0].inst,v=f[1];return i(function(){g.value=p,g.getSnapshot=m,c(g)&&v({inst:g})},[h,p,m]),a(function(){return c(g)&&v({inst:g}),h(function(){c(g)&&v({inst:g})})},[h]),l(p),p}function c(h){var m=h.getSnapshot;h=h.value;try{var p=m();return!n(h,p)}catch{return!0}}function d(h,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return V7e.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,V7e}lUt.exports=EKs();var vtt=lUt.exports;const TKs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},MKs=({contentComponent:s})=>{const t=vtt.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Ft.createElement(Ft.Fragment,null,Object.values(t))};function PKs(){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]:rQe.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 LKs extends Ft.Component{constructor(t){var n;super(t),this.editorContentRef=Ft.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=PKs(),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 Ft.createElement(Ft.Fragment,null,Ft.createElement("div",{ref:TKs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Ft.createElement(MKs,{contentComponent:t.contentComponent}))}}const IKs=_.forwardRef((s,t)=>{const n=Ft.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Ft.createElement(LKs,{key:n,innerRef:t,...s})}),$Le=Ft.memo(IKs);var DKs=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},RKs=AKs(DKs),cUt={exports:{}},H7e={};/** * @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 c0t;function FKs(){if(c0t)return H7e;c0t=1;var s=Ft,t=vtt;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 H7e.useSyncExternalStoreWithSelector=function(d,u,h,m,p){var f=i(null);if(f.current===null){var g={hasValue:!1,value:null};f.current=g}else g=f.current;f=o(function(){function y(E){if(!b){if(b=!0,w=E,E=m(E),p!==void 0&&g.hasValue){var P=g.value;if(p(P,E))return S=P}return S=E}if(P=S,r(w,E))return P;var M=m(E);return p!==void 0&&p(P,M)?P:(w=E,S=M)}var b=!1,w,S,C=h===void 0?null:h;return[function(){return y(u())},C===null?void 0:function(){return y(C())}]},[u,h,m,p]);var v=a(d,f[0],f[1]);return l(function(){g.hasValue=!0,g.value=v},[v]),c(v),v},H7e}cUt.exports=FKs();var OKs=cUt.exports;const zKs=typeof window<"u"?_.useLayoutEffect:_.useEffect;class BKs{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 $Ks(s){var t;const[n]=_.useState(()=>new BKs(s.editor)),r=OKs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:RKs);return zKs(()=>n.watch(s.editor),[s.editor,n]),_.useDebugValue(r),r}const UKs=!1,wHe=typeof window>"u",qKs=wHe||!!(typeof window<"u"&&window.next);class btt{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 wHe||qKs?null:this.createEditor();if(this.options.current.immediatelyRender&&wHe&&UKs)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 kKs(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?btt.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 ULe(s={},t=[]){const n=_.useRef(s);n.current=s;const[r]=_.useState(()=>new btt(n)),a=vtt.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return _.useDebugValue(a),_.useEffect(r.onRender(t)),$Ks({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const VKs=_.createContext({editor:null});VKs.Consumer;const HKs=_.createContext({onDragStart:void 0}),GKs=()=>_.useContext(HKs);Ft.forwardRef((s,t)=>{const{onDragStart:n}=GKs(),r=s.as||"div";return Ft.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const WKs=/^\s*>\s$/,KKs=P0.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setBlockquote:()=>({commands:s})=>s.wrapIn(this.name),toggleBlockquote:()=>({commands:s})=>s.toggleWrap(this.name),unsetBlockquote:()=>({commands:s})=>s.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[Lte({find:WKs,type:this.type})]}}),YKs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,ZKs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,XKs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,QKs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,JKs=LS.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:s=>s.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:s=>s.type.name===this.name},{style:"font-weight",getAttrs:s=>/^(bold(er)?|[5-9]\d{2,})$/.test(s)&&null}]},renderHTML({HTMLAttributes:s}){return["strong",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setBold:()=>({commands:s})=>s.setMark(this.name),toggleBold:()=>({commands:s})=>s.toggleMark(this.name),unsetBold:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[WH({find:YKs,type:this.type}),WH({find:XKs,type:this.type})]},addPasteRules(){return[h9({find:ZKs,type:this.type}),h9({find:QKs,type:this.type})]}}),eYs="listItem",d0t="textStyle",u0t=/^\s*([-+*])\s$/,tYs=P0.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:s}){return["ul",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{toggleBulletList:()=>({commands:s,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(eYs,this.editor.getAttributes(d0t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=Lte({find:u0t,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=Lte({find:u0t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(d0t),editor:this.editor})),[s]}}),sYs=/(^|[^`])`([^`]+)`(?!`)/,nYs=/(^|[^`])`([^`]+)`(?!`)/g,rYs=LS.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setCode:()=>({commands:s})=>s.setMark(this.name),toggleCode:()=>({commands:s})=>s.toggleMark(this.name),unsetCode:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[WH({find:sYs,type:this.type})]},addPasteRules(){return[h9({find:nYs,type:this.type})]}}),aYs=/^```([a-z]+)?[\s\n]$/,iYs=/^~~~([a-z]+)?[\s\n]$/,oYs=P0.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:s=>{var t;const{languageClassPrefix:n}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(n)).map(l=>l.replace(n,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",cp(this.options.HTMLAttributes,t),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},addCommands(){return{setCodeBlock:s=>({commands:t})=>t.setNode(this.name,s),toggleCodeBlock:s=>({commands:t})=>t.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!s||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:n}=t,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,l=r.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:n,doc:r}=t,{$from:a,empty:i}=n;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:r.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(Zl.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[bHe({find:aYs,type:this.type,getAttributes:s=>({language:s[1]})}),bHe({find:iYs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new By({key:new k1("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(Nl.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),lYs=P0.create({name:"doc",topNode:!0,content:"block+"});function cYs(s={}){return new By({view(t){return new dYs(t,s)}})}class dYs{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,m=t.nodeAfter;if(h||m){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let f=p.getBoundingClientRect(),g=h?f.bottom:f.top;h&&m&&(g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let v=this.width/2*o;r={left:f.left,right:f.right,top:g-v,bottom:g+v}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,p=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*p}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}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=JBt(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 uYs=Tv.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[cYs(this.options)]}});class kx extends Zl{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return kx.valid(r)?new kx(r):Zl.near(r)}content(){return Ii.empty}eq(t){return t instanceof kx&&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 kx(t.resolve(n.pos))}getBookmark(){return new _tt(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!hYs(t)||!mYs(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&&kx.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(kx.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!pl.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(kx.valid(o))return o}return null}}}kx.prototype.visible=!1;kx.findFrom=kx.findGapCursorFrom;Zl.jsonID("gapcursor",kx);class _tt{constructor(t){this.pos=t}map(t){return new _tt(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return kx.valid(n)?new kx(n):Zl.near(n)}}function dUt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function hYs(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||dUt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function mYs(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||dUt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function pYs(){return new By({props:{decorations:yYs,createSelectionBetween(s,t,n){return t.pos==n.pos&&kx.valid(n)?new kx(n):null},handleClick:xYs,handleKeyDown:fYs,handleDOMEvents:{beforeinput:gYs}}})}const fYs=dtt({ArrowLeft:ece("horiz",-1),ArrowRight:ece("horiz",1),ArrowUp:ece("vert",-1),ArrowDown:ece("vert",1)});function ece(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 Nl){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=kx.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new kx(d))),!0):!1}}function xYs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!kx.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&pl.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new kx(r))),!0)}function gYs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof kx))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=Ya.empty;for(let l=r.length-1;l>=0;l--)a=Ya.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new Ii(a,0,0));return i.setSelection(Nl.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function yYs(s){if(!(s.selection instanceof kx))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Nx.create(s.doc,[fb.widget(s.selection.head,t,{key:"gapcursor"})])}const vYs=Tv.create({name:"gapCursor",addProseMirrorPlugins(){return[pYs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Vc(So(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),bYs=P0.create({name:"hardBreak",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:s}){return["br",cp(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:n,editor:r})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=r.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(m=>o.includes(m.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),_Ys=P0.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(s=>({tag:`h${s}`,attrs:{level:s}}))},renderHTML({node:s,HTMLAttributes:t}){return[`h${this.options.levels.includes(s.attrs.level)?s.attrs.level:this.options.levels[0]}`,cp(this.options.HTMLAttributes,t),0]},addCommands(){return{setHeading:s=>({commands:t})=>this.options.levels.includes(s.level)?t.setNode(this.name,s):!1,toggleHeading:s=>({commands:t})=>this.options.levels.includes(s.level)?t.toggleNode(this.name,"paragraph",s):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((s,t)=>({...s,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(s=>bHe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var rEe=200,T0=function(){};T0.prototype.append=function(t){return t.length?(t=T0.from(t),!this.length&&t||t.length=n?T0.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};T0.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};T0.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)};T0.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};T0.from=function(t){return t instanceof T0?t:t&&t.length?new uUt(t):T0.empty};var uUt=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<=rEe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=rEe)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}(T0);T0.empty=new uUt([]);var wYs=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}(T0);const jYs=500;class oS{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,i;n&&(a=this.remapping(r,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],u=[];return this.items.forEach((h,m)=>{if(!h.step){a||(a=this.remapping(r,m+1),i=a.maps.length),i--,u.push(h);return}if(a){u.push(new TT(h.map));let p=h.step.map(a.slice(i)),f;p&&l.maybeStep(p).doc&&(f=l.mapping.maps[l.mapping.maps.length-1],d.push(new TT(f,void 0,void 0,d.length+u.length))),i--,f&&a.appendMap(f,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new oS(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;ukYs&&(o=NYs(o,d),l-=d),new oS(o.append(i),l)}remapping(t,n){let r=new Ste;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 oS(this.items.append(t.map(n=>new TT(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let p=i.getMirror(--c);if(p==null)return;l=Math.min(l,p);let f=i.maps[p];if(m.step){let g=t.steps[p].invert(t.docs[p]),v=m.selection&&m.selection.map(i.slice(c+1,p));v&&o++,r.push(new TT(f,g,v))}else r.push(new TT(f))},a);let d=[];for(let m=n;mjYs&&(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 TT(d.invert(),c,u),m,p=a.length-1;(m=a.length&&a[p].merge(h))?a[p]=m:a.push(h)}}else l.map&&r--},this.items.length,0),new oS(T0.from(a.reverse()),i)}}oS.empty=new oS(T0.empty,0);function NYs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let TT=class hUt{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 hUt(n.getMap().invert(),n,this.selection)}}};class w6{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const kYs=20;function SYs(s,t,n,r){let a=n.getMeta(T7),i;if(a)return a.historyState;n.getMeta(EYs)&&(s=new w6(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(T7))return l.getMeta(T7).redo?new w6(s.done.addTransform(n,void 0,r,Q4e(t)),s.undone,h0t(n.mapping.maps),s.prevTime,s.prevComposition):new w6(s.done,s.undone.addTransform(n,void 0,r,Q4e(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||!CYs(n,s.prevRanges)),d=l?G7e(s.prevRanges,n.mapping):h0t(n.mapping.maps);return new w6(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,Q4e(t)),oS.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new w6(s.done.rebased(n,i),s.undone.rebased(n,i),G7e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new w6(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),G7e(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function CYs(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 h0t(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 G7e(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=T7.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=AYs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const pUt=mUt(!1,!0),fUt=mUt(!0,!0),MYs=Tv.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>pUt(s,t),redo:()=>({state:s,dispatch:t})=>fUt(s,t)}},addProseMirrorPlugins(){return[TYs(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()}}}),PYs=P0.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",cp(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!SKs(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}):KWs(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(Nl.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(pl.create(l.doc,d.pos)):l.setSelection(Nl.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(Nl.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[oUt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),LYs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,IYs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,DYs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,RYs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,FYs=LS.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:s=>s.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:s=>s.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:s}){return["em",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setItalic:()=>({commands:s})=>s.setMark(this.name),toggleItalic:()=>({commands:s})=>s.toggleMark(this.name),unsetItalic:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[WH({find:LYs,type:this.type}),WH({find:DYs,type:this.type})]},addPasteRules(){return[h9({find:IYs,type:this.type}),h9({find:RYs,type:this.type})]}}),OYs=P0.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",cp(this.options.HTMLAttributes,s),0]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),zYs="listItem",p0t="textStyle",f0t=/^(\d+)\.\s$/,BYs=P0.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:t,...n}=s;return t===1?["ol",cp(this.options.HTMLAttributes,n),0]:["ol",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{toggleOrderedList:()=>({commands:s,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(zYs,this.editor.getAttributes(p0t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=Lte({find:f0t,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=Lte({find:f0t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(p0t)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),$Ys=P0.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),UYs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,qYs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,VYs=LS.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["s",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setStrike:()=>({commands:s})=>s.setMark(this.name),toggleStrike:()=>({commands:s})=>s.toggleMark(this.name),unsetStrike:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[WH({find:UYs,type:this.type})]},addPasteRules(){return[h9({find:qYs,type:this.type})]}}),HYs=P0.create({name:"text",group:"inline"}),qLe=Tv.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(JKs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(KKs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(tYs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(rYs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(oYs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(lYs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(uYs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(vYs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(bYs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(_Ys.configure(this.options.heading)),this.options.history!==!1&&s.push(MYs.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(PYs.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(FYs.configure(this.options.italic)),this.options.listItem!==!1&&s.push(OYs.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(BYs.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push($Ys.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(VYs.configure(this.options.strike)),this.options.text!==!1&&s.push(HYs.configure(this.options.text)),s}}),GYs="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",WYs="ελ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",jHe="numeric",NHe="ascii",kHe="alpha",HJ="asciinumeric",AX="alphanumeric",SHe="domain",xUt="emoji",KYs="scheme",YYs="slashscheme",K7e="whitespace";function ZYs(s,t){return s in t||(t[s]=[]),t[s]}function AF(s,t,n){t[jHe]&&(t[HJ]=!0,t[AX]=!0),t[NHe]&&(t[HJ]=!0,t[kHe]=!0),t[HJ]&&(t[AX]=!0),t[kHe]&&(t[AX]=!0),t[AX]&&(t[SHe]=!0),t[xUt]&&(t[SHe]=!0);for(const r in t){const a=ZYs(r,n);a.indexOf(s)<0&&a.push(s)}}function XYs(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function N_(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}N_.groups={};N_.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),px=(s,t,n,r,a)=>s.tr(t,n,r,a),x0t=(s,t,n,r,a)=>s.ts(t,n,r,a),si=(s,t,n,r,a)=>s.tt(t,n,r,a),O3="WORD",CHe="UWORD",gUt="ASCIINUMERICAL",yUt="ALPHANUMERICAL",Ite="LOCALHOST",AHe="TLD",EHe="UTLD",J4e="SCHEME",A$="SLASH_SCHEME",wtt="NUM",THe="WS",jtt="NL",GJ="OPENBRACE",WJ="CLOSEBRACE",aEe="OPENBRACKET",iEe="CLOSEBRACKET",oEe="OPENPAREN",lEe="CLOSEPAREN",cEe="OPENANGLEBRACKET",dEe="CLOSEANGLEBRACKET",uEe="FULLWIDTHLEFTPAREN",hEe="FULLWIDTHRIGHTPAREN",mEe="LEFTCORNERBRACKET",pEe="RIGHTCORNERBRACKET",fEe="LEFTWHITECORNERBRACKET",xEe="RIGHTWHITECORNERBRACKET",gEe="FULLWIDTHLESSTHAN",yEe="FULLWIDTHGREATERTHAN",vEe="AMPERSAND",bEe="APOSTROPHE",_Ee="ASTERISK",j6="AT",wEe="BACKSLASH",jEe="BACKTICK",NEe="CARET",D6="COLON",Ntt="COMMA",kEe="DOLLAR",V5="DOT",SEe="EQUALS",ktt="EXCLAMATION",D2="HYPHEN",KJ="PERCENT",CEe="PIPE",AEe="PLUS",EEe="POUND",YJ="QUERY",Stt="QUOTE",vUt="FULLWIDTHMIDDLEDOT",Ctt="SEMI",H5="SLASH",ZJ="TILDE",TEe="UNDERSCORE",bUt="EMOJI",MEe="SYM";var _Ut=Object.freeze({__proto__:null,ALPHANUMERICAL:yUt,AMPERSAND:vEe,APOSTROPHE:bEe,ASCIINUMERICAL:gUt,ASTERISK:_Ee,AT:j6,BACKSLASH:wEe,BACKTICK:jEe,CARET:NEe,CLOSEANGLEBRACKET:dEe,CLOSEBRACE:WJ,CLOSEBRACKET:iEe,CLOSEPAREN:lEe,COLON:D6,COMMA:Ntt,DOLLAR:kEe,DOT:V5,EMOJI:bUt,EQUALS:SEe,EXCLAMATION:ktt,FULLWIDTHGREATERTHAN:yEe,FULLWIDTHLEFTPAREN:uEe,FULLWIDTHLESSTHAN:gEe,FULLWIDTHMIDDLEDOT:vUt,FULLWIDTHRIGHTPAREN:hEe,HYPHEN:D2,LEFTCORNERBRACKET:mEe,LEFTWHITECORNERBRACKET:fEe,LOCALHOST:Ite,NL:jtt,NUM:wtt,OPENANGLEBRACKET:cEe,OPENBRACE:GJ,OPENBRACKET:aEe,OPENPAREN:oEe,PERCENT:KJ,PIPE:CEe,PLUS:AEe,POUND:EEe,QUERY:YJ,QUOTE:Stt,RIGHTCORNERBRACKET:pEe,RIGHTWHITECORNERBRACKET:xEe,SCHEME:J4e,SEMI:Ctt,SLASH:H5,SLASH_SCHEME:A$,SYM:MEe,TILDE:ZJ,TLD:AHe,UNDERSCORE:TEe,UTLD:EHe,UWORD:CHe,WORD:O3,WS:THe});const b3=/[a-z]/,eZ=new RegExp("\\p{L}","u"),Y7e=new RegExp("\\p{Emoji}","u"),_3=/\d/,Z7e=/\s/,g0t="\r",X7e=` `,QYs="️",JYs="‍",Q7e="";let tce=null,sce=null;function eZs(s=[]){const t={};N_.groups=t;const n=new N_;tce==null&&(tce=y0t(GYs)),sce==null&&(sce=y0t(WYs)),si(n,"'",bEe),si(n,"{",GJ),si(n,"}",WJ),si(n,"[",aEe),si(n,"]",iEe),si(n,"(",oEe),si(n,")",lEe),si(n,"<",cEe),si(n,">",dEe),si(n,"(",uEe),si(n,")",hEe),si(n,"「",mEe),si(n,"」",pEe),si(n,"『",fEe),si(n,"』",xEe),si(n,"<",gEe),si(n,">",yEe),si(n,"&",vEe),si(n,"*",_Ee),si(n,"@",j6),si(n,"`",jEe),si(n,"^",NEe),si(n,":",D6),si(n,",",Ntt),si(n,"$",kEe),si(n,".",V5),si(n,"=",SEe),si(n,"!",ktt),si(n,"-",D2),si(n,"%",KJ),si(n,"|",CEe),si(n,"+",AEe),si(n,"#",EEe),si(n,"?",YJ),si(n,'"',Stt),si(n,"/",H5),si(n,";",Ctt),si(n,"~",ZJ),si(n,"_",TEe),si(n,"\\",wEe),si(n,"・",vUt);const r=px(n,_3,wtt,{[jHe]:!0});px(r,_3,r);const a=px(r,b3,gUt,{[HJ]:!0}),i=px(r,eZ,yUt,{[AX]:!0}),l=px(n,b3,O3,{[NHe]:!0});px(l,_3,a),px(l,b3,l),px(a,_3,a),px(a,b3,a);const o=px(n,eZ,CHe,{[kHe]:!0});px(o,b3),px(o,_3,i),px(o,eZ,o),px(i,_3,i),px(i,b3),px(i,eZ,i);const c=si(n,X7e,jtt,{[K7e]:!0}),d=si(n,g0t,THe,{[K7e]:!0}),u=px(n,Z7e,THe,{[K7e]:!0});si(n,Q7e,u),si(d,X7e,c),si(d,Q7e,u),px(d,Z7e,u),si(u,g0t),si(u,X7e),px(u,Z7e,u),si(u,Q7e,u);const h=px(n,Y7e,bUt,{[xUt]:!0});si(h,"#"),px(h,Y7e,h),si(h,QYs,h);const m=si(h,JYs);si(m,"#"),px(m,Y7e,h);const p=[[b3,l],[_3,a]],f=[[b3,null],[eZ,o],[_3,i]];for(let g=0;gg[0]>v[0]?1:-1);for(let g=0;g=0?b[SHe]=!0:b3.test(v)?_3.test(v)?b[HJ]=!0:b[NHe]=!0:b[jHe]=!0,x0t(n,v,v,b)}return x0t(n,"localhost",Ite,{ascii:!0}),n.jd=new N_(MEe),{start:n,tokens:Object.assign({groups:t},_Ut)}}function wUt(s,t){const n=tZs(t.replace(/[A-Z]/g,o=>o.toLowerCase())),r=n.length,a=[];let i=0,l=0;for(;l=0&&(h+=n[l].length,m++),d+=n[l].length,i+=n[l].length,l++;i-=h,l-=m,d-=h,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function tZs(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 MT(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 Dte={defaultProtocol:"http",events:null,format:v0t,formatHref:v0t,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Att(s,t=null){let n=Object.assign({},Dte);s&&(n=Object.assign(n,s instanceof Att?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=Dte.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 VLe(s,t){class n extends jUt{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 b0t=VLe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),_0t=VLe("text"),sZs=VLe("nl"),nce=VLe("url",{isLink:!0,toHref(s=Dte.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==Ite&&s[1].t===D6}}),_2=s=>new N_(s);function nZs({groups:s}){const t=s.domain.concat([vEe,_Ee,j6,wEe,jEe,NEe,kEe,SEe,D2,wtt,KJ,CEe,AEe,EEe,H5,MEe,ZJ,TEe]),n=[bEe,D6,Ntt,V5,ktt,KJ,YJ,Stt,Ctt,cEe,dEe,GJ,WJ,iEe,aEe,oEe,lEe,uEe,hEe,mEe,pEe,fEe,xEe,gEe,yEe],r=[vEe,bEe,_Ee,wEe,jEe,NEe,kEe,SEe,D2,GJ,WJ,KJ,CEe,AEe,EEe,YJ,H5,MEe,ZJ,TEe],a=_2(),i=si(a,ZJ);dd(i,r,i),dd(i,s.domain,i);const l=_2(),o=_2(),c=_2();dd(a,s.domain,l),dd(a,s.scheme,o),dd(a,s.slashscheme,c),dd(l,r,i),dd(l,s.domain,l);const d=si(l,j6);si(i,j6,d),si(o,j6,d),si(c,j6,d);const u=si(i,V5);dd(u,r,i),dd(u,s.domain,i);const h=_2();dd(d,s.domain,h),dd(h,s.domain,h);const m=si(h,V5);dd(m,s.domain,h);const p=_2(b0t);dd(m,s.tld,p),dd(m,s.utld,p),si(d,Ite,p);const f=si(h,D2);si(f,D2,f),dd(f,s.domain,h),dd(p,s.domain,h),si(p,V5,m),si(p,D2,f);const g=si(p,D6);dd(g,s.numeric,b0t);const v=si(l,D2),y=si(l,V5);si(v,D2,v),dd(v,s.domain,l),dd(y,r,i),dd(y,s.domain,l);const b=_2(nce);dd(y,s.tld,b),dd(y,s.utld,b),dd(b,s.domain,l),dd(b,r,i),si(b,V5,y),si(b,D2,v),si(b,j6,d);const w=si(b,D6),S=_2(nce);dd(w,s.numeric,S);const C=_2(nce),E=_2();dd(C,t,C),dd(C,n,E),dd(E,t,C),dd(E,n,E),si(b,H5,C),si(S,H5,C);const P=si(o,D6),M=si(c,D6),I=si(M,H5),D=si(I,H5);dd(o,s.domain,l),si(o,V5,y),si(o,D2,v),dd(c,s.domain,l),si(c,V5,y),si(c,D2,v),dd(P,s.domain,C),si(P,H5,C),si(P,YJ,C),dd(D,s.domain,C),dd(D,t,C),si(D,H5,C);const F=[[GJ,WJ],[aEe,iEe],[oEe,lEe],[cEe,dEe],[uEe,hEe],[mEe,pEe],[fEe,xEe],[gEe,yEe]];for(let q=0;q=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(J7e(_0t,t,l)),l=[]),a-=m,u-=m;const p=h.t,f=n.slice(a-u,a);i.push(J7e(p,t,f))}}return l.length>0&&i.push(J7e(_0t,t,l)),i}function J7e(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 aZs=typeof console<"u"&&console&&console.warn||(()=>{}),iZs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Sp={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function oZs(){return N_.groups={},Sp.scanner=null,Sp.parser=null,Sp.tokenQueue=[],Sp.pluginQueue=[],Sp.customSchemes=[],Sp.initialized=!1,Sp}function w0t(s,t=!1){if(Sp.initialized&&aZs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${iZs}`),!/^[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`);Sp.customSchemes.push([s,t])}function lZs(){Sp.scanner=eZs(Sp.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=zWs(n.doc,[...t]);if(GWs(o).forEach(({newRange:d})=>{const u=$Ws(r.doc,d,p=>p.isTextblock);let h,m;if(u.length>1)h=u[0],m=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const p=r.doc.textBetween(d.from,d.to," "," ");if(!dZs.test(p))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const p=m.split(cZs).filter(Boolean);if(p.length<=0)return!1;const f=p[p.length-1],g=h.pos+m.lastIndexOf(f);if(!f)return!1;const v=Ett(f).map(y=>y.toObject(s.defaultProtocol));if(!hZs(v))return!1;v.filter(y=>y.isLink).map(y=>({...y,from:g+y.start+1,to:g+y.end+1})).filter(y=>r.schema.marks.code?!r.doc.rangeHasMark(y.from,y.to,r.schema.marks.code):!0).filter(y=>s.validate(y.value)).filter(y=>s.shouldAutoLink(y.value)).forEach(y=>{gtt(y.from,y.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(y.from,y.to,s.type.create({href:y.href}))})}}),!!l.steps.length)return l}})}function pZs(s){return new By({key:new k1("handleClickLink"),props:{handleClick:(t,n,r)=>{var a,i;if(r.button!==0||!t.editable)return!1;let l=r.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(m=>m.nodeName==="A"))return!1;const c=iUt(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 fZs(s){return new By({key:new k1("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=NUt(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 MI(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(uZs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const HLe=LS.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"){w0t(s);return}w0t(s.scheme,s.optionalSlashes)})},onDestroy(){oZs()},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)=>!!MI(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=>!!MI(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=>!!MI(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",cp(this.options.HTMLAttributes,s),0]:["a",cp(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!MI(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=>!!MI(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[h9({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=NUt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!MI(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(mZs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!MI(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(pZs({type:this.type})),this.options.linkOnPaste&&s.push(fZs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),GLe=Tv.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")}}}),xZs=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}`)})},Mtt=LS.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&xZs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),gZs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,kUt=P0.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{}}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:s}){return["img",cp(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[oUt({find:gZs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let MHe,PHe;if(typeof WeakMap<"u"){let s=new WeakMap;MHe=t=>s.get(t),PHe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;MHe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var Sx=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:y-w});break}const S=a+w*t;for(let C=0;Cr&&(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 bZs(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 wZs(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 zS(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 WLe(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=m9(t.$head)||jZs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function jZs(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 LHe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function NZs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function Ptt(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function SUt(s,t,n){const r=s.node(-1),a=Sx.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 p9(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 CUt(s,t,n=1){const r={...s,colspan:s.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let a=0;au!=n.pos-i);c.unshift(n.pos-i);const d=c.map(u=>{const h=r.nodeAt(u);if(!h)throw new RangeError(`No cell with offset ${u} found`);const m=i+u+1;return new r$t(o.resolve(m),o.resolve(m+h.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=n}map(t,n){const r=t.resolve(n.map(this.$anchorCell.pos)),a=t.resolve(n.map(this.$headCell.pos));if(LHe(r)&&LHe(a)&&Ptt(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?z3.rowSelection(r,a):i&&this.isColSelection()?z3.colSelection(r,a):new z3(r,a)}return Nl.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=Sx.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 y=f.attrs;if(g>0&&(y=p9(y,0,g)),v>0&&(y=p9(y,y.colspan-v,v)),p.lefta.bottom){const y={...f.attrs,rowspan:Math.min(p.bottom,a.bottom)-Math.max(p.top,a.top)};p.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=Sx.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 z3&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=Sx.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(fb.node(r,r+n.nodeSize,{class:"selectedCell"}))}),Nx.create(s.doc,t)}function AZs({$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 EZs({$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 TZs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof pl&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=lp.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=lp.rowSelection(o,o)}else if(!n){const o=Sx.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=lp.create(a,c+1,d)}}else r instanceof Nl&&AZs(r)?i=Nl.create(a,r.from):r instanceof Nl&&EZs(r)&&(i=Nl.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const MZs=new k1("fix-tables");function EUt(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=PZs(s,a,i,n))};return t?t.doc!=s.doc&&EUt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function PZs(s,t,n,r){const a=Sx.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);const f=[];for(let v=0;v0?-1:0;kZs(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;FZs(t,r,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,u=t.width*a;d0&&a0&&h==t.map[u-t.width]){const m=n.nodeAt(h).attrs;s.setNodeMarkup(s.mapping.slice(o).map(h+r),null,{...m,rowspan:m.rowspan-1}),d+=m.colspan-1}else if(a0&&n[i]==n[i-1]||r.right0&&n[a]==n[a-s]||r.bottom0){const u=c+1+d.content.size,h=j0t(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new lp(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function k0t(s,t){const n=_1(s.schema);return qZs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function qZs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof lp){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=wZs(r.$from),!a)return!1;i=(l=m9(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=TC(t),h=t.tr;for(let p=0;p{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function HZs(s){return function(t,n){if(!zS(t))return!1;if(n){const r=_1(t.schema),a=TC(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const p=m+i.tableStart,f=l.doc.nodeAt(p);f&&l.setNodeMarkup(p,h,f.attrs)}),r(l)}return!0}}Rte("row",{useDeprecatedLogic:!0});Rte("column",{useDeprecatedLogic:!0});const GZs=Rte("cell",{useDeprecatedLogic:!0});function WZs(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 rce(s,t){const n=s.selection;if(!(n instanceof lp))return!1;if(t){const r=s.tr,a=_1(s.schema).cell.createAndFill().content;n.forEachCell((i,l)=>{i.content.eq(a)||r.replace(r.mapping.map(l+1),r.mapping.map(l+i.nodeSize-1),new Ii(a,0,0))}),r.docChanged&&t(r)}return!0}function YZs(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(Ya.empty),n[a]r&&(m=m.type.createChecked(p9(m.attrs,m.attrs.colspan,u+m.attrs.colspan-r),m.content)),d.push(m),u+=m.attrs.colspan;for(let p=1;pa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(Ya.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function QZs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=_1(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let f=0,g=(t.height-1)*t.width;f=t.width?!1:n.nodeAt(t.map[g+f]).type==c.header_cell;h.push(v?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Ya.from(h)),p=[];for(let f=t.height;f{if(!a)return!1;const i=n.selection;if(i instanceof lp)return eCe(n,r,Zl.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=LUt(a,s,t);if(l==null)return!1;if(s=="horiz")return eCe(n,r,Zl.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=SUt(o,s,t);let d;return c?d=Zl.near(c,1):t<0?d=Zl.near(n.doc.resolve(o.before(-1)),-1):d=Zl.near(n.doc.resolve(o.after(-1)),1),eCe(n,r,d)}}}function ice(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof lp)l=i;else{const c=LUt(a,s,t);if(c==null)return!1;l=new lp(n.doc.resolve(c))}const o=SUt(l.$headCell,s,t);return o?eCe(n,r,new lp(l.$anchorCell,o)):!1}}function eXs(s,t){const n=s.state.doc,r=m9(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new lp(r))),!0):!1}function tXs(s,t,n){if(!zS(s.state))return!1;let r=YZs(n);const a=s.state.selection;if(a instanceof lp){r||(r={width:1,height:1,rows:[Ya.from(IHe(_1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=Sx.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=XZs(r,o.right-o.left,o.bottom-o.top),T0t(s.state,s.dispatch,l,o,r),!0}else if(r){const i=WLe(s.state),l=i.start(-1);return T0t(s.state,s.dispatch,l,Sx.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function sXs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=M0t(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof lp)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=m9(s.state.selection.$anchor))!=null&&((n=e9e(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=e9e(s,d);const h=R6.getState(s.state)==null;if(!u||!Ptt(c,u))if(h)u=c;else return;const m=new lp(c,u);if(h||!s.state.selection.eq(m)){const p=s.state.tr.setSelection(m);h&&p.setMeta(R6,c.pos),s.dispatch(p)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),R6.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(R6,-1))}function o(c){const d=c,u=R6.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(M0t(s,d.target)!=r&&(h=e9e(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 LUt(s,t,n){if(!(s.state.selection instanceof Nl))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 M0t(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function e9e(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&&m9(s.state.doc.resolve(r))||m9(s.state.doc.resolve(a))}var nXs=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")),DHe(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,DHe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function DHe(s,t,n,r,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let h=0,m=0;hnew r(h,n,m)),new aXs(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=tj.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{iXs(l,o,s,a)},mouseleave:l=>{oXs(l)},mousedown:(l,o)=>{lXs(l,o,t,n)}},decorations:l=>{const o=tj.getState(l);if(o&&o.activeHandle>-1)return mXs(l,o.activeHandle)},nodeViews:{}}});return i}var aXs=class tCe{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(tj);if(r&&r.setHandle!=null)return new tCe(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new tCe(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return LHe(t.doc.resolve(a))||(a=-1),new tCe(a,n.dragging)}return n}};function iXs(s,t,n,r){if(!s.editable)return;const a=tj.getState(s.state);if(a&&!a.dragging){const i=dXs(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=P0t(s,t,"left",n):c-t.clientX<=n&&(l=P0t(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=Sx.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}IUt(s,l)}}}function oXs(s){if(!s.editable)return;const t=tj.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&IUt(s,-1)}function lXs(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=tj.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=cXs(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(tj,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=tj.getState(s.state);m!=null&&m.dragging&&(uXs(s,m.activeHandle,L0t(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(tj,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=tj.getState(s.state);if(m&&m.dragging){const p=L0t(m.dragging,h,n);I0t(s,m.activeHandle,p,r)}}return I0t(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function cXs(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 yXs(s,t,n,r,a){const i=gXs(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!vXs(t))return!1;let n=0;const r=aUt(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},bXs=P0.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:fXs,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}=xXs(s,this.options.cellMinWidth),i=["table",cp(this.options.HTMLAttributes,t,{style:r?`width: ${r}`:`min-width: ${a}`}),n,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:a,editor:i})=>{const l=yXs(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Nl.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>LZs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>IZs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>RZs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>OZs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>zZs(s,t),deleteRow:()=>({state:s,dispatch:t})=>$Zs(s,t),deleteTable:()=>({state:s,dispatch:t})=>KZs(s,t),mergeCells:()=>({state:s,dispatch:t})=>N0t(s,t),splitCell:()=>({state:s,dispatch:t})=>k0t(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>Rte("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>Rte("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>GZs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>N0t(s,t)?!0:k0t(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>VZs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>C0t(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>C0t(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&TUt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=lp.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:oce,"Mod-Backspace":oce,Delete:oce,"Mod-Delete":oce}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[rXs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],pXs({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Vc(So(s,"tableRole",t))}}}),_Xs=P0.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",cp(this.options.HTMLAttributes,s),0]}}),wXs=P0.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",cp(this.options.HTMLAttributes,s),0]}}),jXs=P0.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",cp(this.options.HTMLAttributes,s),0]}});function GN({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=_.useState(!1),[o,c]=_.useState(""),[d,u]=_.useState(!0),h=ULe({extensions:[qLe,HLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),GLe.configure({types:["heading","paragraph"]}),Mtt,kUt.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),bXs.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),_Xs.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null}}}}),wXs.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),jXs.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:g})=>{t(g.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(g,v)=>{var b;const y=(b=v.clipboardData)==null?void 0:b.items;if(!y)return!1;for(const w of Array.from(y))if(w.type.startsWith("image/")){v.preventDefault();const S=w.getAsFile();if(!S)continue;const C=new FileReader;return C.onload=E=>{var M;const P=(M=E.target)==null?void 0:M.result;g.dispatch(g.state.tr.replaceSelectionWith(g.state.schema.nodes.image.create({src:P})))},C.readAsDataURL(S),!0}return!1}}});_.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const g=h.getAttributes("link").href||"",v=h.getAttributes("link").target;c(g),u(v==="_blank"),l(!0)},p=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},f=()=>{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(z,{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(GU,{className:"h-4 w-4"})}),e.jsx(z,{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(a7,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(HA,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(KA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(My,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(bj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{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(QM,{className:"h-4 w-4"})}),e.jsx(z,{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(XM,{className:"h-4 w-4"})}),e.jsx(z,{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(JM,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Kc,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:f,title:"Remove Link",children:e.jsx(Kc,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(nE,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(tE,{className:"h-4 w-4"})})]}),e.jsx($Le,{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(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-url",children:"URL"}),e.jsx(pe,{id:"link-url",value:o,onChange:g=>c(g.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(mn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(ee,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(z,{type:"button",onClick:p,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var NXs=Object.defineProperty,kXs=(s,t,n)=>t in s?NXs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Jp=(s,t,n)=>kXs(s,typeof t!="symbol"?t+"":t,n);const PEe={x:0,y:0,width:0,height:0,unit:"px"},IB=(s,t,n)=>Math.min(Math.max(s,t),n),SXs=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),F0t=(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 CXs(s,t,n,r){const a=G5(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==="%"?N6(a,n,r):a}function AXs(s,t,n){const r=G5(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?N6(r,t,n):r}function N6(s,t,n){return s.unit==="%"?{...PEe,...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 G5(s,t,n){return s.unit?s.unit==="px"?{...PEe,...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}:{...PEe,...s,unit:"px"}}function O0t(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),m=Math.min(o,r),p=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,p=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const f=r-(d.x+d.width);f<0&&(d.x=Math.min(d.x,r-u),d.width+=f);const g=a-(d.y+d.height);if(g<0&&(d.y=Math.min(d.y,a-h),d.height+=g),d.widthm&&((n==="sw"||n=="nw")&&(d.x-=m-d.width),d.width=m),d.height>p&&((n==="nw"||n=="ne")&&(d.y-=p-d.height),d.height=p),t){const v=d.width/d.height;if(vt){const y=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=y-d.width),d.width=y}}return d}function EXs(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 DB={capture:!0,passive:!1};let TXs=0;const s6=class Sk extends _.PureComponent{constructor(){super(...arguments),Jp(this,"docMoveBound",!1),Jp(this,"mouseDownOnCrop",!1),Jp(this,"dragStarted",!1),Jp(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Jp(this,"componentRef",_.createRef()),Jp(this,"mediaRef",_.createRef()),Jp(this,"resizeObserver"),Jp(this,"initChangeCalled",!1),Jp(this,"instanceId",`rc-${TXs++}`),Jp(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Jp(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=G5(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 m=t.clientX-a.x,p=t.clientY-a.y;let f=0,g=0;l==="ne"||l=="e"?(f=m-(i.x+i.width),g=p-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(f=m-(i.x+i.width),g=p-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(f=m-i.x,g=p-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(f=m-i.x,g=p-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+f,d=h+a.y+g}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})}),Jp(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(G5(u,o.width,o.height),N6(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Jp(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(),F0t(n,c)||a(G5(c,l.width,l.height),N6(c,l.width,l.height))}),Jp(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)?Sk.nudgeStepLarge:t.shiftKey?Sk.nudgeStepMedium:Sk.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=IB(d.x,0,c.width-d.width),d.y=IB(d.y,0,c.height-d.height);const h=G5(d,c.width,c.height),m=N6(d,c.width,c.height);a(h,m),i&&i(h,m)}}),Jp(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,m=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 p=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?Sk.nudgeStepLarge:t.shiftKey?Sk.nudgeStepMedium:Sk.nudgeStep,f=G5(a,m.width,m.height),g=EXs(f,t.key,p,n),v=O0t(g,r,n,m.width,m.height,l,o,c,d);if(!F0t(a,v)){const y=N6(v,m.width,m.height);u(v,y),h&&h(v,y)}}),Jp(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(G5(n,l.width,l.height),N6(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Jp(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(G5(n,a,i),N6(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,DB),this.document.addEventListener("pointerup",this.onDocPointerDone,DB),this.document.addEventListener("pointercancel",this.onDocPointerDone,DB),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,DB),this.document.removeEventListener("pointerup",this.onDocPointerDone,DB),this.document.removeEventListener("pointercancel",this.onDocPointerDone,DB),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=IB(t.startCropX+a,0,n.width-r.width),r.y=IB(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,m=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(m=Math.min(m,-o));const p={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(p.x=t.startCropX,p.width=h,n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY-p.height)):d==="se"?(p.x=t.startCropX,p.y=t.startCropY,p.width=h,n?p.height=p.width/n:p.height=m):d==="sw"?(p.x=t.startCropX+h,p.y=t.startCropY,p.width=Math.abs(h),n?p.height=p.width/n:p.height=m):d==="nw"&&(p.x=t.startCropX+h,p.width=Math.abs(h),n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY+m));const f=O0t(p,n,d,i.width,i.height,l,o,r,a);return n||Sk.xyOrds.indexOf(u)>-1?c=f:Sk.xOrds.indexOf(u)>-1?(c.x=f.x,c.width=f.width):Sk.yOrds.indexOf(u)>-1&&(c.y=f.y,c.height=f.height),c.x=IB(c.x,0,i.width-c.width),c.y=IB(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=Sk.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Ft.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Ft.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Ft.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Ft.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Ft.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Ft.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Ft.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"}),Ft.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"}),Ft.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"}),Ft.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"}),Ft.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"}),Ft.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"}),Ft.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"}),Ft.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&&Ft.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Ft.createElement(Ft.Fragment,null,Ft.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Ft.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...PEe,...this.props.crop||{}};return G5(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,m=i?this.renderCropSelection():null,p=SXs("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 Ft.createElement("div",{ref:this.componentRef,className:p,style:c},Ft.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Ft.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Ft.createElement("defs",null,Ft.createElement("mask",{id:`hole-${this.instanceId}`},Ft.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Ft.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"}):Ft.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Ft.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,m)}};Jp(s6,"xOrds",["e","w"]),Jp(s6,"yOrds",["n","s"]),Jp(s6,"xyOrds",["nw","ne","se","sw"]),Jp(s6,"nudgeStep",1),Jp(s6,"nudgeStepMedium",10),Jp(s6,"nudgeStepLarge",100),Jp(s6,"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 MXs=s6;function PXs(s,t,n){return AXs(CXs({unit:"%",width:90},n,s,t),s,t)}const Ltt=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=_.useRef(null),[l,o]=_.useState(),[c,d]=_.useState(),[u,h]=_.useState(1),[m,p]=_.useState(0),f=_.useCallback(y=>{const{width:b,height:w}=y.currentTarget;o(PXs(b,w,a))},[a]),g=_.useCallback(async()=>{const y=i.current;if(!y||!c)return;const b=document.createElement("canvas"),w=b.getContext("2d");if(!w)return;const S=y.naturalWidth/y.width,C=y.naturalHeight/y.height,E=400;b.width=E,b.height=E,w.imageSmoothingQuality="high";const P=c.x*S,M=c.y*C,I=c.width*S,D=c.height*C,F=m*Math.PI/180,q=b.width/2,G=b.height/2;return w.save(),w.translate(q,G),w.rotate(F),w.scale(u,u),w.translate(-q,-G),w.drawImage(y,P,M,I,D,0,0,E,E),w.restore(),new Promise((V,H)=>{b.toBlob(K=>{K?V(K):H(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),v=async()=>{try{const y=await g();y&&(r(y),t())}catch(y){console.error("Error cropping image:",y)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{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(MXs,{crop:l,onChange:(y,b)=>o(b),onComplete:y=>d(y),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:f})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Nq,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Mx,{value:[u],min:.5,max:3,step:.1,onValueChange:([y])=>h(y),className:"flex-1"}),e.jsx(fP,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(p7,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Mx,{value:[m],min:-180,max:180,step:1,onValueChange:([y])=>p(y),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(z,{onClick:v,children:"Save Photo"})]})]})})},z0t="I agree to receive recurring SMS/MMS text messages from LevelUp, including new lead alerts, account notifications, service updates, and customer support. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.";function LXs(s){const t=s.replace(/\D/g,"");return s.trim().startsWith("+")?t.length>=8?`+${t}`:null:t.length===10?`+1${t}`:t.length===11&&t.startsWith("1")?`+${t}`:null}function IXs(){const{user:s}=hs(),{toast:t}=_i(),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(null),[f,g]=_.useState(!1);_.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:b}=await U.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),w=b;w&&(o(w.phone_e164||w.phone||""),h(!!w.sms_consent),d(!!w.sms_consent),p(w.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const v=async()=>{const b=LXs(l);if(!b){t({title:"Invalid number",description:"Enter a valid mobile number, e.g. (555) 123-4567.",variant:"destructive"});return}if(!c){t({title:"Consent required",description:"Please check the consent box to opt in to text messages.",variant:"destructive"});return}i(!0);const{error:w}=await U.from("profiles").update({phone_e164:b,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:z0t,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),w){t({title:"Error",description:w.message,variant:"destructive"});return}h(!0),p(new Date().toISOString()),t({title:"You're opted in",description:"You'll now receive text alerts for new leads and account notifications."})},y=async()=>{i(!0);const{error:b}=await U.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),b){t({title:"Error",description:b.message,variant:"destructive"});return}h(!1),d(!1),t({title:"Opted out",description:"You will no longer receive text messages from LevelUp."})};return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(qi,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx(ze,{variant:"secondary",children:"Opted in"})]}),e.jsx(En,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Le,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS is completely optional. It is not required to create an account, save your profile, purchase, access, or use LevelUp. You may leave this blank or decline."})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(pe,{id:"sms-mobile",type:"tel",value:l,onChange:b=>o(b.target.value),placeholder:"(555) 123-4567",maxLength:30,autoComplete:"tel"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only needed if you choose to opt in. Must be a mobile number that can receive text messages."})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(za,{id:"sms-consent",checked:c,onCheckedChange:b=>d(b===!0),disabled:u,className:"mt-0.5"}),e.jsx(ee,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:z0t})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Message types: new lead alerts, account notifications, service updates, customer support. Frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. No mobile information will be shared with third parties or affiliates for marketing purposes."}),u&&m&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded on ",new Date(m).toLocaleString("en-US",{timeZone:"America/New_York"}),"."]}),f&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{onClick:v,disabled:a||u&&!l,children:[a&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx(z,{variant:"outline",onClick:y,disabled:a,children:"Opt out"}):e.jsx(z,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),g(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const B0t="#2a4c64",$0t="#B8965A",U0t="Inter",q0t="Inter";function E$(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function s_(s,t=null){for(const[n,r]of s){const a=E$(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function DXs(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(E,P,M)=>a?[["brokerage",P],["agent",E],["legacy",M]]:[["agent",E],["brokerage",P],["legacy",M]],o=s_(l(t.brand_color,n.primary_color,r.brand_color),B0t),c=s_(l(t.accent_color,n.accent_color,r.accent_color),$0t),d=s_([["brokerage",n.secondary_color]]),u=i?[["brokerage",n.logo_url],["agent",t.logo_url],["legacy",r.brokerage_logo_url||r.team_logo_url]]:[["agent",t.logo_url],["legacy",r.team_logo_url],["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]],h=s_(u),m=s_([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),p=s_([["agent",t.headshot_url],["legacy",r.avatar_url]]),f=s_([["agent",t.tagline],["legacy",r.tagline||r.title]]),g=s_([["agent",t.preferred_font],["brokerage",n.heading_font]],U0t),v=s_([["brokerage",n.body_font]],q0t),y=s_([["agent",t.license_number],["legacy",r.license_number]]),b=s_([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),w=s_([["agent",t.website_url],["legacy",r.website_url]]),S=s_([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),C=s_([["brokerage",n.compliance_line]]);return{agent_name:E$(r.name),brokerage_name:S.value,brand_color:o.value??B0t,secondary_color:d.value,accent_color:c.value??$0t,heading_font:g.value??U0t,body_font:v.value??q0t,logo_url:h.value,logo_dark_url:E$(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:E$(n.icon_mark_url),headshot_url:p.value,tagline:f.value,license_number:y.value,license_state:b.value,website_url:w.value,email:E$(r.email),phone:E$(r.phone),compliance_line:C.value,show_equal_housing:!!n.show_equal_housing,show_realtor_logo:!!n.show_realtor_logo,locked:{colors:a,logo:i},sources:{brand_color:o.source,accent_color:c.source,secondary_color:d.source,logo_url:h.source,brokerage_logo_url:m.source,headshot_url:p.source,tagline:f.source,heading_font:g.source,body_font:v.source,license_number:y.source,license_state:b.source,website_url:w.source,brokerage_name:S.source,compliance_line:C.source}}}function RXs(){const{user:s}=hs();return rt({queryKey:["agent-brand-profile",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("agent_brand_profiles").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t??null}})}function FXs(){const{user:s}=hs(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");const{data:r,error:a}=await U.from("agent_brand_profiles").upsert({user_id:s.id,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-brand-profile",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["brand-kit",s==null?void 0:s.id]})}})}function OXs(s){return rt({queryKey:["brokerage-brand-profile",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_brand_profiles").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t??null}})}function zXs(s){const{user:t}=hs(),n=$t();return mt({mutationFn:async r=>{if(!s)throw new Error("No brokerage selected");const{data:a,error:i}=await U.from("brokerage_brand_profiles").upsert({brokerage_id:s,updated_by:(t==null?void 0:t.id)??null,...r},{onConflict:"brokerage_id"}).select().single();if(i)throw i;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-brand-profile",s]}),n.invalidateQueries({queryKey:["brand-kit"]})}})}function DUt(){const{user:s}=hs();return rt({queryKey:["brand-kit",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{var m;const t=s.id,[n,r,a,i]=await Promise.all([U.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),U.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle(),U.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, display_email, title, positioning_statement").eq("user_id",t).maybeSingle(),U.from("lead_sites").select("brand_color, accent_color, agent_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5)]),l=n.data??{},o=a.data??{},c=i.data??[],d=c.find(p=>p.is_active)??c[0]??{};let u=null,h=null;if(l.brokerage_id){const[p,f]=await Promise.all([U.from("brokerage_brand_profiles").select("*").eq("brokerage_id",l.brokerage_id).maybeSingle(),U.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle()]);u=p.data??null,h=((m=f.data)==null?void 0:m.name)??null}return DXs({agent:r.data??null,brokerage:u,legacy:{name:l.name??null,email:o.display_email||l.email||s.email||null,phone:l.phone??null,avatar_url:l.avatar_url??null,website_url:l.website_url??null,title:l.title??null,brokerage_name:l.brokerage_name||o.brokerage_display_name||d.brokerage_legal_name||h,brokerage_logo_url:o.brokerage_logo_url??null,team_logo_url:o.team_logo_url||d.team_logo_url||null,brand_color:d.brand_color??null,accent_color:d.accent_color??null,license_number:d.agent_license_number??null,license_state:d.license_state??null,tagline:o.positioning_statement??null}})}})}async function RUt(s,t,n){var l;const r=((l=t.name.split(".").pop())==null?void 0:l.toLowerCase())||"png",a=`${s}/brand-${n}-${Date.now()}.${r}`,{error:i}=await U.storage.from("card-logos").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;return U.storage.from("card-logos").getPublicUrl(a).data.publicUrl}const BXs=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function $Xs(){const{user:s}=hs(),{toast:t}=_i(),{data:n,isLoading:r}=RXs(),{data:a}=DUt(),i=FXs(),l=_.useRef(null),[o,c]=_.useState(!1),[d,u]=_.useState({brand_color:"",accent_color:"",logo_url:"",tagline:"",preferred_font:"",license_number:"",license_state:"",website_url:""});_.useEffect(()=>{n&&u({brand_color:n.brand_color||"",accent_color:n.accent_color||"",logo_url:n.logo_url||"",tagline:n.tagline||"",preferred_font:n.preferred_font||"",license_number:n.license_number||"",license_state:n.license_state||"",website_url:n.website_url||""})},[n]);const h=!!(a!=null&&a.locked.colors),m=!!(a!=null&&a.locked.logo),p=(v,y)=>u(b=>({...b,[v]:y})),f=async v=>{if(s){c(!0);try{const y=await RUt(s.id,v,"logo");p("logo_url",y),t({title:"Logo uploaded"})}catch(y){t({title:"Upload failed",description:y.message,variant:"destructive"})}finally{c(!1)}}},g=async()=>{try{await i.mutateAsync({brand_color:d.brand_color||null,accent_color:d.accent_color||null,logo_url:d.logo_url||null,tagline:d.tagline||null,preferred_font:d.preferred_font||null,license_number:d.license_number||null,license_state:d.license_state||null,website_url:d.website_url||null}),t({title:"Brand kit saved"})}catch(v){t({title:"Could not save",description:v.message,variant:"destructive"})}};return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(En,{children:"Used by AI tools (ChatGPT via the LevelUp connector), flyers, presentations and your public pages. Anything you leave blank falls back to your brokerage's brand, then LevelUp defaults."})]}),e.jsx(Le,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Hl,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",value:d.brand_color||(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:v=>p("brand_color",v.target.value)}),e.jsx(pe,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:v=>p("brand_color",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",value:d.accent_color||(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:v=>p("accent_color",v.target.value)}),e.jsx(pe,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:v=>p("accent_color",v.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Hl,{className:"h-3 w-3"})," Brokerage logo required"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[d.logo_url&&e.jsx("img",{src:d.logo_url,alt:"Your logo",className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var y;return((y=v.target.files)==null?void 0:y[0])&&f(v.target.files[0])}}),e.jsxs(z,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},children:[o?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx(z,{type:"button",variant:"ghost",onClick:()=>p("logo_url",""),disabled:m,children:"Remove"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(pe,{id:"brand-tagline",value:d.tagline,placeholder:(a==null?void 0:a.tagline)||"Your positioning statement",onChange:v=>p("tagline",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(pe,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:v=>p("preferred_font",v.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:BXs.map(v=>e.jsx("option",{value:v},v))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-license",children:"License number"}),e.jsx(pe,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:v=>p("license_number",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(pe,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:v=>p("license_state",v.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{htmlFor:"brand-website",children:"Website"}),e.jsx(pe,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:v=>p("website_url",v.target.value)})]})]}),(a==null?void 0:a.compliance_line)&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Required disclaimer from your brokerage: "}),a.compliance_line]}),e.jsxs(z,{onClick:g,disabled:i.isPending,children:[i.isPending?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const t9e="id, name, address, notes, created_at, locked_style, share_token, share_enabled, share_headline, share_message, share_views";function Nwr(s,t){const[n,r]=_.useState(null);return _.useEffect(()=>{let a=!1;if(!t){r(null);return}if(t.startsWith("http")||t.startsWith("data:")){r(t);return}return U.storage.from(s).createSignedUrl(t,60*60).then(({data:i})=>{a||r((i==null?void 0:i.signedUrl)??null)}),()=>{a=!0}},[s,t]),n}function UXs(){var o,c,d;const{user:s}=hs(),t=$t(),n=rt({queryKey:["staging-credits",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const{data:u,error:h}=await U.functions.invoke("staging-credits-sync");if(h)throw h;return{credits:(u==null?void 0:u.credits)??null,unlimited:!!(u!=null&&u.unlimited),unlimitedReason:(u==null?void 0:u.unlimitedReason)??null}}}),r=((o=n.data)==null?void 0:o.credits)??null,a=!!((c=n.data)!=null&&c.unlimited),i=r?Math.max(r.monthly_included-r.monthly_used,0):0,l=i+((r==null?void 0:r.purchased_balance)??0);return{credits:r,unlimited:a,unlimitedReason:((d=n.data)==null?void 0:d.unlimitedReason)??null,remainingMonthly:i,purchased:(r==null?void 0:r.purchased_balance)??0,total:l,legacyPlan:(r==null?void 0:r.legacy_plan)??null,isLoading:n.isLoading,refresh:()=>t.invalidateQueries({queryKey:["staging-credits"]})}}function kwr(){return rt({queryKey:["staging-credit-packs"],staleTime:5*6e4,queryFn:async()=>{const{data:s,error:t}=await U.from("staging_credit_packs").select("id, key, name, credits, price_cents, sort_order").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function Swr(){const{user:s}=hs(),t=$t(),n=rt({queryKey:["staging-projects",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:o,error:c}=await U.from("staging_projects").select(t9e).eq("user_id",s.id).order("created_at",{ascending:!1});if(c)throw c;return o??[]}}),r=mt({mutationFn:async o=>{const{data:c,error:d}=await U.from("staging_projects").insert({user_id:s.id,name:o.name,address:o.address??null}).select(t9e).single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),a=mt({mutationFn:async o=>{const{error:c}=await U.from("staging_projects").update({name:o.name,address:o.address??null}).eq("id",o.id);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),i=mt({mutationFn:async o=>{await U.from("staging_images").update({project_id:null}).eq("project_id",o);const{error:c}=await U.from("staging_projects").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["staging-projects"]}),t.invalidateQueries({queryKey:["staging-images"]})}}),l=mt({mutationFn:async o=>{const{id:c,...d}=o,{data:u,error:h}=await U.from("staging_projects").update(d).eq("id",c).select(t9e).single();if(h)throw h;return u},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})});return{projects:n.data??[],isLoading:n.isLoading,createProject:r,renameProject:a,deleteProject:i,updateProject:l}}function Cwr(){return mt({mutationFn:async s=>{if(s.length===0)return[];const{data:t,error:n}=await U.functions.invoke("staging-analyze",{body:{images:s}});if(n)throw n;return(t==null?void 0:t.results)??[]}})}function Awr(s){const{user:t}=hs(),n=$t(),r=rt({queryKey:["staging-images",t==null?void 0:t.id,s??"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let o=U.from("staging_images").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(300);s&&(o=o.eq("project_id",s));const{data:c,error:d}=await o;if(d)throw d;return c??[]}}),a=mt({mutationFn:async o=>{const{data:c,error:d}=await U.from("staging_images").delete().eq("id",o).select("id");if(d)throw d;if(!(c!=null&&c.length))throw new Error("This photo could not be deleted.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})}),i=mt({mutationFn:async o=>{const{data:c,error:d}=await U.from("staging_images").update({is_favorite:!o.is_favorite}).eq("id",o.id).select("id");if(d)throw d;if(!(c!=null&&c.length))throw new Error("This photo could not be updated.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})}),l=mt({mutationFn:async({id:o,projectId:c})=>{const{data:d,error:u}=await U.from("staging_images").update({project_id:c}).eq("id",o).select("id");if(u)throw u;if(!(d!=null&&d.length))throw new Error("This photo could not be moved.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})});return{images:r.data??[],isLoading:r.isLoading,remove:a,toggleFavorite:i,assignProject:l}}function Ewr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("staging-generate",{body:t});if(r){let a=r.message;try{const i=r.context;if(i){const l=await i.json();a=(l==null?void 0:l.message)||(l==null?void 0:l.error)||a}}catch{}throw new Error(a)}if(n!=null&&n.error)throw new Error(n.message||n.error);return{image:n.image,generatedUrl:n.generatedUrl}},onSuccess:()=>{s.invalidateQueries({queryKey:["staging-images"]}),s.invalidateQueries({queryKey:["staging-credits"]})}})}async function Twr(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(s)})}function qXs(){try{return window.open("","_blank")}catch{return null}}function VXs(s,t){var n;if(s&&!s.closed)try{s.location.href=t,(n=s.focus)==null||n.call(s);return}catch{}window.location.assign(t)}function HXs(s){try{s&&!s.closed&&s.close()}catch{}}async function GXs(s,t){if(s instanceof Bre)try{const n=await s.context.text();try{const r=JSON.parse(n),a=(r==null?void 0:r.error)??(r==null?void 0:r.message);if(typeof a=="string"&&a.trim())return a}catch{if(n.trim())return n.trim().slice(0,300)}}catch{}return s instanceof Error&&s.message?s.message:t}function WXs(){var i;const s=UXs(),[t,n]=_.useState(!1);if(s.isLoading)return null;const r=s.unlimited&&s.unlimitedReason==="plan",a=async()=>{if(t)return;const l=qXs();n(!0);try{const{data:o,error:c}=await U.functions.invoke("staging-portal");if(c)throw c;if(!(o!=null&&o.url))throw new Error("No billing portal available");VXs(l,o.url)}catch(o){HXs(l);const c=await GXs(o,"We could not open your billing portal. Contact support and we will sort it out.");console.error("[staging-portal]",c,o),ne.error(c)}finally{n(!1)}};return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5"}),"Staging Studio Billing"]}),e.jsx(En,{children:"Manage the plan and credits that power your AI photo staging"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ze,{variant:r?"default":"secondary",children:s.legacyPlan?`${s.legacyPlan} plan`:"Included with LevelUp"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r?"Unlimited staged photos each month":`${s.remainingMonthly} of ${((i=s.credits)==null?void 0:i.monthly_included)??0} photos left this month`,!r&&s.purchased>0&&` · ${s.purchased} pack credits`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:a,disabled:t,children:[t?e.jsx(bt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(j0,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage billing"]}),e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(or,{to:"/apps/staging-studio/credits",children:["Credits & history ",e.jsx(mr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.legacyPlan?"Cancel, update your card or change plans in the billing portal. Changes apply to your Staging Studio credits automatically.":"If you ever bought a Staging Studio plan or credit packs, open the billing portal to update your card, change plans or cancel."})]})]})}const V0t=["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"],KXs=5*1024*1024;function YXs({userId:s,value:t,onChange:n,persistToProfile:r=!0,label:a="Brokerage logo",description:i="PNG, JPG, SVG or WebP — up to 5MB. Used on your website and marketing.",className:l}){const o=_.useRef(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),m=async f=>{if(!V0t.includes(f.type)){ne.error("Please upload a PNG, JPG, SVG or WebP file");return}if(f.size>KXs){ne.error("Please choose a logo under 5MB");return}d(!0);try{const g=(f.name.split(".").pop()||"png").toLowerCase(),v=`${s}/brokerage-logo-${Date.now()}.${g}`,{error:y}=await U.storage.from("card-logos").upload(v,f,{cacheControl:"3600",upsert:!0,contentType:f.type});if(y)throw y;const{data:b}=U.storage.from("card-logos").getPublicUrl(v),w=b.publicUrl;r&&await U.from("profiles").update({brokerage_logo_url:w}).eq("id",s),n(w),ne.success("Brokerage logo uploaded")}catch(g){ne.error((g==null?void 0:g.message)||"Upload failed")}finally{d(!1)}},p=async()=>{r&&await U.from("profiles").update({brokerage_logo_url:null}).eq("id",s),n(null)};return e.jsxs("div",{className:Ct("space-y-2",l),children:[e.jsx(ee,{children:a}),e.jsxs("div",{onDragOver:f=>{f.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:f=>{var v;f.preventDefault(),h(!1);const g=(v=f.dataTransfer.files)==null?void 0:v[0];g&&m(g)},onClick:()=>{var f;return!c&&((f=o.current)==null?void 0:f.click())},className:Ct("flex cursor-pointer items-center gap-4 rounded-xl border border-dashed p-4 transition-colors",u?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[e.jsx("div",{className:"flex h-16 w-24 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted",children:t?e.jsx("img",{src:t,alt:"Brokerage logo",className:"h-full w-full object-contain p-1"}):e.jsx(oi,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:c?"Uploading…":t?"Logo added":"Drag & drop your brokerage logo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:f=>{var g;f.stopPropagation(),(g=o.current)==null||g.click()},children:[c?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:t?"Replace":"Upload"})]}),t&&!c&&e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:f=>{f.stopPropagation(),p()},children:e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx("input",{ref:o,type:"file",accept:V0t.join(","),className:"hidden",onChange:f=>{var v;const g=(v=f.target.files)==null?void 0:v[0];g&&m(g),f.target.value=""}})]})}const ZXs=()=>{const{user:s}=hs(),{toast:t}=_i(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(null);_.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await U.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 U.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:p}=await U.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(p)throw p;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(ze,{className:"bg-green-500",children:"Active"});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(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(j0,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Le,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(j0,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(En,{children:"Manage your subscription and billing"})]}),e.jsxs(Le,{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 membership is active and included with your account. To update or manage billing, 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(z,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(mr,{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."})]})]})},XXs=()=>{const{user:s}=hs(),t=zn(),{toast:n}=_i(),[r]=Gl(),a=r.get("setup")==="true",i=r.get("reset")==="true",l=i&&r.get("activation")==="1",{isSupported:o,isSubscribed:c,isLoading:d,subscribe:u,unsubscribe:h}=NFt(),[m,p]=_.useState(!1),[f,g]=_.useState(""),[v,y]=_.useState(null),[b,w]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(""),[M,I]=_.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",google_business_url:"",zillow_profile_url:"",realtor_profile_url:"",specialties:"",email_signature:"",use_email_signature:!1}),[D,F]=_.useState(!1),[q,G]=_.useState(!1),[V,H]=_.useState(!1),[K,Z]=_.useState(!1),[oe,re]=_.useState(!1),[ae,J]=_.useState({newPassword:"",confirmPassword:""});_.useEffect(()=>{s&&te()},[s]),_.useEffect(()=>{i&&s&&setTimeout(()=>{var ke;(ke=document.getElementById("change-password-section"))==null||ke.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const te=async()=>{var ke,Ve,_e,Ae;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Se,error:We}=await U.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, brokerage_logo_url, instagram_url, facebook_url, linkedin_url, google_business_url, zillow_profile_url, realtor_profile_url, specialties, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(We)throw console.error("Profile query error:",We),We;if(Se){console.log("Profile loaded successfully:",Se);const Be=((ke=Se.brokerages)==null?void 0:ke.name)||"";F(!!Se.brokerage_id),I({name:Se.name||"",email:Se.email||"",phone:Se.phone||"",title:Se.title||"",bio:Se.bio||"",areas_served:Se.areas_served||"",years_experience:((Ve=Se.years_experience)==null?void 0:Ve.toString())||"",brokerage_name:Se.brokerage_id?Be:Se.brokerage_name||"",instagram_url:Se.instagram_url||"",facebook_url:Se.facebook_url||"",linkedin_url:Se.linkedin_url||"",google_business_url:Se.google_business_url||"",zillow_profile_url:Se.zillow_profile_url||"",realtor_profile_url:Se.realtor_profile_url||"",specialties:Se.specialties||"",email_signature:Se.email_signature||"",use_email_signature:Se.use_email_signature||!1}),G(Se.digest_opt_out||!1),Z(Se.event_invite_opt_out||!1),y(Se.brokerage_logo_url||null)}else console.warn("No profile found for user"),I({name:((_e=s.user_metadata)==null?void 0:_e.name)||((Ae=s.email)==null?void 0:Ae.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",google_business_url:"",zillow_profile_url:"",realtor_profile_url:"",specialties:"",email_signature:"",use_email_signature:!1});const{data:qe}=await U.storage.from("avatars").list(`${s.id}`);if(qe&&qe.length>0){const{data:Be}=U.storage.from("avatars").getPublicUrl(`${s.id}/${qe[0].name}`);g(Be.publicUrl)}}catch(Se){console.error("Error loading profile:",Se),n({title:"Error",description:Se.message||"Failed to load profile",variant:"destructive"})}},ce=ke=>{var Ae;const Ve=(Ae=ke.target.files)==null?void 0:Ae[0];if(!Ve)return;const _e=new FileReader;_e.onloadend=()=>{P(_e.result),C(!0)},_e.readAsDataURL(Ve),ke.target.value=""},ve=async ke=>{if(s){w(!0);try{const{data:Ve}=await U.storage.from("avatars").list(`${s.id}`),_e=(Ve??[]).filter(Ze=>/^avatar[.-]/i.test(Ze.name));_e.length>0&&await U.storage.from("avatars").remove(_e.map(Ze=>`${s.id}/${Ze.name}`));const Se=`${s.id}/avatar.jpg`,{error:We}=await U.storage.from("avatars").upload(Se,ke,{upsert:!0,contentType:"image/jpeg"});if(We)throw We;const{data:qe}=U.storage.from("avatars").getPublicUrl(Se),Be=qe.publicUrl;g(`${Be}?t=${Date.now()}`),await U.from("profiles").update({avatar_url:Be}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Ve){console.error("Error uploading avatar:",Ve),n({title:"Error",description:Ve.message||"Failed to upload photo",variant:"destructive"})}finally{w(!1)}}},me=async()=>{if(!M.name.trim()||!M.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}p(!0);try{const ke=M.email.trim().toLowerCase(),Ve=((s==null?void 0:s.email)||"").toLowerCase(),_e=!!ke&&ke!==Ve;if(_e){const{data:Se,error:We}=await U.functions.invoke("update-own-email",{body:{newEmail:ke}}),qe=We||(Se==null?void 0:Se.error);if(qe)throw new Error(typeof qe=="string"?qe:"Could not update your login email. Please try a different address.")}const{error:Ae}=await U.from("profiles").update({name:M.name.trim(),email:ke,phone:M.phone.trim()||null,title:M.title.trim()||null,bio:M.bio.trim()||null,areas_served:M.areas_served.trim()||null,years_experience:M.years_experience?parseInt(M.years_experience):null,...D?{}:{brokerage_name:M.brokerage_name.trim()||null},instagram_url:M.instagram_url.trim()||null,facebook_url:M.facebook_url.trim()||null,linkedin_url:M.linkedin_url.trim()||null,google_business_url:M.google_business_url.trim()||null,zillow_profile_url:M.zillow_profile_url.trim()||null,realtor_profile_url:M.realtor_profile_url.trim()||null,specialties:M.specialties.trim()||null,email_signature:M.email_signature||"",use_email_signature:M.use_email_signature}).eq("id",s==null?void 0:s.id);if(Ae)throw Ae;n({title:"Success",description:_e?"Profile updated. Your login email is now "+ke:"Profile updated successfully"})}catch(ke){console.error("Error updating profile:",ke),n({title:"Error",description:ke.message||"Failed to update profile",variant:"destructive"})}finally{p(!1)}},he=async()=>{if(!ae.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ae.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ae.newPassword!==ae.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}p(!0);try{const{error:ke}=await U.auth.updateUser({password:ae.newPassword});if(ke)throw ke;n({title:"Success",description:"Password updated successfully"}),J({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ke){console.error("Error updating password:",ke),n({title:"Error",description:ke.message||"Failed to update password",variant:"destructive"})}finally{p(!1)}},ge=[M.name,M.email,M.phone,M.title,M.bio,M.areas_served,M.brokerage_name,f],Ee=ge.filter(ke=>ke.trim()).length,Ne=Math.round(Ee/ge.length*100),Pe=M.name.split(" ").filter(Boolean).map(ke=>ke[0]).join("").toUpperCase().slice(0,2)||"U",Oe=ke=>{var Ve;(Ve=document.getElementById(ke))==null||Ve.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsx($s,{title:a?"Complete Your Profile":l?"Welcome to LevelUp":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":l?"Choose a password below and your account is active":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"profile-workspace mx-auto max-w-7xl",children:[e.jsxs("div",{className:"profile-shell",children:[e.jsx("aside",{className:"profile-summary",children:e.jsxs("div",{className:"profile-summary-inner",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ja,{className:"profile-avatar",children:[e.jsx(xi,{src:f}),e.jsx(Na,{children:Pe})]}),e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ce,disabled:b}),e.jsx(z,{type:"button",size:"icon",className:"profile-avatar-button",onClick:()=>{var ke;return(ke=document.getElementById("avatar-upload"))==null?void 0:ke.click()},disabled:b,"aria-label":"Change profile photo",children:b?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Lx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-6 text-center",children:[e.jsx("h2",{className:"profile-name",children:M.name||"Your profile"}),e.jsx("p",{className:"profile-role",children:M.title||"Real estate professional"}),M.brokerage_name&&e.jsx("p",{className:"profile-brokerage",children:M.brokerage_name})]}),e.jsxs("div",{className:"profile-completion",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{children:"Profile strength"}),e.jsxs("strong",{children:[Ne,"%"]})]}),e.jsx("div",{className:"profile-progress","aria-label":`Profile ${Ne}% complete`,children:e.jsx("span",{style:{width:`${Ne}%`}})}),e.jsx("p",{children:Ne===100?"Your professional profile is complete.":"Complete your details to strengthen your presence across LevelUp."})]}),e.jsxs("nav",{className:"profile-section-nav","aria-label":"Profile sections",children:[e.jsxs(z,{variant:"ghost",onClick:()=>Oe("profile-details"),children:[e.jsx(x6,{className:"h-4 w-4"})," Profile details"]}),e.jsxs(z,{variant:"ghost",onClick:()=>Oe("profile-brand"),children:[e.jsx(yc,{className:"h-4 w-4"})," Brand & signature"]}),e.jsxs(z,{variant:"ghost",onClick:()=>Oe("change-password-section"),children:[e.jsx(Ch,{className:"h-4 w-4"})," Account security"]}),e.jsxs(z,{variant:"ghost",onClick:()=>Oe("profile-notifications"),children:[e.jsx(fS,{className:"h-4 w-4"})," Notifications"]}),e.jsxs(z,{variant:"ghost",onClick:()=>Oe("profile-billing"),children:[e.jsx(aq,{className:"h-4 w-4"})," Billing"]})]}),e.jsxs(z,{className:"profile-save",onClick:me,disabled:m,children:[m?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4"}),"Save profile"]})]})}),e.jsxs("main",{className:"profile-content",children:[e.jsxs("header",{className:"profile-page-heading",children:[e.jsx("p",{className:"profile-eyebrow",children:"Your professional presence"}),e.jsx("h1",{children:a?"Complete your profile":l?"Welcome to LevelUp":i?"Reset your password":"Personal details"}),e.jsx("p",{children:a?"Add the details clients and collaborators should know about you.":"Keep your identity, brand, and account preferences current in one place."})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{id:"profile-details",children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Personal Information"}),e.jsx(En,{children:"Update your profile details"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:M.name,onChange:ke=>I({...M,name:ke.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:M.email,onChange:ke=>I({...M,email:ke.target.value}),maxLength:255}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing this also updates the email you use to sign in."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"phone",children:"Phone Number"}),e.jsx(pe,{id:"phone",type:"tel",value:M.phone,onChange:ke=>I({...M,phone:ke.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(ee,{htmlFor:"title",children:"Job Title"}),e.jsx(pe,{id:"title",value:M.title,onChange:ke=>I({...M,title:ke.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"bio",children:"Bio"}),e.jsx(Ps,{id:"bio",value:M.bio,onChange:ke=>I({...M,bio:ke.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(ee,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(pe,{id:"areas_served",value:M.areas_served,onChange:ke=>I({...M,areas_served:ke.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(pe,{id:"years_experience",type:"number",min:"0",value:M.years_experience,onChange:ke=>I({...M,years_experience:ke.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"brokerage_name",children:["Brokerage ",D&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(pe,{id:"brokerage_name",value:M.brokerage_name,onChange:ke=>I({...M,brokerage_name:ke.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:D,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),s&&e.jsx(YXs,{userId:s.id,value:v,onChange:y,description:"PNG, JPG, SVG or WebP up to 5MB. Used on your agent website, marketing and email signatures."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(pe,{value:M.linkedin_url,onChange:ke=>I({...M,linkedin_url:ke.target.value}),placeholder:"LinkedIn URL"}),e.jsx(pe,{value:M.instagram_url,onChange:ke=>I({...M,instagram_url:ke.target.value}),placeholder:"Instagram URL"}),e.jsx(pe,{value:M.facebook_url,onChange:ke=>I({...M,facebook_url:ke.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"AI Search & Verified Profiles"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Adding these helps ChatGPT, Perplexity, Google and other AI assistants confirm who you are and recommend you for local searches."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(pe,{value:M.google_business_url,onChange:ke=>I({...M,google_business_url:ke.target.value}),placeholder:"Google Business Profile URL"}),e.jsx(pe,{value:M.zillow_profile_url,onChange:ke=>I({...M,zillow_profile_url:ke.target.value}),placeholder:"Zillow agent profile URL"}),e.jsx(pe,{value:M.realtor_profile_url,onChange:ke=>I({...M,realtor_profile_url:ke.target.value}),placeholder:"Realtor.com profile URL"}),e.jsx(pe,{value:M.specialties,onChange:ke=>I({...M,specialties:ke.target.value}),placeholder:"Specialties (e.g. Waterfront homes, Acreage & farms, First-time buyers)"})]})]}),e.jsxs(z,{onClick:me,disabled:m,className:"profile-inline-save",children:[e.jsx(Bo,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(be,{id:"profile-brand",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Mm,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(En,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Le,{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:M.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(mn,{checked:M.use_email_signature,onCheckedChange:ke=>I({...M,use_email_signature:ke})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Signature"}),e.jsx(GN,{content:M.email_signature,onChange:ke=>I({...M,email_signature:ke}),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(z,{onClick:me,disabled:m,children:[e.jsx(Bo,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx($Xs,{})}),e.jsxs(be,{id:"change-password-section",children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:a||l?"Set Your Password":"Change Password"}),e.jsx(En,{children:a||l?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"newPassword",children:"New Password"}),e.jsx(pe,{id:"newPassword",type:"password",value:ae.newPassword,onChange:ke=>J({...ae,newPassword:ke.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(pe,{id:"confirmPassword",type:"password",value:ae.confirmPassword,onChange:ke=>J({...ae,confirmPassword:ke.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(z,{onClick:he,disabled:m,children:[e.jsx(Bo,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(z,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(be,{id:"profile-notifications",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[c?e.jsx($g,{className:"h-5 w-5"}):e.jsx(pS,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(En,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Le,{children:o?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:c?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(mn,{checked:c,onCheckedChange:ke=>{ke?u():h()},disabled:d})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(IXs,{})}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[q?e.jsx(cP,{className:"h-5 w-5"}):e.jsx(on,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(En,{children:"Manage your email subscription settings"})]}),e.jsxs(Le,{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:q?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(mn,{checked:!q,onCheckedChange:async ke=>{H(!0);try{const{error:Ve}=await U.from("profiles").update({digest_opt_out:!ke}).eq("id",s==null?void 0:s.id);if(Ve)throw Ve;G(!ke),n({title:ke?"Subscribed":"Unsubscribed",description:ke?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Ve){n({title:"Error",description:Ve.message||"Failed to update preference",variant:"destructive"})}finally{H(!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(mn,{checked:!K,onCheckedChange:async ke=>{re(!0);try{const{error:Ve}=await U.from("profiles").update({event_invite_opt_out:!ke}).eq("id",s==null?void 0:s.id);if(Ve)throw Ve;Z(!ke),n({title:ke?"Subscribed":"Unsubscribed",description:ke?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Ve){n({title:"Error",description:Ve.message||"Failed to update preference",variant:"destructive"})}finally{re(!1)}},disabled:oe})]})]})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(jqs,{})}),e.jsx("div",{id:"profile-billing",className:"profile-embedded-section",children:e.jsx(ZXs,{})}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(WXs,{})})]})]})]}),e.jsx(Ltt,{open:S,onClose:()=>C(!1),imageSrc:E,onCropComplete:ve,aspectRatio:1})]})})};var QXs="AspectRatio",FUt=_.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(ci.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});FUt.displayName=QXs;var JXs=FUt;const eQs=JXs;function tQs(){const{user:s}=hs(),t=$t(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),{data:l,isLoading:o}=rt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:f,error:g}=await U.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(g)throw g;return f},enabled:!!s&&a}),c=mt({mutationFn:async()=>{const f=new Uint8Array(12);crypto.getRandomValues(f);const g=btoa(String.fromCharCode(...f)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:v}=await U.from("profiles").update({calendar_token:g}).eq("id",s==null?void 0:s.id);if(v)throw v;return g},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ne.success("Calendar subscription URL generated!")},onError:f=>{ne.error("Failed to generate calendar URL: "+f.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),ne.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const f=d.replace("https://","webcal://"),g=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(f)}`;window.open(g,"_blank")}},p=()=>{if(d){const f=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(f,"_blank")}};return e.jsxs(Is,{open:a,onOpenChange:i,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(_r,{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(bt,{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(pe,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(z,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(Wr,{className:"h-4 w-4 text-green-500"}):e.jsx(Sa,{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(z,{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(mr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(z,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(mr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(z,{variant:"outline",className:"w-full justify-start gap-2",onClick:p,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(mr,{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(z,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const sQs={first_timer:Ia,regular:YA,dedicated:Kh,veteran:jl,streak_master:vu,century:jl},nQs={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 H0t(s){return s===1?e.jsx(jl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(YA,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Kh,{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 OUt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=hs(),{data:i,isLoading:l}=bBt(t?5:10,n),{data:o}=_Bt(a==null?void 0:a.id),{data:c}=jBt(a==null?void 0:a.id),{data:d}=wBt(a==null?void 0:a.id);return l?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(ln,{className:"h-12 w-full"},h))})})]}):e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Le,{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(vu,{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=sQs[u.badge_type]||Ia;return e.jsxs(ze,{variant:"outline",className:`text-xs ${nQs[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(Qr,{defaultValue:"points",className:"w-full",children:[e.jsxs(Jr,{className:"w-full mb-3",children:[e.jsx(Wt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Wt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Kt,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,p,f;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:H0t(h+1)}),e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((f=u.profile)==null?void 0:f.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(Kt,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,p,f;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:H0t(h+1)}),e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((f=u.profile)==null?void 0:f.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 rQs(){const s=zn(),{user:t,isAdmin:n}=hs(),r=$t(),[a,i]=_.useState(!1),[l,o]=_.useState(!1),{data:c,isLoading:d}=rt({queryKey:["public-events"],queryFn:async()=>{const{data:E,error:P}=await U.from("events").select("*").order("event_date",{ascending:!0});if(P)throw P;return E}}),{data:u}=rt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:E,error:P}=await U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(P)throw P;return E},enabled:!!t}),{data:h}=rt({queryKey:["event-registration-counts"],queryFn:async()=>{let E=[],P=0;const M=1e3;for(;;){const{data:D,error:F}=await U.from("event_registrations").select("event_id").range(P,P+M-1);if(F)throw F;if(!D||D.length===0||(E=E.concat(D),D.length{I[D.event_id]=(I[D.event_id]||0)+1}),I}}),m=mt({mutationFn:async E=>{await U.auth.refreshSession();const{data:P,error:M}=await U.functions.invoke("zoom-register",{body:{event_id:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);return P},onSuccess:E=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),E!=null&&E.join_url?ne.success("Successfully registered! You'll receive a Zoom confirmation email."):ne.success("Successfully registered for the event!")},onError:E=>{ne.error("Failed to register: "+E.message)}}),p=mt({mutationFn:async E=>{const{data:P,error:M}=await U.functions.invoke("zoom-unregister",{body:{event_id:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);return P},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ne.success("Registration cancelled and removed from Zoom")},onError:E=>{ne.error("Failed to cancel: "+E.message)}}),f=E=>u==null?void 0:u.some(P=>P.event_id===E),g=E=>{const P=u==null?void 0:u.find(M=>M.event_id===E);return P==null?void 0:P.zoom_join_url},v=E=>E.capacity?((h==null?void 0:h[E.id])||0)>=E.capacity:!1,y=(c==null?void 0:c.filter(E=>NF(E.event_date)!=="ended"))||[],b=(c==null?void 0:c.filter(E=>NF(E.event_date)==="ended"))||[],w=y.filter(E=>NF(E.event_date)==="live").length,S=y.filter(E=>f(E.id)).length,C=l?b:b.slice(0,6);return e.jsx($s,{title:"Events",children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6",children:[e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"LevelUp Live"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Events"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:w>0?"An event is live right now — jump in.":y.length>0?`Next up: ${y[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(tQs,{}),n&&e.jsxs("button",{onClick:()=>s("/admin/events"),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(Gc,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Manage Events"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[{label:"Upcoming",value:y.length,icon:ya},{label:"You're registered",value:S,icon:Wr},{label:"Live now",value:w,icon:Nv},{label:"Past events",value:b.length,icon:O_}].map(E=>e.jsxs("div",{className:"hub-glass rounded-xl px-3 py-2.5",children:[e.jsx("span",{className:"text-xl font-bold",children:E.value}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-1 text-[11px] hub-ink-muted",children:[e.jsx(E.icon,{className:"h-3 w-3"}),E.label]})]},E.label))})]})}),e.jsxs("div",{className:`grid grid-cols-1 gap-6 ${n?"lg:grid-cols-3":""}`,children:[e.jsxs("div",{className:`space-y-6 ${n?"lg:col-span-2":""}`,children:[d?e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:[0,1].map(E=>e.jsx("div",{className:"h-72 animate-pulse rounded-2xl border bg-muted/40"},E))}):y.length===0?e.jsx(be,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Le,{className:"space-y-2",children:[e.jsx(ya,{className:"mx-auto h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:y.map(E=>{const P=NF(E.event_date),M=Get(E.event_date),I=P==="live",D=P==="starting_soon";return e.jsxs(be,{className:`group flex flex-col overflow-hidden rounded-2xl cursor-pointer transition-all hover:shadow-lg ${I?"border-red-500 ring-2 ring-red-500/20":D?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${E.id}`),children:[M&&e.jsxs("div",{className:`${I?"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"})]}),I?e.jsxs(e.Fragment,{children:[e.jsx(Nv,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),E.image_url&&e.jsxs(eQs,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:E.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:E.image_url,alt:E.title,className:"relative w-full h-full object-contain transition-transform group-hover:scale-[1.03]"})]}),e.jsxs(_t,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 px-2.5 py-1 text-[11px] font-semibold text-primary",children:[e.jsx(ya,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))]}),f(E.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-semibold text-emerald-600 dark:text-emerald-400",children:[e.jsx(Wr,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(Nt,{className:"line-clamp-2 pt-1",children:E.title}),E.description&&e.jsx(En,{className:"line-clamp-2",children:E.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Le,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ya,{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(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Zr,{className:"h-4 w-4"}),jte(new Date(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(On,{className:"h-4 w-4"}),(h==null?void 0:h[E.id])||0," registered",E.capacity&&` / ${E.capacity} spots`]})]}),e.jsx(dAe,{className:"flex gap-2",onClick:F=>F.stopPropagation(),children:f(E.id)?e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",className:"flex-1",onClick:()=>p.mutate(E.id),disabled:p.isPending,children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(z,{className:"flex-1",onClick:()=>window.open(g(E.id)||E.zoom_link,"_blank"),children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(z,{className:"w-full",onClick:()=>m.mutate(E.id),disabled:m.isPending||v(E),children:v(E)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},E.id)})}),b.length>0&&e.jsxs(be,{className:"rounded-2xl",children:[e.jsxs("button",{type:"button",onClick:()=>i(E=>!E),className:"flex w-full items-center justify-between gap-3 px-5 py-4 text-left",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-muted",children:e.jsx(O_,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Past Events"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," previous ",b.length===1?"session":"sessions"," — open one to watch the replay"]})]})]}),e.jsx(cl,{className:`h-4 w-4 text-muted-foreground transition-transform ${a?"rotate-180":""}`})]}),a&&e.jsxs("div",{className:"border-t",children:[e.jsx("ul",{className:"divide-y",children:C.map(E=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(`/events/${E.id}`),className:"flex w-full items-center gap-3 px-5 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex w-12 shrink-0 flex-col items-center rounded-lg border bg-muted/40 py-1",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(E.event_date))}),e.jsx("span",{className:"text-sm font-bold leading-none",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:E.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))})]}),e.jsx(dm,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})},E.id))}),b.length>6&&e.jsx("div",{className:"border-t px-5 py-3",children:e.jsx(z,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>o(E=>!E),children:l?"Show less":`Show all ${b.length}`})})]})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(OUt,{showUserStats:!0})})]})]})})}const s9e=[{value:"all",label:"All Roles",icon:On},{value:"newest",label:"Newest Members",icon:Zr},{value:"brokerage_manager",label:"Brokerage Managers",icon:wJ},{value:"admin",label:"Admins",icon:Om}];function aQs({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Pe,Oe;const{user:i,isAdmin:l,isBrokerageManager:o}=hs(),[c,d]=_.useState([]),[u,h]=_.useState([]),[m,p]=_.useState([]),[f,g]=_.useState([]),[v,y]=_.useState(""),[b,w]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,F]=_.useState("agents"),[q,G]=_.useState("all"),[V,H]=_.useState({}),K=l||o;_.useEffect(()=>{s&&i&&(l?Z():oe())},[s,i,l]),_.useEffect(()=>{s||(p([]),g([]),y(""),w(""),C(""),F("agents"),G("all"))},[s]);const Z=async()=>{if(i){P(!0);try{const{data:ke,error:Ve}=await U.from("brokerages").select("id, name").order("name");if(Ve)throw Ve;const _e=1e3,Ae={};let Se=0,We=!0;for(;We;){const{data:Ze,error:$e}=await U.from("profiles").select("brokerage_id").range(Se*_e,(Se+1)*_e-1);if($e)throw $e;Ze==null||Ze.forEach(Xe=>{Xe.brokerage_id&&(Ae[Xe.brokerage_id]=(Ae[Xe.brokerage_id]||0)+1)}),We=(Ze==null?void 0:Ze.length)===_e,Se++}h((ke==null?void 0:ke.map(Ze=>({...Ze,agent_count:Ae[Ze.id]||0})))||[]);const qe=[];for(Se=0,We=!0;We;){const{data:Ze,error:$e}=await U.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Se*_e,(Se+1)*_e-1);if($e)throw $e;Ze&&qe.push(...Ze),We=(Ze==null?void 0:Ze.length)===_e,Se++}const Be={};for(Se=0,We=!0;We;){const{data:Ze,error:$e}=await U.from("user_roles").select("user_id, role").range(Se*_e,(Se+1)*_e-1);if($e)throw $e;Ze==null||Ze.forEach(Xe=>{Be[Xe.user_id]||(Be[Xe.user_id]=[]),Be[Xe.user_id].push(Xe.role)}),We=(Ze==null?void 0:Ze.length)===_e,Se++}H(Be),d(qe.map(Ze=>{var $e;return{id:Ze.id,name:Ze.name,email:Ze.email,brokerage_name:(($e=Ze.brokerages)==null?void 0:$e.name)||"No Brokerage",roles:Be[Ze.id]||[],created_at:Ze.created_at}}))}catch(ke){console.error("Error loading data:",ke),ne.error("Failed to load agents and brokerages")}finally{P(!1)}}},oe=async()=>{if(i){P(!0);try{const{data:ke}=await U.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ke!=null&&ke.brokerage_id)){ne.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ve,error:_e}=await U.from("profiles").select("id, name, email").eq("brokerage_id",ke.brokerage_id).neq("id",i.id).order("name");if(_e)throw _e;d(Ve||[])}catch(ke){console.error("Error loading agents:",ke),ne.error("Failed to load agents")}finally{P(!1)}}},re=c.filter(ke=>{var _e;const Ve=ke.name.toLowerCase().includes(v.toLowerCase())||ke.email.toLowerCase().includes(v.toLowerCase())||((_e=ke.brokerage_name)==null?void 0:_e.toLowerCase().includes(v.toLowerCase()));if(l&&q!=="all"&&q!=="newest"){const Ae=V[ke.id]||[];return Ve&&Ae.includes(q)}return Ve}).sort((ke,Ve)=>q==="newest"?(Ve.created_at||"").localeCompare(ke.created_at||""):0),ae=u.filter(ke=>ke.name.toLowerCase().includes(b.toLowerCase())),J=()=>{m.length===re.length?p([]):p(re.map(ke=>ke.id))},te=()=>{f.length===ae.length?g([]):g(ae.map(ke=>ke.id))},ce=ke=>{if(!K){p([ke]);return}p(Ve=>Ve.includes(ke)?Ve.filter(_e=>_e!==ke):[...Ve,ke])},ve=ke=>{g(Ve=>Ve.includes(ke)?Ve.filter(_e=>_e!==ke):[...Ve,ke])},me=async()=>{if(!(m.length>0||f.length>0)){ne.error("Please select at least one agent or brokerage to share with");return}I(!0);try{const{data:Ve,error:_e}=await U.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:f,resourceType:n,resourceId:r,resourceTitle:a,message:S.trim()||void 0}});if(_e)throw _e;const Ae=(Ve==null?void 0:Ve.sharesCreated)||m.length;ne.success(`Shared with ${Ae} agent${Ae!==1?"s":""}`),t(!1)}catch(Ve){console.error("Error sharing resource:",Ve),ne.error("Failed to share resource")}finally{I(!1)}},he=ke=>ke.split(" ").map(Ve=>Ve[0]).join("").toUpperCase().slice(0,2),ge=ke=>{const Ve=V[ke]||[];return Ve.includes("admin")?e.jsx(ze,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ve.includes("brokerage_manager")?e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ee=m.length+f.length,Ne=q!=="all"&&q!=="newest"?re.length:null;return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{className:"flex-shrink-0",children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(_r,{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(Qr,{value:D,onValueChange:F,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Wt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(ze,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(Wt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),f.length>0&&e.jsx(ze,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:f.length})]})]}),e.jsxs(Kt,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or brokerage...",value:v,onChange:ke=>y(ke.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:q,onValueChange:G,children:[e.jsxs(rs,{className:"w-[180px]",children:[e.jsx(F_,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(cs,{placeholder:"Filter by role"})]}),e.jsx(as,{children:s9e.map(ke=>e.jsx(He,{value:ke.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ke.label})]})},ke.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:J,className:"text-xs h-8",disabled:re.length===0,children:[e.jsx(On,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===re.length&&re.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Ne!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Ne," ",(Pe=s9e.find(ke=>ke.value===q))==null?void 0:Pe.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(Ki,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):re.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(On,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:q!=="all"?`No ${(Oe=s9e.find(ke=>ke.value===q))==null?void 0:Oe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:re.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>ce(ke.id),children:[e.jsx(za,{checked:m.includes(ke.id),onCheckedChange:()=>ce(ke.id),className:"flex-shrink-0"}),e.jsx(ja,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Na,{className:"text-xs bg-primary/10 text-primary",children:he(ke.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:ke.name}),ge(ke.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email,ke.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ke.brokerage_name]})]})]})]},ke.id))})})]}),e.jsxs(Kt,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:b,onChange:ke=>w(ke.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:ae.length===0,children:[e.jsx(oi,{className:"h-3.5 w-3.5 mr-1.5"}),f.length===ae.length&&ae.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[f.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(Ki,{className:"h-[250px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ae.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(oi,{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:ae.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${f.includes(ke.id)?"bg-accent":""}`,onClick:()=>ve(ke.id),children:[e.jsx(za,{checked:f.includes(ke.id),onCheckedChange:()=>ve(ke.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(oi,{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:ke.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ke.agent_count," agent",ke.agent_count!==1?"s":""]})]})]},ke.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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:v,onChange:ke=>y(ke.target.value),className:"pl-9"})]}),K&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:J,className:"text-xs h-8",disabled:re.length===0,children:[e.jsx(On,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===re.length&&re.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(Ki,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):re.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(On,{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:re.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>ce(ke.id),children:[e.jsx(za,{checked:m.includes(ke.id),onCheckedChange:()=>ce(ke.id),className:"flex-shrink-0"}),e.jsx(ja,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Na,{className:"text-xs bg-primary/10 text-primary",children:he(ke.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ke.email})]})]},ke.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(ee,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ps,{id:"message",placeholder:"I thought you might find this useful...",value:S,onChange:ke=>C(ke.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:me,disabled:Ee===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function TW({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=_.useState(!1),{user:c}=hs();return c?e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(aQs,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function iQs(){const{eventId:s}=Mi(),t=zn(),{user:n}=hs(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(0),[d,u]=_.useState(!0),[h,m]=_.useState(!1);_.useEffect(()=>{s&&p()},[s,n]);const p=async()=>{try{const{data:w,error:S}=await U.from("events").select("*").eq("id",s).single();if(S)throw S;a(w);const{count:C}=await U.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(C||0),n){const{data:E}=await U.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(E)}}catch(w){console.error("Error loading event:",w),ne.error("Failed to load event"),t("/events")}finally{u(!1)}},f=async()=>{if(!(!n||!r)){m(!0);try{const{error:w}=await U.auth.refreshSession();if(w){console.error("Session refresh failed:",w),ne.error("Your session has expired. Please log in again.");return}if(i){const{error:S}=await U.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(S)throw S;ne.success("Successfully cancelled registration"),l(null),c(C=>C-1)}else{const{data:S,error:C}=await U.functions.invoke("zoom-register",{body:{event_id:r.id}});if(C)throw C;ne.success("Successfully registered for event!"),l({id:S.registration_id,zoom_join_url:S.zoom_join_url}),c(E=>E+1)}}catch(w){console.error("Registration error:",w),ne.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},g=w=>{var S,C,E;if(w.includes("iframe.mediadelivery.net")||w.includes("video.bunnycdn.com")){const P=w.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(P)return`https://iframe.mediadelivery.net/embed/${P[1]}/${P[2]}?autoplay=false&preload=true`}if(w.includes("youtube.com")||w.includes("youtu.be")){const P=w.includes("youtu.be")?(S=w.split("youtu.be/")[1])==null?void 0:S.split("?")[0]:(C=w.split("v=")[1])==null?void 0:C.split("&")[0];if(P)return`https://www.youtube.com/embed/${P}`}if(w.includes("vimeo.com")){const P=(E=w.split("vimeo.com/")[1])==null?void 0:E.split("?")[0];if(P)return`https://player.vimeo.com/video/${P}`}return w};if(d)return e.jsx($s,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!r)return e.jsx($s,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(z,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const v=sC(new Date(r.event_date)),y=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx($s,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(z,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(ka,{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(TW,{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(dm,{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:g(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(be,{children:e.jsxs(Le,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ya,{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:jte(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(On,{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(Xl,{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(z,{className:"w-full gap-2",onClick:()=>window.open(b,"_blank"),children:[e.jsx(mr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(z,{variant:"outline",className:"w-full",onClick:f,disabled:h,children:[h?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(z,{className:"w-full gap-2",onClick:f,disabled:h||(y??!1),children:h?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):y?"Event Full":"Register Now"})}),v&&i&&e.jsxs(z,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(mr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const oQs=[{to:"/apps",label:"Home",end:!0},{to:"/apps/my-apps",label:"My Apps"},{to:"/apps/browse",label:"Browse Apps"},{to:"/apps/workflows",label:"Workflows",adminOnly:!0},{to:"/apps/connected",label:"Connected Apps"}];function lQs(){const{isAdmin:s}=hs(),t=oQs.filter(n=>!n.adminOnly||s);return e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsx("nav",{className:"inline-flex gap-1 bg-muted/60 p-1 rounded-xl min-w-max",children:t.map(n=>e.jsx(g6,{to:n.to,end:n.end,className:({isActive:r})=>Ct("px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors",r?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:n.label},n.to))})})}const LEe=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:sa,color:"bg-violet-500/15 text-violet-600"},{id:"follow-up",title:"Follow Up With My Database",blurb:"Emails, cards, mail and check-ins",icon:on,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:Nh,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:fj,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:kl,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:yc,color:"bg-teal-500/15 text-teal-600"}];LEe.reduce((s,t)=>({...s,[t.id]:t}),{});const cQs=[{id:"listings",label:"Listings"},{id:"database",label:"Database & Follow-Up"},{id:"leads",label:"Leads & Conversion"},{id:"social",label:"Social & Content"},{id:"open-houses",label:"Open Houses"},{id:"brand",label:"Brand & Presence"},{id:"ai",label:"AI Assistants"}],zUt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:Ud,path:"/mission-control/scheduler",color:"bg-blue-500/15 text-blue-600",isNew:!0,goals:["follow-up","new-business","brand"],categories:["database","leads","brand"],keywords:["scheduler","calendar","booking link","book a meeting","appointments","calendly","availability"]},{id:"quickvid",name:"QuickVid",description:"Record and share personalized video messages",icon:Xr,path:"/mission-control/video/record",color:"bg-rose-500/15 text-rose-600",popular:!0,goals:["follow-up","social-content","open-house"],categories:["database","social","open-houses"],keywords:["video","record a video","send a video","video email","screen record"]},{id:"smart-card",name:"Smart Card",description:"Your digital business card in one shareable link",icon:j0,path:"/mission-control/my-card",color:"bg-sky-500/15 text-sky-600",goals:["brand"],categories:["brand"],keywords:["business card","digital card","share my info","contact card"]},{id:"smart-presentations",name:"Smart Presentations",description:"Beautiful listing and buyer presentations",icon:C0,path:"/mission-control/presentations",color:"bg-amber-500/15 text-amber-600",goals:["market-listing","brand"],categories:["listings","brand"],keywords:["buyer presentation","listing presentation","pitch","slides"]},{id:"landing-pages",name:"Landing Pages",description:"Custom landing pages that capture leads",icon:$r,path:"/mission-control/landing-pages",color:"bg-emerald-500/15 text-emerald-600",goals:["market-listing","new-business","open-house"],categories:["listings","leads","open-houses"],keywords:["landing page","capture leads","promote an open house","single property site"]},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in that captures visitors",icon:ip,path:"/mission-control/guest-book",color:"bg-orange-500/15 text-orange-600",popular:!0,goals:["open-house","new-business"],categories:["open-houses","leads"],keywords:["open house sign in","sign-in sheet","visitors","host an open house"]},{id:"card-studio",name:"Card Studio",description:"Animated cards for birthdays and milestones",icon:un,path:"/mission-control/card-studio",color:"bg-pink-500/15 text-pink-600",goals:["follow-up","social-content"],categories:["database","social"],keywords:["birthday card","anniversary","greeting","thank you card"]},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts",icon:on,path:"/mission-control/direct-mail",color:"bg-indigo-500/15 text-indigo-600",adminOnly:!0,beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["postcard","mailer","farming","direct mail"]},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic reels with AI",icon:Yh,path:"/admin/beta/homereel",color:"bg-violet-500/15 text-violet-600",beta:!0,isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["create a reel","video from photos","instagram","cinematic"]},{id:"mass-emails",name:"Mass Emails",description:"Send bulk email campaigns to your contacts",icon:Fr,path:"/admin/email-campaigns",color:"bg-teal-500/15 text-teal-600",beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["email my database","bulk email","campaign","blast","invite"]},{id:"listing-studio",name:"Listing Studio",description:"AI MLS descriptions, luxury copy and open house blurbs",icon:Mm,path:"/mission-control/listing-studio",color:"bg-fuchsia-500/15 text-fuchsia-600",isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["mls description","write listing copy","captions","ai writing"]},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website",icon:tq,path:"/website-apps",color:"bg-cyan-500/15 text-cyan-600",isNew:!0,goals:["new-business","brand"],categories:["leads","brand"],keywords:["website widget","video greeter","lead magnet","pop up"]},{id:"newsletter-pro",name:"Newsletter Pro",description:"Branded newsletters for your database",icon:vN,path:"/newsletters",color:"bg-yellow-500/15 text-yellow-600",goals:["follow-up"],categories:["database"],keywords:["newsletter","monthly email","market update"]},{id:"weekly-reels",name:"Weekly Reels",description:"5 personalized Reel scripts every Monday morning",icon:Yh,path:"/weekly-reels",color:"bg-orange-500/15 text-orange-600",isNew:!0,requiresWeeklyReels:!0,goals:["social-content"],categories:["social","ai"],keywords:["reel scripts","instagram","content ideas","social posts"]},{id:"cma",name:"CMA Reports",description:"Interactive CMAs with live comps you can share",icon:wl,path:"/mission-control/cma",color:"bg-blue-500/15 text-blue-600",isNew:!0,requiresLeadSiteMLS:!0,goals:["market-listing","new-business"],categories:["listings","leads"],keywords:["cma","comps","home value","pricing"]},{id:"listing-presentation-studio",name:"Listing Presentation Studio",description:"A branded 12-page seller presentation in minutes",icon:C0,path:"/apps/listing-presentation-studio",color:"bg-emerald-500/15 text-emerald-600",isNew:!0,popular:!0,goals:["market-listing"],categories:["listings"],keywords:["make a listing presentation","seller presentation","pdf","pre-listing"]},{id:"listing-revival",name:"Listing Revival",description:"Turn expired listings into appointments",icon:un,path:"/apps/listing-revival",color:"bg-amber-500/15 text-amber-600",isNew:!0,goals:["new-business"],categories:["leads","listings","ai"],keywords:["expired listing","expired","withdrawn","revival letter"]},{id:"fsbo-breakthrough",name:"By-Owner Breakthrough",description:"Convert FSBO sellers with letters, guides and pages",icon:sa,path:"/apps/fsbo-breakthrough",color:"bg-[#5b8a5c]/15 text-[#5b8a5c]",isNew:!0,goals:["new-business"],categories:["leads","ai"],keywords:["fsbo","for sale by owner","by owner","convert fsbo"]},{id:"staging-studio",name:"Staging Studio",description:"Virtually stage, declutter and brighten listing photos",icon:hq,path:"/apps/staging-studio",color:"bg-[#406E71]/15 text-[#406E71]",isNew:!0,featureFlag:"staging_studio_enabled",goals:["market-listing"],categories:["listings","ai"],keywords:["virtual staging","staging","twilight","declutter","sky replacement","landscaping","photo"]}],G0t=zUt.reduce((s,t)=>({...s,[t.id]:t}),{}),dQs={agent_review:{goals:[],categories:[],keywords:[]},sigflow:{goals:["brand","follow-up"],categories:["brand","database"],keywords:["email signature","signature","branding"]},social_autopilot:{goals:["social-content","brand"],categories:["social","brand"],keywords:["social posts","schedule posts","autopilot","facebook","instagram"]}},uQs={AgentReview:"Replaced by the new built-in Reviews app"};function hQs(s){return dQs[s]??{goals:[],categories:[],keywords:[]}}const Itt=[{id:"new-listing-launch",title:"New Listing Launch",description:"Everything you need to take a new listing to market.",outcome:"A listing that is presented, promoted and seen",namePrompt:"What listing is this for?",namePlaceholder:"520 Harlan Drive",icon:sa,color:"bg-violet-500/15 text-violet-600",steps:[{key:"presentation",title:"Build the listing presentation",detail:"Create your branded seller presentation.",toolId:"listing-presentation-studio"},{key:"copy",title:"Write the listing copy",detail:"Generate the MLS description and marketing copy.",toolId:"listing-studio"},{key:"page",title:"Create the property page",detail:"Publish a landing page for the listing.",toolId:"landing-pages"},{key:"reel",title:"Make a reel",detail:"Turn the photos into a cinematic video.",toolId:"reelflow"},{key:"email",title:"Email your database",detail:"Announce the listing to your contacts.",toolId:"mass-emails"},{key:"video",title:"Send a personal video",detail:"Record a quick note for your top contacts.",toolId:"quickvid"}]},{id:"open-house-success",title:"Open House Success Kit",description:"Plan, promote, capture visitors, and follow up.",outcome:"A full open house with every visitor captured",namePrompt:"Which open house is this for?",namePlaceholder:"Sunday open house — 12 Oak St",icon:fj,color:"bg-sky-500/15 text-sky-600",steps:[{key:"page",title:"Build the open house page",detail:"Create a page with the date, time and details.",toolId:"landing-pages"},{key:"invite",title:"Invite your database",detail:"Send the invitation email.",toolId:"mass-emails"},{key:"signin",title:"Set up sign-in",detail:"Turn on the digital guest book for the event.",toolId:"guest-book"},{key:"followup",title:"Follow up with visitors",detail:"Send a personal video to everyone who came.",toolId:"quickvid"}]},{id:"database-touchpoint",title:"Database Touchpoint",description:"Get a valuable message in front of your whole database.",outcome:"Your sphere hears from you this month",namePrompt:"What month or theme is this for?",namePlaceholder:"August market update",icon:On,color:"bg-emerald-500/15 text-emerald-600",steps:[{key:"pick",title:"Pick your message",detail:"Start from a newsletter or market update.",toolId:"newsletter-pro"},{key:"personal",title:"Add a personal touch",detail:"Record a short video intro.",toolId:"quickvid"},{key:"send",title:"Send it out",detail:"Deliver it to your contacts.",toolId:"mass-emails"},{key:"cards",title:"Celebrate milestones",detail:"Send cards to anyone with a milestone this month.",toolId:"card-studio"}]}],f9=Itt.reduce((s,t)=>({...s,[t.id]:t}),{});function mQs({goal:s,onSelect:t}){const n=s.icon;return e.jsxs("button",{type:"button",onClick:()=>t(s),className:"group text-left bg-card border border-border rounded-2xl p-5 transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx("div",{className:Ct("w-12 h-12 rounded-xl flex items-center justify-center mb-4",s.color),children:e.jsx(n,{className:"h-6 w-6"})}),e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.blurb})]})}function pQs({item:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){const a=typeof s.icon=="string"?null:s.icon,i=!!s.lockedFeature,l=i?{label:"Upgrade",className:"bg-muted text-muted-foreground"}:s.isNew?{label:"New",className:"bg-primary/10 text-primary"}:s.beta?{label:"Beta",className:"bg-amber-500/15 text-amber-600"}:s.popular?{label:"Popular",className:"bg-emerald-500/15 text-emerald-600"}:s.kind==="app"&&s.deprecated?{label:"Going away soon",className:"bg-amber-500/15 text-amber-700"}:s.kind==="app"?{label:"Connected",className:"bg-muted text-muted-foreground"}:null;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>n(s),onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n(s))},className:Ct("group h-full text-left bg-card border border-border rounded-2xl p-5 flex flex-col gap-3 cursor-pointer transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",i&&"opacity-80"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ct("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(Hl,{className:"h-5 w-5"}):a?e.jsx(a,{className:"h-6 w-6"}):e.jsx("span",{children:s.icon})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.name}),l&&e.jsx("span",{className:Ct("text-[11px] font-medium px-2 py-0.5 rounded-full",l.className),children:l.label})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsx("button",{type:"button","aria-label":t?`Remove ${s.name} from favorites`:`Add ${s.name} to favorites`,onClick:o=>{o.stopPropagation(),r(s)},className:Ct("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(Ty,{className:Ct("h-5 w-5",t&&"fill-current")})})]}),e.jsx("div",{className:"mt-auto pt-1",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i?"Request access →":"Open →"})})]})}function M7({items:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){return e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(a=>e.jsx(pQs,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const fQs="bg-primary/10 text-primary";function wae(){const{user:s,isAdmin:t}=hs(),n=OS(),r=zn(),{hasAccess:a}=hPe(),{isFeatureEnabled:i}=Wre(),[l,o]=_.useState([]),[c,d]=_.useState(!0),[u,h]=_.useState(new Set),[m,p]=_.useState(new Set),[f,g]=_.useState(!1),[v,y]=_.useState([]),[b,w]=_.useState(""),S=_.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:H},{data:K},{data:Z},{data:oe},{data:re},{data:ae},{data:J}]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s.id),U.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),U.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),U.from("profiles").select("name").eq("id",s.id).maybeSingle()]),te=(H||[]).map(ge=>ge.tag);g((re||[]).some(ge=>ge.is_active&&ge.mls_provider_id&&!ge.no_mls_mode)),h(new Set((Z||[]).map(ge=>ge.app_id))),p(new Set((oe||[]).map(ge=>ge.tool_id)));const ce=(K||[]).filter(ge=>ge.app_id==="newsletter_studio"?!1:!ge.required_tags||ge.required_tags.length===0?!0:ge.required_tags.some(Ee=>te.includes(Ee)));o(ce.sort((ge,Ee)=>ge.name==="LevelUp Members Portal"?-1:Ee.name==="LevelUp Members Portal"?1:0));const ve=new Set,me=[];for(const ge of ae||[])if(!(!ge.app_id||ve.has(ge.app_id))&&(ve.add(ge.app_id),me.push({appId:ge.app_id,name:ge.app_name,at:ge.launched_at}),me.length>=8))break;y(me);const he=J==null?void 0:J.name;w(he?he.trim().split(" ")[0]:"")}catch(H){console.error("Error loading app catalog:",H),ne.error("Failed to load apps")}finally{d(!1)}},[s==null?void 0:s.id]);_.useEffect(()=>{S()},[S]);const C=_.useMemo(()=>{const H=re=>{if(!n.isRestricted)return null;const ae=gNs(re);return ae&&!n.hasFeature(ae)?ae:null},K=zUt.filter(re=>!(re.adminOnly&&!t||re.requiresLeadSiteMLS&&!f&&!t||re.requiresWeeklyReels&&!a||re.featureFlag&&!i(re.featureFlag)&&!t)).map(re=>({key:`tool:${re.id}`,kind:"tool",id:re.id,name:re.name,description:re.description,icon:re.icon,color:re.color,isNew:re.isNew,beta:re.beta,popular:re.popular,goals:re.goals,categories:re.categories,keywords:re.keywords,lockedFeature:H(re.id),tool:re})),Z={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},oe=l.map(re=>{const ae=hQs(re.app_id),J=Z[re.app_id];return{key:`app:${re.app_id}`,kind:"app",id:re.app_id,name:re.name,description:re.description,icon:re.icon,color:fQs,goals:ae.goals,categories:ae.categories,keywords:ae.keywords,lockedFeature:n.isRestricted&&J&&!n.hasFeature(J)?J:null,deprecated:!!uQs[re.app_id],tile:re}});return[...K,...oe]},[l,t,f,a,i,n.isRestricted,n.features]),E=_.useCallback(H=>{var K;return H.kind==="tool"?m.has(H.id):u.has(((K=H.tile)==null?void 0:K.id)??"")},[m,u]),P=_.useMemo(()=>C.filter(E),[C,E]),M=_.useMemo(()=>{const H=new Map(C.map(K=>[K.id,K]));return v.map(K=>H.get(K.appId)).filter(Boolean)},[C,v]),I=_.useMemo(()=>C.filter(H=>H.kind==="app"),[C]),D=_.useCallback(async(H,K)=>{try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:H,app_name:K,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),F=_.useCallback(async H=>{var Z;if(H.target_url.startsWith("/")){await D(H.app_id,H.name),r(H.target_url);return}try{const oe=new URL(H.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(oe.hostname)){await D(H.app_id,H.name),r(oe.pathname+oe.search+oe.hash);return}}catch{}const K=window.open("about:blank","_blank");try{const{data:oe,error:re}=await U.auth.getSession();if(re||!oe.session){K==null||K.close(),ne.error("Session expired. Please refresh the page and try again.");return}await D(H.app_id,H.name);const{data:ae,error:J}=await U.functions.invoke("sso-launch",{body:{app_id:H.app_id},headers:{Authorization:`Bearer ${oe.session.access_token}`}});if(J)throw J;ae!=null&&ae.redirect_url?K&&!K.closed?(K.location.href=ae.redirect_url,(Z=K.focus)==null||Z.call(K)):window.location.assign(ae.redirect_url):(K==null||K.close(),ne.error("Launch link unavailable"))}catch(oe){K==null||K.close(),console.error("Error launching app:",oe),ne.error("Failed to launch app. Please try again.")}},[D,r]),q=_.useCallback(H=>{if(H.lockedFeature){r(`/upgrade/${H.lockedFeature}`);return}if(H.kind==="app"&&H.tile){F(H.tile);return}H.tool&&(D(H.tool.id,H.tool.name),r(H.tool.path))},[F,D,r]),G=_.useCallback(async H=>{var J;if(!(s!=null&&s.id))return;const K=E(H),Z=H.kind==="tool"?"user_tool_favorites":"user_favorites",oe=H.kind==="tool"?"tool_id":"app_id",re=H.kind==="tool"?H.id:(J=H.tile)==null?void 0:J.id;if(!re)return;const ae=H.kind==="tool"?p:h;ae(te=>{const ce=new Set(te);return K?ce.delete(re):ce.add(re),ce});try{if(K){const{error:te}=await U.from(Z).delete().eq("user_id",s.id).eq(oe,re);if(te)throw te}else{const{error:te}=await U.from(Z).insert({user_id:s.id,[oe]:re});if(te)throw te}}catch(te){console.error("Error toggling favorite:",te),ne.error("Failed to update favorites"),ae(ce=>{const ve=new Set(ce);return K?ve.add(re):ve.delete(re),ve})}},[E,s==null?void 0:s.id]),V=_.useCallback((H,K=C)=>{const Z=H.trim().toLowerCase();if(!Z)return K;const oe=Z.split(/\s+/);return K.filter(re=>{if(re.deprecated)return!1;const ae=[re.name,re.description,...re.keywords,...re.categories,...re.goals].join(" ").toLowerCase();return oe.every(J=>ae.includes(J))||ae.includes(Z)})},[C]);return{loading:c,items:C,favoriteItems:P,recentItems:M,connectedItems:I,recent:v,firstName:b,isFavorite:E,toggleFavorite:G,openItem:q,search:V,reload:S}}function n9e(s){return{id:s.id,workflow_id:s.workflow_id,run_name:s.run_name,status:s.status==="completed"?"completed":"in_progress",step_state:s.step_state??{},completed_at:s.completed_at,last_activity_at:s.last_activity_at,created_at:s.created_at}}function KLe(s){const t=f9[s.workflow_id],n=(t==null?void 0:t.steps.length)??0,r=t?t.steps.filter(a=>s.step_state[a.key]).length:Object.keys(s.step_state).length;return{touched:r,total:n,pct:n?Math.round(r/n*100):0}}function YLe(){const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),i=_.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:p}=await U.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(p)throw p;n((m||[]).map(n9e))}catch(m){console.error("Error loading workflow runs:",m)}finally{a(!1)}},[s==null?void 0:s.id]);_.useEffect(()=>{i()},[i]);const l=_.useCallback(async(m,p)=>{var f;if(!(s!=null&&s.id))return null;try{const{data:g,error:v}=await U.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:p.trim()||((f=f9[m])==null?void 0:f.title)||"Untitled"}).select("*").single();if(v)throw v;const y=n9e(g);return n(b=>[y,...b]),y}catch(g){return console.error("Error starting workflow:",g),ne.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=_.useCallback(async(m,p)=>{const f={...p,last_activity_at:new Date().toISOString()};n(v=>v.map(y=>y.id===m?n9e({...y,...f}):y));const{error:g}=await U.from("workflow_runs").update(f).eq("id",m);g&&(console.error("Error updating workflow run:",g),ne.error("Could not save your progress"))},[]),c=_.useCallback(async(m,p,f)=>{const g={...m.step_state};f?g[p]=f:delete g[p];const v=f9[m.workflow_id],y=v?v.steps.every(b=>g[b.key]):!1;await o(m.id,{step_state:g,status:y?"completed":"in_progress",completed_at:y?new Date().toISOString():null}),y&&m.status!=="completed"&&ne.success("Workflow complete — nice work!")},[o]),d=_.useCallback((m,p)=>o(m.id,{run_name:p.trim()}),[o]),u=_.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=_.useCallback(async m=>{n(f=>f.filter(g=>g.id!==m));const{error:p}=await U.from("workflow_runs").delete().eq("id",m);p&&(console.error("Error deleting workflow run:",p),ne.error("Could not delete this workflow"))},[]);return{runs:t,loading:r,activeRuns:t.filter(m=>m.status==="in_progress"),completedRuns:t.filter(m=>m.status==="completed"),startRun:l,setStep:c,renameRun:d,reopenRun:u,deleteRun:h,reload:i}}function xQs(){const s=Number(new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",hour:"numeric",hour12:!1}).format(new Date));return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}function gQs(){const s=zn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=wae(),{isAdmin:d}=hs(),{activeRuns:u}=YLe(),h=d?u:[],[m,p]=_.useState(""),f=_.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),g=_.useMemo(()=>{const y=new Set(r.map(S=>S.id)),b=[],w=S=>{for(const C of S){if(b.length>=4)break;b.some(E=>E.key===C.key)||b.push(C)}};return w(a.filter(S=>!y.has(S.id))),w(t.filter(S=>S.isNew&&!y.has(S.id))),w(t.filter(S=>S.popular&&!y.has(S.id))),b},[t,a,r]),v=y=>s(`/apps/browse?goal=${y.id}`);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:[xQs(),n?`, ${n}`:""]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"What do you want to accomplish today?"}),e.jsxs("div",{className:"relative mt-5 max-w-2xl",children:[e.jsx(Rr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(pe,{value:m,onChange:y=>p(y.target.value),onKeyDown:y=>{y.key==="Enter"&&m.trim()&&s(`/apps/browse?q=${encodeURIComponent(m.trim())}`)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-14 text-base rounded-2xl"})]}),m.trim()&&e.jsx("div",{className:"mt-4 max-w-2xl bg-card border border-border rounded-2xl divide-y divide-border overflow-hidden",children:f.length===0?e.jsxs("p",{className:"p-4 text-sm text-muted-foreground",children:["Nothing matched “",m,"”. Try “open house”, “email my database” or “reel”."]}):f.map(y=>{const b=typeof y.icon=="string"?null:y.icon;return e.jsxs("button",{type:"button",onClick:()=>o(y),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:Ct("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",y.color),children:b?e.jsx(b,{className:"h-5 w-5"}):y.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:y.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:y.description})]})]},y.key)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start with a goal"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:LEe.map(y=>e.jsx(mQs,{goal:y,onSelect:v},y.id))})]}),(h.length>0||r.length>0)&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})," Continue working"]}),h.length>0&&e.jsx("div",{className:"space-y-3 mb-4",children:h.slice(0,2).map(y=>{const b=f9[y.workflow_id],w=KLe(y);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${y.id}`),className:"w-full text-left bg-card border border-border rounded-2xl p-4 hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:y.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[b==null?void 0:b.title," · Step ",Math.min(w.touched+1,w.total)," of ",w.total]})]}),e.jsx(Da,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${w.pct}%`}})})]},y.id)})}),r.length>0&&e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 sm:mx-0 sm:px-0 scrollbar-hide",children:r.slice(0,6).map(y=>{const b=typeof y.icon=="string"?null:y.icon;return e.jsxs("button",{type:"button",onClick:()=>o(y),className:"flex-shrink-0 w-44 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Ct("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",y.color),children:b?e.jsx(b,{className:"h-5 w-5"}):y.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:y.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},y.key)})})]})]}),g.length>0&&e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:g.map(y=>{const b=typeof y.icon=="string"?null:y.icon;return e.jsxs("button",{type:"button",onClick:()=>o(y),className:"w-full flex items-start gap-3 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Ct("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",y.color),children:b?e.jsx(b,{className:"h-5 w-5"}):y.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:y.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:y.description})]})]},y.key)})}),e.jsx(z,{variant:"outline",className:"w-full",onClick:()=>s("/apps/browse"),children:"Browse all apps"})]})]}),a.length>0&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Your favorites"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(M7,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function BUt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?KLe(t):null;return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5 flex flex-col gap-4 h-full",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ct("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",s.color),children:e.jsx(a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Mr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[s.steps.length," steps · ",s.outcome]})]}),t&&i?e.jsxs("div",{className:"mt-auto space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsx("span",{className:"truncate pr-2",children:t.run_name}),e.jsxs("span",{className:"flex-shrink-0",children:["Step ",Math.min(i.touched+1,i.total)," of ",i.total]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${i.pct}%`}})})]}),e.jsxs(z,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(Da,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs(z,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(Da,{className:"h-4 w-4 ml-1"})]})})]})}function $Ut({workflow:s,onClose:t,onStart:n}){const[r,a]=_.useState(""),[i,l]=_.useState(!1);_.useEffect(()=>{a(""),l(!1)},[s==null?void 0:s.id]);const o=async()=>{s&&(l(!0),await n(s,r.trim()||s.title),l(!1))};return e.jsx(Is,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:s==null?void 0:s.title}),e.jsxs(_r,{children:[s==null?void 0:s.steps.length," steps · your progress saves automatically so you can come back any time."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(pe,{id:"workflow-run-name",value:r,onChange:c=>a(c.target.value),placeholder:s==null?void 0:s.namePlaceholder,onKeyDown:c=>{c.key==="Enter"&&o()},autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is just so you recognize it later. You can change it any time."})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx(z,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function yQs(){const s=zn(),[t,n]=Gl(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=wae(),{isAdmin:c}=hs(),{activeRuns:d,startRun:u}=YLe(),h=t.get("goal"),m=t.get("category")??null,[p,f]=_.useState(t.get("q")??""),[g,v]=_.useState(null);_.useEffect(()=>{f(t.get("q")??"")},[t]);const y=(E,P)=>{const M=new URLSearchParams(t);P?M.set(E,P):M.delete(E),n(M,{replace:!0})},b=()=>{const E=new URLSearchParams(t);E.delete("category"),E.delete("goal"),E.delete("q"),n(E,{replace:!0}),f("")},w=_.useMemo(()=>{let E=r;return h&&(E=E.filter(P=>P.goals.includes(h))),m&&(E=E.filter(P=>P.categories.includes(m))),p.trim()&&(E=o(p,E)),E},[r,h,m,p,o]),S=_.useMemo(()=>h||m||p.trim()?null:LEe.map(E=>({goal:E,apps:r.filter(P=>P.goals.includes(E.id))})).filter(E=>E.apps.length>0),[r,h,m,p]),C=h?LEe.find(E=>E.id===h):null;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Browse apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Every LevelUp app in one place, grouped by what it helps you get done."})]}),e.jsxs("div",{className:"relative max-w-2xl",children:[e.jsx(Rr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(pe,{value:p,onChange:E=>{f(E.target.value),y("q",E.target.value||null)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-12 rounded-2xl"})]}),e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsxs("div",{className:"inline-flex gap-2 min-w-max pb-1",children:[e.jsx("button",{type:"button",onClick:b,className:Ct("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",!m&&!h&&!p.trim()?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:"All"}),cQs.map(E=>e.jsx("button",{type:"button",onClick:()=>y("category",m===E.id?null:E.id),className:Ct("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===E.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:E.label},E.id))]})}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing apps for"}),e.jsxs("button",{type:"button",onClick:()=>y("goal",null),className:"text-sm font-medium px-3 py-1.5 rounded-full bg-primary/10 text-primary",children:[C.title," ✕"]})]}),c&&!p.trim()&&!m&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Popular workflows"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Itt.map(E=>e.jsx(BUt,{workflow:E,activeRun:d.find(P=>P.workflow_id===E.id),onStart:v,onResume:P=>s(`/apps/workflows/${P.id}`)},E.id))})]}),S?S.map(({goal:E,apps:P})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:E.title}),e.jsx(M7,{items:P,isFavorite:a,onOpen:l,onToggleFavorite:i})]},E.id)):w.length>0?e.jsx(M7,{items:w,isFavorite:a,onOpen:l,onToggleFavorite:i}):e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Rr,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No apps matched that"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Try a simpler phrase, like “open house” or “email”."})]}),e.jsx($Ut,{workflow:g,onClose:()=>v(null),onStart:async(E,P)=>{const M=await u(E.id,P);v(null),M&&s(`/apps/workflows/${M.id}`)}})]})}function vQs(){const s=zn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=wae(),o=t.length===0&&n.length===0;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"My apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Your favorites and what you've used recently."})]}),o&&e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Ty,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"Nothing saved yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Tap the bookmark on any app to pin it here for quick access."}),e.jsx(z,{className:"mt-4",onClick:()=>s("/apps/browse"),children:"Browse apps"})]}),t.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Ty,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(M7,{items:t,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(M7,{items:n,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),r.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Vw,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(M7,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function bQs(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=wae();return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Connected apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Partner apps that are activated for your LevelUp account. Open one and you're signed in automatically."})]}),s.length===0?e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Oc,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No connected apps yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Connected apps appear here once they're activated for your account."})]}):e.jsx(M7,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function _Qs(){const s=zn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=YLe(),[l,o]=_.useState(null);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Workflows"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Step-by-step playbooks that walk you through the whole job. Your progress saves as you go."})]}),t.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"In progress"}),e.jsx("div",{className:"space-y-3",children:t.map(c=>{const d=f9[c.workflow_id],u=KLe(c);return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-4 flex items-center gap-4",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[d==null?void 0:d.title," · Step ",Math.min(u.touched+1,u.total)," of ",u.total]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${u.pct}%`}})})]}),e.jsx(z,{onClick:()=>s(`/apps/workflows/${c.id}`),children:"Continue"})]},c.id)})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start a workflow"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Itt.map(c=>e.jsx(BUt,{workflow:c,onStart:o,onResume:d=>s(`/apps/workflows/${d.id}`)},c.id))})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Mr,{className:"h-4 w-4 text-emerald-600"})," Completed"]}),e.jsx("div",{className:"space-y-2",children:n.map(c=>{var d;return e.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:(d=f9[c.workflow_id])==null?void 0:d.title})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Dx,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx(z,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx($Ut,{workflow:l,onClose:()=>o(null),onStart:async(c,d)=>{const u=await r(c.id,d);o(null),u&&s(`/apps/workflows/${u.id}`)}})]})}function wQs(){const{runId:s}=Mi(),t=zn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=YLe(),{items:c,openItem:d}=wae(),[u,h]=_.useState(!1),[m,p]=_.useState(""),f=_.useMemo(()=>n.find(w=>w.id===s),[n,s]),g=f?f9[f.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!f||!g)return e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx("p",{className:"font-medium text-foreground",children:"This workflow isn't available"}),e.jsx(z,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const v=KLe(f),y=g.icon,b=w=>{if(!w)return;const S=c.find(E=>E.kind==="tool"&&E.id===w);if(S){d(S);return}const C=G0t[w];C&&t(C.path)};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("button",{type:"button",onClick:()=>t("/apps/workflows"),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(ka,{className:"h-4 w-4"})," All workflows"]}),e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Ct("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",g.color),children:e.jsx(y,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:m,onChange:w=>p(w.target.value),autoFocus:!0,onKeyDown:w=>{w.key==="Enter"&&(i(f,m),h(!1))}}),e.jsx(z,{size:"sm",onClick:()=>{i(f,m),h(!1)},children:"Save"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:f.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{p(f.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(Wa,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[g.title," · ",g.description]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground mb-2",children:[e.jsxs("span",{children:[v.touched," of ",v.total," steps done"]}),e.jsxs("span",{children:[v.pct,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${v.pct}%`}})})]}),f.status==="completed"&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 rounded-xl bg-emerald-500/10 p-3",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-700 flex items-center gap-2",children:[e.jsx(Mr,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>l(f),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:g.steps.map((w,S)=>{const C=f.step_state[w.key],E=w.toolId?G0t[w.toolId]:void 0,P=C==="done",M=C==="skipped";return e.jsx("li",{className:Ct("bg-card border rounded-2xl p-4 sm:p-5 transition-colors",P?"border-emerald-500/40":M?"border-border opacity-70":"border-border"),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Ct("w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-semibold",P?"bg-emerald-500 text-white":M?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"),children:P?e.jsx(Wr,{className:"h-4 w-4"}):S+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ct("font-medium text-foreground",(P||M)&&"line-through decoration-muted-foreground/40"),children:w.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:w.detail}),E&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Uses ",E.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[E&&e.jsxs(z,{size:"sm",onClick:()=>b(w.toolId),children:["Open ",E.name," ",e.jsx(mr,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(z,{size:"sm",variant:P?"secondary":"outline",onClick:()=>a(f,w.key,P?null:"done"),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),P?"Done":"Mark done"]}),e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>a(f,w.key,M?null:"skipped"),children:[e.jsx(fJ,{className:"h-3.5 w-3.5 mr-1"}),M?"Un-skip":"Skip"]})]})]})]})},w.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs(z,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(f.id),t("/apps/workflows")},children:[e.jsx(Cn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const jQs=()=>{const{isAdmin:s}=hs();return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(lQs,{}),e.jsxs(TH,{children:[e.jsx(Jt,{index:!0,element:e.jsx(gQs,{})}),e.jsx(Jt,{path:"browse",element:e.jsx(yQs,{})}),e.jsx(Jt,{path:"my-apps",element:e.jsx(vQs,{})}),e.jsx(Jt,{path:"connected",element:e.jsx(bQs,{})}),s&&e.jsx(Jt,{path:"workflows",element:e.jsx(_Qs,{})}),s&&e.jsx(Jt,{path:"workflows/:runId",element:e.jsx(wQs,{})}),e.jsx(Jt,{path:"*",element:e.jsx(ed,{to:"/apps",replace:!0})})]})]})})},NQs=()=>{var w;const s=zn(),{isAdmin:t}=hs(),[n,r]=_.useState(""),[a,i]=_.useState("all"),[l,o]=_.useState("all"),[c,d]=_.useState("grid"),{data:u=[]}=rt({queryKey:["template-categories"],queryFn:async()=>{const{data:S,error:C}=await U.from("template_categories").select("*").order("name");if(C)throw C;return S}}),{data:h=[]}=rt({queryKey:["template-types"],queryFn:async()=>{const{data:S,error:C}=await U.from("template_types").select("*").order("name");if(C)throw C;return S}}),{data:m=[],isLoading:p}=rt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:S,error:C}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(C)throw C;const{data:E,error:P}=await U.from("template_links").select("*").order("sort_order");if(P)throw P;const M=async H=>{let Z=0;const oe=[];for(;;){const{data:re,error:ae}=await H().range(Z,Z+1e3-1);if(ae)throw ae;if(!re||re.length===0||(oe.push(...re),re.length<1e3))break;Z+=1e3}return oe},I=await M(()=>U.from("template_likes").select("template_id")),D=await M(()=>U.from("template_comments").select("template_id")),F=new Map;I.forEach(H=>{F.set(H.template_id,(F.get(H.template_id)||0)+1)});const q=new Map;D.forEach(H=>{q.set(H.template_id,(q.get(H.template_id)||0)+1)});const G=new Map;return t&&(await M(()=>U.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(K=>{G.set(K.resource_id,(G.get(K.resource_id)||0)+1)}),(S||[]).map(H=>({...H,links:(E||[]).filter(K=>K.template_id===H.id)||[],likesCount:F.get(H.id)||0,commentsCount:q.get(H.id)||0,viewsCount:G.get(H.id)||0}))}}),f=m.filter(S=>{var M;const C=S.name.toLowerCase().includes(n.toLowerCase())||((M=S.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),E=a==="all"||S.category_id===a,P=l==="all"||S.type_id===l;return C&&E&&P}),g=()=>{r(""),i("all"),o("all")},v=n||a!=="all"||l!=="all",y=(w=[...m].sort((S,C)=>new Date(C.publish_date||C.created_at).getTime()-new Date(S.publish_date||S.created_at).getTime())[0])==null?void 0:w.id,b=S=>{s(`/templates/${S}`)};return e.jsx($s,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!p&&m.filter(S=>S.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(Ia,{className:"h-5 w-5 fill-foreground text-foreground"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Featured Templates"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:m.filter(S=>S.is_featured).slice(0,4).map(S=>e.jsxs(be,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>b(S.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[S.id===y&&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!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.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(Le,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:ete(S.description)})]})]},S.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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search templates...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-full sm:w-48",children:e.jsx(cs,{placeholder:"All Categories"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Categories"}),u.map(S=>e.jsx(He,{value:S.id,children:S.name},S.id))]})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-full sm:w-48",children:e.jsx(cs,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),h.map(S=>e.jsx(He,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[v&&e.jsx(z,{variant:"outline",size:"sm",onClick:g,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(op,{className:"h-4 w-4"})}),e.jsx(z,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(My,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[f.length," template",f.length!==1?"s":""," found"]}),p&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((S,C)=>e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(ln,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(ln,{className:"h-5 w-3/4 mb-2"}),e.jsx(ln,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ln,{className:"h-5 w-16"}),e.jsx(ln,{className:"h-5 w-20"})]})]})},C))}),!p&&f.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(z,{variant:"outline",onClick:g,children:"Clear Filters"})]}),!p&&f.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:f.map(S=>e.jsxs(be,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>b(S.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[S.id===y&&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!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.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"}),S.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(Kc,{className:"h-3 w-3"}),S.links.length]})})]}),e.jsxs(Le,{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:S.name}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:ete(S.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[S.category&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:S.category.name}),S.type&&e.jsx(ze,{variant:"outline",className:"text-xs",children:S.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(Ug,{className:"h-3.5 w-3.5"}),S.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),S.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(xa,{className:"h-3.5 w-3.5"}),S.viewsCount]})]}),e.jsxs(z,{size:"sm",className:"w-full gap-2",onClick:C=>{C.stopPropagation(),b(S.id)},children:[e.jsx(mr,{className:"h-4 w-4"}),"View Template"]})]})]},S.id))})]})})},kQs=()=>{const{templateId:s}=Mi(),t=zn(),{user:n,isAdmin:r}=hs(),{toast:a}=_i(),i=$t(),{trackEngagement:l}=CW(),[o,c]=_.useState(""),{data:d,isLoading:u}=rt({queryKey:["template-detail",s],queryFn:async()=>{const{data:S,error:C}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(C)throw C;const{data:E}=await U.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:P}=await U.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...S,links:E||[],guides:P||[]}},enabled:!!s}),{data:h=[]}=rt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:S,error:C}=await U.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(C)throw C;return(S||[]).map(E=>E.resource_kits).filter(Boolean)},enabled:!!s});_.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:m=[]}=rt({queryKey:["template-likes",s],queryFn:async()=>{const{data:S,error:C}=await U.from("template_likes").select("*").eq("template_id",s);if(C)throw C;return S},enabled:!!s}),{data:p=[]}=rt({queryKey:["template-comments",s],queryFn:async()=>{const{data:S,error:C}=await U.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(C)throw C;const E=[...new Set(S.map(I=>I.user_id))],{data:P}=await U.from("profiles").select("id, name").in("id",E),M=new Map((P==null?void 0:P.map(I=>[I.id,I.name]))||[]);return S.map(I=>({...I,user_name:M.get(I.user_id)||"Unknown User"}))},enabled:!!s}),f=mt({mutationFn:async S=>{const{error:C}=await U.from("template_comments").insert({template_id:s,user_id:n.id,content:S});if(C)throw C},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:S=>{a({title:"Error adding comment",description:S.message,variant:"destructive"})}}),g=mt({mutationFn:async S=>{const{error:C}=await U.from("template_comments").delete().eq("id",S);if(C)throw C},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),v=mt({mutationFn:async()=>{const S=m.find(C=>C.user_id===(n==null?void 0:n.id));if(S){const{error:C}=await U.from("template_likes").delete().eq("id",S.id);if(C)throw C}else{const{error:C}=await U.from("template_likes").insert({template_id:s,user_id:n.id});if(C)throw C}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),y=m.some(S=>S.user_id===(n==null?void 0:n.id)),b=S=>S.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),w=S=>{S.preventDefault(),!(!o.trim()||!n)&&f.mutate(o.trim())};return u?e.jsx($s,{title:"Templates",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):d?e.jsx($s,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/templates",children:[e.jsx(ka,{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(z,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(or,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Wa,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(TW,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(z,{variant:y?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!n||v.isPending,children:[e.jsx(Ug,{className:`h-4 w-4 ${y?"fill-current":""}`}),m.length," ",m.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Kc,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(S=>e.jsxs(z,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(S.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:S.title}),e.jsx(mr,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),d.video_url&&e.jsx(be,{children:e.jsx(Le,{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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(S=>e.jsxs(z,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(S.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:S.name}),S.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(S.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),h.length>0&&e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Sh,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(S=>e.jsxs(z,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${S.id}`),children:[S.featured_image_url?e.jsx("img",{src:S.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(Sh,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:S.name})]},S.id))})]})}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Bu,{className:"h-5 w-5"}),"Comments (",p.length,")"]}),n?e.jsxs("form",{onSubmit:w,className:"flex gap-2",children:[e.jsx(Ps,{placeholder:"Add a comment...",value:o,onChange:S=>c(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(z,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||f.isPending,children:e.jsx(Fr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:p.length===0?e.jsx(be,{children:e.jsx(Le,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):p.map(S=>e.jsx(be,{children:e.jsx(Le,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:b(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:Md(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(n==null?void 0:n.id)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>g.mutate(S.id),children:e.jsx(Cn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx($s,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Kc,{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(z,{asChild:!0,className:"mt-4",children:e.jsx(or,{to:"/templates",children:"Back to Templates"})})]})})},W0t=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=kLe(s);return e.jsxs(be,{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(Mr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Le,{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(Zr,{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(gc,{className:"h-3.5 w-3.5"}),"Starts ",yu(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(On,{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":Df(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 ",_te(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${yu(s.charge_at)}`:""]}):null]}),e.jsx(z,{asChild:!0,size:"sm",children:e.jsxs(or,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Da,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},SQs=()=>{const{data:s=[],isLoading:t}=mBt(),{data:n=[]}=Vet(),r=new Set(n.filter(l=>UH(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($s,{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(ln,{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(W0t,{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(be,{className:"border-dashed",children:e.jsxs(Le,{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(W0t,{program:l,enrolled:!1},l.id))})]})]})]})})},CQs=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},AQs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=_.useState(!1),i=(s||"").trim();if(!i)return null;const l=CQs(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(dm,{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 ZLe="Collapsible",[EQs,UUt]=uf(ZLe),[TQs,Dtt]=EQs(ZLe),qUt=_.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Gg({prop:r,defaultProp:a??!1,onChange:l,caller:ZLe});return e.jsx(TQs,{scope:n,disabled:i,contentId:qg(),open:c,onOpenToggle:_.useCallback(()=>d(u=>!u),[d]),children:e.jsx(ci.div,{"data-state":ztt(c),"data-disabled":i?"":void 0,...o,ref:t})})});qUt.displayName=ZLe;var VUt="CollapsibleTrigger",Rtt=_.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=Dtt(VUt,n);return e.jsx(ci.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":ztt(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:wa(s.onClick,a.onOpenToggle)})});Rtt.displayName=VUt;var Ftt="CollapsibleContent",Ott=_.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Dtt(Ftt,s.__scopeCollapsible);return e.jsx(vg,{present:n||a.open,children:({present:i})=>e.jsx(MQs,{...r,ref:t,present:i})})});Ott.displayName=Ftt;var MQs=_.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=Dtt(Ftt,n),[o,c]=_.useState(r),d=_.useRef(null),u=el(t,d),h=_.useRef(0),m=h.current,p=_.useRef(0),f=p.current,g=l.open||o,v=_.useRef(g),y=_.useRef(void 0);return _.useEffect(()=>{const b=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(b)},[]),Rx(()=>{const b=d.current;if(b){y.current=y.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const w=b.getBoundingClientRect();h.current=w.height,p.current=w.width,v.current||(b.style.transitionDuration=y.current.transitionDuration,b.style.animationName=y.current.animationName),c(r)}},[l.open,r]),e.jsx(ci.div,{"data-state":ztt(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!g,...i,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":f?`${f}px`:void 0,...s.style},children:g&&a})});function ztt(s){return s?"open":"closed"}var HUt=qUt,PQs=Rtt,LQs=Ott,BS="Accordion",IQs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Btt,DQs,RQs]=tW(BS),[XLe,Mwr]=uf(BS,[RQs,UUt]),$tt=UUt(),GUt=Ft.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(Btt.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(BQs,{...i,ref:t}):e.jsx(zQs,{...a,ref:t})})});GUt.displayName=BS;var[WUt,FQs]=XLe(BS),[KUt,OQs]=XLe(BS,{collapsible:!1}),zQs=Ft.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=Gg({prop:n,defaultProp:r??"",onChange:a,caller:BS});return e.jsx(WUt,{scope:s.__scopeAccordion,value:Ft.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Ft.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(KUt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(YUt,{...l,ref:t})})})}),BQs=Ft.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Gg({prop:n,defaultProp:r??[],onChange:a,caller:BS}),c=Ft.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Ft.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(WUt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(KUt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(YUt,{...i,ref:t})})})}),[$Qs,QLe]=XLe(BS),YUt=Ft.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Ft.useRef(null),c=el(o,t),d=DQs(n),h=$E(a)==="ltr",m=wa(s.onKeyDown,p=>{var M;if(!IQs.includes(p.key))return;const f=p.target,g=d().filter(I=>{var D;return!((D=I.ref.current)!=null&&D.disabled)}),v=g.findIndex(I=>I.ref.current===f),y=g.length;if(v===-1)return;p.preventDefault();let b=v;const w=0,S=y-1,C=()=>{b=v+1,b>S&&(b=w)},E=()=>{b=v-1,b{const{__scopeAccordion:n,value:r,...a}=s,i=QLe(IEe,n),l=FQs(IEe,n),o=$tt(n),c=qg(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(UQs,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(HUt,{"data-orientation":i.orientation,"data-state":sqt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});ZUt.displayName=IEe;var XUt="AccordionHeader",QUt=Ft.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=QLe(BS,n),i=Utt(XUt,n);return e.jsx(ci.h3,{"data-orientation":a.orientation,"data-state":sqt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});QUt.displayName=XUt;var FHe="AccordionTrigger",JUt=Ft.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=QLe(BS,n),i=Utt(FHe,n),l=OQs(FHe,n),o=$tt(n);return e.jsx(Btt.ItemSlot,{scope:n,children:e.jsx(PQs,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});JUt.displayName=FHe;var eqt="AccordionContent",tqt=Ft.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=QLe(BS,n),i=Utt(eqt,n),l=$tt(n);return e.jsx(LQs,{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}})});tqt.displayName=eqt;function sqt(s){return s?"open":"closed"}var qQs=GUt,VQs=ZUt,HQs=QUt,nqt=JUt,rqt=tqt;const ez=qQs,AL=_.forwardRef(({className:s,...t},n)=>e.jsx(VQs,{ref:n,className:Ct("border-b",s),...t}));AL.displayName="AccordionItem";const EL=_.forwardRef(({className:s,children:t,...n},r)=>e.jsx(HQs,{className:"flex",children:e.jsxs(nqt,{ref:r,className:Ct("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(cl,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));EL.displayName=nqt.displayName;const TL=_.forwardRef(({className:s,children:t,...n},r)=>e.jsx(rqt,{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:Ct("pb-4 pt-0",s),children:t})}));TL.displayName=rqt.displayName;const GQs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=dUs(s),a=uUs(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(fS,{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(z,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(Wr,{className:"mr-2 h-4 w-4"}):e.jsx(fS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},WQs=()=>{const{slug:s}=Mi(),{data:t,isLoading:n}=qet(s),{data:r}=pBt(t==null?void 0:t.id),{data:a}=Het(t==null?void 0:t.id),i=UH(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],m=l.phases||[];if(n)return e.jsx($s,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(ln,{className:"h-64 w-full rounded-xl"}),e.jsx(ln,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx($s,{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(z,{asChild:!0,className:"mt-6",children:e.jsx(or,{to:"/programs",children:"Back to Programs"})})]})});const p=typeof r=="number"&&r<=0&&!i,{notOpenYet:f,closed:g,opensLabel:v}=kLe(t),y=!i&&(p||g||f),b=i?"Open your program":f?`Enrollment opens ${yu(t.enrollment_open_at)}`:p?"Cohort is full":g?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",w=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs($s,{children:[e.jsxs(dl,{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(AQs,{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(Mr,{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":Df(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 ",_te(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:yu(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(j0,{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:[JVe(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:yu(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(z,{asChild:!y,size:"lg",disabled:y,children:y?e.jsx("span",{children:b}):e.jsxs(or,{to:w,children:[b,e.jsx(Da,{className:"ml-2 h-4 w-4"})]})}),e.jsx(z,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(or,{to:"/programs",children:"All programs"})})]}),f&&!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(gc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}),e.jsx(GQs,{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((S,C)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Mr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:S})]},C))})]}),m.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-xl font-semibold",children:["How the ",t.duration_weeks," weeks flow"]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:m.map((S,C)=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",C+1]}),e.jsx("h3",{className:"font-semibold",children:S.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.detail})]})},C))})]}),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((S,C)=>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"}),S]},C))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{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((S,C)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Mr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},C))})]})}),u.length>0&&e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{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((S,C)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Zr,{className:"mt-0.5 h-4 w-4 shrink-0"}),S]},C))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(ez,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((S,C)=>e.jsxs(AL,{value:`faq-${C}`,children:[e.jsx(EL,{className:"text-left text-sm font-medium",children:S.q}),e.jsx(TL,{className:"text-sm text-muted-foreground",children:S.a})]},C))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(Xr,{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(z,{asChild:!y,size:"lg",disabled:y,children:y?e.jsx("span",{children:b}):e.jsxs(or,{to:w,children:[b,e.jsx(Da,{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(On,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(f?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(gc,{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(gc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",yu(t.enrollment_close_at)]}):null)]})]})]})},lce=["Your business","Your content","Your goals","Reserve your seat"],KQs=()=>{const{slug:s}=Mi(),t=zn(),[n,r]=Gl(),{user:a}=hs(),{data:i,isLoading:l}=qet(s),{data:o}=pBt(i==null?void 0:i.id),{data:c,refetch:d}=Het(i==null?void 0:i.id),{data:u}=fBt(i==null?void 0:i.id),h=$$s(),m=U$s(),p=X$s(),f=Q$s(),[g,v]=_.useState(0),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(""),[F,q]=_.useState(null),G=_.useRef({}),[V,H]=_.useState({}),K=_.useRef(!1),Z=(qe,Be)=>{G.current={...G.current,[qe]:Be},H(G.current)};_.useEffect(()=>{K.current||(u?(G.current={...u},H(G.current),K.current=!0):a&&(G.current={email:a.email,...G.current},H(G.current)))},[u,a]),_.useEffect(()=>{const qe=c;!i||!(qe!=null&&qe.discount_code)||F||q({code:qe.discount_code,discount_cents:qe.discount_cents||0,amount_cents:qe.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,F]);const oe=F?F.amount_cents:(i==null?void 0:i.price_cents)??0,re=_.useMemo(()=>wte(i),[i]),ae=qe=>B$s(re,qe),J=qe=>Qgt(re,qe)?e.jsx("span",{className:"text-destructive",children:" *"}):null,te=(qe,Be)=>{const Ze={...G.current.extra||{},[qe]:Be};Z("extra",Ze)},ce=qe=>re.custom.filter((Be,Ze)=>Ze%3===qe),ve=qe=>{const Be=ce(qe);if(!Be.length)return null;const Ze=V.extra||{};return e.jsx("div",{className:"space-y-4",children:Be.map($e=>e.jsxs("div",{className:"space-y-2",children:[$e.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(za,{id:$e.id,checked:!!Ze[$e.id],onCheckedChange:Xe=>te($e.id,!!Xe)}),e.jsxs(ee,{htmlFor:$e.id,className:"text-sm font-normal leading-relaxed",children:[$e.label,$e.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{htmlFor:$e.id,children:[$e.label,$e.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),$e.type==="long_text"?e.jsx(Ps,{id:$e.id,rows:3,value:Ze[$e.id]||"",onChange:Xe=>te($e.id,Xe.target.value)}):$e.type==="select"?e.jsxs(ls,{value:Ze[$e.id]||"",onValueChange:Xe=>te($e.id,Xe),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsx(as,{children:($e.options||[]).map(Xe=>e.jsx(He,{value:Xe,children:Xe},Xe))})]}):e.jsx(pe,{id:$e.id,value:Ze[$e.id]||"",onChange:Xe=>te($e.id,Xe.target.value)})]}),$e.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:$e.help})]},$e.id))})},me=qe=>{const Be=G.current,Ze=Ge=>Ge==null||Ge===""||Ge===!1,$e=Uet.find(Ge=>Ge.step===qe&&Qgt(re,Ge.key)&&Ze(Ge.key==="timezone"?Be.timezone||(i==null?void 0:i.timezone):Be[Ge.key]));if($e)return $e.label;const Xe=Be.extra||{},nt=ce(qe).find(Ge=>Ge.required&&Ze(Xe[Ge.id]));return nt?nt.label:null},he=()=>{if(g<=2){const qe=me(g);if(qe)return ne.error(`Please answer: ${qe}`)}v(qe=>qe+1)},ge=async()=>{if(!(!i||!I.trim()))try{let qe=c==null?void 0:c.id;(!qe||(c==null?void 0:c.status)==="canceled")&&(qe=await m.mutateAsync(i.id));const Be=await p.mutateAsync({enrollmentId:qe,code:I});q(Be),D(""),await d(),ne.success(`Code applied — you save ${Df(Be.discount_cents,i.currency)}`)}catch(qe){ne.error(qe.message||"That code could not be applied")}},Ee=async()=>{if(!(c!=null&&c.id))return q(null);try{await f.mutateAsync(c.id),q(null),await d()}catch(qe){ne.error(qe.message||"Could not remove the code")}},Ne=n.get("setup"),Pe=n.get("session_id"),Oe=_.useRef(!1);_.useEffect(()=>{Ne!=="success"||!Pe||!(c!=null&&c.id)||Oe.current||(Oe.current=!0,S(!0),(async()=>{const{data:qe,error:Be}=await U.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Pe}});if(S(!1),Be||qe!=null&&qe.error||(qe==null?void 0:qe.success)===!1){ne.error((qe==null?void 0:qe.error)||(Be==null?void 0:Be.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ne.success("Your seat is confirmed")})())},[Ne,Pe,c==null?void 0:c.id]),_.useEffect(()=>{Ne==="cancelled"&&ne.info("Checkout cancelled — your seat is held for a short while.")},[Ne]);const ke=_.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ve=async()=>{if(i){if(!C||i.payment_mode!=="free"&&!P){ne.error("Please confirm the checkboxes to continue");return}b(!0);try{let qe=c==null?void 0:c.id;(!qe||(c==null?void 0:c.status)==="canceled")&&(qe=await m.mutateAsync(i.id)),await h.mutateAsync({...G.current,id:void 0,program_id:i.id,enrollment_id:qe,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Be,error:Ze}=await U.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:qe}});if(Ze||Be!=null&&Be.error)throw new Error((Be==null?void 0:Be.error)||(Ze==null?void 0:Ze.message));if(Be!=null&&Be.free){await d(),ne.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Be!=null&&Be.url&&(window.location.href=Be.url)}catch(qe){ne.error(qe.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx($s,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(ln,{className:"h-10 w-1/2"}),e.jsx(ln,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx($s,{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(z,{asChild:!0,className:"mt-6",children:e.jsx(or,{to:"/programs",children:"Back to Programs"})})]})});if(UH(c)&&ke&&Ne!=="success")return e.jsx($s,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(Mr,{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 ${yu(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(z,{asChild:!0,size:"lg",children:e.jsx(or,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const _e=typeof o=="number"&&o<=0,{notOpenYet:Ae,closed:Se,opensLabel:We}=kLe(i);return Ae||Se?e.jsx($s,{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:Ae?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Ae?`Enrollment for ${i.name} opens ${We}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx(z,{asChild:!0,children:e.jsx(or,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx($s,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(z,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(or,{to:`/programs/${i.slug}`,children:[e.jsx(ka,{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?`${JVe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${yu(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:lce[g]}),e.jsxs("span",{children:["Step ",g+1," of ",lce.length]})]}),e.jsx(Di,{value:(g+1)/lce.length*100})]}),w&&e.jsx(be,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(be,{children:e.jsxs(Le,{className:"space-y-5 p-6",children:[g===0&&re.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:re.intro}),g===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ae("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"full_name",children:["Full name",J("full_name")]}),e.jsx(pe,{id:"full_name",value:V.full_name||"",onChange:qe=>Z("full_name",qe.target.value)})]}),ae("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"phone",children:["Mobile number",J("phone")]}),e.jsx(pe,{id:"phone",value:V.phone||"",onChange:qe=>Z("phone",qe.target.value)})]}),ae("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"instagram_handle",children:["Instagram handle",J("instagram_handle")]}),e.jsx(pe,{id:"instagram_handle",placeholder:"@yourhandle",value:V.instagram_handle||"",onChange:qe=>Z("instagram_handle",qe.target.value)})]}),ae("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"city",children:["Primary city / market",J("city")]}),e.jsx(pe,{id:"city",value:V.city||"",onChange:qe=>Z("city",qe.target.value)})]})]}),ae("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",J("service_areas")]}),e.jsx(Ps,{id:"service_areas",rows:2,value:V.service_areas||"",onChange:qe=>Z("service_areas",qe.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ae("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["Years in real estate",J("years_experience")]}),e.jsxs(ls,{value:V.years_experience||"",onValueChange:qe=>Z("years_experience",qe),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsx(as,{children:["Less than 1","1-3","4-7","8-15","15+"].map(qe=>e.jsx(He,{value:qe,children:qe},qe))})]})]}),ae("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"specialty",children:["Specialty or niche",J("specialty")]}),e.jsx(pe,{id:"specialty",value:V.specialty||"",onChange:qe=>Z("specialty",qe.target.value)})]})]}),ve(0)]}),g===1&&e.jsxs(e.Fragment,{children:[ae("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"target_audience",children:["Who are you trying to reach?",J("target_audience")]}),e.jsx(Ps,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:V.target_audience||"",onChange:qe=>Z("target_audience",qe.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ae("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["How comfortable are you on camera?",J("video_comfort")]}),e.jsxs(ls,{value:V.video_comfort||"",onValueChange:qe=>Z("video_comfort",qe),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsx(as,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(qe=>e.jsx(He,{value:qe,children:qe},qe))})]})]}),ae("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["How often do you post today?",J("posting_frequency")]}),e.jsxs(ls,{value:V.posting_frequency||"",onValueChange:qe=>Z("posting_frequency",qe),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsx(as,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(qe=>e.jsx(He,{value:qe,children:qe},qe))})]})]})]}),ae("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"content_style",children:["What content style feels like you?",J("content_style")]}),e.jsx(Ps,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:V.content_style||"",onChange:qe=>Z("content_style",qe.target.value)})]}),ae("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",J("personal_interests")]}),e.jsx(Ps,{id:"personal_interests",rows:2,value:V.personal_interests||"",onChange:qe=>Z("personal_interests",qe.target.value)})]}),ve(1)]}),g===2&&e.jsxs(e.Fragment,{children:[ae("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"primary_goal",children:["Your #1 goal for this program",J("primary_goal")]}),e.jsx(Ps,{id:"primary_goal",rows:3,value:V.primary_goal||"",onChange:qe=>Z("primary_goal",qe.target.value)})]}),ae("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",J("topics_to_avoid")]}),e.jsx(Ps,{id:"topics_to_avoid",rows:2,value:V.topics_to_avoid||"",onChange:qe=>Z("topics_to_avoid",qe.target.value)})]}),ae("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["Your time zone",J("timezone")]}),e.jsxs(ls,{value:V.timezone||i.timezone,onValueChange:qe=>Z("timezone",qe),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select"})}),e.jsx(as,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(qe=>e.jsx(He,{value:qe,children:qe.replace("America/","").replace("_"," ")},qe))})]})]}),ve(2),ae("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(za,{id:"consent_public_profile",checked:!!V.consent_public_profile,onCheckedChange:qe=>Z("consent_public_profile",!!qe)}),e.jsx(ee,{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."})]})]}),g===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":F?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Df(F.original_cents,i.currency)}),Df(oe,i.currency)]}):Df(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:JVe(oe,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:F?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(Ip,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:F.code})," applied — you save ",Df(F.discount_cents,i.currency)]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:Ee,disabled:f.isPending,children:[e.jsx(er,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:I,onChange:qe=>D(qe.target.value.toUpperCase()),onKeyDown:qe=>{qe.key==="Enter"&&(qe.preventDefault(),ge())}}),e.jsx(z,{variant:"outline",onClick:ge,disabled:!I.trim()||p.isPending||m.isPending,children:p.isPending||m.isPending?e.jsx(bt,{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(j0,{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:yu(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(za,{id:"terms",checked:C,onCheckedChange:qe=>E(!!qe)}),e.jsx(ee,{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(za,{id:"charge",checked:P,onCheckedChange:qe=>M(!!qe)}),e.jsx(ee,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Df(oe,i.currency)} for the ${_te(i.duration_weeks)} — on ${yu(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 — ${Df(oe,i.currency)} for the ${_te(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(Ch,{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(z,{variant:"ghost",onClick:()=>v(qe=>Math.max(0,qe-1)),disabled:g===0||y,children:[e.jsx(ka,{className:"mr-1.5 h-4 w-4"})," Back"]}),gString(s).padStart(2,"0"),a9e=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",YQs=({program:s,intakeComplete:t})=>{const n=s!=null&&s.kickoff_at?new Date(s.kickoff_at).getTime():null,[r,a]=_.useState(()=>Date.now());_.useEffect(()=>{const d=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(d)},[]);const i=_.useMemo(()=>{if(!n)return null;const d=Math.max(n-r,0);return{days:Math.floor(d/864e5),hours:Math.floor(d%864e5/36e5),minutes:Math.floor(d%36e5/6e4),seconds:Math.floor(d%6e4/1e3),done:d===0}},[n,r]);if(!n||!i)return null;const l=new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:"America/New_York"}).format(new Date(n)),o=()=>{const d=new Date(n),u=new Date(n+90*6e4),h=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:kickoff-${s.id}@levelup`,`DTSTAMP:${a9e(new Date)}`,`DTSTART:${a9e(d)}`,`DTEND:${a9e(u)}`,`SUMMARY:${s.name} — Kickoff Call`,`DESCRIPTION:The official kickoff for ${s.name}. Bring a phone and a story.`,"END:VEVENT","END:VCALENDAR"].join(`\r `),m=URL.createObjectURL(new Blob([h],{type:"text/calendar"})),p=document.createElement("a");p.href=m,p.download="program-kickoff.ics",p.click(),URL.revokeObjectURL(m)},c=[{label:"Days",value:i.days},{label:"Hours",value:r9e(i.hours)},{label:"Minutes",value:r9e(i.minutes)},{label:"Seconds",value:r9e(i.seconds)}];return e.jsxs(be,{className:"relative overflow-hidden border-primary/25",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/15 via-background to-secondary/10"}),s.hero_image_url&&e.jsx("img",{src:s.hero_image_url,alt:"",className:"pointer-events-none absolute inset-0 h-full w-full object-cover opacity-10"}),e.jsxs(Le,{className:"relative space-y-6 p-6 md:p-9",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{className:"gap-1.5",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(ze,{variant:"outline",className:"gap-1.5",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," ",l]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:i.done?"We're live — let's go":`${s.name} kicks off soon`}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground md:text-base",children:i.done?"The kickoff call is starting. Head to your sessions below to join.":"Everything unlocks on kickoff day. Until then, get your setup dialed in so week one is pure momentum."})]}),e.jsx("div",{className:"grid max-w-xl grid-cols-4 gap-2 md:gap-3",children:c.map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/80 px-2 py-4 text-center backdrop-blur-sm",children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums tracking-tight md:text-4xl",children:d.value}),e.jsx("div",{className:"mt-1 text-[10px] uppercase tracking-widest text-muted-foreground md:text-xs",children:d.label})]},d.label))}),e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs(z,{onClick:o,size:"lg",children:[e.jsx(v0,{className:"mr-2 h-4 w-4"})," Add kickoff to calendar"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{title:"Intake complete",body:t?"We've got what we need to tailor your coaching.":"Finish your intake so your coach knows your market and goals.",done:!!t},{title:"Kickoff on the calendar",body:"One click above adds it to Google, Apple or Outlook.",done:!1},{title:"Set up your shooting kit",body:"Phone, clip mic, tripod. That is genuinely all you need.",done:!1}].map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/70 p-4 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Mr,{className:`h-4 w-4 ${d.done?"text-primary":"text-muted-foreground/40"}`}),d.title]}),e.jsx("p",{className:"mt-1.5 text-xs leading-relaxed text-muted-foreground",children:d.body})]},d.title))})]})]})},i9e=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",ZQs=(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:${i9e(new Date)}`,`DTSTART:${i9e(n)}`,`DTEND:${i9e(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)},XQs={pdf:$r,document:xN,checklist:k0,template_link:yj,video:Yh,external:Oc},QQs=()=>{var ce;const{slug:s}=Mi(),[t]=Gl(),{isAdmin:n}=hs(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=qet(s),{data:c}=Het(l==null?void 0:l.id),{data:d,isLoading:u}=q$s(l==null?void 0:l.id,r),h=V$s(l==null?void 0:l.id),m=H$s(l==null?void 0:l.id),p=G$s(l==null?void 0:l.id),f=W$s(l==null?void 0:l.id),{data:g}=fBt(l==null?void 0:l.id),v=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[y,b]=_.useState(!1),[w,S]=_.useState({title:"",instagram_url:""}),[C,E]=_.useState({}),[P,M]=_.useState(null),I=_.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const ve=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ve/7)+1,1),l.duration_weeks)},[l]),D=new Set(((d==null?void 0:d.completions)||[]).map(ve=>ve.lesson_id)),F=(d==null?void 0:d.lessons)||[],q=F.length?Math.round(D.size/F.length*100):0,G=((d==null?void 0:d.videoLogs)||[]).filter(ve=>ve.week_number===I).length,V=((d==null?void 0:d.videoLogs)||[]).length,H=(l==null?void 0:l.weekly_video_goal)||3,K=_.useMemo(()=>{const ve=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(he=>ve.set(he.week_number,(ve.get(he.week_number)||0)+1));let me=0;for(let he=I;he>=1;he--)if((ve.get(he)||0)>=H)me++;else if(he!==I)break;return me},[d==null?void 0:d.videoLogs,I,H]);if(o||u)return e.jsx($s,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(ln,{className:"h-28 w-full rounded-xl"}),e.jsx(ln,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx($s,{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(z,{asChild:!0,className:"mt-6",children:e.jsx(or,{to:"/programs",children:"Back to Programs"})})]})});if(!UH(c)&&!i)return e.jsx($s,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx(z,{asChild:!0,size:"lg",children:e.jsx(or,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const Z=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)>=new Date),oe=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)ve.is_pinned),J=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((ve,me)=>{const he=me.user_id?`Just for you · ${me.category}`:me.category;return(ve[he]||(ve[he]=[])).push(me),ve},{}),te=((d==null?void 0:d.progress)||[]).find(ve=>ve.week_number===I)||{};return e.jsx($s,{children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[i&&(r||!UH(c))&&e.jsx(be,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Le,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsx("span",{children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin view"})," — you're seeing ",a,"'s dashboard exactly as they see it (progress, check-ins, videos and personal resources). It's read-only: avoid logging videos or check-ins here."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]})}),e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(or,{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 ",I," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(ze,{variant:"outline",children:["Billing ",yu(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(ze,{variant:"destructive",children:"Payment issue"})]}),e.jsx("p",{className:"neon-eyebrow font-semibold",children:"LevelUp Program"}),e.jsx("h1",{className:"neon-title w-fit text-4xl font-black uppercase tracking-tight md:text-5xl",children:l.name}),l.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:l.subtitle})]}),v&&e.jsx(YQs,{program:l,intakeComplete:!!g}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(be,{className:"neon-topline",children:e.jsxs(Le,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(bu,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[G,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",H]})]}),e.jsx(Di,{value:Math.min(G/H*100,100),className:"h-1.5"})]})}),e.jsx(be,{className:"neon-topline",children:e.jsxs(Le,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(Yh,{className:"h-3.5 w-3.5 text-primary"})," Videos posted"]}),e.jsx("p",{className:"neon-stat text-3xl font-black",children:V}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(be,{className:"neon-topline",children:e.jsxs(Le,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(vu,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[K," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(be,{className:"neon-topline",children:e.jsxs(Le,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(kl,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[q,"%"]}),e.jsx(Di,{value:q,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Is,{open:y,onOpenChange:b,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(pe,{id:"v-title",value:w.title,onChange:ve=>S(me=>({...me,title:ve.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(pe,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:w.instagram_url,onChange:ve=>S(me=>({...me,instagram_url:ve.target.value}))})]})]}),e.jsx(hr,{children:e.jsx(z,{onClick:async()=>{await m.mutateAsync({week_number:I,...w}),S({title:"",instagram_url:""}),b(!1)},children:"Log video"})})]})]}),((ce=Z[0])==null?void 0:ce.meeting_link)&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:Z[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(dm,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),re.length>0&&e.jsx(be,{className:"border-primary/30 bg-primary/5",children:e.jsx(Le,{className:"space-y-3 p-5",children:re.map(ve=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Nh,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.body})]})]},ve.id))})}),e.jsxs(Qr,{defaultValue:"roadmap",children:[e.jsxs(Jr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Wt,{value:"roadmap",children:"Roadmap"}),e.jsx(Wt,{value:"lessons",children:"Lessons"}),e.jsx(Wt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Wt,{value:"events",children:"Sessions"}),e.jsx(Wt,{value:"resources",children:"Resources"}),e.jsx(Wt,{value:"profile",children:"Profile review"})]}),e.jsxs(Kt,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(ve=>{const me=ve.release_at&&new Date(ve.release_at)>new Date;return e.jsx(be,{className:me?"opacity-60":ve.week_number===I?"border-primary/50":"",children:e.jsxs(Le,{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 ",ve.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ve.phase}),ve.week_number===I&&e.jsx(ze,{children:"Current"}),me&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Zr,{className:"h-3 w-3"})," Unlocks ",yu(ve.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ve.title}),ve.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.learning_goal}),!me&&Array.isArray(ve.tasks)&&ve.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ve.tasks.map((he,ge)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Mr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof he=="string"?he:he.label]},ge))})]})},ve.id)})]}),e.jsxs(Kt,{value:"lessons",className:"mt-6 space-y-3",children:[F.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),F.map(ve=>{const me=xBt(ve.video_url),he=P===ve.id;return e.jsx(be,{children:e.jsxs(Le,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(za,{checked:D.has(ve.id),onCheckedChange:ge=>h.mutate({lessonId:ve.id,done:!!ge}),"aria-label":`Mark ${ve.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.summary}),ve.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ve.action_assignment]})]}),ve.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Zr,{className:"h-3 w-3"})," ",ve.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ve.video_url&&(me||OJ(ve.video_url))&&e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>M(he?null:ve.id),children:[e.jsx(dm,{className:"mr-1.5 h-3.5 w-3.5"})," ",he?"Close":"Watch"]}),ve.video_url&&!me&&!OJ(ve.video_url)&&e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(dm,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ve.worksheet_url&&e.jsx(z,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ve.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ga,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),he&&me&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:me,title:ve.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),he&&!me&&OJ(ve.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:ve.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},ve.id)})]}),e.jsx(Kt,{value:"checkin",className:"mt-6",children:e.jsx(be,{children:e.jsxs(Le,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",I," 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(([ve,me])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:ve,children:me}),e.jsx(pe,{id:ve,type:"number",min:0,defaultValue:te[ve]??"",onChange:he=>E(ge=>({...ge,[ve]:Number(he.target.value)}))})]},ve))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ve,me])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:ve,children:me}),e.jsx(Ps,{id:ve,rows:2,defaultValue:te[ve]??"",onChange:he=>E(ge=>({...ge,[ve]:he.target.value}))})]},ve)),e.jsx(z,{onClick:()=>p.mutate({week_number:I,goal_videos:H,...C}),children:"Save check-in"})]})})}),e.jsxs(Kt,{value:"events",className:"mt-6 space-y-4",children:[Z.length===0&&oe.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),Z.map(ve=>e.jsx(be,{className:"border-primary/30",children:e.jsxs(Le,{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(ve.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(gc,{className:"h-3 w-3"})," ",yu(ve.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ve.title}),ve.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ve.speaker]}),ve.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ve.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{size:"sm",variant:"outline",onClick:()=>f.mutate({eventId:ve.id,optIn:!0}),children:"Remind me"}),e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>ZQs(ve,l.name),children:[e.jsx(gc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ve.meeting_link&&e.jsx(z,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ve.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(mr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ve.id)),oe.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"pt-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Replays"}),oe.map(ve=>e.jsx(be,{children:e.jsxs(Le,{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:ve.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:yu(ve.starts_at,!0)})]}),ve.replay_url?e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(dm,{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"})]})},ve.id))]})]}),e.jsxs(Kt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(J).length===0&&e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx($r,{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(J).map(([ve,me])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:ve}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[me.length," item",me.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:me.map(he=>{const ge=gae(he),Ee=XQs[he.resource_kind]||$r;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>ge&&zJ(he),onKeyDown:Ne=>{ge&&(Ne.key==="Enter"||Ne.key===" ")&&(Ne.preventDefault(),zJ(he))},className:"group relative flex cursor-pointer flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(Ee,{className:"h-5 w-5"})}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(he.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:he.title}),he.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:he.description})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-4",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:[e.jsx(mr,{className:"h-3.5 w-3.5"})," Open"]}),he.file_path&&e.jsxs("button",{type:"button",onClick:Ne=>{Ne.stopPropagation(),zJ(he,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Download"]})]})]},he.id)})})]},ve))]}),e.jsx(Kt,{value:"profile",className:"mt-6",children:e.jsx(be,{children:e.jsxs(Le,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fm,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(d!=null&&d.analysis)||d.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):d.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[d.analysis.scores&&Object.keys(d.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(d.analysis.scores).map(([ve,me])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:ve.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[me,"/10"]})]}),e.jsx(Di,{value:Number(me)*10,className:"h-1.5"})]},ve))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((ve,me)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Kh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ve=="string"?ve:ve.label]},me))})]}),d.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:d.analysis.member_notes}),d.analysis.report_url&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ga,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Za=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Ct("w-full caption-bottom text-sm",s),...t})}));Za.displayName="Table";const Xa=_.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Ct("[&_tr]:border-b",s),...t}));Xa.displayName="TableHeader";const Qa=_.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Ct("[&_tr:last-child]:border-0",s),...t}));Qa.displayName="TableBody";const JQs=_.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Ct("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));JQs.displayName="TableFooter";const fn=_.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Ct("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));fn.displayName="TableRow";const Tt=_.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Ct("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Tt.displayName="TableHead";const yt=_.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Ct("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));yt.displayName="TableCell";const eJs=_.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Ct("mt-4 text-sm text-muted-foreground",s),...t}));eJs.displayName="TableCaption";const cce=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())}`},dce=s=>s?new Date(s).toISOString():null,o9e=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:cce(s.enrollment_open_at),enrollment_close_at:cce(s.enrollment_close_at),kickoff_at:cce(s.kickoff_at),charge_at:cce(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),tJs=({program:s,onSaved:t})=>{const[n,r]=_.useState(()=>o9e(s)),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(null),u=_.useRef(null),h=_.useRef(null);_.useEffect(()=>{r(o9e(s)),i(!1)},[s.id,s.updated_at]);const m=(v,y)=>{r(b=>({...b,[v]:y})),i(!0)},p=async(v,y)=>{if(!v.type.startsWith("image/")){ne.error("Please choose an image file");return}if(v.size>8*1024*1024){ne.error("Image must be under 8MB");return}d(y);try{const b=v.name.split(".").pop()||"jpg",w=`programs/${s.id}/${y}-${Date.now()}.${b}`,{error:S}=await U.storage.from("event-images").upload(w,v,{cacheControl:"31536000",upsert:!0});if(S)throw S;const{data:C}=U.storage.from("event-images").getPublicUrl(w);m(y==="cover"?"cover_image_url":"hero_image_url",C.publicUrl),ne.success(`${y==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){ne.error(b.message||"Upload failed")}finally{d(null)}},f=async()=>{if(!n.name.trim())return ne.error("Program name is required");if(!n.slug.trim())return ne.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:dce(n.enrollment_open_at),enrollment_close_at:dce(n.enrollment_close_at),kickoff_at:dce(n.kickoff_at),charge_at:dce(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:y}=await U.from("programs").update(v).eq("id",s.id);if(y)throw y;ne.success("Program saved"),i(!1),t()}catch(v){ne.error(v.message||"Could not save the program")}finally{o(!1)}},g=({kind:v,label:y,hint:b})=>{const w=v==="cover"?n.cover_image_url:n.hero_image_url,S=v==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:y}),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:w?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:w,alt:`${y} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(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 ${y}`,children:e.jsx(er,{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(N0,{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:S,type:"file",accept:"image/*",className:"hidden",onChange:C=>{var P;const E=(P=C.target.files)==null?void 0:P[0];E&&p(E,v),C.target.value=""}}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{var C;return(C=S.current)==null?void 0:C.click()},disabled:c===v,children:[c===v?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(pe,{placeholder:"…or paste an image URL",value:w,onChange:C=>m(v==="cover"?"cover_image_url":"hero_image_url",C.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]})]})]})};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(z,{variant:"ghost",onClick:()=>{r(o9e(s)),i(!1)},children:"Discard"}),e.jsxs(z,{onClick:f,disabled:l||!a,children:[l?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(be,{children:e.jsxs(Le,{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(ee,{children:"Program name"}),e.jsx(pe,{value:n.name,onChange:v=>m("name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (public URL)"}),e.jsx(pe,{value:n.slug,onChange:v=>m("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(ee,{children:"Subtitle"}),e.jsx(pe,{value:n.subtitle,onChange:v=>m("subtitle",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:n.tagline,onChange:v=>m("tagline",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Short description (cards & previews)"}),e.jsx(Ps,{rows:2,value:n.short_description,onChange:v=>m("short_description",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Full program description (sales page)"}),e.jsx(Ps,{rows:8,value:n.description,onChange:v=>m("description",v.target.value)})]})]})}),e.jsx(be,{children:e.jsxs(Le,{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(g,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(g,{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(ee,{children:"Promo video URL (optional)"}),e.jsx(pe,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:v=>m("promo_video_url",v.target.value)}),e.jsx(pe,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:v=>m("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(ee,{children:"Accent color"}),e.jsx(pe,{placeholder:"#406E71",value:n.accent_color,onChange:v=>m("accent_color",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:n.sort_order,onChange:v=>m("sort_order",Number(v.target.value))})]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{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(ee,{children:"One-time price (USD)"}),e.jsx(pe,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:v=>m("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(ee,{children:"Seats (capacity)"}),e.jsx(pe,{type:"number",min:0,value:n.capacity,onChange:v=>m("capacity",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Billing mode"}),e.jsxs(ls,{value:n.payment_mode,onValueChange:v=>m("payment_mode",v),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"delayed",children:"Save card, charge once later"}),e.jsx(He,{value:"immediate",children:"Charge once at checkout"}),e.jsx(He,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Charge date (one-time)"}),e.jsx(pe,{type:"datetime-local",value:n.charge_at,onChange:v=>m("charge_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Payment grace days"}),e.jsx(pe,{type:"number",min:0,value:n.payment_grace_days,onChange:v=>m("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(ee,{children:"Currency"}),e.jsx(pe,{value:n.currency,onChange:v=>m("currency",v.target.value)})]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{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(ee,{children:"Enrollment opens"}),e.jsx(pe,{type:"datetime-local",value:n.enrollment_open_at,onChange:v=>m("enrollment_open_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Enrollment closes"}),e.jsx(pe,{type:"datetime-local",value:n.enrollment_close_at,onChange:v=>m("enrollment_close_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Kickoff"}),e.jsx(pe,{type:"datetime-local",value:n.kickoff_at,onChange:v=>m("kickoff_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (weeks)"}),e.jsx(pe,{type:"number",min:1,value:n.duration_weeks,onChange:v=>m("duration_weeks",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Videos per week goal"}),e.jsx(pe,{type:"number",min:0,value:n.weekly_video_goal,onChange:v=>m("weekly_video_goal",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Timezone"}),e.jsx(pe,{value:n.timezone,onChange:v=>m("timezone",v.target.value)})]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{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(ee,{children:"Status"}),e.jsxs(ls,{value:n.status,onValueChange:v=>m("status",v),children:[e.jsx(rs,{className:"sm:max-w-xs",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"draft",children:"Draft (hidden)"}),e.jsx(He,{value:"published",children:"Published (members can enroll)"}),e.jsx(He,{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(mn,{checked:n.is_featured,onCheckedChange:v=>m("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(mn,{checked:n.is_public,onCheckedChange:v=>m("is_public",v)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(z,{onClick:f,disabled:l||!a,size:"lg",children:[l?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},K0t={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},sJs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=oUs(s,t),i=lUs(s,t),l=cUs(),[o,c]=_.useState(!1),[d,u]=_.useState({...K0t}),[h,m]=_.useState(!1),p=_.useRef(null),f=()=>{u({...K0t,sort_order:r.length}),c(!0)},g=b=>{u({id:b.id,title:b.title,description:b.description||"",category:b.category||"Personal",resource_kind:b.resource_kind,url:b.url||"",file_path:b.file_path||"",status:b.status,sort_order:b.sort_order}),c(!0)},v=async b=>{if(!(!b||!s||!t)){if(b.size>50*1024*1024)return ne.error("File must be under 50MB");m(!0);try{const w=b.name.split(".").pop()||"pdf",S=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${w}`,{error:C}=await U.storage.from(AW).upload(S,b,{contentType:b.type||"application/pdf",upsert:!1});if(C)throw C;u(E=>({...E,file_path:S,url:"",title:E.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":E.resource_kind})),ne.success("File uploaded")}catch(w){ne.error(w.message||"Upload failed")}finally{m(!1),p.current&&(p.current.value="")}}},y=async()=>{if(!d.title.trim())return ne.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return ne.error("Upload a file or paste a link");await i.mutateAsync({...d,sort_order:Number(d.sort_order)||0}),c(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"flex items-center gap-1.5 font-medium",children:[e.jsx(Hl,{className:"h-4 w-4 text-primary"})," Personal resources"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Only ",n||"this member"," can see these — they appear in a “Just for you” section on their program dashboard."]})]}),e.jsxs(z,{size:"sm",onClick:f,disabled:!t,children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," Add for this member"]})]}),a?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):r.length===0?e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{className:"p-6 text-center text-sm text-muted-foreground",children:"No personal resources yet. Upload their custom plan, feedback doc or scripts."})}):e.jsx("div",{className:"space-y-2",children:r.map(b=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:b.title}),e.jsx(ze,{variant:"secondary",children:b.category}),e.jsx(ze,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:b.description}),gae(b)&&e.jsxs("button",{type:"button",onClick:()=>zJ(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(mr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>g(b),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:d.title,onChange:b=>u({...d,title:b.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{rows:2,value:d.description,onChange:b=>u({...d,description:b.target.value})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsx(pe,{value:d.category,onChange:b=>u({...d,category:b.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ls,{value:d.resource_kind,onValueChange:b=>u({...d,resource_kind:b}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:gBt.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var b;return(b=p.current)==null?void 0:b.click()},children:[h?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"mr-1.5 h-4 w-4"}),d.file_path?"Replace file":"Upload file"]}),d.file_path&&e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:d.file_path.split("/").pop()})]}),e.jsx("input",{ref:p,type:"file",hidden:!0,onChange:b=>{var w;return v((w=b.target.files)==null?void 0:w[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"…or link"}),e.jsx(pe,{value:d.url,onChange:b=>u({...d,url:b.target.value,file_path:""}),placeholder:"https://…"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ls,{value:d.status,onValueChange:b=>u({...d,status:b}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"published",children:"Published"}),e.jsx(He,{value:"draft",children:"Draft"}),e.jsx(He,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:b.target.value})})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(z,{onClick:y,disabled:i.isPending||h,children:[i.isPending&&e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},nJs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var H,K,Z,oe,re,ae,J,te,ce,ve;const i=t==null?void 0:t.user_id,[l,o]=_.useState((t==null?void 0:t.admin_notes)||""),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(!1),[f,g]=_.useState(!1),v=_.useRef(null),{data:y,isLoading:b,refetch:w}=rt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[me,he,ge,Ee,Ne,Pe,Oe,ke]=await Promise.all([U.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),U.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),U.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),U.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_lessons").select("id").eq("program_id",s.id),U.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:me.data||[],videos:he.data||[],completions:ge.data||[],badges:Ee.data||[],intake:Ne.data,attendance:Pe.data||[],lessonCount:(Oe.data||[]).length,analysis:ke.data}}});_.useEffect(()=>{var me;h(((me=y==null?void 0:y.analysis)==null?void 0:me.member_notes)||"")},[(H=y==null?void 0:y.analysis)==null?void 0:H.id]);const S=_.useMemo(()=>{var ge;const me=wte(s),he=((ge=y==null?void 0:y.intake)==null?void 0:ge.extra)||{};return me.custom.map(Ee=>({label:Ee.label,value:typeof he[Ee.id]=="boolean"?he[Ee.id]?"Yes":"No":he[Ee.id]||""})).filter(Ee=>!!Ee.value)},[s,y==null?void 0:y.intake]),C=async me=>i?U.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...me},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},E=async me=>{if(me.type!=="application/pdf")return ne.error("Please choose a PDF file");if(me.size>25*1024*1024)return ne.error("PDF must be under 25MB");g(!0);try{const he=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:ge}=await U.storage.from("event-images").upload(he,me,{contentType:"application/pdf",upsert:!0});if(ge)throw ge;const{data:Ee}=U.storage.from("event-images").getPublicUrl(he),{error:Ne}=await C({report_url:Ee.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Ne)throw Ne;ne.success("Profile review uploaded"),await w()}catch(he){ne.error(he.message||"Upload failed")}finally{g(!1)}},P=async()=>{const{error:me}=await C({report_url:null,status:"in_review"});if(me)return ne.error(me.message);ne.success("Review removed"),await w()},M=async()=>{p(!0);const{error:me}=await C({member_notes:u});if(p(!1),me)return ne.error(me.message);ne.success("Review notes saved"),await w()},I=async()=>{if(!t)return;d(!0);const{error:me}=await U.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),me)return ne.error(me.message);ne.success("Notes saved"),a()},D=((y==null?void 0:y.videos)||[]).filter(me=>me.posted).length,F=(s.weekly_video_goal||0)*(s.duration_weeks||0),q=y!=null&&y.lessonCount?Math.round(((y==null?void 0:y.completions.length)||0)/y.lessonCount*100):0,G=F?Math.min(100,Math.round(D/F*100)):0,V=((y==null?void 0:y.attendance)||[]).filter(me=>me.attended).length;return e.jsx(Wg,{open:n,onOpenChange:r,children:e.jsxs(gg,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(Dy,{className:"mb-4",children:[e.jsxs(Ry,{children:[((K=t==null?void 0:t.profile)==null?void 0:K.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Z=t==null?void 0:t.profile)==null?void 0:Z.email}),i&&e.jsx(z,{variant:"outline",size:"sm",className:"mt-3 w-fit",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/workspace?preview=1&as=${i}&name=${encodeURIComponent(((oe=t==null?void 0:t.profile)==null?void 0:oe.name)||((re=t==null?void 0:t.profile)==null?void 0:re.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?b?e.jsx(ln,{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(be,{children:e.jsxs(Le,{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:[Df(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${yu(t.charged_at)}`:`Charge ${yu(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(be,{children:e.jsxs(Le,{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:yu(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",yu(t.created_at)]})]})})]}),e.jsx(be,{children:e.jsxs(Le,{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:[D," / ",F||"—"]})]}),e.jsx(Di,{value:G})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(y==null?void 0:y.completions.length)||0," / ",(y==null?void 0:y.lessonCount)||0]})]}),e.jsx(Di,{value:q})]}),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: "}),V]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(y==null?void 0:y.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(y==null?void 0:y.weekly.length)||0]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((y==null?void 0:y.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:y.weekly.map(me=>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 ",me.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[me.videos_posted,"/",me.goal_videos||s.weekly_video_goal," posted ·"," ",me.stories_posted," stories"]})]}),me.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",me.biggest_win]}),me.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",me.biggest_challenge]})]},me.id))})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((y==null?void 0:y.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:y.videos.slice(0,25).map(me=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:me.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",me.week_number," · ",yu(me.posted_at)]}),me.instagram_url&&e.jsx("a",{href:me.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]},me.id))})]})}),(y==null?void 0:y.intake)&&e.jsx(be,{children:e.jsxs(Le,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",y.intake.full_name],["Email",y.intake.email],["Phone",y.intake.phone],["Instagram",y.intake.instagram_handle],["City / market",y.intake.city],["Areas served",y.intake.service_areas],["Years in real estate",y.intake.years_experience],["Specialty",y.intake.specialty],["Target audience",y.intake.target_audience],["On camera",y.intake.video_comfort],["Posts today",y.intake.posting_frequency],["Content style",y.intake.content_style],["Interests",y.intake.personal_interests],["#1 goal",y.intake.primary_goal],["Topics to avoid",y.intake.topics_to_avoid],["Time zone",y.intake.timezone]].filter(([,me])=>!!me).map(([me,he])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[me,": "]}),he]},me)),S.map(({label:me,value:he})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[me,": "]}),he]},me)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",y.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(be,{children:e.jsx(Le,{className:"p-5",children:e.jsx(sJs,{programId:s.id,userId:i,memberName:(ae=t==null?void 0:t.profile)==null?void 0:ae.name})})}),e.jsx(be,{children:e.jsxs(Le,{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."})]}),((J=y==null?void 0:y.analysis)==null?void 0:J.status)&&e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(y.analysis.status).replace(/_/g," ")})]}),(te=y==null?void 0:y.analysis)!=null&&te.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($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:y.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(mr,{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:me=>{var ge;const he=(ge=me.target.files)==null?void 0:ge[0];he&&E(he),me.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{var me;return(me=v.current)==null?void 0:me.click()},disabled:f,children:[e.jsx(Ra,{className:"mr-1.5 h-3.5 w-3.5"}),f?"Uploading…":(ce=y==null?void 0:y.analysis)!=null&&ce.report_url?"Replace PDF":"Upload PDF"]}),((ve=y==null?void 0:y.analysis)==null?void 0:ve.report_url)&&e.jsx(z,{size:"sm",variant:"ghost",onClick:P,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(ee,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ps,{rows:3,value:u,onChange:me=>h(me.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(z,{size:"sm",variant:"outline",onClick:M,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"space-y-3 p-5",children:[e.jsx(ee,{children:"Coach notes (internal)"}),e.jsx(Ps,{rows:4,value:l,onChange:me=>o(me.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(z,{size:"sm",onClick:I,disabled:c,children:"Save notes"})})]})})]}):null]})})},Y0t={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},Z0t=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},rJs=({program:s})=>{const{data:t=[],isLoading:n}=K$s(s.id),r=Y$s(s.id),a=Z$s(),[i,l]=_.useState(!1),[o,c]=_.useState({...Y0t}),d=()=>{c({...Y0t}),l(!0)},u=f=>{c({id:f.id,code:f.code,label:f.label||"",kind:f.percent_off!=null?"percent":"amount",percent_off:f.percent_off!=null?String(f.percent_off):"",amount_off:f.amount_off_cents!=null?String(f.amount_off_cents/100):"",max_redemptions:f.max_redemptions!=null?String(f.max_redemptions):"",starts_at:Z0t(f.starts_at),expires_at:Z0t(f.expires_at),is_active:f.is_active}),l(!0)},h=_.useMemo(()=>{const f=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),g=Math.min(Math.max(f,0),s.price_cents);return{discount:g,final:s.price_cents-g}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return ne.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},p=f=>{const g=f.percent_off!=null?Math.floor(s.price_cents*Number(f.percent_off)/100):f.amount_off_cents||0,v=Math.max(s.price_cents-Math.min(g,s.price_cents),0);return{off:f.percent_off!=null?`${Number(f.percent_off)}% off`:`${Df(f.amount_off_cents||0,s.currency)} off`,final:Df(v,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{children:e.jsxs(Le,{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 ",Df(s.price_cents,s.currency)," charge."]})]}),e.jsxs(Is,{open:i,onOpenChange:l,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{onClick:d,children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Ls,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Code"}),e.jsx(pe,{placeholder:"FOUNDER50",value:o.code,onChange:f=>c({...o,code:f.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Internal label (optional)"}),e.jsx(pe,{placeholder:"Founding cohort",value:o.label,onChange:f=>c({...o,label:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Discount type"}),e.jsxs(ls,{value:o.kind,onValueChange:f=>c({...o,kind:f}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"percent",children:"Percent off"}),e.jsx(He,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Percent off"}),e.jsx(pe,{type:"number",min:1,max:100,value:o.percent_off,onChange:f=>c({...o,percent_off:f.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Amount off (USD)"}),e.jsx(pe,{type:"number",min:0,value:o.amount_off,onChange:f=>c({...o,amount_off:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Max redemptions (blank = unlimited)"}),e.jsx(pe,{type:"number",min:1,value:o.max_redemptions,onChange:f=>c({...o,max_redemptions:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Active from (optional)"}),e.jsx(pe,{type:"datetime-local",value:o.starts_at,onChange:f=>c({...o,starts_at:f.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Expires (optional)"}),e.jsx(pe,{type:"datetime-local",value:o.expires_at,onChange:f=>c({...o,expires_at:f.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(mn,{checked:o.is_active,onCheckedChange:f=>c({...o,is_active:f})})]}),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:[Df(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Df(h.final,s.currency)})," ","(",Df(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(hr,{children:e.jsxs(z,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(ln,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ip,{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(be,{children:e.jsx(Le,{className:"overflow-x-auto p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Code"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Price after"}),e.jsx(Tt,{children:"Used"}),e.jsx(Tt,{children:"Window"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:t.map(f=>{const g=p(f);return e.jsxs(fn,{children:[e.jsxs(yt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:f.code}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(f.code),ne.success("Code copied")},children:e.jsx(Sa,{className:"h-3.5 w-3.5"})})]}),f.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.label})]}),e.jsx(yt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(z_,{className:"h-3.5 w-3.5 text-muted-foreground"}),g.off]})}),e.jsx(yt,{className:"font-medium",children:g.final}),e.jsxs(yt,{children:[f.times_redeemed,f.max_redemptions?` / ${f.max_redemptions}`:""]}),e.jsxs(yt,{className:"text-xs text-muted-foreground",children:[f.starts_at?`From ${yu(f.starts_at)}`:"Anytime",f.expires_at?` · until ${yu(f.expires_at)}`:""]}),e.jsx(yt,{children:e.jsx(ze,{variant:f.is_active?"default":"secondary",children:f.is_active?"Active":"Paused"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>u(f),children:"Edit"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi(`Delete ${f.code}?`)&&a.mutate(f.id)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},f.id)})})]})})})]})},N5=({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(Mr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(nl,{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})]})]}),aJs=({program:s})=>{var c,d;const{data:t,isLoading:n}=rt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,p,f]=await Promise.all([U.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),U.from("program_lessons").select("id, title").eq("program_id",s.id),U.from("program_resources").select("id, title").eq("program_id",s.id),U.from("program_events").select("id, title, starts_at").eq("program_id",s.id),U.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:m.data||[],events:p.data||[],announcements:f.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=kLe(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:lq,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:j0,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 ${Df(s.price_cents,s.currency)} charge runs on ${yu(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Df(s.price_cents,s.currency)} once at checkout.`},{icon:on,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:tq,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(be,{children:e.jsxs(Le,{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(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(mr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(z,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(mr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(be,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Le,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(nl,{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(be,{children:e.jsxs(Le,{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(z,{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(mr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(be,{children:e.jsxs(Le,{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(ln,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(N5,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(N5,{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(N5,{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(N5,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Df(s.price_cents,s.currency)}),e.jsx(N5,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${yu(s.kickoff_at)||"not set"} · charge ${yu(s.charge_at)||"not set"}`}),e.jsx(N5,{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(N5,{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(N5,{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(N5,{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 ${yu(t.events[0].starts_at)}`:""}`}),e.jsx(N5,{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(be,{children:e.jsx(Le,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:gc,label:"Weeks",value:t.weeks.length},{icon:$r,label:"Lessons",value:t.lessons.length},{icon:$r,label:"Resources",value:t.resources.length},{icon:gc,label:"Events",value:t.events.length},{icon:Nh,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."})]})},iJs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],oJs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},lJs=({program:s,onSaved:t})=>{const[n,r]=_.useState(()=>wte(s)),[a,i]=_.useState(!1),[l,o]=_.useState(!1);_.useEffect(()=>{r(wte(s)),i(!1)},[s.id,s.updated_at]);const c=v=>{r(y=>({...y,...v})),i(!0)},d=(v,y)=>{const b=y?n.hidden.filter(S=>S!==v):[...new Set([...n.hidden,v])],w=y?n.required:n.required.filter(S=>S!==v);c({hidden:b,required:w})},u=(v,y)=>{c({required:y?[...new Set([...n.required,v])]:n.required.filter(b=>b!==v)})},h=()=>{const v={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,v]})},m=(v,y)=>c({custom:n.custom.map(b=>b.id===v?{...b,...y}:b)}),p=v=>c({custom:n.custom.filter(y=>y.id!==v)}),f=(v,y)=>{const b=[...n.custom],w=v+y;w<0||w>=b.length||([b[v],b[w]]=[b[w],b[v]],c({custom:b}))},g=async()=>{if(n.custom.find(w=>!w.label.trim()))return ne.error("Every custom question needs a label");o(!0);const y={...s.sales_copy||{},intake:n},{error:b}=await U.from("programs").update({sales_copy:y}).eq("id",s.id);if(o(!1),b)return ne.error(b.message);i(!1),ne.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(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs(z,{size:"sm",onClick:g,disabled:!a||l,children:[e.jsx(Bo,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-sm",children:"Intro message"})}),e.jsx(Le,{children:e.jsx(Ps,{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(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-sm",children:iJs[v]})}),e.jsxs(Le,{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"})]}),Uet.filter(y=>y.step===v).map(y=>{const b=!n.hidden.includes(y.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:y.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(mn,{checked:b,onCheckedChange:w=>d(y.key,w),"aria-label":`Show ${y.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(mn,{checked:n.required.includes(y.key),disabled:!b,onCheckedChange:w=>u(y.key,w),"aria-label":`Require ${y.label}`})})]},y.key)})]})]},v)),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Nt,{className:"text-sm",children:["Custom questions"," ",e.jsx(ze,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(sn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Le,{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,y)=>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:()=>f(y,-1),"aria-label":"Move up",children:e.jsx(Zf,{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(ee,{className:"text-xs",children:"Question"}),e.jsx(pe,{value:v.label,placeholder:"What is your biggest content roadblock?",onChange:b=>m(v.id,{label:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Answer type"}),e.jsxs(ls,{value:v.type,onValueChange:b=>m(v.id,{type:b}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(oJs).map(([b,w])=>e.jsx(He,{value:b,children:w},b))})]})]})]}),e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>p(v.id),"aria-label":"Delete question",children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]}),v.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ps,{rows:3,value:(v.options||[]).join(` `),onChange:b=>m(v.id,{options:b.target.value.split(` `).map(w=>w.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(ee,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(pe,{value:v.help||"",onChange:b=>m(v.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(mn,{checked:!!v.required,onCheckedChange:b=>m(v.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},v.id))]})]})]})},f1=HUt,x1=Rtt,g1=Ott,cJs=[Px,$r,bu],dJs=["Business profile","Content style","Goals & consent"],uJs=({fieldKey:s})=>s.includes("phone")?e.jsx(va,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(on,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Fm,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(Ha,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(Zr,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Mr,{className:"h-3.5 w-3.5"}):e.jsx(Bd,{className:"h-3.5 w-3.5"}):e.jsx(Oo,{className:"h-3.5 w-3.5"}),X0t=(s,t)=>s==null||s===""?"—":typeof s=="boolean"?s?e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600",children:[e.jsx(Mr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(Bd,{className:"h-3.5 w-3.5"})," No"]}):String(s),hJs=({program:s})=>{const[t,n]=_.useState(""),[r,a]=_.useState(new Set),{data:i=[],isLoading:l}=rt({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await U.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=wte(s),c=Uet.filter(h=>!o.hidden.includes(h.key)),d=i.filter(h=>{const m=t.toLowerCase();return m?String(h.full_name||"").toLowerCase().includes(m)||String(h.email||"").toLowerCase().includes(m)||String(h.city||"").toLowerCase().includes(m)||Object.values(h).some(p=>String(p).toLowerCase().includes(m)):!0}),u=h=>{const m=new Set(r);m.has(h)?m.delete(h):m.add(h),a(m)};return l?e.jsx(ln,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx($r,{className:"mx-auto mb-3 h-6 w-6"}),e.jsx("p",{children:"No intake responses yet."}),e.jsx("p",{className:"mt-1 text-xs",children:"Responses appear here once members complete the enrollment intake form."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake responses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," of ",i.length," response",i.length===1?"":"s"," · every field from the enrollment intake form"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Rr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search responses…",value:t,onChange:h=>n(h.target.value),className:"pl-9"})]})]}),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses match your search."}),e.jsx("div",{className:"space-y-3",children:d.map(h=>{const m=r.has(h.id),p=yu(h.created_at,!0);return e.jsx(be,{className:"overflow-hidden",children:e.jsxs(f1,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(x1,{asChild:!0,children:e.jsxs(_t,{className:"flex cursor-pointer flex-row items-center justify-between gap-3 bg-muted/30 px-5 py-3 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-primary/10",children:e.jsx(Oo,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(Nt,{className:"text-sm font-semibold",children:[h.full_name||"Unnamed member",h.city&&e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["· ",h.city]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.email,h.email&&h.phone&&" · ",h.phone]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"hidden text-right sm:block",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Submitted"}),e.jsx("p",{className:"text-xs font-medium",children:p})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(cl,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(g1,{children:e.jsxs(Le,{className:"space-y-5 p-5",children:[[0,1,2].map(f=>{const g=c.filter(y=>y.step===f),v=cJs[f];return g.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(v,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:dJs[f]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:g.map(y=>{const b=h[y.key];return b==null||b===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(uJs,{fieldKey:y.key}),y.label]}),e.jsx("p",{className:"text-sm font-medium",children:X0t(b,y.key)})]},y.key)})})]},f)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx($r,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(f=>{var v;const g=(v=h.extra)==null?void 0:v[f.id];return g==null||g===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:f.label}),e.jsx("p",{className:"text-sm font-medium",children:X0t(g,f.id)})]},f.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),"Submitted ",p,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},mJs=[{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"}],pJs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},Q0t={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},fJs=({programId:s})=>{const{data:t=[],isLoading:n}=J$s(s),r=eUs(s),a=tUs(),[i,l]=_.useState(!1),[o,c]=_.useState({...Q0t}),d=()=>{c({...Q0t}),l(!0)},u=v=>{c({id:v.id,title:v.title,description:v.description||"",event_kind:v.event_kind,starts_at:pJs(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 ne.error("Give the session a title");if(!o.starts_at)return ne.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},m=Date.now(),p=t.filter(v=>new Date(v.starts_at).getTime()>=m),f=t.filter(v=>new Date(v.starts_at).getTime()e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{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:[yu(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(mr,{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),ne.success("Join link copied")},children:[e.jsx(Sa,{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(Xr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>u(v),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"outline",size:"sm",onClick:async()=>{await Qi(`Remove "${v.title}"?`)&&a.mutate(v.id)},children:e.jsx(Cn,{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(z,{onClick:d,children:[e.jsx(sn,{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(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ud,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",p.length,")"]}),p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):p.map(v=>e.jsx(g,{e:v},v.id))]}),f.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 (",f.length,") — add replay links so members can catch up"]}),f.map(v=>e.jsx(g,{e:v},v.id))]})]}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Title"}),e.jsx(pe,{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(ee,{children:"Type"}),e.jsxs(ls,{value:o.event_kind,onValueChange:v=>c({...o,event_kind:v}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:mJs.map(v=>e.jsx(He,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Host / speaker"}),e.jsx(pe,{value:o.speaker,onChange:v=>c({...o,speaker:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Starts (your local time)"}),e.jsx(pe,{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(ee,{children:"Length (minutes)"}),e.jsx(pe,{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(ee,{children:"Zoom / meeting link"}),e.jsx(pe,{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(ee,{children:"Replay link (after the call)"}),e.jsx(pe,{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(ee,{children:"What we'll cover"}),e.jsx(Ps,{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(mn,{checked:o.is_published,onCheckedChange:v=>c({...o,is_published:v})})]})]}),e.jsx(hr,{children:e.jsxs(z,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},J0t={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},xJs=({programId:s})=>{const{data:t,isLoading:n}=sUs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=yBt(s),l=nUs(s),o=rUs(),[c,d]=_.useState(!1),[u,h]=_.useState({...J0t}),[m,p]=_.useState(!1),f=_.useRef(null),g=async C=>{if(f.current&&(f.current.value=""),!!C){if(!C.type.startsWith("video/"))return ne.error("Please choose a video file");if(C.size>500*1024*1024)return ne.error("Video must be under 500MB");p(!0);try{const E=C.name.split(".").pop()||"mp4",P=`lessons/${crypto.randomUUID()}.${E}`,{error:M}=await U.storage.from("program-assets").upload(P,C,{contentType:C.type,upsert:!1});if(M)throw M;const{data:I,error:D}=await U.storage.from("program-assets").createSignedUrl(P,60*60*24*365*5);if(D||!(I!=null&&I.signedUrl))throw D||new Error("Could not sign video URL");h(F=>({...F,video_url:I.signedUrl})),ne.success("Video uploaded")}catch(E){ne.error((E==null?void 0:E.message)||"Upload failed")}finally{p(!1)}}},v=()=>{h({...J0t,sort_order:r.length}),d(!0)},y=C=>{h({id:C.id,title:C.title,summary:C.summary||"",week_id:C.week_id||"none",duration_minutes:C.duration_minutes??"",video_url:C.video_url||"",worksheet_url:C.worksheet_url||"",action_assignment:C.action_assignment||"",status:C.status,sort_order:C.sort_order}),d(!0)},b=async()=>{if(!u.title.trim())return ne.error("Give the video a title");await l.mutateAsync({...u,week_id:u.week_id==="none"?null:u.week_id,duration_minutes:u.duration_minutes===""?null:Number(u.duration_minutes),sort_order:Number(u.sort_order)||0}),d(!1)},w=C=>{const E=a.find(P=>P.id===C);return E?`Week ${E.week_number}`:"Unassigned"},S=xBt(u.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs(z,{onClick:v,children:[e.jsx(sn,{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(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Yh,{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(C=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{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:C.title}),e.jsx(ze,{variant:"secondary",children:w(C.week_id)}),C.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:C.status}),C.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[C.duration_minutes," min"]}):null]}),C.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:C.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[C.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:C.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),C.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:C.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>y(C),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"outline",size:"sm",onClick:async()=>{await Qi(`Remove "${C.title}"?`)&&o.mutate(C.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})},C.id))}),e.jsx(Is,{open:c,onOpenChange:d,children:e.jsxs(Ls,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:u.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{placeholder:"How to script a 30-second listing reel",value:u.title,onChange:C=>h({...u,title:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:u.video_url,onChange:C=>h({...u,video_url:C.target.value})}),e.jsxs(z,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var C;return(C=f.current)==null?void 0:C.click()},children:[m?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"mr-1.5 h-4 w-4"}),m?"Uploading…":"Upload"]}),e.jsx("input",{ref:f,type:"file",accept:"video/*",className:"hidden",onChange:C=>{var E;return g((E=C.target.files)==null?void 0:E[0])}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste a YouTube / Vimeo / Loom link, or upload an MP4 (up to 500MB) hosted by LevelUp."}),u.video_url&&!S&&!OJ(u.video_url)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),S&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:S,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),!S&&OJ(u.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:u.video_url,controls:!0,className:"aspect-video w-full",preload:"metadata"})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Week"}),e.jsxs(ls,{value:u.week_id,onValueChange:C=>h({...u,week_id:C}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"Unassigned (library)"}),a.map(C=>e.jsxs(He,{value:C.id,children:["Week ",C.week_number," — ",C.title]},C.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (minutes)"}),e.jsx(pe,{type:"number",value:u.duration_minutes,onChange:C=>h({...u,duration_minutes:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ls,{value:u.status,onValueChange:C=>h({...u,status:C}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"published",children:"Published (visible)"}),e.jsx(He,{value:"draft",children:"Draft (hidden)"}),e.jsx(He,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Order"}),e.jsx(pe,{type:"number",value:u.sort_order,onChange:C=>h({...u,sort_order:C.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Summary"}),e.jsx(Ps,{rows:3,value:u.summary,onChange:C=>h({...u,summary:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Worksheet / download link"}),i.length>0&&e.jsxs(ls,{value:"",onValueChange:C=>{const E=i.find(M=>M.id===C),P=E?gae(E):null;P?h({...u,worksheet_url:P}):ne.error("That resource has no file or link yet")},children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(as,{children:i.map(C=>e.jsx(He,{value:C.id,children:C.title},C.id))})]}),e.jsx(pe,{placeholder:"Or paste a link",value:u.worksheet_url,onChange:C=>h({...u,worksheet_url:C.target.value})}),u.worksheet_url&&e.jsxs("a",{href:u.worksheet_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(mr,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Action assignment"}),e.jsx(Ps,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:u.action_assignment,onChange:C=>h({...u,action_assignment:C.target.value})})]})]}),e.jsx(hr,{children:e.jsxs(z,{onClick:b,disabled:l.isPending,children:[l.isPending&&e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},evt={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},gJs=({programId:s})=>{const{data:t=[],isLoading:n}=yBt(s),r=aUs(s),a=iUs(),[i,l]=_.useState(!1),[o,c]=_.useState({...evt}),[d,u]=_.useState(!1),h=_.useRef(null),m=Array.from(new Set(t.map(y=>y.category))).filter(Boolean),p=()=>{c({...evt,sort_order:t.length}),l(!0)},f=y=>{c({id:y.id,title:y.title,description:y.description||"",category:y.category||"Resources",resource_kind:y.resource_kind,url:y.url||"",file_path:y.file_path||"",status:y.status,sort_order:y.sort_order}),l(!0)},g=async y=>{if(!(!y||!s)){if(y.size>50*1024*1024)return ne.error("File must be under 50MB");u(!0);try{const b=y.name.split(".").pop()||"pdf",w=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:S}=await U.storage.from(AW).upload(w,y,{contentType:y.type||"application/pdf",upsert:!1});if(S)throw S;c(C=>({...C,file_path:w,url:"",title:C.title||y.name.replace(/\.[^.]+$/,""),resource_kind:y.type==="application/pdf"?"pdf":C.resource_kind})),ne.success("File uploaded")}catch(b){ne.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},v=async()=>{if(!o.title.trim())return ne.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ne.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(z,{onClick:p,children:[e.jsx(sn,{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(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx($r,{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(y=>{const b=gae(y);return e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:y.title}),e.jsx(ze,{variant:"secondary",children:y.category}),e.jsx(ze,{variant:"outline",className:"capitalize",children:y.resource_kind.replace("_"," ")}),y.status!=="published"&&e.jsx(ze,{variant:"outline",className:"capitalize",children:y.status})]}),y.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:y.description}),b&&e.jsxs("button",{type:"button",onClick:()=>zJ(y),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(mr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>f(y),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi(`Remove "${y.title}"?`)&&a.mutate(y)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})]})},y.id)})}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Title"}),e.jsx(pe,{value:o.title,onChange:y=>c({...o,title:y.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{rows:2,value:o.description,onChange:y=>c({...o,description:y.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(ee,{children:"Category"}),e.jsx(pe,{value:o.category,onChange:y=>c({...o,category:y.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ls,{value:o.resource_kind,onValueChange:y=>c({...o,resource_kind:y}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:gBt.map(y=>e.jsx(He,{value:y.value,children:y.label},y.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(ee,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:y=>{var b;return g((b=y.target.files)==null?void 0:b[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(z,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>{var y;return(y=h.current)==null?void 0:y.click()},disabled:d,children:[d?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ra,{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(pe,{value:o.url,onChange:y=>c({...o,url:y.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(ee,{children:"Status"}),e.jsxs(ls,{value:o.status,onValueChange:y=>c({...o,status:y}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"published",children:"Published (visible)"}),e.jsx(He,{value:"draft",children:"Draft (hidden)"}),e.jsx(He,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:o.sort_order,onChange:y=>c({...o,sort_order:y.target.value})})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(z,{onClick:v,disabled:r.isPending||d,children:[r.isPending&&e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},yJs=({programId:s})=>{const{data:t=[],isLoading:n}=hUs(s),r=_.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(ln,{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(be,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(fS,{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(be,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(On,{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(be,{children:e.jsx(Le,{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(z,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),ne.success("Emails copied")},children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(z,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(Ga,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Joined"})]})}),e.jsx(Qa,{children:t.map(l=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:l.full_name||"—"}),e.jsx(yt,{children:l.email||"—"}),e.jsx(yt,{children:l.phone||"—"}),e.jsx(yt,{children:l.brokerage||"—"}),e.jsx(yt,{className:"text-muted-foreground",children:yu(l.created_at)})]},l.id))})]})})]})},tvt={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:""},vJs=()=>{const s=$t(),[t,n]=_.useState(null),[r,a]=_.useState(!1),[i,l]=_.useState({...tvt}),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(null),{data:p=[],isLoading:f}=rt({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:I}=await U.from("programs").select("*").order("created_at",{ascending:!1});if(I)throw I;return M||[]}}),g=p.find(M=>M.id===t)||p[0]||null,{data:v=[]}=rt({queryKey:["admin-program-enrollments",g==null?void 0:g.id],enabled:!!(g!=null&&g.id),queryFn:async()=>{const{data:M,error:I}=await U.from("program_enrollments").select("*").eq("program_id",g.id).order("created_at",{ascending:!1});if(I)throw I;const D=(M||[]).map(G=>G.user_id),{data:F}=D.length?await U.from("profiles").select("id, name, email").in("id",D):{data:[]},q=new Map((F||[]).map(G=>[G.id,G]));return(M||[]).map(G=>({...G,profile:q.get(G.user_id)}))}}),{data:y=[]}=rt({queryKey:["admin-program-intakes",g==null?void 0:g.id],enabled:!!(g!=null&&g.id),queryFn:async()=>{const{data:M,error:I}=await U.from("program_intake_responses").select("*").eq("program_id",g.id);if(I)throw I;return M||[]}}),{data:b=[]}=rt({queryKey:["admin-program-audit",g==null?void 0:g.id],enabled:!!(g!=null&&g.id),queryFn:async()=>{const{data:M,error:I}=await U.from("program_audit_logs").select("*").eq("program_id",g.id).order("created_at",{ascending:!1}).limit(100);if(I)throw I;return M||[]}}),w=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:I}=await U.from("programs").insert(M);if(I)throw I;ne.success("Program created"),a(!1),l({...tvt}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){ne.error(M.message||"Could not create the program")}finally{c(!1)}},S=async M=>{if(!g)return;const{error:I}=await U.from("programs").update(M).eq("id",g.id);if(I)return ne.error(I.message);s.invalidateQueries({queryKey:["admin-programs"]})},C=async(M,I)=>{const{error:D}=await U.from("program_enrollments").update(I).eq("id",M);if(D)return ne.error(D.message);ne.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},E=async M=>{u(!0);const{data:I,error:D}=await U.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),D||I!=null&&I.error)return ne.error((I==null?void 0:I.error)||(D==null?void 0:D.message));ne.success(`Processed ${(I==null?void 0:I.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},P=M=>M==="paid"||M==="completed"?"default":M==="payment_failed"?"destructive":"secondary";return e.jsx($s,{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(z,{variant:"outline",onClick:()=>E(),disabled:d,children:[d?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(j0,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(Is,{open:r,onOpenChange:a,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Ls,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (URL)"}),e.jsx(pe,{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(ee,{children:"Subtitle"}),e.jsx(pe,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{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(ee,{children:"One-time price (USD)"}),e.jsx(pe,{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(ee,{children:"Seats"}),e.jsx(pe,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Weeks"}),e.jsx(pe,{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(ee,{children:"Videos per week"}),e.jsx(pe,{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(ee,{children:"Billing"}),e.jsxs(ls,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"delayed",children:"Save card, charge later"}),e.jsx(He,{value:"immediate",children:"Charge at checkout"}),e.jsx(He,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Kickoff"}),e.jsx(pe,{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(ee,{children:"Charge date"}),e.jsx(pe,{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(ee,{children:"Enrollment closes"}),e.jsx(pe,{type:"datetime-local",value:i.enrollment_close_at,onChange:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(hr,{children:e.jsxs(z,{onClick:w,disabled:o||!i.name,children:[o&&e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),f?e.jsx(ln,{className:"h-40 w-full rounded-xl"}):p.length===0?e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(M=>e.jsxs(z,{variant:(g==null?void 0:g.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))}),g&&e.jsxs(Qr,{defaultValue:"overview",children:[e.jsxs(Jr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Wt,{value:"overview",children:"Overview"}),e.jsx(Wt,{value:"details",children:"Details & pricing"}),e.jsx(Wt,{value:"sessions",children:"Live sessions"}),e.jsx(Wt,{value:"videos",children:"On-demand videos"}),e.jsx(Wt,{value:"resources",children:"Resources"}),e.jsx(Wt,{value:"intake-form",children:"Intake form"}),e.jsx(Wt,{value:"discounts",children:"Discount codes"}),e.jsx(Wt,{value:"experience",children:"Enrollee experience"}),e.jsx(Wt,{value:"interest",children:"Interest list"}),e.jsxs(Wt,{value:"enrollments",children:["Enrollments (",v.length,")"]}),e.jsxs(Wt,{value:"intake",children:["Intake (",y.length,")"]}),e.jsx(Wt,{value:"audit",children:"Audit"})]}),e.jsxs(Kt,{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(be,{children:e.jsxs(Le,{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:[" / ",g.capacity]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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:Df(v.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,I)=>M+(I.amount_cents||0),0),g.currency)})]})})]}),e.jsx(be,{children:e.jsxs(Le,{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(mn,{checked:g.status==="published",onCheckedChange:M=>S({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(mn,{checked:g.is_featured,onCheckedChange:M=>S({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:Df(g.price_cents,g.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:yu(g.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:yu(g.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(Kt,{value:"details",className:"mt-6",children:e.jsx(tJs,{program:g,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Kt,{value:"sessions",className:"mt-6",children:e.jsx(fJs,{programId:g.id})}),e.jsx(Kt,{value:"videos",className:"mt-6",children:e.jsx(xJs,{programId:g.id})}),e.jsx(Kt,{value:"resources",className:"mt-6",children:e.jsx(gJs,{programId:g.id})}),e.jsx(Kt,{value:"discounts",className:"mt-6",children:e.jsx(rJs,{program:g})}),e.jsx(Kt,{value:"intake-form",className:"mt-6",children:e.jsx(lJs,{program:g,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Kt,{value:"experience",className:"mt-6",children:e.jsx(aJs,{program:g})}),e.jsx(Kt,{value:"interest",className:"mt-6",children:e.jsx(yJs,{programId:g.id})}),e.jsx(Kt,{value:"enrollments",className:"mt-6",children:e.jsx(be,{children:e.jsx(Le,{className:"overflow-x-auto p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Charge date"}),e.jsx(Tt,{children:"Amount"}),e.jsx(Tt,{children:"Access"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsxs(Qa,{children:[v.length===0&&e.jsx(fn,{children:e.jsxs(yt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(On,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),v.map(M=>{var I,D;return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>m(M),children:[e.jsx("p",{className:"font-medium",children:((I=M.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(D=M.profile)==null?void 0:D.email})]})}),e.jsxs(yt,{children:[e.jsx(ze,{variant:P(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(yt,{className:"text-sm",children:yu(M.charge_scheduled_at)||"—"}),e.jsx(yt,{className:"text-sm",children:Df(M.amount_cents,M.currency)}),e.jsx(yt,{children:e.jsx(mn,{checked:M.access_override,onCheckedChange:F=>C(M.id,{access_override:F})})}),e.jsxs(yt,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(M.status)&&e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>E(M.id),disabled:d,children:[e.jsx(Gi,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(M.status)&&e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>C(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsx(Kt,{value:"intake",className:"mt-6",children:e.jsx(hJs,{program:g})}),e.jsx(Kt,{value:"audit",className:"mt-6",children:e.jsx(be,{children:e.jsxs(Le,{className:"space-y-2 p-5 text-sm",children:[b.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),b.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:yu(M.created_at,!0)})]},M.id))]})})})]}),g&&e.jsx(nJs,{program:g,enrollment:h,open:!!h,onOpenChange:M=>!M&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},bJs=()=>{const{user:s}=hs(),[t,n]=_.useState(""),[r,a]=_.useState("all"),{data:i=[]}=rt({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(p)throw p;return m}}),{data:l=[],isLoading:o}=rt({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(p)throw p;const{data:f,error:g}=await U.from("academy_resources").select("*").order("sort_order");if(g)throw g;return m.map(y=>({...y,resources:(f==null?void 0:f.filter(b=>b.video_id===y.id))||[]}))}}),{data:c=[]}=rt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_video_likes").select("video_id, user_id");if(p)throw p;return m}}),d=l.filter(m=>{var g;const p=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((g=m.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase())),f=r==="all"||m.category_id===r;return p&&f}),u=m=>c.filter(p=>p.video_id===m).length,h=m=>c.some(p=>p.video_id===m&&p.user_id===(s==null?void 0:s.id));return e.jsx($s,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(Qr,{value:r,onValueChange:a,children:e.jsxs(Jr,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Wt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Wt,{value:m.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:m.name},m.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:t?"Try adjusting your search terms":"Check back soon for new content"})]})}):e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:d.map(m=>e.jsx(or,{to:`/academy/${m.id}`,children:e.jsxs(be,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[m.thumbnail_url?e.jsx("img",{src:m.thumbnail_url,alt:m.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Xr,{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(su,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),m.duration&&e.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(_t,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Nt,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(ze,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Le,{className:"pt-0",children:[m.description&&e.jsx(En,{className:"line-clamp-2",children:m.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ug,{className:`h-4 w-4 ${h(m.id)?"fill-primary text-primary":""}`}),u(m.id)]}),m.resources&&m.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function aqt({resourceType:s,resourceId:t}){const{data:n=[]}=rt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await U.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await U.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(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(yc,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(or,{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(yc,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const _Js=(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},wJs=()=>{const{videoId:s}=Mi();zn();const{user:t,isAdmin:n}=hs(),{toast:r}=_i(),a=$t(),{trackEngagement:i}=CW(),[l,o]=_.useState(""),{data:c,isLoading:d}=rt({queryKey:["academy-video",s],queryFn:async()=>{const{data:w,error:S}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(S)throw S;const{data:C}=await U.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...w,resources:C||[]}},enabled:!!s});_.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=rt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:w,error:S}=await U.from("academy_video_likes").select("*").eq("video_id",s);if(S)throw S;return w},enabled:!!s}),{data:h=[]}=rt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:w,error:S}=await U.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(S)throw S;const C=[...new Set(w.map(M=>M.user_id))],{data:E}=await U.from("profiles").select("id, name").in("id",C),P=new Map((E==null?void 0:E.map(M=>[M.id,M.name]))||[]);return w.map(M=>({...M,user_name:P.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=mt({mutationFn:async w=>{const{error:S}=await U.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:w});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:w=>{r({title:"Error adding comment",description:w.message,variant:"destructive"})}}),p=mt({mutationFn:async w=>{const{error:S}=await U.from("academy_video_comments").delete().eq("id",w);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),f=mt({mutationFn:async()=>{const w=u.find(S=>S.user_id===(t==null?void 0:t.id));if(w){const{error:S}=await U.from("academy_video_likes").delete().eq("id",w.id);if(S)throw S}else{const{error:S}=await U.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),g=u.some(w=>w.user_id===(t==null?void 0:t.id)),v=w=>{switch(w==null?void 0:w.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},y=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=w=>{w.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx($s,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx($s,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/academy",children:[e.jsx(ka,{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:_Js(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(Xr,{className:"h-16 w-16 opacity-50"}),e.jsx(z,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(mr,{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(z,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(or,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Wa,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(TW,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(z,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Ug,{className:`h-4 w-4 ${g?"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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(w=>e.jsxs("a",{href:w.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(w.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:w.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:w.file_type})]}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]},w.id))})]})}),e.jsx(aqt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Bu,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Ps,{placeholder:"Add a comment...",value:l,onChange:w=>o(w.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(z,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Fr,{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(be,{children:e.jsx(Le,{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(w=>e.jsx(be,{children:e.jsx(Le,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:y(w.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:w.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Md(new Date(w.created_at),{addSuffix:!0})}),w.user_id===(t==null?void 0:t.id)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(w.id),children:e.jsx(Cn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:w.content})]})]})})},w.id))})]})]})}):e.jsx($s,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xr,{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(z,{asChild:!0,className:"mt-4",children:e.jsx(or,{to:"/academy",children:"Back to Academy"})})]})})},RB="https://dashboard.relevelup.com",jJs=(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},NJs=[{icon:dm,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:cf,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:On,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:jl,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function kJs(){var i;const{slug:s}=Mi(),{data:t,isLoading:n,error:r}=rt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await U.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});_.useEffect(()=>{if(t&&s){U.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy.");const c=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/academy-og?slug=${encodeURIComponent(s)}&mode=image`;let d=document.querySelector('meta[property="og:image"]');d||(d=document.createElement("meta"),d.setAttribute("property","og:image"),document.head.appendChild(d)),d.setAttribute("content",c)}},[t,s]);const a=_.useMemo(()=>t?jJs(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:RB,children:e.jsx(z,{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:RB,children:e.jsx(z,{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(dm,{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(Xf,{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:RB,className:"w-full sm:w-auto",children:e.jsxs(z,{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(Da,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:RB,className:"w-full sm:w-auto",children:e.jsx(z,{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:NJs.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(Mr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Mr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Mr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:RB,children:e.jsxs(z,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(Da,{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:RB,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function SJs(){const s=zn(),[t,n]=_.useState(""),{data:r,isLoading:a}=rt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:p,error:f}=await U.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;return p}}),{data:i}=rt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:p,error:f}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(f)throw f;return p}}),{data:l}=rt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:p,error:f}=await U.from("resource_kit_likes").select("kit_id");if(f)throw f;return p}}),{data:o}=rt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:p,error:f}=await U.from("resource_kit_comments").select("kit_id");if(f)throw f;return p}}),c=r==null?void 0:r.filter(p=>{var f;return p.name.toLowerCase().includes(t.toLowerCase())||((f=p.description)==null?void 0:f.toLowerCase().includes(t.toLowerCase()))}),d=p=>(i==null?void 0:i.filter(f=>f.kit_id===p))||[],u=p=>(l==null?void 0:l.filter(f=>f.kit_id===p).length)||0,h=p=>(o==null?void 0:o.filter(f=>f.kit_id===p).length)||0,m=p=>{s(`/toolbox/${p}`)};return e.jsx($s,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search resource kits...",value:t,onChange:p=>n(p.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((p,f)=>e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(ln,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(ln,{className:"h-5 w-3/4 mb-2"}),e.jsx(ln,{className:"h-4 w-full mb-4"}),e.jsx(ln,{className:"h-4 w-2/3"})]})},f))}):(c==null?void 0:c.length)===0?e.jsxs(be,{className:"p-12 text-center",children:[e.jsx(Sh,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(p=>{const f=d(p.id).length,g=u(p.id),v=h(p.id);return e.jsxs(be,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>m(p.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:p.featured_image_url?e.jsx("img",{src:p.featured_image_url,alt:p.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Sh,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Le,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:p.name}),p.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:ete(p.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-4 w-4"}),f," file",f!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ug,{className:"h-3.5 w-3.5"}),g]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),v]})]})]})]})]},p.id)})})]})})}const CJs=()=>{const{kitId:s}=Mi(),{user:t,isAdmin:n}=hs(),{toast:r}=_i(),a=$t(),{trackEngagement:i}=CW(),[l,o]=_.useState(""),{data:c,isLoading:d}=rt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:w,error:S}=await U.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(S)throw S;const{data:C}=await U.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:E}=await U.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...w,files:C||[],links:E||[]}},enabled:!!s});_.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=rt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:w,error:S}=await U.from("resource_kit_likes").select("*").eq("kit_id",s);if(S)throw S;return w},enabled:!!s}),{data:h=[]}=rt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:w,error:S}=await U.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(S)throw S;const C=[...new Set(w.map(M=>M.user_id))],{data:E}=await U.from("profiles").select("id, name").in("id",C),P=new Map((E==null?void 0:E.map(M=>[M.id,M.name]))||[]);return w.map(M=>({...M,user_name:P.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=mt({mutationFn:async w=>{const{error:S}=await U.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:w});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:w=>{r({title:"Error adding comment",description:w.message,variant:"destructive"})}}),p=mt({mutationFn:async w=>{const{error:S}=await U.from("resource_kit_comments").delete().eq("id",w);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),f=mt({mutationFn:async()=>{const w=u.find(S=>S.user_id===(t==null?void 0:t.id));if(w){const{error:S}=await U.from("resource_kit_likes").delete().eq("id",w.id);if(S)throw S}else{const{error:S}=await U.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),g=u.some(w=>w.user_id===(t==null?void 0:t.id)),v=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),y=w=>w?w<1024?w+" B":w<1024*1024?(w/1024).toFixed(1)+" KB":(w/(1024*1024)).toFixed(1)+" MB":"",b=w=>{w.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx($s,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx($s,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/toolbox",children:[e.jsx(ka,{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(z,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(or,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Wa,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(TW,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(z,{variant:g?"default":"outline",className:"gap-2 rounded-full",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Ug,{className:`h-4 w-4 ${g?"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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(w=>e.jsxs("a",{href:w.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($r,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:w.name}),w.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y(w.file_size)})]})]}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},w.id))})]})}),c.links&&c.links.length>0&&e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(mr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(w=>e.jsxs("a",{href:w.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(mr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:w.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},w.id))})]})}),e.jsx(aqt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Bu,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Ps,{placeholder:"Add a comment...",value:l,onChange:w=>o(w.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(z,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Fr,{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(be,{children:e.jsx(Le,{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(w=>e.jsx(be,{children:e.jsx(Le,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:v(w.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:w.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Md(new Date(w.created_at),{addSuffix:!0})}),w.user_id===(t==null?void 0:t.id)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(w.id),children:e.jsx(Cn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:w.content})]})]})})},w.id))})]})]})}):e.jsx($s,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sh,{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(z,{asChild:!0,className:"mt-4",children:e.jsx(or,{to:"/toolbox",children:"Back to Toolbox"})})]})})},AJs=()=>{const s=zn(),[t,n]=_.useState(""),[r,a]=_.useState("grid"),{data:i=[],isLoading:l}=rt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await U.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await U.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:p}=await U.from("social_swag_likes").select("swag_id"),{data:f}=await U.from("social_swag_comments").select("swag_id"),g=new Map;p==null||p.forEach(b=>{g.set(b.swag_id,(g.get(b.swag_id)||0)+1)});const v=new Map;return f==null||f.forEach(b=>{v.set(b.swag_id,(v.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(w=>w.swag_id===b.id)||[],likesCount:g.get(b.id)||0,commentsCount:v.get(b.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($s,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{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(z,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(op,{className:"h-4 w-4"})}),e.jsx(z,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(My,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(ln,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(ln,{className:"h-5 w-3/4 mb-2"}),e.jsx(ln,{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(z,{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(be,{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(Kc,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Le,{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(Ug,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(z,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(mr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var ec=function(){return ec=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),m=function(){r&&i(r)},p=function(){a&&i(a)};return e.jsx(oen,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:p})}function len(s){var t,n=up(),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:lqt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(svt,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(svt,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(nvt,{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(nvt,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function cen(s){var t=up(),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 den(s,t,n){for(var r=n?SE(new Date):v1(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Uh(r,i);a.push(l)}return a}function uen(){var s=up(),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=den(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 hen(){var s,t=up(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:uen;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function men(s){var t=up(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var qtt=_.createContext(void 0);function pen(s){if(!jae(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(qtt.Provider,{value:t,children:s.children})}return e.jsx(fen,{initialProps:s.initialProps,children:s.children})}function fen(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,p;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var f=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!f){var g=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!g){var v=r?iqt([],r):[];if(u.selected){var y=v.findIndex(function(b){return hm(d,b)});v.splice(y,1)}else v.push(d);(p=t.onSelect)===null||p===void 0||p.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(m){return hm(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(qtt.Provider,{value:c,children:n})}function Vtt(){var s=_.useContext(qtt);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function xen(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?hm(a,s)&&hm(r,s)?void 0:hm(a,s)?{from:a,to:void 0}:hm(r,s)?void 0:tC(r,s)?{from:s,to:a}:{from:r,to:s}:a?tC(s,a)?{from:a,to:s}:{from:s,to:a}:r?wS(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var Htt=_.createContext(void 0);function gen(s){if(!Nae(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(Htt.Provider,{value:t,children:s.children})}return e.jsx(yen,{initialProps:s.initialProps,children:s.children})}function yen(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(p,f,g){var v,y;(v=t.onDayClick)===null||v===void 0||v.call(t,p,f,g);var b=xen(p,r);(y=t.onSelect)===null||y===void 0||y.call(t,b,p,f,g)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],hm(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:L4e(i,o-1),before:Uh(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Uh(i,o-1)}),!i&&l&&u.disabled.push({after:L4e(l,o-1),before:Uh(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Uh(i,-c+1)}),u.disabled.push({after:Uh(i,c-1)})),i&&l){var h=fv(l,i)+1,m=c-h;u.disabled.push({before:L4e(i,m)}),u.disabled.push({after:Uh(l,m)})}!i&&l&&(u.disabled.push({before:Uh(l,-c+1)}),u.disabled.push({after:Uh(l,c-1)}))}return e.jsx(Htt.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function Gtt(){var s=_.useContext(Htt);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function sCe(s){return Array.isArray(s)?iqt([],s):s!==void 0?[s]:[]}function ven(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=sCe(a)}),t}var IS;(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"})(IS||(IS={}));var ben=IS.Selected,w3=IS.Disabled,_en=IS.Hidden,wen=IS.Today,l9e=IS.RangeEnd,c9e=IS.RangeMiddle,d9e=IS.RangeStart,jen=IS.Outside;function Nen(s,t,n){var r,a=(r={},r[ben]=sCe(s.selected),r[w3]=sCe(s.disabled),r[_en]=sCe(s.hidden),r[wen]=[s.today],r[l9e]=[],r[c9e]=[],r[d9e]=[],r[jen]=[],r);return s.fromDate&&a[w3].push({before:s.fromDate}),s.toDate&&a[w3].push({after:s.toDate}),jae(s)?a[w3]=a[w3].concat(t.modifiers[w3]):Nae(s)&&(a[w3]=a[w3].concat(n.modifiers[w3]),a[d9e]=n.modifiers[d9e],a[c9e]=n.modifiers[c9e],a[l9e]=n.modifiers[l9e]),a}var uqt=_.createContext(void 0);function ken(s){var t=up(),n=Vtt(),r=Gtt(),a=Nen(t,n,r),i=ven(t.modifiers),l=ec(ec({},a),i);return e.jsx(uqt.Provider,{value:l,children:s.children})}function hqt(){var s=_.useContext(uqt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function Sen(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function Cen(s){return!!(s&&typeof s=="object"&&"from"in s)}function Aen(s){return!!(s&&typeof s=="object"&&"after"in s)}function Een(s){return!!(s&&typeof s=="object"&&"before"in s)}function Ten(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function Men(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=fv(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=fv(s,r)>=0&&fv(a,s)>=0;return l}return a?hm(a,s):r?hm(r,s):!1}function Pen(s){return pJe(s)}function Len(s){return Array.isArray(s)&&s.every(pJe)}function Ien(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(Pen(n))return hm(s,n);if(Len(n))return n.includes(s);if(Cen(n))return Men(s,n);if(Ten(n))return n.dayOfWeek.includes(s.getDay());if(Sen(n)){var r=fv(n.before,s),a=fv(n.after,s),i=r>0,l=a<0,o=tC(n.before,n.after);return o?l&&i:i||l}return Aen(n)?fv(s,n.after)>0:Een(n)?fv(n.before,s)>0:typeof n=="function"?n(s):!1})}function Wtt(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return Ien(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!eae(s,n)&&(a.outside=!0),a}function Den(s,t){for(var n=om(s[0]),r=b_(s[s.length-1]),a,i,l=n;l<=r;){var o=Wtt(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Uh(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Uh(l,1)}return i||a}var Ren=365;function mqt(s,t){var n=t.moveBy,r=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,u=a.toDate,h=a.locale,m={day:Uh,week:bF,month:A0,year:I3s,startOfWeek:function(v){return a.ISOWeek?SE(v):v1(v,{locale:h,weekStartsOn:c})},endOfWeek:function(v){return a.ISOWeek?MRt(v):TPe(v,{locale:h,weekStartsOn:c})}},p=m[n](s,r==="after"?1:-1);r==="before"&&d?p=D3s([d,p]):r==="after"&&u&&(p=R3s([u,p]));var f=!0;if(i){var g=Wtt(p,i);f=!g.disabled&&!g.hidden}return f?p:o.count>Ren?o.lastFocused:mqt(p,{moveBy:n,direction:r,context:a,modifiers:i,retry:ec(ec({},o),{count:o.count+1})})}var pqt=_.createContext(void 0);function Fen(s){var t=kae(),n=hqt(),r=_.useState(),a=r[0],i=r[1],l=_.useState(),o=l[0],c=l[1],d=Den(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(v){i(v)},p=up(),f=function(v,y){if(a){var b=mqt(a,{moveBy:v,direction:y,context:p,modifiers:n});hm(a,b)||(t.goToDate(b,a),m(b))}},g={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return f("day","after")},focusDayBefore:function(){return f("day","before")},focusWeekAfter:function(){return f("week","after")},focusWeekBefore:function(){return f("week","before")},focusMonthBefore:function(){return f("month","before")},focusMonthAfter:function(){return f("month","after")},focusYearBefore:function(){return f("year","before")},focusYearAfter:function(){return f("year","after")},focusStartOfWeek:function(){return f("startOfWeek","before")},focusEndOfWeek:function(){return f("endOfWeek","after")}};return e.jsx(pqt.Provider,{value:g,children:s.children})}function Ktt(){var s=_.useContext(pqt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function Oen(s,t){var n=hqt(),r=Wtt(s,n,t);return r}var Ytt=_.createContext(void 0);function zen(s){if(!JLe(s.initialProps)){var t={selected:void 0};return e.jsx(Ytt.Provider,{value:t,children:s.children})}return e.jsx(Ben,{initialProps:s.initialProps,children:s.children})}function Ben(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(Ytt.Provider,{value:a,children:n})}function fqt(){var s=_.useContext(Ytt);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function $en(s,t){var n=up(),r=fqt(),a=Vtt(),i=Gtt(),l=Ktt(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,p=l.focusMonthBefore,f=l.focusMonthAfter,g=l.focusYearBefore,v=l.focusYearAfter,y=l.focusStartOfWeek,b=l.focusEndOfWeek,w=function(Z){var oe,re,ae,J;JLe(n)?(oe=r.onDayClick)===null||oe===void 0||oe.call(r,s,t,Z):jae(n)?(re=a.onDayClick)===null||re===void 0||re.call(a,s,t,Z):Nae(n)?(ae=i.onDayClick)===null||ae===void 0||ae.call(i,s,t,Z):(J=n.onDayClick)===null||J===void 0||J.call(n,s,t,Z)},S=function(Z){var oe;m(s),(oe=n.onDayFocus)===null||oe===void 0||oe.call(n,s,t,Z)},C=function(Z){var oe;h(),(oe=n.onDayBlur)===null||oe===void 0||oe.call(n,s,t,Z)},E=function(Z){var oe;(oe=n.onDayMouseEnter)===null||oe===void 0||oe.call(n,s,t,Z)},P=function(Z){var oe;(oe=n.onDayMouseLeave)===null||oe===void 0||oe.call(n,s,t,Z)},M=function(Z){var oe;(oe=n.onDayPointerEnter)===null||oe===void 0||oe.call(n,s,t,Z)},I=function(Z){var oe;(oe=n.onDayPointerLeave)===null||oe===void 0||oe.call(n,s,t,Z)},D=function(Z){var oe;(oe=n.onDayTouchCancel)===null||oe===void 0||oe.call(n,s,t,Z)},F=function(Z){var oe;(oe=n.onDayTouchEnd)===null||oe===void 0||oe.call(n,s,t,Z)},q=function(Z){var oe;(oe=n.onDayTouchMove)===null||oe===void 0||oe.call(n,s,t,Z)},G=function(Z){var oe;(oe=n.onDayTouchStart)===null||oe===void 0||oe.call(n,s,t,Z)},V=function(Z){var oe;(oe=n.onDayKeyUp)===null||oe===void 0||oe.call(n,s,t,Z)},H=function(Z){var oe;switch(Z.key){case"ArrowLeft":Z.preventDefault(),Z.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":Z.preventDefault(),Z.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":Z.preventDefault(),Z.stopPropagation(),d();break;case"ArrowUp":Z.preventDefault(),Z.stopPropagation(),u();break;case"PageUp":Z.preventDefault(),Z.stopPropagation(),Z.shiftKey?g():p();break;case"PageDown":Z.preventDefault(),Z.stopPropagation(),Z.shiftKey?v():f();break;case"Home":Z.preventDefault(),Z.stopPropagation(),y();break;case"End":Z.preventDefault(),Z.stopPropagation(),b();break}(oe=n.onDayKeyDown)===null||oe===void 0||oe.call(n,s,t,Z)},K={onClick:w,onFocus:S,onBlur:C,onKeyDown:H,onKeyUp:V,onMouseEnter:E,onMouseLeave:P,onPointerEnter:M,onPointerLeave:I,onTouchCancel:D,onTouchEnd:F,onTouchMove:q,onTouchStart:G};return K}function Uen(){var s=up(),t=fqt(),n=Vtt(),r=Gtt(),a=JLe(s)?t.selected:jae(s)?n.selected:Nae(s)?r.selected:void 0;return a}function qen(s){return Object.values(IS).includes(s)}function Ven(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(qen(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Hen(s,t){var n=ec({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=ec(ec({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function Gen(s,t,n){var r,a,i,l=up(),o=Ktt(),c=Oen(s,t),d=$en(s,c),u=Uen(),h=!!(l.onDayClick||l.mode!=="default");_.useEffect(function(){var E;c.outside||o.focusedDay&&h&&hm(o.focusedDay,s)&&((E=n.current)===null||E===void 0||E.focus())},[o.focusedDay,s,n,h,c.outside]);var m=Ven(l,c).join(" "),p=Hen(l,c),f=!!(c.outside&&!l.showOutsideDays||c.hidden),g=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:men,v=e.jsx(g,{date:s,displayMonth:t,activeModifiers:c}),y={style:p,className:m,children:v,role:"gridcell"},b=o.focusTarget&&hm(o.focusTarget,s)&&!c.outside,w=o.focusedDay&&hm(o.focusedDay,s),S=ec(ec(ec({},y),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||b?0:-1,r)),d),C={isButton:h,isHidden:f,activeModifiers:c,selectedDays:u,buttonProps:S,divProps:y};return C}function Wen(s){var t=_.useRef(null),n=Gen(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(DEe,ec({name:"day",ref:t},n.buttonProps)):e.jsx("div",ec({},n.divProps))}function Ken(s){var t=s.number,n=s.dates,r=up(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),m=function(p){a(t,n,p)};return e.jsx(DEe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function Yen(s){var t,n,r=up(),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:Wen,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:Ken,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})},$As(h))})]})}function rvt(s,t,n){for(var r=n!=null&&n.ISOWeek?MRt(t):TPe(t,n),a=n!=null&&n.ISOWeek?SE(s):v1(s,n),i=fv(r,a),l=[],o=0;o<=i;o++)l.push(Uh(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?xJe(u):yJe(u,n),m=d.find(function(p){return p.weekNumber===h});return m?(m.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function Zen(s,t){var n=rvt(om(s),b_(s),t);if(t!=null&&t.useFixedWeeks){var r=qAs(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=bF(i,6-r),o=rvt(bF(i,1),l,t);n.push.apply(n,o)}}return n}function Xen(s){var t,n,r,a=up(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,p=a.ISOWeek,f=Zen(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),g=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:hen,v=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:Yen,y=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:cen;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(g,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:f.map(function(b){return e.jsx(v,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(y,{displayMonth:s.displayMonth})]})}function Qen(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Jen=Qen()?_.useLayoutEffect:_.useEffect,u9e=!1,etn=0;function avt(){return"react-day-picker-".concat(++etn)}function ttn(s){var t,n=s??(u9e?avt():null),r=_.useState(n),a=r[0],i=r[1];return Jen(function(){a===null&&i(avt())},[]),_.useEffect(function(){u9e===!1&&(u9e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function stn(s){var t,n,r=up(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=kae().displayMonths,d=ttn(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],m=l.month,p=s.displayIndex===0,f=s.displayIndex===c.length-1,g=!p&&!f;a==="rtl"&&(t=[p,f],f=t[0],p=t[1]),p&&(h.push(i.caption_start),m=ec(ec({},m),l.caption_start)),f&&(h.push(i.caption_end),m=ec(ec({},m),l.caption_end)),g&&(h.push(i.caption_between),m=ec(ec({},m),l.caption_between));var v=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:len;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(v,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Xen,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function ntn(s){var t=up(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function rtn(s){var t,n,r=s.initialProps,a=up(),i=Ktt(),l=kae(),o=_.useState(!1),c=o[0],d=o[1];_.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=ec(ec({},a.styles.root),a.style),m=Object.keys(r).filter(function(f){return f.startsWith("data-")}).reduce(function(f,g){var v;return ec(ec({},f),(v={},v[g]=r[g],v))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:ntn;return e.jsx("div",ec({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(p,{children:l.displayMonths.map(function(f,g){return e.jsx(stn,{displayIndex:g,displayMonth:f},g)})})}))}function atn(s){var t=s.children,n=EJs(s,["children"]);return e.jsx(KJs,{initialProps:n,children:e.jsx(ren,{children:e.jsx(zen,{initialProps:n,children:e.jsx(pen,{initialProps:n,children:e.jsx(gen,{initialProps:n,children:e.jsx(ken,{children:e.jsx(Fen,{children:t})})})})})})})}function itn(s){return e.jsx(atn,ec({},s,{children:e.jsx(rtn,{initialProps:s})}))}function Oj({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(itn,{showOutsideDays:n,className:Ct("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",caption_dropdowns:"flex gap-2 items-center justify-center",vhidden:"sr-only",nav:"space-x-1 flex items-center",nav_button:Ct(SH({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:Ct(SH({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",dropdown:"h-8 rounded-md border border-input bg-background px-2 py-1 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",...t},components:{IconLeft:({...a})=>e.jsx(Wc,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(yi,{className:"h-4 w-4"})},...r})}Oj.displayName="Calendar";var eIe="Popover",[xqt,Pwr]=uf(eIe,[CC]),Sae=CC(),[otn,ML]=xqt(eIe),gqt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=Sae(t),c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=Gg({prop:r,defaultProp:a??!1,onChange:i,caller:eIe});return e.jsx(Fre,{...o,children:e.jsx(otn,{scope:t,contentId:qg(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:_.useCallback(()=>m(p=>!p),[m]),hasCustomAnchor:d,onCustomAnchorAdd:_.useCallback(()=>u(!0),[]),onCustomAnchorRemove:_.useCallback(()=>u(!1),[]),modal:l,children:n})})};gqt.displayName=eIe;var yqt="PopoverAnchor",ltn=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ML(yqt,n),i=Sae(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return _.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(lW,{...i,...r,ref:t})});ltn.displayName=yqt;var vqt="PopoverTrigger",bqt=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ML(vqt,n),i=Sae(n),l=el(t,a.triggerRef),o=e.jsx(ci.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":kqt(a.open),...r,ref:l,onClick:wa(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(lW,{asChild:!0,...i,children:o})});bqt.displayName=vqt;var Ztt="PopoverPortal",[ctn,dtn]=xqt(Ztt,{forceMount:void 0}),_qt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=ML(Ztt,t);return e.jsx(ctn,{scope:t,forceMount:n,children:e.jsx(vg,{present:n||i.open,children:e.jsx(sW,{asChild:!0,container:a,children:r})})})};_qt.displayName=Ztt;var KH="PopoverContent",wqt=_.forwardRef((s,t)=>{const n=dtn(KH,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=ML(KH,s.__scopePopover);return e.jsx(vg,{present:r||i.open,children:i.modal?e.jsx(htn,{...a,ref:t}):e.jsx(mtn,{...a,ref:t})})});wqt.displayName=KH;var utn=OP("PopoverContent.RemoveScroll"),htn=_.forwardRef((s,t)=>{const n=ML(KH,s.__scopePopover),r=_.useRef(null),a=el(t,r),i=_.useRef(!1);return _.useEffect(()=>{const l=r.current;if(l)return BMe(l)},[]),e.jsx(Mre,{as:utn,allowPinchZoom:!0,children:e.jsx(jqt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:wa(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:wa(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:wa(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),mtn=_.forwardRef((s,t)=>{const n=ML(KH,s.__scopePopover),r=_.useRef(!1),a=_.useRef(!1);return e.jsx(jqt,{...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()}})}),jqt=_.forwardRef((s,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=s,m=ML(KH,n),p=Sae(n);return OMe(),e.jsx(Tre,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(pL,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:e.jsx(Ore,{"data-state":kqt(m.open),role:"dialog",id:m.contentId,...p,...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)"}})})})}),Nqt="PopoverClose",ptn=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=ML(Nqt,n);return e.jsx(ci.button,{type:"button",...r,ref:t,onClick:wa(s.onClick,()=>a.onOpenChange(!1))})});ptn.displayName=Nqt;var ftn="PopoverArrow",xtn=_.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=Sae(n);return e.jsx(zre,{...a,...r,ref:t})});xtn.displayName=ftn;function kqt(s){return s?"open":"closed"}var gtn=gqt,ytn=bqt,vtn=_qt,Sqt=wqt;const hd=gtn,md=ytn,nd=_.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(vtn,{children:e.jsx(Sqt,{ref:a,align:t,sideOffset:n,className:Ct("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})}));nd.displayName=Sqt.displayName;async function Fte(s){if(s instanceof Bre)try{const t=await s.context.text();try{const n=JSON.parse(t),r=(n==null?void 0:n.error)??(n==null?void 0:n.message);if(typeof r=="string"&&r.trim())return r}catch{if(t.trim())return t.trim()}}catch{}return s instanceof Error&&s.message?s.message:"Something went wrong. Please try again."}const btn=G9("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Ote=_.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Ct(btn({variant:t}),s),...n}));Ote.displayName="Alert";const _tn=_.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Ct("mb-1 font-medium leading-none tracking-tight",s),...t}));_tn.displayName="AlertTitle";const zte=_.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ct("text-sm [&_p]:leading-relaxed",s),...t}));zte.displayName="AlertDescription";function wtn({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=$t(),{user:c}=hs(),d=(c==null?void 0:c.id)??null,[u,h]=_.useState(a),[m,p]=_.useState([]),[f,g]=_.useState(null),[v,y]=_.useState("now"),[b,w]=_.useState(aft(hft(new Date),1)),[S,C]=_.useState("12"),[E,P]=_.useState("00"),[M,I]=_.useState("PM");_.useEffect(()=>{if(s){h(a),y("now"),p([]);const me=aft(hft(new Date),1);w(me);const he=me.getHours();C(String(he>12?he-12:he===0?12:he)),P("00"),I(he>=12?"PM":"AM")}},[s,a]);const D=()=>{if(!b)return null;let me=parseInt(S);const he=parseInt(E);return M==="PM"&&me!==12&&(me+=12),M==="AM"&&me===12&&(me=0),$Rt(BRt(b,me),he)},{data:F,isLoading:q}=rt({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:me}}=await U.auth.getUser();if(!me)return[];const{data:he,error:ge}=await U.from("social_accounts").select("*").eq("user_id",me.id).eq("is_active",!0).order("platform",{ascending:!0});if(ge)throw ge;return console.log("Fetched social accounts for posting:",he),he},enabled:s,staleTime:0}),G=mt({mutationFn:async({accountId:me,platform:he})=>{g(me);const{data:ge,error:Ee}=await U.functions.invoke("social-post",{body:{platform:he,accountId:me,imageUrl:n,caption:u}});if(Ee)throw new Error(await Fte(Ee));if(ge!=null&&ge.error)throw new Error(ge.error);return ge},onSuccess:me=>{const he=me.platform==="facebook"?"Facebook":me.platform==="instagram"?"Instagram":me.platform==="linkedin"?"LinkedIn":"Google Business";ne.success(`Posted to ${he}!`)},onError:me=>{ne.error(`Failed to post: ${me.message}`)},onSettled:()=>{g(null)}}),V=mt({mutationFn:async({accountId:me,platform:he,scheduledFor:ge})=>{const{data:{user:Ee}}=await U.auth.getUser();if(!Ee)throw new Error("Not authenticated");const{error:Ne}=await U.from("scheduled_posts").insert({user_id:Ee.id,social_account_id:me,platform:he,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:ge.toISOString(),status:"scheduled"});if(Ne)throw Ne;return{platform:he}},onSuccess:me=>{const he=me.platform==="facebook"?"Facebook":me.platform==="instagram"?"Instagram":"LinkedIn";ne.success(`Post scheduled for ${he}!`)},onError:me=>{ne.error(`Failed to schedule: ${me.message}`)}}),H=async()=>{if(m.length===0){ne.error("Please select at least one account");return}if(v==="schedule"){const me=D();if(!me||me<=new Date){ne.error("Please select a future date and time");return}for(const he of m){const ge=F==null?void 0:F.find(Ee=>Ee.id===he);ge&&await V.mutateAsync({accountId:he,platform:ge.platform,scheduledFor:me})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),ne.success(`${m.length} post(s) scheduled for ${Ys(me,"PPp")}`)}else for(const me of m){const he=F==null?void 0:F.find(ge=>ge.id===me);he&&await G.mutateAsync({accountId:me,platform:he.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),p([]),t(!1)},K=me=>{p(he=>he.includes(me)?he.filter(ge=>ge!==me):[...he,me])},Z=(F==null?void 0:F.filter(me=>me.platform==="facebook"))||[],oe=(F==null?void 0:F.filter(me=>me.platform==="instagram"))||[],re=(F==null?void 0:F.filter(me=>me.platform==="linkedin"))||[],ae=(F==null?void 0:F.filter(me=>me.platform==="google_business"))||[],J=((F==null?void 0:F.length)||0)>0,te=G.isPending||V.isPending,ce=Array.from({length:12},(me,he)=>String(he+1)),ve=["00","15","30","45"];return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create Social Post"}),e.jsx(_r,{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(ee,{htmlFor:"caption",children:"Caption"}),e.jsx(Ps,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:me=>h(me.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(ee,{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:()=>y("now"),className:Ct("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:()=>y("schedule"),className:Ct("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(Zr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),b?Ys(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{mode:"single",selected:b,onSelect:w,disabled:me=>mee.jsx(He,{value:me,children:me},me))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ls,{value:E,onValueChange:P,children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(cs,{})}),e.jsx(as,{children:ve.map(me=>e.jsx(He,{value:me,children:me},me))})]}),e.jsxs(ls,{value:M,onValueChange:me=>I(me),children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"AM",children:"AM"}),e.jsx(He,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Ys(D()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Post to"}),q&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(bt,{className:"h-6 w-6 animate-spin"})}),!q&&!J&&e.jsxs(Ote,{children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs(zte,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(or,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Gc,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),Z.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(of,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),Z.map(me=>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(za,{checked:m.includes(me.id),onCheckedChange:()=>K(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(of,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:me.page_name||me.platform_username}),f===me.id&&e.jsx(bt,{className:"h-4 w-4 animate-spin"})]},me.id))]}),oe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Fm,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),oe.map(me=>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(za,{checked:m.includes(me.id),onCheckedChange:()=>K(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Fm,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",me.platform_username]}),f===me.id&&e.jsx(bt,{className:"h-4 w-4 animate-spin"})]},me.id))]}),re.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(fg,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),re.map(me=>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(za,{checked:m.includes(me.id),onCheckedChange:()=>K(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(fg,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:me.platform_username}),f===me.id&&e.jsx(bt,{className:"h-4 w-4 animate-spin"})]},me.id))]}),ae.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ha,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ae.map(me=>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(za,{checked:m.includes(me.id),onCheckedChange:()=>K(me.id),disabled:f===me.id}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:me.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Ha,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:me.page_name||me.platform_username}),f===me.id&&e.jsx(bt,{className:"h-4 w-4 animate-spin"})]},me.id))]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:H,disabled:m.length===0||te,className:"gap-2",children:[te?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):v==="schedule"?e.jsx(ya,{className:"h-4 w-4"}):e.jsx(Fr,{className:"h-4 w-4"}),v==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function jtn(){const{user:s}=hs(),t=(s==null?void 0:s.id)??null,n=$t(),[r,a]=_.useState(void 0),[i,l]=_.useState("all"),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState(void 0),[p,f]=_.useState("12"),[g,v]=_.useState("00"),[y,b]=_.useState("PM"),{data:w=[],isLoading:S}=rt({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:ae,error:J}=await U.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(J)throw J;return ae}}),C=w.filter(ae=>{if(i!=="all"&&ae.status!==i)return!1;if(r&&ae.scheduled_for){const J=new Date(ae.scheduled_for);if(!hm(J,r))return!1}return!0}),E=w.filter(ae=>ae.scheduled_for).map(ae=>zf(new Date(ae.scheduled_for))),P=mt({mutationFn:async ae=>{const{error:J}=await U.from("scheduled_posts").update({caption:ae.caption,scheduled_for:ae.scheduled_for}).eq("id",ae.id);if(J)throw J},onSuccess:()=>{ne.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:ae=>{ne.error(`Failed to update: ${ae.message}`)}}),M=mt({mutationFn:async ae=>{const{error:J}=await U.from("scheduled_posts").update({status:"cancelled"}).eq("id",ae);if(J)throw J},onSuccess:()=>{ne.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ae=>{ne.error(`Failed to cancel: ${ae.message}`)}}),I=mt({mutationFn:async ae=>{const{error:J}=await U.from("scheduled_posts").delete().eq("id",ae);if(J)throw J},onSuccess:()=>{ne.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ae=>{ne.error(`Failed to delete: ${ae.message}`)}}),D=mt({mutationFn:async ae=>{const{data:J,error:te}=await U.functions.invoke("social-post",{body:{platform:ae.platform,accountId:ae.social_account_id,imageUrl:ae.image_url,caption:ae.caption}});if(te)throw new Error(await Fte(te));if(J!=null&&J.error)throw new Error(J.error);return await U.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:J.postId}).eq("id",ae.id),J},onSuccess:ae=>{const J=ae.platform==="facebook"?"Facebook":ae.platform==="instagram"?"Instagram":"LinkedIn";ne.success(`Posted to ${J}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ae=>{ne.error(`Failed to post: ${ae.message}`)}}),F=ae=>{if(c(ae),u(ae.caption||""),ae.scheduled_for){const J=new Date(ae.scheduled_for);m(J);const te=J.getHours();f(String(te>12?te-12:te===0?12:te)),v(String(J.getMinutes()).padStart(2,"0")),b(te>=12?"PM":"AM")}},q=()=>{if(!o||!h)return;let ae=parseInt(p);const J=parseInt(g);y==="PM"&&ae!==12&&(ae+=12),y==="AM"&&ae===12&&(ae=0);const te=$Rt(BRt(h,ae),J);P.mutate({id:o.id,caption:d,scheduled_for:te.toISOString()})},G=ae=>{switch(ae){case"facebook":return e.jsx(of,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Fm,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(fg,{className:"h-4 w-4 text-blue-700"});default:return null}},V=ae=>{switch(ae){case"scheduled":return e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(ze,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Xl,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Bd,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(ze,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Ho,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(ze,{variant:"outline",children:ae})}},H=Array.from({length:12},(ae,J)=>String(J+1)),K=["00","15","30","45"],Z=w.filter(ae=>ae.status==="scheduled").length,oe=w.filter(ae=>ae.status==="posted").length,re=w.filter(ae=>ae.status==="scheduled"&&ae.scheduled_for&&VAs(new Date(ae.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(be,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Z}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(be,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:re}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(be,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(be,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:w.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(be,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(gc,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Oj,{mode:"single",selected:r,onSelect:a,className:Ct("pointer-events-auto"),modifiers:{hasPost:E},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx(z,{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(F_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ae=>e.jsx(z,{variant:i===ae?"default":"outline",size:"sm",onClick:()=>l(ae),className:"capitalize",children:ae},ae))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!S&&C.length===0&&e.jsxs(be,{className:"p-8 text-center",children:[e.jsx(ya,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?`No posts scheduled for ${Ys(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:C.map(ae=>{var J,te;return e.jsx(be,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:ae.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Le,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[G(ae.platform),e.jsx("span",{className:"font-medium",children:((J=ae.social_accounts)==null?void 0:J.page_name)||((te=ae.social_accounts)==null?void 0:te.platform_username)||"Unknown"}),V(ae.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ae.status==="scheduled"&&e.jsxs(UN,{children:[e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>F(ae),children:e.jsx(Wa,{className:"h-4 w-4"})})}),e.jsx(Tx,{children:"Edit post"})]}),e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>D.mutate(ae),disabled:D.isPending,children:D.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"})})}),e.jsx(Tx,{children:"Post now"})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Cancel this scheduled post?"}),e.jsx(ql,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Keep"}),e.jsx(Ml,{onClick:()=>M.mutate(ae.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Ml,{onClick:()=>I.mutate(ae.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ae.status==="posted"||ae.status==="cancelled"||ae.status==="failed")&&e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete this post?"}),e.jsx(ql,{children:"This will permanently remove this post from your history."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>I.mutate(ae.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ae.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ae.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),ae.status==="posted"&&ae.posted_at?`Posted ${Ys(new Date(ae.posted_at),"PPp")}`:ae.scheduled_for?`Scheduled for ${Ys(new Date(ae.scheduled_for),"PPp")}`:"Not scheduled"]}),ae.status==="failed"&&ae.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ae.error_message]})]})]})},ae.id)})})]})]}),e.jsx(Is,{open:!!o,onOpenChange:ae=>!ae&&c(null),children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Edit Scheduled Post"}),e.jsx(_r,{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(ee,{children:"Caption"}),e.jsx(Ps,{value:d,onChange:ae=>u(ae.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(ee,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),h?Ys(h,"PPP"):"Pick a date"]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{mode:"single",selected:h,onSelect:m,disabled:ae=>aee.jsx(He,{value:ae,children:ae},ae))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ls,{value:g,onValueChange:v,children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(cs,{})}),e.jsx(as,{children:K.map(ae=>e.jsx(He,{value:ae,children:ae},ae))})]}),e.jsxs(ls,{value:y,onValueChange:ae=>b(ae),children:[e.jsx(rs,{className:"w-[70px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"AM",children:"AM"}),e.jsx(He,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs(z,{onClick:q,disabled:P.isPending,children:[P.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function uce(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 Cqt={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 uce=="function"&&uce;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var m=new Error("Cannot find module '"+d+"'");throw m.code="MODULE_NOT_FOUND",m}var p=a[d]={exports:{}};r[d][0].call(p.exports,function(f){var g=r[d][1][f];return l(g||f)},p,p.exports,n,r,a,i)}return a[d].exports}for(var o=typeof uce=="function"&&uce,c=0;c>2,p=(3&d)<<4|u>>4,f=1>6:64,g=2>4,u=(15&m)<<4|(p=o.indexOf(c.charAt(g++)))>>2,h=(3&p)<<6|(f=o.indexOf(c.charAt(g++))),b[v++]=d,p!==64&&(b[v++]=u),f!==64&&(b[v++]=h);return b}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,p,f){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=p,this.compressedContent=f}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var p=l,f=m+h;d^=-1;for(var g=m;g>>8^p[255&(d^u[g])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var p=l,f=m+h;d^=-1;for(var g=m;g>>8^p[255&(d^u.charCodeAt(g))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,m){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=m,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(m){h.push({data:m,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(p,f){var g,v="";for(g=0;g>>=8;return v}function l(p,f,g,v,y,b){var w,S,C=p.file,E=p.compression,P=b!==d.utf8encode,M=o.transformTo("string",b(C.name)),I=o.transformTo("string",d.utf8encode(C.name)),D=C.comment,F=o.transformTo("string",b(D)),q=o.transformTo("string",d.utf8encode(D)),G=I.length!==C.name.length,V=q.length!==D.length,H="",K="",Z="",oe=C.dir,re=C.date,ae={crc32:0,compressedSize:0,uncompressedSize:0};f&&!g||(ae.crc32=p.crc32,ae.compressedSize=p.compressedSize,ae.uncompressedSize=p.uncompressedSize);var J=0;f&&(J|=8),P||!G&&!V||(J|=2048);var te=0,ce=0;oe&&(te|=16),y==="UNIX"?(ce=798,te|=function(me,he){var ge=me;return me||(ge=he?16893:33204),(65535&ge)<<16}(C.unixPermissions,oe)):(ce=20,te|=function(me){return 63&(me||0)}(C.dosPermissions)),w=re.getUTCHours(),w<<=6,w|=re.getUTCMinutes(),w<<=5,w|=re.getUTCSeconds()/2,S=re.getUTCFullYear()-1980,S<<=4,S|=re.getUTCMonth()+1,S<<=5,S|=re.getUTCDate(),G&&(K=i(1,1)+i(u(M),4)+I,H+="up"+i(K.length,2)+K),V&&(Z=i(1,1)+i(u(F),4)+q,H+="uc"+i(Z.length,2)+Z);var ve="";return ve+=` \0`,ve+=i(J,2),ve+=E.magic,ve+=i(w,2),ve+=i(S,2),ve+=i(ae.crc32,4),ve+=i(ae.compressedSize,4),ve+=i(ae.uncompressedSize,4),ve+=i(M.length,2),ve+=i(H.length,2),{fileRecord:h.LOCAL_FILE_HEADER+ve+M+H,dirRecord:h.CENTRAL_FILE_HEADER+i(ce,2)+ve+i(F.length,2)+"\0\0\0\0"+i(te,4)+i(v,4)+M+H+F}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(p,f,g,v){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=f,this.zipPlatform=g,this.encodeFileName=v,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(p){var f=p.meta.percent||0,g=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,c.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:g?(f+100*(g-v-1))/g:100}}))},m.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var f=this.streamFiles&&!p.file.dir;if(f){var g=l(p,f,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(p){this.accumulate=!1;var f=this.streamFiles&&!p.file.dir,g=l(p,f,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),f)this.push({data:function(v){return h.DATA_DESCRIPTOR+i(v.crc32,4)+i(v.compressedSize,4)+i(v.uncompressedSize,4)}(p),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var p=this.bytesWritten,f=0;f=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(f,g){return new u.Promise(function(v,y){var b=[],w=f._internalType,S=f._outputType,C=f._mimeType;f.on("data",function(E,P){b.push(E),g&&g(P)}).on("error",function(E){b=[],y(E)}).on("end",function(){try{var E=function(P,M,I){switch(P){case"blob":return i.newBlob(i.transformTo("arraybuffer",M),I);case"base64":return c.encode(M);default:return i.transformTo(P,M)}}(S,function(P,M){var I,D=0,F=null,q=0;for(I=0;I"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(p){return l.nodebuffer?o.newBufferFrom(p,"utf-8"):function(f){var g,v,y,b,w,S=f.length,C=0;for(b=0;b>>6:(v<65536?g[w++]=224|v>>>12:(g[w++]=240|v>>>18,g[w++]=128|v>>>12&63),g[w++]=128|v>>>6&63),g[w++]=128|63&v);return g}(p)},a.utf8decode=function(p){return l.nodebuffer?i.transformTo("nodebuffer",p).toString("utf-8"):function(f){var g,v,y,b,w=f.length,S=new Array(2*w);for(g=v=0;g>10&1023,S[v++]=56320|1023&y)}return S.length!==v&&(S.subarray?S=S.subarray(0,v):S.length=v),i.applyFromCharCode(S)}(p=i.transformTo(l.uint8array?"uint8array":"array",p))},i.inherits(h,c),h.prototype.processChunk=function(p){var f=i.transformTo(l.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var g=f;(f=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),f.set(g,this.leftOver.length)}else f=this.leftOver.concat(f);this.leftOver=null}var v=function(b,w){var S;for((w=w||b.length)>b.length&&(w=b.length),S=w-1;0<=S&&(192&b[S])==128;)S--;return S<0||S===0?w:S+d[b[S]]>w?S:w}(f),y=f;v!==f.length&&(l.uint8array?(y=f.subarray(0,v),this.leftOver=f.subarray(v,f.length)):(y=f.slice(0,v),this.leftOver=f.slice(v,f.length))),this.push({data:a.utf8decode(y),meta:p.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(m,c),m.prototype.processChunk=function(p){this.push({data:a.utf8encode(p.data),meta:p.meta})},a.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(g){return g}function u(g,v){for(var y=0;y>8;this.dir=!!(16&this.externalFileAttributes),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var f,g,v,y=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4>>6:(p<65536?m[v++]=224|p>>>12:(m[v++]=240|p>>>18,m[v++]=128|p>>>12&63),m[v++]=128|p>>>6&63),m[v++]=128|63&p);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),p=0,f=m.length;p>10&1023,b[f++]=56320|1023&g)}return u(b,f)},a.utf8border=function(h,m){var p;for((m=m||h.length)>h.length&&(m=h.length),p=m-1;0<=p&&(192&h[p])==128;)p--;return p<0||p===0?m:p+c[h[p]]>m?p:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,p=0,f=-2,g=-1,v=4,y=2,b=8,w=9,S=286,C=30,E=19,P=2*S+1,M=15,I=3,D=258,F=D+I+1,q=42,G=113,V=1,H=2,K=3,Z=4;function oe(_e,Ae){return _e.msg=u[Ae],Ae}function re(_e){return(_e<<1)-(4<_e?9:0)}function ae(_e){for(var Ae=_e.length;0<=--Ae;)_e[Ae]=0}function J(_e){var Ae=_e.state,Se=Ae.pending;Se>_e.avail_out&&(Se=_e.avail_out),Se!==0&&(l.arraySet(_e.output,Ae.pending_buf,Ae.pending_out,Se,_e.next_out),_e.next_out+=Se,Ae.pending_out+=Se,_e.total_out+=Se,_e.avail_out-=Se,Ae.pending-=Se,Ae.pending===0&&(Ae.pending_out=0))}function te(_e,Ae){o._tr_flush_block(_e,0<=_e.block_start?_e.block_start:-1,_e.strstart-_e.block_start,Ae),_e.block_start=_e.strstart,J(_e.strm)}function ce(_e,Ae){_e.pending_buf[_e.pending++]=Ae}function ve(_e,Ae){_e.pending_buf[_e.pending++]=Ae>>>8&255,_e.pending_buf[_e.pending++]=255&Ae}function me(_e,Ae){var Se,We,qe=_e.max_chain_length,Be=_e.strstart,Ze=_e.prev_length,$e=_e.nice_match,Xe=_e.strstart>_e.w_size-F?_e.strstart-(_e.w_size-F):0,nt=_e.window,Ge=_e.w_mask,Je=_e.prev,ut=_e.strstart+D,lt=nt[Be+Ze-1],qt=nt[Be+Ze];_e.prev_length>=_e.good_match&&(qe>>=2),$e>_e.lookahead&&($e=_e.lookahead);do if(nt[(Se=Ae)+Ze]===qt&&nt[Se+Ze-1]===lt&&nt[Se]===nt[Be]&&nt[++Se]===nt[Be+1]){Be+=2,Se++;do;while(nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&nt[++Be]===nt[++Se]&&BeXe&&--qe!=0);return Ze<=_e.lookahead?Ze:_e.lookahead}function he(_e){var Ae,Se,We,qe,Be,Ze,$e,Xe,nt,Ge,Je=_e.w_size;do{if(qe=_e.window_size-_e.lookahead-_e.strstart,_e.strstart>=Je+(Je-F)){for(l.arraySet(_e.window,_e.window,Je,Je,0),_e.match_start-=Je,_e.strstart-=Je,_e.block_start-=Je,Ae=Se=_e.hash_size;We=_e.head[--Ae],_e.head[Ae]=Je<=We?We-Je:0,--Se;);for(Ae=Se=Je;We=_e.prev[--Ae],_e.prev[Ae]=Je<=We?We-Je:0,--Se;);qe+=Je}if(_e.strm.avail_in===0)break;if(Ze=_e.strm,$e=_e.window,Xe=_e.strstart+_e.lookahead,nt=qe,Ge=void 0,Ge=Ze.avail_in,nt=I)for(Be=_e.strstart-_e.insert,_e.ins_h=_e.window[Be],_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[Be+1])&_e.hash_mask;_e.insert&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[Be+I-1])&_e.hash_mask,_e.prev[Be&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=Be,Be++,_e.insert--,!(_e.lookahead+_e.insert=I&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Se=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart),Se!==0&&_e.strstart-Se<=_e.w_size-F&&(_e.match_length=me(_e,Se)),_e.match_length>=I)if(We=o._tr_tally(_e,_e.strstart-_e.match_start,_e.match_length-I),_e.lookahead-=_e.match_length,_e.match_length<=_e.max_lazy_match&&_e.lookahead>=I){for(_e.match_length--;_e.strstart++,_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Se=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart,--_e.match_length!=0;);_e.strstart++}else _e.strstart+=_e.match_length,_e.match_length=0,_e.ins_h=_e.window[_e.strstart],_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+1])&_e.hash_mask;else We=o._tr_tally(_e,0,_e.window[_e.strstart]),_e.lookahead--,_e.strstart++;if(We&&(te(_e,!1),_e.strm.avail_out===0))return V}return _e.insert=_e.strstart=I&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Se=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart),_e.prev_length=_e.match_length,_e.prev_match=_e.match_start,_e.match_length=I-1,Se!==0&&_e.prev_length<_e.max_lazy_match&&_e.strstart-Se<=_e.w_size-F&&(_e.match_length=me(_e,Se),_e.match_length<=5&&(_e.strategy===1||_e.match_length===I&&4096<_e.strstart-_e.match_start)&&(_e.match_length=I-1)),_e.prev_length>=I&&_e.match_length<=_e.prev_length){for(qe=_e.strstart+_e.lookahead-I,We=o._tr_tally(_e,_e.strstart-1-_e.prev_match,_e.prev_length-I),_e.lookahead-=_e.prev_length-1,_e.prev_length-=2;++_e.strstart<=qe&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Se=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart),--_e.prev_length!=0;);if(_e.match_available=0,_e.match_length=I-1,_e.strstart++,We&&(te(_e,!1),_e.strm.avail_out===0))return V}else if(_e.match_available){if((We=o._tr_tally(_e,0,_e.window[_e.strstart-1]))&&te(_e,!1),_e.strstart++,_e.lookahead--,_e.strm.avail_out===0)return V}else _e.match_available=1,_e.strstart++,_e.lookahead--}return _e.match_available&&(We=o._tr_tally(_e,0,_e.window[_e.strstart-1]),_e.match_available=0),_e.insert=_e.strstart_e.pending_buf_size-5&&(Se=_e.pending_buf_size-5);;){if(_e.lookahead<=1){if(he(_e),_e.lookahead===0&&Ae===h)return V;if(_e.lookahead===0)break}_e.strstart+=_e.lookahead,_e.lookahead=0;var We=_e.block_start+Se;if((_e.strstart===0||_e.strstart>=We)&&(_e.lookahead=_e.strstart-We,_e.strstart=We,te(_e,!1),_e.strm.avail_out===0)||_e.strstart-_e.block_start>=_e.w_size-F&&(te(_e,!1),_e.strm.avail_out===0))return V}return _e.insert=0,Ae===m?(te(_e,!0),_e.strm.avail_out===0?K:Z):(_e.strstart>_e.block_start&&(te(_e,!1),_e.strm.avail_out),V)}),new Ne(4,4,8,4,ge),new Ne(4,5,16,8,ge),new Ne(4,6,32,32,ge),new Ne(4,4,16,16,Ee),new Ne(8,16,32,32,Ee),new Ne(8,16,128,128,Ee),new Ne(8,32,128,256,Ee),new Ne(32,128,258,1024,Ee),new Ne(32,258,258,4096,Ee)],a.deflateInit=function(_e,Ae){return Ve(_e,Ae,b,15,8,0)},a.deflateInit2=Ve,a.deflateReset=ke,a.deflateResetKeep=Oe,a.deflateSetHeader=function(_e,Ae){return _e&&_e.state?_e.state.wrap!==2?f:(_e.state.gzhead=Ae,p):f},a.deflate=function(_e,Ae){var Se,We,qe,Be;if(!_e||!_e.state||5>8&255),ce(We,We.gzhead.time>>16&255),ce(We,We.gzhead.time>>24&255),ce(We,We.level===9?2:2<=We.strategy||We.level<2?4:0),ce(We,255&We.gzhead.os),We.gzhead.extra&&We.gzhead.extra.length&&(ce(We,255&We.gzhead.extra.length),ce(We,We.gzhead.extra.length>>8&255)),We.gzhead.hcrc&&(_e.adler=d(_e.adler,We.pending_buf,We.pending,0)),We.gzindex=0,We.status=69):(ce(We,0),ce(We,0),ce(We,0),ce(We,0),ce(We,0),ce(We,We.level===9?2:2<=We.strategy||We.level<2?4:0),ce(We,3),We.status=G);else{var Ze=b+(We.w_bits-8<<4)<<8;Ze|=(2<=We.strategy||We.level<2?0:We.level<6?1:We.level===6?2:3)<<6,We.strstart!==0&&(Ze|=32),Ze+=31-Ze%31,We.status=G,ve(We,Ze),We.strstart!==0&&(ve(We,_e.adler>>>16),ve(We,65535&_e.adler)),_e.adler=1}if(We.status===69)if(We.gzhead.extra){for(qe=We.pending;We.gzindex<(65535&We.gzhead.extra.length)&&(We.pending!==We.pending_buf_size||(We.gzhead.hcrc&&We.pending>qe&&(_e.adler=d(_e.adler,We.pending_buf,We.pending-qe,qe)),J(_e),qe=We.pending,We.pending!==We.pending_buf_size));)ce(We,255&We.gzhead.extra[We.gzindex]),We.gzindex++;We.gzhead.hcrc&&We.pending>qe&&(_e.adler=d(_e.adler,We.pending_buf,We.pending-qe,qe)),We.gzindex===We.gzhead.extra.length&&(We.gzindex=0,We.status=73)}else We.status=73;if(We.status===73)if(We.gzhead.name){qe=We.pending;do{if(We.pending===We.pending_buf_size&&(We.gzhead.hcrc&&We.pending>qe&&(_e.adler=d(_e.adler,We.pending_buf,We.pending-qe,qe)),J(_e),qe=We.pending,We.pending===We.pending_buf_size)){Be=1;break}Be=We.gzindexqe&&(_e.adler=d(_e.adler,We.pending_buf,We.pending-qe,qe)),Be===0&&(We.gzindex=0,We.status=91)}else We.status=91;if(We.status===91)if(We.gzhead.comment){qe=We.pending;do{if(We.pending===We.pending_buf_size&&(We.gzhead.hcrc&&We.pending>qe&&(_e.adler=d(_e.adler,We.pending_buf,We.pending-qe,qe)),J(_e),qe=We.pending,We.pending===We.pending_buf_size)){Be=1;break}Be=We.gzindexqe&&(_e.adler=d(_e.adler,We.pending_buf,We.pending-qe,qe)),Be===0&&(We.status=103)}else We.status=103;if(We.status===103&&(We.gzhead.hcrc?(We.pending+2>We.pending_buf_size&&J(_e),We.pending+2<=We.pending_buf_size&&(ce(We,255&_e.adler),ce(We,_e.adler>>8&255),_e.adler=0,We.status=G)):We.status=G),We.pending!==0){if(J(_e),_e.avail_out===0)return We.last_flush=-1,p}else if(_e.avail_in===0&&re(Ae)<=re(Se)&&Ae!==m)return oe(_e,-5);if(We.status===666&&_e.avail_in!==0)return oe(_e,-5);if(_e.avail_in!==0||We.lookahead!==0||Ae!==h&&We.status!==666){var $e=We.strategy===2?function(Xe,nt){for(var Ge;;){if(Xe.lookahead===0&&(he(Xe),Xe.lookahead===0)){if(nt===h)return V;break}if(Xe.match_length=0,Ge=o._tr_tally(Xe,0,Xe.window[Xe.strstart]),Xe.lookahead--,Xe.strstart++,Ge&&(te(Xe,!1),Xe.strm.avail_out===0))return V}return Xe.insert=0,nt===m?(te(Xe,!0),Xe.strm.avail_out===0?K:Z):Xe.last_lit&&(te(Xe,!1),Xe.strm.avail_out===0)?V:H}(We,Ae):We.strategy===3?function(Xe,nt){for(var Ge,Je,ut,lt,qt=Xe.window;;){if(Xe.lookahead<=D){if(he(Xe),Xe.lookahead<=D&&nt===h)return V;if(Xe.lookahead===0)break}if(Xe.match_length=0,Xe.lookahead>=I&&0Xe.lookahead&&(Xe.match_length=Xe.lookahead)}if(Xe.match_length>=I?(Ge=o._tr_tally(Xe,1,Xe.match_length-I),Xe.lookahead-=Xe.match_length,Xe.strstart+=Xe.match_length,Xe.match_length=0):(Ge=o._tr_tally(Xe,0,Xe.window[Xe.strstart]),Xe.lookahead--,Xe.strstart++),Ge&&(te(Xe,!1),Xe.strm.avail_out===0))return V}return Xe.insert=0,nt===m?(te(Xe,!0),Xe.strm.avail_out===0?K:Z):Xe.last_lit&&(te(Xe,!1),Xe.strm.avail_out===0)?V:H}(We,Ae):i[We.level].func(We,Ae);if($e!==K&&$e!==Z||(We.status=666),$e===V||$e===K)return _e.avail_out===0&&(We.last_flush=-1),p;if($e===H&&(Ae===1?o._tr_align(We):Ae!==5&&(o._tr_stored_block(We,0,0,!1),Ae===3&&(ae(We.head),We.lookahead===0&&(We.strstart=0,We.block_start=0,We.insert=0))),J(_e),_e.avail_out===0))return We.last_flush=-1,p}return Ae!==m?p:We.wrap<=0?1:(We.wrap===2?(ce(We,255&_e.adler),ce(We,_e.adler>>8&255),ce(We,_e.adler>>16&255),ce(We,_e.adler>>24&255),ce(We,255&_e.total_in),ce(We,_e.total_in>>8&255),ce(We,_e.total_in>>16&255),ce(We,_e.total_in>>24&255)):(ve(We,_e.adler>>>16),ve(We,65535&_e.adler)),J(_e),0=Se.w_size&&(Be===0&&(ae(Se.head),Se.strstart=0,Se.block_start=0,Se.insert=0),nt=new l.Buf8(Se.w_size),l.arraySet(nt,Ae,Ge-Se.w_size,Se.w_size,0),Ae=nt,Ge=Se.w_size),Ze=_e.avail_in,$e=_e.next_in,Xe=_e.input,_e.avail_in=Ge,_e.next_in=0,_e.input=Ae,he(Se);Se.lookahead>=I;){for(We=Se.strstart,qe=Se.lookahead-(I-1);Se.ins_h=(Se.ins_h<>>=I=M>>>24,w-=I,(I=M>>>16&255)===0)H[u++]=65535&M;else{if(!(16&I)){if(!(64&I)){M=S[(65535&M)+(b&(1<>>=I,w-=I),w<15&&(b+=V[c++]<>>=I=M>>>24,w-=I,!(16&(I=M>>>16&255))){if(!(64&I)){M=C[(65535&M)+(b&(1<>>=I,w-=I,(I=u-h)>3,b&=(1<<(w-=D<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)}function b(){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 w(q){var G;return q&&q.state?(G=q.state,q.total_in=q.total_out=G.total=0,q.msg="",G.wrap&&(q.adler=1&G.wrap),G.mode=f,G.last=0,G.havedict=0,G.dmax=32768,G.head=null,G.hold=0,G.bits=0,G.lencode=G.lendyn=new i.Buf32(g),G.distcode=G.distdyn=new i.Buf32(v),G.sane=1,G.back=-1,m):p}function S(q){var G;return q&&q.state?((G=q.state).wsize=0,G.whave=0,G.wnext=0,w(q)):p}function C(q,G){var V,H;return q&&q.state?(H=q.state,G<0?(V=0,G=-G):(V=1+(G>>4),G<48&&(G&=15)),G&&(G<8||15=Z.wsize?(i.arraySet(Z.window,G,V-Z.wsize,Z.wsize,0),Z.wnext=0,Z.whave=Z.wsize):(H<(K=Z.wsize-Z.wnext)&&(K=H),i.arraySet(Z.window,G,V-H,K,Z.wnext),(H-=K)?(i.arraySet(Z.window,G,V-H,H,0),Z.wnext=H,Z.whave=Z.wsize):(Z.wnext+=K,Z.wnext===Z.wsize&&(Z.wnext=0),Z.whave>>8&255,V.check=o(V.check,Be,2,0),te=J=0,V.mode=2;break}if(V.flags=0,V.head&&(V.head.done=!1),!(1&V.wrap)||(((255&J)<<8)+(J>>8))%31){q.msg="incorrect header check",V.mode=30;break}if((15&J)!=8){q.msg="unknown compression method",V.mode=30;break}if(te-=4,_e=8+(15&(J>>>=4)),V.wbits===0)V.wbits=_e;else if(_e>V.wbits){q.msg="invalid window size",V.mode=30;break}V.dmax=1<<_e,q.adler=V.check=1,V.mode=512&J?10:12,te=J=0;break;case 2:for(;te<16;){if(re===0)break e;re--,J+=H[Z++]<>8&1),512&V.flags&&(Be[0]=255&J,Be[1]=J>>>8&255,V.check=o(V.check,Be,2,0)),te=J=0,V.mode=3;case 3:for(;te<32;){if(re===0)break e;re--,J+=H[Z++]<>>8&255,Be[2]=J>>>16&255,Be[3]=J>>>24&255,V.check=o(V.check,Be,4,0)),te=J=0,V.mode=4;case 4:for(;te<16;){if(re===0)break e;re--,J+=H[Z++]<>8),512&V.flags&&(Be[0]=255&J,Be[1]=J>>>8&255,V.check=o(V.check,Be,2,0)),te=J=0,V.mode=5;case 5:if(1024&V.flags){for(;te<16;){if(re===0)break e;re--,J+=H[Z++]<>>8&255,V.check=o(V.check,Be,2,0)),te=J=0}else V.head&&(V.head.extra=null);V.mode=6;case 6:if(1024&V.flags&&(re<(me=V.length)&&(me=re),me&&(V.head&&(_e=V.head.extra_len-V.length,V.head.extra||(V.head.extra=new Array(V.head.extra_len)),i.arraySet(V.head.extra,H,Z,me,_e)),512&V.flags&&(V.check=o(V.check,H,me,Z)),re-=me,Z+=me,V.length-=me),V.length))break e;V.length=0,V.mode=7;case 7:if(2048&V.flags){if(re===0)break e;for(me=0;_e=H[Z+me++],V.head&&_e&&V.length<65536&&(V.head.name+=String.fromCharCode(_e)),_e&&me>9&1,V.head.done=!0),q.adler=V.check=0,V.mode=12;break;case 10:for(;te<32;){if(re===0)break e;re--,J+=H[Z++]<>>=7&te,te-=7&te,V.mode=27;break}for(;te<3;){if(re===0)break e;re--,J+=H[Z++]<>>=1)){case 0:V.mode=14;break;case 1:if(D(V),V.mode=20,G!==6)break;J>>>=2,te-=2;break e;case 2:V.mode=17;break;case 3:q.msg="invalid block type",V.mode=30}J>>>=2,te-=2;break;case 14:for(J>>>=7&te,te-=7&te;te<32;){if(re===0)break e;re--,J+=H[Z++]<>>16^65535)){q.msg="invalid stored block lengths",V.mode=30;break}if(V.length=65535&J,te=J=0,V.mode=15,G===6)break e;case 15:V.mode=16;case 16:if(me=V.length){if(re>>=5,te-=5,V.ndist=1+(31&J),J>>>=5,te-=5,V.ncode=4+(15&J),J>>>=4,te-=4,286>>=3,te-=3}for(;V.have<19;)V.lens[Ze[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,Se={bits:V.lenbits},Ae=d(0,V.lens,0,19,V.lencode,0,V.work,Se),V.lenbits=Se.bits,Ae){q.msg="invalid code lengths set",V.mode=30;break}V.have=0,V.mode=19;case 19:for(;V.have>>16&255,Pe=65535&qe,!((Ee=qe>>>24)<=te);){if(re===0)break e;re--,J+=H[Z++]<>>=Ee,te-=Ee,V.lens[V.have++]=Pe;else{if(Pe===16){for(We=Ee+2;te>>=Ee,te-=Ee,V.have===0){q.msg="invalid bit length repeat",V.mode=30;break}_e=V.lens[V.have-1],me=3+(3&J),J>>>=2,te-=2}else if(Pe===17){for(We=Ee+3;te>>=Ee)),J>>>=3,te-=3}else{for(We=Ee+7;te>>=Ee)),J>>>=7,te-=7}if(V.have+me>V.nlen+V.ndist){q.msg="invalid bit length repeat",V.mode=30;break}for(;me--;)V.lens[V.have++]=_e}}if(V.mode===30)break;if(V.lens[256]===0){q.msg="invalid code -- missing end-of-block",V.mode=30;break}if(V.lenbits=9,Se={bits:V.lenbits},Ae=d(u,V.lens,0,V.nlen,V.lencode,0,V.work,Se),V.lenbits=Se.bits,Ae){q.msg="invalid literal/lengths set",V.mode=30;break}if(V.distbits=6,V.distcode=V.distdyn,Se={bits:V.distbits},Ae=d(h,V.lens,V.nlen,V.ndist,V.distcode,0,V.work,Se),V.distbits=Se.bits,Ae){q.msg="invalid distances set",V.mode=30;break}if(V.mode=20,G===6)break e;case 20:V.mode=21;case 21:if(6<=re&&258<=ae){q.next_out=oe,q.avail_out=ae,q.next_in=Z,q.avail_in=re,V.hold=J,V.bits=te,c(q,ve),oe=q.next_out,K=q.output,ae=q.avail_out,Z=q.next_in,H=q.input,re=q.avail_in,J=V.hold,te=V.bits,V.mode===12&&(V.back=-1);break}for(V.back=0;Ne=(qe=V.lencode[J&(1<>>16&255,Pe=65535&qe,!((Ee=qe>>>24)<=te);){if(re===0)break e;re--,J+=H[Z++]<>Oe)])>>>16&255,Pe=65535&qe,!(Oe+(Ee=qe>>>24)<=te);){if(re===0)break e;re--,J+=H[Z++]<>>=Oe,te-=Oe,V.back+=Oe}if(J>>>=Ee,te-=Ee,V.back+=Ee,V.length=Pe,Ne===0){V.mode=26;break}if(32&Ne){V.back=-1,V.mode=12;break}if(64&Ne){q.msg="invalid literal/length code",V.mode=30;break}V.extra=15&Ne,V.mode=22;case 22:if(V.extra){for(We=V.extra;te>>=V.extra,te-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=23;case 23:for(;Ne=(qe=V.distcode[J&(1<>>16&255,Pe=65535&qe,!((Ee=qe>>>24)<=te);){if(re===0)break e;re--,J+=H[Z++]<>Oe)])>>>16&255,Pe=65535&qe,!(Oe+(Ee=qe>>>24)<=te);){if(re===0)break e;re--,J+=H[Z++]<>>=Oe,te-=Oe,V.back+=Oe}if(J>>>=Ee,te-=Ee,V.back+=Ee,64&Ne){q.msg="invalid distance code",V.mode=30;break}V.offset=Pe,V.extra=15&Ne,V.mode=24;case 24:if(V.extra){for(We=V.extra;te>>=V.extra,te-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){q.msg="invalid distance too far back",V.mode=30;break}V.mode=25;case 25:if(ae===0)break e;if(me=ve-ae,V.offset>me){if((me=V.offset-me)>V.whave&&V.sane){q.msg="invalid distance too far back",V.mode=30;break}he=me>V.wnext?(me-=V.wnext,V.wsize-me):V.wnext-me,me>V.length&&(me=V.length),ge=V.window}else ge=K,he=oe-V.offset,me=V.length;for(aeP?(I=he[ge+v[G]],te[ce+v[G]]):(I=96,0),b=1<>oe)+(w-=b)]=M<<24|I<<16|D|0,w!==0;);for(b=1<>=1;if(b!==0?(J&=b-1,J+=b):J=0,G++,--ve[q]==0){if(q===H)break;q=h[m+v[G]]}if(K>>7)]}function ce(qe,Be){qe.pending_buf[qe.pending++]=255&Be,qe.pending_buf[qe.pending++]=Be>>>8&255}function ve(qe,Be,Ze){qe.bi_valid>y-Ze?(qe.bi_buf|=Be<>y-qe.bi_valid,qe.bi_valid+=Ze-y):(qe.bi_buf|=Be<>>=1,Ze<<=1,0<--Be;);return Ze>>>1}function ge(qe,Be,Ze){var $e,Xe,nt=new Array(v+1),Ge=0;for($e=1;$e<=v;$e++)nt[$e]=Ge=Ge+Ze[$e-1]<<1;for(Xe=0;Xe<=Be;Xe++){var Je=qe[2*Xe+1];Je!==0&&(qe[2*Xe]=he(nt[Je]++,Je))}}function Ee(qe){var Be;for(Be=0;Be>1;1<=Ze;Ze--)Oe(qe,nt,Ze);for(Xe=ut;Ze=qe.heap[1],qe.heap[1]=qe.heap[qe.heap_len--],Oe(qe,nt,1),$e=qe.heap[1],qe.heap[--qe.heap_max]=Ze,qe.heap[--qe.heap_max]=$e,nt[2*Xe]=nt[2*Ze]+nt[2*$e],qe.depth[Xe]=(qe.depth[Ze]>=qe.depth[$e]?qe.depth[Ze]:qe.depth[$e])+1,nt[2*Ze+1]=nt[2*$e+1]=Xe,qe.heap[1]=Xe++,Oe(qe,nt,1),2<=qe.heap_len;);qe.heap[--qe.heap_max]=qe.heap[1],function(qt,zt){var Zt,ms,Dt,It,qs,wt,Us=zt.dyn_tree,Es=zt.max_code,kn=zt.stat_desc.static_tree,Sn=zt.stat_desc.has_stree,bn=zt.stat_desc.extra_bits,cr=zt.stat_desc.extra_base,Fs=zt.stat_desc.max_length,cn=0;for(It=0;It<=v;It++)qt.bl_count[It]=0;for(Us[2*qt.heap[qt.heap_max]+1]=0,Zt=qt.heap_max+1;Zt>=7;Xe>>=1)if(1<&&Je.dyn_ltree[2*ut]!==0)return l;if(Je.dyn_ltree[18]!==0||Je.dyn_ltree[20]!==0||Je.dyn_ltree[26]!==0)return o;for(ut=32;ut>>3,(nt=qe.static_len+3+7>>>3)<=Xe&&(Xe=nt)):Xe=nt=Ze+5,Ze+4<=Xe&&Be!==-1?We(qe,Be,Ze,$e):qe.strategy===4||nt===Xe?(ve(qe,2+($e?1:0),3),ke(qe,F,q)):(ve(qe,4+($e?1:0),3),function(Je,ut,lt,qt){var zt;for(ve(Je,ut-257,5),ve(Je,lt-1,5),ve(Je,qt-4,4),zt=0;zt>>8&255,qe.pending_buf[qe.d_buf+2*qe.last_lit+1]=255&Be,qe.pending_buf[qe.l_buf+qe.last_lit]=255&Ze,qe.last_lit++,Be===0?qe.dyn_ltree[2*Ze]++:(qe.matches++,Be--,qe.dyn_ltree[2*(V[Ze]+h+1)]++,qe.dyn_dtree[2*te(Be)]++),qe.last_lit===qe.lit_bufsize-1},a._tr_align=function(qe){ve(qe,2,3),me(qe,w,F),function(Be){Be.bi_valid===16?(ce(Be,Be.bi_buf),Be.bi_buf=0,Be.bi_valid=0):8<=Be.bi_valid&&(Be.pending_buf[Be.pending++]=255&Be.bi_buf,Be.bi_buf>>=8,Be.bi_valid-=8)}(qe)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,p={},f=!1,g=l.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(l);v=v&&v.setTimeout?v:l,c={}.toString.call(l.process)==="[object process]"?function(S){process.nextTick(function(){b(S)})}:function(){if(l.postMessage&&!l.importScripts){var S=!0,C=l.onmessage;return l.onmessage=function(){S=!1},l.postMessage("","*"),l.onmessage=C,S}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",w,!1):l.attachEvent("onmessage",w),function(S){l.postMessage(h+S,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){b(S.data)},function(S){u.port2.postMessage(S)}):g&&"onreadystatechange"in g.createElement("script")?(d=g.documentElement,function(S){var C=g.createElement("script");C.onreadystatechange=function(){b(S),C.onreadystatechange=null,d.removeChild(C),C=null},d.appendChild(C)}):function(S){setTimeout(b,0,S)},v.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var C=new Array(arguments.length-1),E=0;E"u"?i===void 0?this:i:self)}).call(this,typeof Pp<"u"?Pp:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Cqt);var Ntn=Cqt.exports;const Aqt=kd(Ntn);function h9e(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 Eqt=({embedded:s=!1,onCompose:t}={})=>{hs();const[n,r]=_.useState(null),[a,i]=_.useState(null),[l,o]=_.useState("all"),[c,d]=_.useState(new Set),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState("images"),[v,y]=_.useState(null),{data:b=[],isLoading:w}=rt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:J,error:te}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(te)throw te;return J}}),{data:S=[]}=rt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:J,error:te}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(te)throw te;return J}}),{data:C=[]}=rt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:J,error:te}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(te)throw te;return J}}),{data:E=[]}=rt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:J,error:te}=await U.from("social_accounts").select("id, platform").eq("is_active",!0);if(te)throw te;return J||[]}}),P=E.length>0,M=_.useMemo(()=>l==="all"?null:C.find(J=>J.month===l)||null,[l,C]),I=_.useMemo(()=>[...new Set(b.map(te=>te.month))].sort((te,ce)=>ce.localeCompare(te)),[b]);_.useEffect(()=>{I.length>0&&l==="all"&&o(I[0])},[I,l]);const D=J=>{try{const te=_Je(J,"yyyy-MM",new Date);return Ys(te,"MMMM yyyy")}catch{return J}},F=_.useMemo(()=>l==="all"?b:b.filter(J=>J.month===l),[l,b]),q=_.useMemo(()=>{var J;return l==="all"?null:((J=S.find(te=>te.month===l))==null?void 0:J.canva_link)||null},[l,S]),G=async J=>{try{await navigator.clipboard.writeText(J),ne.success("Caption copied to clipboard!")}catch{ne.error("Failed to copy caption")}},V=async(J,te)=>{try{const ve=await(await fetch(J)).blob(),me=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),he=navigator.canShare&&navigator.canShare({files:[new File([ve],"test.jpg",{type:"image/jpeg"})]});if(me&&he){const ge=new File([ve],`social-swag-${te}.jpg`,{type:"image/jpeg"});await navigator.share({files:[ge],title:"Social Swag Image"}),ne.success("Image ready to save!")}else{const ge=window.URL.createObjectURL(ve),Ee=document.createElement("a");Ee.href=ge,Ee.download=`social-swag-${te}.jpg`,document.body.appendChild(Ee),Ee.click(),document.body.removeChild(Ee),window.URL.revokeObjectURL(ge),ne.success("Image downloaded!")}}catch(ce){ce.name!=="AbortError"&&ne.error("Failed to download image")}},H=J=>{d(te=>{const ce=new Set(te);return ce.has(J)?ce.delete(J):ce.add(J),ce})},K=()=>{d(new Set(F.map(J=>J.id)))},Z=()=>{d(new Set),h(!1)},oe=async()=>{const J=F.filter(te=>c.has(te.id));if(J.length===0){ne.error("No images selected");return}p(!0),ne.info(`Preparing ${J.length} images for download...`);try{const te=new Aqt,ce=[...J].sort((Ee,Ne)=>Ee.sort_order-Ne.sort_order);for(let Ee=0;Ee{u?H(J.id):r(J)},ae=({children:J})=>s?e.jsx(e.Fragment,{children:J}):e.jsx($s,{title:"Social Swag 2.0",children:J});return e.jsx(ae,{children:e.jsxs("div",{className:"space-y-8",children:[!s&&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(nc,{className:"h-3 w-3 mr-1"}),b.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(Qr,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(Jr,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Wt,{value:"gallery",className:"gap-2",children:[e.jsx(nc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Wt,{value:"scheduled",className:"gap-2",children:[e.jsx(gc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Kt,{value:"gallery",className:"space-y-6",children:[P?e.jsx(be,{className:"border rounded-xl",children:e.jsx(Le,{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(z,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(or,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(be,{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(Le,{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(of,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Fm,{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(z,{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(or,{to:"/social-connections",children:[e.jsx(Oc,{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:I.map(J=>e.jsx("button",{onClick:()=>o(J),className:Ct("px-4 py-2 rounded-full text-sm font-medium transition-all",l===J?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:D(J)},J))}),l!=="all"&&(q?e.jsxs("a",{href:q,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 ",D(l)," 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 ",D(l)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{g("images"),Z()},className:Ct("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(nc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{g("reels"),Z()},className:Ct("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",f==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Yh,{className:"h-4 w-4"}),"Reels"]})]}),f==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:u?e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:K,className:"gap-2",children:["Select All (",F.length,")"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:Z,className:"gap-2",children:[e.jsx(er,{className:"h-4 w-4"}),"Cancel"]}),c.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(z,{size:"sm",onClick:oe,disabled:m,className:"gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),m?"Downloading...":`Download ${c.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(z,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Select Images"]})})]}),w&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!w&&f==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:F.map(J=>{const te=c.has(J.id);return e.jsx(be,{className:Ct("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",u&&te&&"ring-2 ring-primary ring-offset-2"),onClick:()=>re(J),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:h9e(J.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"}),J.post_date&&!u&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:Ys(new Date(J.post_date+"T00:00:00"),"MMM d")})}),u&&e.jsx("div",{className:Ct("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",te?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:te&&e.jsx(Wr,{className:"h-4 w-4"})}),!u&&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"})})]})},J.id)})}),F.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nc,{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."})]})]}),!w&&f==="reels"&&e.jsx(e.Fragment,{children:M?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(be,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>i(M),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:h9e(M.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(Yh,{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(Yh,{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(Is,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(Ls,{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-muted",children:e.jsx("div",{className:"aspect-[4/5]",children:e.jsx("img",{src:h9e(n.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(ya,{className:"h-4 w-4"}),Ys(new Date(n.created_at),"MMMM d, yyyy")]}),n.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(ya,{className:"h-3.5 w-3.5"}),"Post on ",Ys(new Date(n.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:n.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(z,{onClick:()=>{if(t){t({mediaUrl:n.image_url,mediaType:"image",caption:n.caption,swagItemId:n.id}),r(null);return}y({imageUrl:n.image_url,imageId:n.id,caption:n.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(Fr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(z,{variant:"outline",onClick:()=>G(n.caption),className:"flex-1 gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(z,{variant:"outline",onClick:()=>V(n.image_url,n.id),className:"flex-1 gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(Is,{open:!!a,onOpenChange:()=>i(null),children:e.jsx(Ls,{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:a&&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:a.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(Yh,{className:"h-4 w-4"}),"Monthly Reel"]}),a.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:a.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[a.caption&&e.jsxs(z,{onClick:()=>G(a.caption||""),className:"flex-1 gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),"Copy Caption"]}),a.canva_link&&e.jsxs(z,{variant:"outline",onClick:()=>window.open(a.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(mr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(wtn,{open:!!v,onOpenChange:J=>!J&&y(null),imageUrl:(v==null?void 0:v.imageUrl)||"",imageId:(v==null?void 0:v.imageId)||"",defaultCaption:(v==null?void 0:v.caption)||"",swagItemId:v==null?void 0:v.imageId})]}),e.jsx(Kt,{value:"scheduled",children:e.jsx(jtn,{})})]})]})})};async function NP(s){var r,a;const{data:t,error:n}=await U.functions.invoke("canva-mail-studio",{body:s});if(n){let i=n.message;try{const l=await((a=(r=n.context)==null?void 0:r.json)==null?void 0:a.call(r));l!=null&&l.error&&(i=l.error)}catch{}throw new Error(i)}if(t!=null&&t.error)throw new Error(t.error);return t}function Xtt(){return rt({queryKey:["canva-agent-status"],queryFn:()=>NP({action:"status"})})}class m9e extends Error{constructor(){super("Canva connection was cancelled — nothing was connected.")}}function Tqt(){const s=$t();return mt({mutationFn:async t=>{const n=window.open("about:blank","canva-connect","width=620,height=760");let r=!1;try{r=!!(await NP({action:"status"})).connected}catch{}let a,i;try{({authUrl:a,state:i}=await NP({action:"start",...t!=null&&t.client?{client:t.client}:{}}))}catch(l){throw n==null||n.close(),l}if(localStorage.setItem("canva_oauth_state",i),localStorage.setItem("canva_oauth_mode","agent"),localStorage.removeItem("canva_code_verifier"),!n){window.location.assign(a);return}n.location.href=a,await new Promise((l,o)=>{const c=h=>{if(h.origin!==window.location.origin)return;const m=h.data;(m==null?void 0:m.type)==="canva-oauth-success"&&(u(),l()),(m==null?void 0:m.type)==="canva-oauth-error"&&(u(),o(new Error(m.message||"Canva connection failed")))},d=setInterval(async()=>{if(n.closed){u();try{(await NP({action:"status"})).connected&&!r?l():o(new m9e)}catch{o(new m9e)}}},800),u=()=>{clearInterval(d),window.removeEventListener("message",c)};window.addEventListener("message",c)})},onSuccess:()=>ne.success("Canva connected"),onSettled:()=>s.invalidateQueries({queryKey:["canva-agent-status"]}),onError:t=>t instanceof m9e?ne.info(t.message):ne.error(t.message)})}function Mqt(){const s=$t();return mt({mutationFn:()=>NP({action:"disconnect"}),onSuccess:()=>{ne.success("Canva disconnected"),s.invalidateQueries({queryKey:["canva-agent-status"]}),s.removeQueries({queryKey:["canva-agent-designs"]})},onError:t=>ne.error(t.message)})}function ktn(s,t){return TLt({queryKey:["canva-agent-designs",t],enabled:s,initialPageParam:null,queryFn:({pageParam:n})=>NP({action:"list_designs",query:t,continuation:n}),getNextPageParam:n=>n.continuation})}function Stn(s){return rt({queryKey:["canva-agent-design",s],enabled:!!s,queryFn:()=>NP({action:"get_design",design_id:s})})}function Ctn(){const s=$t();return mt({mutationFn:t=>NP({action:"import_design",design_id:t.designId,workflow:t.workflow,format:t.format,pages:t.pages,width:t.width,height:t.height}),onSuccess:()=>s.invalidateQueries({queryKey:["canva-imports"]}),onError:t=>ne.error(t.message)})}const Atn={postcard:"https://www.canva.com/create/postcards/",letter:"https://www.canva.com/create/letterheads/",library:"https://www.canva.com/",image:"https://www.canva.com/",social:"https://www.canva.com/create/social-media-graphics/"};function Pqt({open:s,onOpenChange:t,mode:n="postcard",workflow:r="mail_studio",exportSize:a,onImported:i}){var F,q,G,V,H,K,Z,oe;const l=Xtt(),o=Tqt(),c=Mqt(),d=!!((F=l.data)!=null&&F.connected),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(null),[v,y]=_.useState([]),b=ktn(s&&d,m),w=Stn(f),S=Ctn(),[C,E]=_.useState("jpg");_.useEffect(()=>{s||(g(null),y([]))},[s]),_.useEffect(()=>{const re=setTimeout(()=>p(u.trim()),400);return()=>clearTimeout(re)},[u]),_.useEffect(()=>{w.data&&y(w.data.pages.length===1?[w.data.pages[0].index]:[])},[w.data]);const P=re=>{if(n==="postcard"||n==="image"){y([re]);return}y(ae=>ae.includes(re)?ae.filter(J=>J!==re):[...ae,re].sort((J,te)=>J-te))},M=async()=>{if(!f||!v.length)return;const re=await S.mutateAsync({designId:f,workflow:r,pages:v,format:n==="letter"?"pdf":n==="social"?C:"png",...n!=="letter"&&a?a:{}}).catch(()=>null);re&&(await i(re),t(!1))},I=(((q=b.data)==null?void 0:q.pages)||[]).flatMap(re=>re.designs),D=((G=w.data)==null?void 0:G.pages.length)||0;return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-h-[88vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:f?((V=w.data)==null?void 0:V.design.title)||"Choose pages":"Import from Canva"}),e.jsx(_r,{children:d?f?n==="postcard"?"Choose the page to print on the front. thanks.io prints the back from your message, so a back page isn’t used.":n==="image"?"Choose the page to place in your design.":n==="letter"?"Choose the pages to mail. They’re saved as one PDF.":n==="social"?"Choose the pages to add to your media library. Nothing is posted until you schedule or publish it yourself.":"Choose the pages to save to LevelUp.":"Search your designs. Edit in Canva, then come back and refresh to bring in the latest version.":"Connect your own Canva account once, then bring your designs into LevelUp."})]}),l.isLoading&&e.jsx(bt,{className:"mx-auto h-5 w-5 animate-spin"}),l.error&&e.jsx("p",{className:"text-sm text-destructive",children:l.error.message}),l.data&&!l.data.configured&&e.jsx("p",{className:"rounded border border-dashed p-6 text-center text-sm text-muted-foreground",children:"The Canva connection isn't set up for LevelUp yet. Ask an admin to finish the Canva app setup."}),((H=l.data)==null?void 0:H.configured)&&!d&&e.jsxs("div",{className:"space-y-3 py-4 text-center",children:[l.data.needs_reconnect&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Canva connection needs to be renewed."}),e.jsxs(z,{onClick:()=>o.mutate({}),disabled:o.isPending,children:[o.isPending?e.jsx(bt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Oc,{className:"mr-1 h-4 w-4"}),"Connect Canva"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A Canva window opens so you can approve read-only access to your designs."})]}),d&&!f&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Connected",(K=l.data)!=null&&K.display_name?` as ${l.data.display_name}`:""]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>b.refetch(),disabled:b.isFetching,children:[e.jsx(Gi,{className:`mr-1 h-3.5 w-3.5 ${b.isFetching?"animate-spin":""}`}),"Refresh"]}),e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:Atn[n],target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-1 h-3.5 w-3.5"}),"New design in Canva"]})}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(rE,{className:"mr-1 h-3.5 w-3.5"}),"Disconnect"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:u,onChange:re=>h(re.target.value),placeholder:"Search your Canva designs",className:"pl-8"})]}),b.isLoading&&e.jsx(bt,{className:"mx-auto h-5 w-5 animate-spin"}),b.error&&e.jsx("p",{className:"text-sm text-destructive",children:b.error.message}),!b.isLoading&&!b.error&&I.length===0&&e.jsx("p",{className:"rounded border border-dashed p-6 text-center text-sm text-muted-foreground",children:m?"No designs match that search.":"No designs found in your Canva account yet."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:I.map(re=>e.jsxs("div",{className:"overflow-hidden rounded-lg border bg-card",children:[e.jsx("button",{type:"button",onClick:()=>g(re.id),className:"block w-full text-left transition hover:opacity-90",children:re.thumbnail?e.jsx("img",{src:re.thumbnail,alt:re.title,className:"h-28 w-full object-cover"}):e.jsx("div",{className:"h-28 w-full bg-muted"})}),e.jsxs("div",{className:"flex items-center justify-between gap-1 p-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-xs font-medium",children:re.title}),re.page_count&&re.page_count>1&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[re.page_count," pages"]})]}),re.edit_url&&e.jsx("a",{href:re.edit_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-primary",title:"Edit in Canva",children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]})]},re.id))}),b.hasNextPage&&e.jsxs(z,{variant:"outline",size:"sm",className:"mx-auto flex",onClick:()=>b.fetchNextPage(),disabled:b.isFetchingNextPage,children:[b.isFetchingNextPage&&e.jsx(bt,{className:"mr-1 h-4 w-4 animate-spin"}),"Load more"]})]}),d&&f&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>g(null),children:[e.jsx(ka,{className:"mr-1 h-4 w-4"}),"All designs"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>w.refetch(),disabled:w.isFetching,children:[e.jsx(Gi,{className:`mr-1 h-3.5 w-3.5 ${w.isFetching?"animate-spin":""}`}),"Refresh"]}),((Z=w.data)==null?void 0:Z.design.edit_url)&&e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:w.data.design.edit_url,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-1 h-3.5 w-3.5"}),"Edit in Canva"]})})]})]}),w.isLoading&&e.jsx(bt,{className:"mx-auto h-5 w-5 animate-spin"}),w.error&&e.jsx("p",{className:"text-sm text-destructive",children:w.error.message}),n==="postcard"&&D>1&&e.jsxs("p",{className:"flex items-start gap-1.5 rounded-md bg-muted p-2 text-xs text-muted-foreground",children:[e.jsx(nl,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"This design has ",D," pages. Only the page you choose is printed on the front."]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:(((oe=w.data)==null?void 0:oe.pages)||[]).map(re=>{const ae=v.includes(re.index);return e.jsxs("button",{type:"button",onClick:()=>P(re.index),"aria-pressed":ae,className:`relative overflow-hidden rounded-lg border-2 text-left transition ${ae?"border-primary shadow-md":"border-border hover:border-primary/50"}`,children:[re.thumbnail?e.jsx("img",{src:re.thumbnail,alt:`Page ${re.index}`,className:"h-28 w-full bg-muted object-contain"}):e.jsxs("div",{className:"flex h-28 w-full items-center justify-center bg-muted text-xs text-muted-foreground",children:["Page ",re.index]}),e.jsxs("div",{className:"flex items-center justify-between p-1.5 text-xs",children:[e.jsxs("span",{children:["Page ",re.index]}),ae&&e.jsxs(ze,{className:"h-5 gap-0.5 px-1.5 text-[10px]",children:[e.jsx(Wr,{className:"h-3 w-3"}),n==="postcard"?"Front":"Selected"]})]})]},re.index)})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t pt-3",children:[n==="social"&&e.jsx("div",{className:"flex items-center gap-1 text-xs",children:["jpg","png"].map(re=>e.jsx(z,{type:"button",size:"sm",variant:C===re?"default":"outline",className:"h-7 px-2",onClick:()=>E(re),children:re.toUpperCase()},re))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n==="social"?`${C.toUpperCase()}, up to 8 MB per image${C==="png"?" (Instagram needs JPG)":" — works on every platform"}.`:n==="letter"?"Saved as an 8.5×11 PDF.":a?`Exported at ${a.width}×${a.height} px.`:"Exported as full-quality PNG."," A permanent copy is saved in LevelUp."]}),e.jsx(z,{onClick:M,disabled:!v.length||S.isPending,children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-1 h-4 w-4 animate-spin"}),"Bringing it over…"]}):n==="postcard"?"Use as front":n==="image"?"Use this page":`Bring in ${v.length||""} page${v.length===1?"":"s"}`})]})]})]})})}const ivt={facebook:{id:"facebook",label:"Facebook Page",icon:of,dot:"bg-blue-500",chip:"bg-blue-500/10 text-blue-600 border-blue-500/20",captionLimit:63206,supportsVideo:!0,requiresMedia:!1},instagram:{id:"instagram",label:"Instagram",icon:Fm,dot:"bg-pink-500",chip:"bg-pink-500/10 text-pink-600 border-pink-500/20",captionLimit:2200,supportsVideo:!0,requiresMedia:!0},linkedin:{id:"linkedin",label:"LinkedIn",icon:fg,dot:"bg-sky-600",chip:"bg-sky-600/10 text-sky-700 border-sky-600/20",captionLimit:3e3,supportsVideo:!1,requiresMedia:!1},google_business:{id:"google_business",label:"Google Business",icon:Ha,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},rC=s=>ivt[s]??ivt.facebook,Etn=[{label:"Morning · 8:00 AM",hour:8,minute:0},{label:"Lunch · 12:00 PM",hour:12,minute:0},{label:"Afternoon · 3:00 PM",hour:15,minute:0},{label:"Evening · 7:00 PM",hour:19,minute:0}],ovt="agent-uploads",Ttn="social-studio",Mtn=200*1024*1024,lvt=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function Ptn({onSelect:s}){const{user:t}=hs(),n=_.useRef(null),[r,a]=_.useState(!1),[i,l]=_.useState(!1),o=$t(),{data:c=[]}=rt({queryKey:["studio-uploads",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:f,error:g}=await U.from("social_media_assets").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(60);if(g)throw g;return f??[]}}),{data:d=[]}=rt({queryKey:["studio-swag"],queryFn:async()=>{const{data:f,error:g}=await U.from("social_swag_2").select("id, image_url, caption, month").order("month",{ascending:!1}).order("sort_order").limit(120);if(g)throw g;return f??[]}}),{data:u=[]}=Aet(),h=u.length?u:t!=null&&t.id?[t.id]:[],{data:m=[]}=rt({queryKey:["studio-listings",h],enabled:h.length>0,queryFn:async()=>{const{data:f,error:g}=await U.from("listings").select("id, agent_id, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, listing_photos(photo_url, sort_order, is_primary)").in("agent_id",h).order("created_at",{ascending:!1}).limit(80);if(g)throw g;const v=f??[],y=Array.from(new Set(v.map(S=>S.agent_id).filter(S=>S&&S!==(t==null?void 0:t.id))));if(!y.length)return v;const{data:b}=await U.from("profiles").select("id, name").in("id",y),w=new Map((b??[]).map(S=>[S.id,S.name]));return v.map(S=>({...S,agent_name:w.get(S.agent_id)||null}))}}),p=async f=>{if(!(t!=null&&t.id))return;if(f.size>Mtn){ne.error("That file is over 200MB. Please pick a smaller one.");return}const g=f.type.startsWith("video/");a(!0);try{const v=f.name.split(".").pop()||(g?"mp4":"jpg"),y=`${Ttn}/${t.id}/${crypto.randomUUID()}.${v}`,{error:b}=await U.storage.from(ovt).upload(y,f,{cacheControl:"3600",upsert:!1,contentType:f.type});if(b)throw b;const{data:w}=U.storage.from(ovt).getPublicUrl(y),S=w.publicUrl;await U.from("social_media_assets").insert({user_id:t.id,storage_path:y,public_url:S,media_type:g?"video":"image",file_name:f.name,file_size:f.size}),s({mediaUrl:S,mediaType:g?"video":"image",source:"upload"}),ne.success("Media uploaded")}catch(v){console.error(v),ne.error("Upload failed. Please try again.")}finally{a(!1),n.current&&(n.current.value="")}};return e.jsxs(Qr,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(Jr,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Wt,{value:"upload",className:"gap-2",children:[e.jsx(Ra,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Wt,{value:"swag",className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Wt,{value:"listings",className:"gap-2",children:[e.jsx(sa,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Kt,{value:"upload",className:"space-y-4",children:[e.jsx("input",{ref:n,type:"file",accept:"image/*,video/*",className:"hidden",onChange:f=>{var g;return((g=f.target.files)==null?void 0:g[0])&&p(f.target.files[0])}}),e.jsx(be,{className:"border-dashed border-2",children:e.jsxs(Le,{className:"p-6 flex flex-col items-center text-center gap-3",children:[e.jsx(nc,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Upload a photo or video"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"JPG, PNG or MP4 up to 200MB"})]}),e.jsxs(z,{onClick:()=>{var f;return(f=n.current)==null?void 0:f.click()},disabled:r,className:"gap-2",children:[r?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4"}),r?"Uploading…":"Choose file"]}),e.jsxs(z,{variant:"outline",onClick:()=>l(!0),className:"gap-2",children:[e.jsx(yc,{className:"h-4 w-4"}),"Import from Canva"]}),e.jsx(Pqt,{open:i,onOpenChange:l,mode:"social",workflow:"social_studio",onImported:f=>{o.invalidateQueries({queryKey:["studio-uploads",t==null?void 0:t.id]});const g=f.files[0];g!=null&&g.preview_url&&s({mediaUrl:g.preview_url,mediaType:"image",source:"upload"}),ne.success(f.files.length>1?`${f.files.length} Canva pages added to your media library`:"Canva design added to your media library")}})]})}),c.length>0&&e.jsx(Ki,{className:"h-56",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:c.map(f=>e.jsxs("button",{type:"button",onClick:()=>s({mediaUrl:f.public_url,mediaType:f.media_type,source:"upload"}),className:"relative overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:[f.media_type==="video"?e.jsx("video",{src:f.public_url,className:"h-24 w-full object-cover"}):e.jsx("img",{src:f.public_url,alt:f.file_name??"",loading:"lazy",className:"h-24 w-full object-cover"}),f.media_type==="video"&&e.jsx(ze,{className:"absolute bottom-1 left-1 text-[10px]",children:"Video"})]},f.id))})})]}),e.jsx(Kt,{value:"swag",children:e.jsx(Ki,{className:"h-72",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:d.map(f=>e.jsx("button",{type:"button",onClick:()=>s({mediaUrl:f.image_url,mediaType:"image",caption:f.caption??"",source:"swag",sourceRef:f.id}),className:"overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:e.jsx("img",{src:f.image_url,alt:"",loading:"lazy",className:"h-24 w-full object-cover"})},f.id))})})}),e.jsx(Kt,{value:"listings",children:e.jsx(Ki,{className:"h-72",children:e.jsxs("div",{className:"space-y-3 pr-3",children:[m.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"There aren't any listings to post yet."}),m.map(f=>{const g=[...f.listing_photos??[]].sort((y,b)=>Number(b.is_primary)-Number(y.is_primary)||y.sort_order-b.sort_order),v=[`${f.property_address??""}`.trim(),`${f.city}, ${f.state}`,lvt(f.price),[f.bedrooms?`${f.bedrooms} bed`:null,f.bathrooms?`${f.bathrooms} bath`:null,f.square_footage?`${f.square_footage.toLocaleString()} sq ft`:null].filter(Boolean).join(" · "),"DM me for a private tour."].filter(Boolean).join(` `);return e.jsx(be,{children:e.jsxs(Le,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:f.property_address||`${f.city}, ${f.state}`}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[lvt(f.price),f.agent_name?` · ${f.agent_name}`:""]})]}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:String(f.status).replace(/_/g," ")})]}),g.length>0?e.jsx("div",{className:"grid grid-cols-4 gap-2",children:g.slice(0,8).map((y,b)=>e.jsx("button",{type:"button",onClick:()=>s({mediaUrl:y.photo_url,mediaType:"image",caption:v,source:"listing",sourceRef:f.id}),className:"overflow-hidden rounded-md border hover:ring-2 hover:ring-primary transition",children:e.jsx("img",{src:y.photo_url,alt:"",loading:"lazy",className:"h-16 w-full object-cover"})},b))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No photos on this listing yet."})]})},f.id)})]})})})]})}function Ltn({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=rC(s),o=l.icon,c=s==="instagram",d=a?i==="video"?e.jsx("video",{src:a,className:c?"w-full aspect-square object-cover":"w-full max-h-80 object-cover",controls:!0,playsInline:!0}):e.jsx("img",{src:a,alt:"Post preview",loading:"lazy",className:c?"w-full aspect-square object-cover":"w-full max-h-80 object-cover"}):null;return e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 border-b",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(xi,{src:n??void 0,alt:t}),e.jsx(Na,{children:t.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:t}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.label," · just now"]})]}),e.jsx(o,{className:"h-4 w-4 text-muted-foreground"})]}),c?e.jsxs(e.Fragment,{children:[d,e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-4 text-muted-foreground",children:[e.jsx(Fo,{className:"h-5 w-5"}),e.jsx(Bu,{className:"h-5 w-5"}),e.jsx(Fr,{className:"h-5 w-5"})]}),e.jsxs("p",{className:"text-sm whitespace-pre-wrap break-words",children:[e.jsx("span",{className:"font-semibold mr-1",children:t}),r]})]})]}):e.jsxs(e.Fragment,{children:[r&&e.jsx("p",{className:"p-3 text-sm whitespace-pre-wrap break-words",children:r}),d,e.jsxs("div",{className:"flex items-center gap-5 p-3 text-muted-foreground border-t",children:[e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Ug,{className:"h-4 w-4"})," Like"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Bu,{className:"h-4 w-4"})," Comment"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(hJ,{className:"h-4 w-4"})," Share"]})]})]})]})}function Qtt(){const{user:s}=hs();return rt({queryKey:["studio-accounts",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await U.from("social_accounts").select("id, platform, platform_username, page_name, profile_picture_url, is_active").eq("user_id",s.id).eq("is_active",!0).order("platform");if(n)throw n;return t??[]}})}function Itn(s){const{user:t}=hs();return rt({queryKey:["studio-posts",t==null?void 0:t.id,"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let n=U.from("social_posts").select("*, social_post_targets(*)").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(500);const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function Lqt(){const s=$t();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const Dtn="America/New_York",Iqt="levelup.calendar.timezone";function P7(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}),!0}catch{return!1}}function Rtn(){try{const s=localStorage.getItem(Iqt);if(P7(s))return s}catch{}return null}let nCe=Rtn();function UE(){return nCe||Cae()}function cvt(s){nCe=P7(s)?s:Cae();try{localStorage.setItem(Iqt,nCe)}catch{}return nCe}function Cae(){const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return P7(s)?s:Dtn}function kP(s,t=new Date){try{const n=new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"short"}).formatToParts(t).find(r=>r.type==="timeZoneName");return(n==null?void 0:n.value)||""}catch{return""}}function p9e(s,t=new Date){try{return new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"2-digit"}).format(t)}catch{return""}}const Dqt=[{value:"America/New_York",label:"Eastern — New York"},{value:"America/Detroit",label:"Eastern — Detroit"},{value:"America/Indiana/Indianapolis",label:"Eastern — Indianapolis"},{value:"America/Chicago",label:"Central — Chicago"},{value:"America/Denver",label:"Mountain — Denver"},{value:"America/Phoenix",label:"Mountain (no DST) — Phoenix"},{value:"America/Los_Angeles",label:"Pacific — Los Angeles"},{value:"America/Anchorage",label:"Alaska — Anchorage"},{value:"Pacific/Honolulu",label:"Hawaii — Honolulu"},{value:"America/Toronto",label:"Eastern — Toronto"},{value:"America/Vancouver",label:"Pacific — Vancouver"},{value:"America/Puerto_Rico",label:"Atlantic — Puerto Rico"}];function Ftn(){var r;let s=[];try{s=((r=Intl.supportedValuesOf)==null?void 0:r.call(Intl,"timeZone"))||[]}catch{s=[]}const t=Dqt.map(a=>a.value),n=s.filter(a=>!t.includes(a));return[...t,...n]}function Otn(s,t){const n=(s||"").split("@")[0].replace(/[^a-z0-9]+/gi,"-").toLowerCase(),r=(t||"").slice(0,6);return`${n||"agent"}-${r}`.replace(/^-+|-+$/g,"")||`agent-${Date.now()}`}function MW(){const{user:s}=hs(),t=$t(),n=rt({queryKey:["calendar-timezone",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:i,error:l}=await U.from("agent_booking_settings").select("timezone").eq("user_id",s.id).maybeSingle();if(l)throw l;return(i==null?void 0:i.timezone)||null}});_.useEffect(()=>{n.data&&P7(n.data)&&cvt(n.data)},[n.data]);const r=P7(n.data)?n.data:UE()||Cae(),a=mt({mutationFn:async i=>{if(!P7(i))throw new Error("That timezone isn't recognized");const{data:l,error:o}=await U.from("agent_booking_settings").update({timezone:i}).eq("user_id",s.id).select("id");if(o)throw o;if(!l||l.length===0){const{error:c}=await U.from("agent_booking_settings").insert({user_id:s.id,slug:Otn(s.email,s.id),timezone:i,is_active:!1});if(c)throw c}return cvt(i),i},onSuccess:i=>{t.setQueryData(["calendar-timezone",s==null?void 0:s.id],i),t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["my-calendar"]}),ne.success("Calendar timezone updated")},onError:i=>ne.error(i.message||"Could not update timezone")});return{timezone:r,isLoading:n.isLoading,update:a}}function Rqt({open:s,onOpenChange:t}){const{timezone:n,update:r}=MW(),[a,i]=_.useState(n),[l,o]=_.useState("");_.useEffect(()=>{s&&(i(n),o(""))},[s,n]);const c=Cae(),d=_.useMemo(()=>{const h=l.trim().toLowerCase();return h?Ftn().filter(m=>m.toLowerCase().includes(h.replace(/\s+/g,"_"))).slice(0,40):[]},[l]),u=()=>{r.mutate(a,{onSuccess:()=>t(!1)})};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(K2,{className:"h-4 w-4 text-primary"}),"Calendar settings"]}),e.jsx(_r,{children:"Pick the timezone your calendar, appointments and bookings display in."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border bg-muted/40 px-4 py-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Currently showing"}),e.jsxs("p",{className:"text-sm font-medium mt-0.5",children:[a.replace(/_/g," ")," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",p9e(a)," ",kP(a)]})]})]}),c!==a&&e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"w-full justify-start gap-2",onClick:()=>i(c),children:[e.jsx(Ha,{className:"h-4 w-4"}),"Use my device timezone (",c.replace(/_/g," "),")"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Common timezones"}),e.jsx("div",{className:"grid gap-1.5",children:Dqt.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h.value),className:Ct("flex items-center justify-between rounded-lg border px-3 py-2 text-left text-sm transition-colors",a===h.value?"border-primary bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.label}),e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:p9e(h.value)})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"tz-search",className:"text-sm font-medium",children:"Search all timezones"}),e.jsx(pe,{id:"tz-search",value:l,onChange:h=>o(h.target.value),placeholder:"e.g. Denver, London, Sao Paulo"}),d.length>0&&e.jsx("div",{className:"max-h-52 overflow-y-auto rounded-lg border divide-y",children:d.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h),className:Ct("flex w-full items-center justify-between px-3 py-2 text-left text-sm transition-colors",a===h?"bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.replace(/_/g," ")}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p9e(h)})]},h))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(z,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:u,disabled:r.isPending||a===n,children:[r.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save timezone"]})]})]})})}const j4=s=>String(s).padStart(2,"0");function Aae(s){return P7(s)?s:UE()}function Jtt(s,t){const n=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),r={};for(const a of n.formatToParts(s))a.type!=="literal"&&(r[a.type]=Number(a.value));return r.hour===24&&(r.hour=0),r}function dvt(s,t){const n=Jtt(s,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-s.getTime()}function REe(s,t){const n=Aae(t),[r,a="00:00"]=s.split("T"),[i,l,o]=r.split("-").map(Number),[c,d]=a.split(":").map(Number),u=Date.UTC(i,(l||1)-1,o||1,c||0,d||0,0);let h=new Date(u-dvt(new Date(u),n));return h=new Date(u-dvt(h,n)),h}function Fqt(s,t){const n=Aae(t),r=typeof s=="string"?new Date(s):s,a=Jtt(r,n);return`${a.year}-${j4(a.month)}-${j4(a.day)}T${j4(a.hour)}:${j4(a.minute)}`}function ztn(s,t){const n=Aae(t),r=typeof s=="string"?new Date(s):s,a=Jtt(r,n);return`${a.year}-${a.month-1}-${a.day}`}function Oqt(s,t,n){const r=typeof s=="string"?new Date(s):s;return new Intl.DateTimeFormat("en-US",{timeZone:Aae(t),...n}).format(r)}function zqt(s,t){return Oqt(s,t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function Btn(s,t){return Oqt(s,t,{hour:"numeric",minute:"2-digit"})}function $tn(s,t,n,r){const a=Aae(n),i=r&&r.includes("T")?r.split("T")[0]:Fqt(new Date,a).split("T")[0];let l=`${i}T${j4(s)}:${j4(t)}`;if(REe(l,a).getTime()<=Date.now()){const[o,c,d]=i.split("-").map(Number),u=new Date(Date.UTC(o,c-1,d+1));l=`${u.getUTCFullYear()}-${j4(u.getUTCMonth()+1)}-${j4(u.getUTCDate())}T${j4(s)}:${j4(t)}`}return l}const hce=s=>s.page_name||s.platform_username||rC(s.platform).label;function Utn({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=hs(),{data:i=[],isLoading:l}=Qtt(),{timezone:o}=MW(),[c,d]=_.useState(!1),u=he=>Fqt(he,o),[h,m]=_.useState(""),[p,f]=_.useState(null),[g,v]=_.useState("text"),[y,b]=_.useState("manual"),[w,S]=_.useState([]),[C,E]=_.useState({}),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[F,q]=_.useState(""),[G,V]=_.useState(null);_.useEffect(()=>{s&&(s.mediaUrl&&(f(s.mediaUrl),v(s.mediaType??"image")),s.caption!==void 0&&m(s.caption),s.source&&b(s.source),s.scheduledFor&&(D(!0),q(u(s.scheduledFor))))},[s]),_.useEffect(()=>{var ge;if(!t)return;m(t.caption??""),f(((ge=t.media_urls)==null?void 0:ge[0])??null),v(t.media_type),b(t.source??"manual"),S(t.social_post_targets.map(Ee=>Ee.social_account_id));const he={};t.social_post_targets.forEach(Ee=>{Ee.caption_override&&(he[Ee.social_account_id]=Ee.caption_override)}),E(he),M(Object.keys(he).length>0),t.scheduled_for&&(D(!0),q(u(new Date(t.scheduled_for))))},[t]);const H=_.useMemo(()=>i.filter(he=>w.includes(he.id)),[i,w]),K=he=>{var ge;return P&&((ge=C[he])!=null&&ge.trim())?C[he]:h},Z=_.useMemo(()=>{const he=[];return H.forEach(ge=>{const Ee=rC(ge.platform),Ne=K(ge.id);Ee.requiresMedia&&!p&&he.push(`${Ee.label} requires a photo or video.`),!Ee.supportsVideo&&g==="video"&&he.push(`${Ee.label} can't publish video from LevelUp yet.`),ge.platform==="instagram"&&g==="image"&&/\.png(\?|$)/i.test(p??"")&&he.push("Instagram only accepts JPG images — pick a JPG version."),Ne.length>Ee.captionLimit&&he.push(`${Ee.label} caption is over the ${Ee.captionLimit.toLocaleString()} character limit.`)}),Array.from(new Set(he))},[H,p,g,h,C,P]),oe=()=>{m(""),f(null),v("text"),b("manual"),S([]),E({}),M(!1),D(!1),q("")},re=he=>{f(he.mediaUrl),v(he.mediaType),b(he.source),he.caption&&!h.trim()&&m(he.caption)},ae=he=>S(ge=>ge.includes(he)?ge.filter(Ee=>Ee!==he):[...ge,he]),J=async he=>{if(a!=null&&a.id){if(he!=="draft"&&w.length===0){ne.error("Choose at least one account to post to.");return}if(he!=="draft"&&!h.trim()&&!p){ne.error("Add a caption or media before publishing.");return}if(he==="schedule"&&!F){ne.error("Pick a date and time to schedule.");return}if(he!=="draft"&&Z.length>0){ne.error(Z[0]);return}V(he);try{const ge={user_id:a.id,caption:h.trim()||null,media_type:g,media_urls:p?[p]:[],source:y,status:he==="draft"?"draft":he==="schedule"?"scheduled":"publishing",scheduled_for:he==="schedule"?REe(F,o).toISOString():null,timezone:o};let Ee=(t==null?void 0:t.id)??null;if(Ee){const{error:Ne}=await U.from("social_posts").update(ge).eq("id",Ee);if(Ne)throw Ne;await U.from("social_post_targets").delete().eq("post_id",Ee)}else{const{data:Ne,error:Pe}=await U.from("social_posts").insert(ge).select("id").single();if(Pe)throw Pe;Ee=Ne.id}if(w.length>0){const Ne=H.map(Oe=>{var ke;return{post_id:Ee,user_id:a.id,social_account_id:Oe.id,platform:Oe.platform,caption_override:P&&((ke=C[Oe.id])!=null&&ke.trim())?C[Oe.id].trim():null,status:"pending"}}),{error:Pe}=await U.from("social_post_targets").insert(Ne);if(Pe)throw Pe}if(he==="now"){const{data:Ne,error:Pe}=await U.functions.invoke("social-publish-post",{body:{post_id:Ee}});if(Pe)throw Pe;const Oe=Ne==null?void 0:Ne.status;Oe==="failed"?ne.error("Publishing failed. Check the Queue tab for details."):Oe==="partial"?ne.warning("Some accounts failed. Check the Queue tab to retry."):ne.success("Posted to your accounts.")}else ne.success(he==="draft"?"Draft saved":"Post scheduled");t||oe(),n==null||n()}catch(ge){console.error(ge),ne.error((ge==null?void 0:ge.message)??"Something went wrong saving your post.")}finally{V(null)}}},te=(he,ge)=>{D(!0),q($tn(he,ge,o,F))},ce=kP(o),ve=Cae(),me=ve!==o;return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_380px]",children:[e.jsxs("div",{className:"space-y-6",children:[t&&e.jsx(Ote,{children:e.jsxs(zte,{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:"Editing a saved post."}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:r,className:"gap-1",children:[e.jsx(er,{className:"h-4 w-4"})," Cancel"]})]})}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"1. Choose your media"})}),e.jsxs(Le,{className:"space-y-4",children:[p&&e.jsxs("div",{className:"relative w-full max-w-xs overflow-hidden rounded-lg border",children:[g==="video"?e.jsx("video",{src:p,className:"w-full",controls:!0,playsInline:!0}):e.jsx("img",{src:p,alt:"Selected media",className:"w-full object-cover"}),e.jsx(z,{variant:"secondary",size:"icon",className:"absolute top-2 right-2 h-8 w-8",onClick:()=>{f(null),v("text")},children:e.jsx(Cn,{className:"h-4 w-4"})})]}),e.jsx(Ptn,{onSelect:re})]})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"2. Write your caption"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(Ps,{value:h,onChange:he=>m(he.target.value),rows:6,placeholder:"What do you want to share with your audience?"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.length," characters"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{htmlFor:"per-platform",className:"text-xs",children:"Customize per platform"}),e.jsx(mn,{id:"per-platform",checked:P,onCheckedChange:M})]})]}),P&&H.length>0&&e.jsxs(Qr,{defaultValue:H[0].id,className:"pt-2",children:[e.jsx(Jr,{className:"flex-wrap h-auto",children:H.map(he=>e.jsx(Wt,{value:he.id,className:"text-xs",children:hce(he)},he.id))}),H.map(he=>e.jsx(Kt,{value:he.id,className:"pt-3",children:e.jsx(Ps,{rows:5,value:C[he.id]??"",placeholder:`Leave blank to use the main caption for ${rC(he.platform).label}`,onChange:ge=>E(Ee=>({...Ee,[he.id]:ge.target.value}))})},he.id))]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"3. Pick your accounts"})}),e.jsxs(Le,{className:"space-y-3",children:[l&&e.jsx(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),!l&&i.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No connected accounts yet. Connect Facebook, Instagram, LinkedIn or Google Business in Social settings."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:i.map(he=>{const ge=rC(he.platform),Ee=ge.icon,Ne=w.includes(he.id);return e.jsxs("button",{type:"button",onClick:()=>ae(he.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${Ne?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(xi,{src:he.profile_picture_url??void 0}),e.jsx(Na,{children:hce(he).slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:hce(he)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"h-3 w-3"})," ",ge.label]})]}),Ne&&e.jsx(Wr,{className:"h-4 w-4 text-primary"})]},he.id)})})]})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"4. Publish or schedule"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"schedule-toggle",children:"Schedule for later"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Otherwise it goes out right away."})]}),e.jsx(mn,{id:"schedule-toggle",checked:I,onCheckedChange:D})]}),I&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{type:"datetime-local",value:F,onChange:he=>q(he.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(K2,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Times are in ",e.jsx("span",{className:"font-medium text-foreground",children:o.replace(/_/g," ")}),ce?` (${ce})`:""]}),e.jsx("button",{type:"button",className:"underline underline-offset-2 hover:text-foreground",onClick:()=>d(!0),children:"Change"})]}),F&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Goes out ",e.jsx("span",{className:"font-medium text-foreground",children:zqt(REe(F,o),o)})]}),me&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Your device is set to ",ve.replace(/_/g," ")," — posts still go out on your ",ce||"saved"," schedule."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Etn.map(he=>e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>te(he.hour,he.minute),children:he.label},he.label))})]}),Z.length>0&&e.jsxs(Ote,{variant:"destructive",children:[e.jsx(nl,{className:"h-4 w-4"}),e.jsx(zte,{children:e.jsx("ul",{className:"list-disc pl-4 space-y-1",children:Z.map(he=>e.jsx("li",{children:he},he))})})]}),e.jsx(fc,{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>J("draft"),disabled:!!G,className:"gap-2",children:[G==="draft"?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4"}),"Save draft"]}),I?e.jsxs(z,{onClick:()=>J("schedule"),disabled:!!G,className:"gap-2",children:[G==="schedule"?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ud,{className:"h-4 w-4"}),"Schedule post"]}):e.jsxs(z,{onClick:()=>J("now"),disabled:!!G,className:"gap-2",children:[G==="now"?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),"Post now"]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Live preview"}),e.jsxs(ze,{variant:"secondary",children:[H.length," selected"]})]}),H.length===0?e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-sm text-muted-foreground",children:"Select an account to see exactly how your post will look."})}):e.jsx("div",{className:"space-y-4",children:H.map(he=>e.jsx(Ltn,{platform:he.platform,accountName:hce(he),avatarUrl:he.profile_picture_url,caption:K(he.id),mediaUrl:p,mediaType:g},he.id))})]}),e.jsx(Rqt,{open:c,onOpenChange:d})]})}const qtn=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],uvt={scheduled:"bg-primary/10 text-primary border-primary/20",publishing:"bg-amber-500/10 text-amber-700 border-amber-500/20",published:"bg-emerald-500/10 text-emerald-700 border-emerald-500/20",partial:"bg-amber-500/10 text-amber-700 border-amber-500/20",failed:"bg-destructive/10 text-destructive border-destructive/20",draft:"bg-muted text-muted-foreground border-border"};function Vtn({posts:s,onCreateAt:t,onOpenPost:n}){const{timezone:r}=MW(),a=kP(r),[i,l]=_.useState(()=>{const h=new Date;return new Date(h.getFullYear(),h.getMonth(),1)}),o=_.useMemo(()=>{const h=new Date(i);return h.setDate(1-h.getDay()),Array.from({length:42},(m,p)=>{const f=new Date(h);return f.setDate(h.getDate()+p),f})},[i]),c=_.useMemo(()=>{const h=new Map;return s.forEach(m=>{const p=m.scheduled_for??m.published_at;if(!p)return;const f=ztn(p,r);h.set(f,[...h.get(f)??[],m])}),h},[s,r]),d=new Date,u=h=>h.toDateString()===d.toDateString();return e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:i.toLocaleDateString("en-US",{month:"long",year:"numeric"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["All times ",a||r.replace(/_/g," ")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>l(new Date(d.getFullYear(),d.getMonth(),1)),children:"Today"}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()-1,1)),children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()+1,1)),children:e.jsx(yi,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-px text-center text-xs font-medium text-muted-foreground",children:qtn.map(h=>e.jsx("div",{className:"py-1",children:h},h))}),e.jsx("div",{className:"grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden",children:o.map(h=>{const m=`${h.getFullYear()}-${h.getMonth()}-${h.getDate()}`,p=c.get(m)??[],f=h.getMonth()!==i.getMonth();return e.jsxs("div",{className:`group relative min-h-[104px] bg-background p-1.5 ${f?"opacity-50":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-xs ${u(h)?"flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground":"text-muted-foreground"}`,children:h.getDate()}),e.jsx("button",{type:"button","aria-label":"Create post",onClick:()=>{const g=new Date(h);g.setHours(9,0,0,0),t(g)},className:"opacity-0 group-hover:opacity-100 transition text-muted-foreground hover:text-foreground",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[p.slice(0,3).map(g=>{var y;const v=g.scheduled_for??g.published_at;return e.jsxs("button",{type:"button",onClick:()=>n(g),className:`w-full rounded border px-1.5 py-1 text-left text-[10px] leading-tight ${uvt[g.status]??uvt.draft}`,children:[e.jsx("span",{className:"font-medium",children:Btn(v,r)})," ",e.jsx("span",{className:"truncate",children:((y=g.caption)==null?void 0:y.slice(0,24))||"Media post"}),e.jsx("span",{className:"mt-1 flex gap-1",children:g.social_post_targets.slice(0,4).map(b=>e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${rC(b.platform).dot}`},b.id))})]},g.id)}),p.length>3&&e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:["+",p.length-3," more"]})]})]},m)})})]})})}const Htn=s=>{switch(s){case"published":case"success":return{label:"Published",variant:"default",icon:Mr};case"partial":return{label:"Partly published",variant:"secondary",icon:nl};case"failed":return{label:"Failed",variant:"destructive",icon:nl};case"publishing":case"pending":return{label:"Publishing",variant:"secondary",icon:bt};case"scheduled":return{label:"Scheduled",variant:"outline",icon:Ud};default:return{label:"Draft",variant:"outline",icon:Wa}}};function hvt({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=_.useState(null),{timezone:o}=MW(),c=h=>t.find(m=>m.id===h),d=async h=>{l(h.id);try{await U.from("social_posts").update({status:"publishing",scheduled_for:null,error_message:null}).eq("id",h.id),await U.from("social_post_targets").update({status:"pending"}).eq("post_id",h.id).in("status",["cancelled","failed"]);const{data:m,error:p}=await U.functions.invoke("social-publish-post",{body:{post_id:h.id}});if(p)throw p;const f=m==null?void 0:m.status;f==="failed"?ne.error("Publishing failed. See the error details below."):f==="partial"?ne.warning("Some accounts failed."):ne.success("Published."),r()}catch(m){ne.error((m==null?void 0:m.message)??"Could not publish this post.")}finally{l(null)}},u=async h=>{l(h.id);try{const{error:m}=await U.from("social_posts").delete().eq("id",h.id);if(m)throw m;ne.success("Post deleted"),r()}catch(m){ne.error((m==null?void 0:m.message)??"Could not delete this post.")}finally{l(null)}};return s.length===0?e.jsx(be,{children:e.jsx(Le,{className:"p-8 text-center text-sm text-muted-foreground",children:a??"Nothing here yet."})}):e.jsx("div",{className:"space-y-3",children:s.map(h=>{var v,y;const p=h.status==="failed"&&!!((v=h.error_message)!=null&&v.startsWith("Missed its scheduled time"))?{label:"Didn't send",variant:"destructive",icon:nl}:Htn(h.status),f=p.icon,g=h.scheduled_for??h.published_at??h.created_at;return e.jsx(be,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((y=h.media_urls)==null?void 0:y[0])&&(h.media_type==="video"?e.jsx("video",{src:h.media_urls[0],className:"h-20 w-20 rounded-lg object-cover shrink-0"}):e.jsx("img",{src:h.media_urls[0],alt:"",loading:"lazy",className:"h-20 w-20 rounded-lg object-cover shrink-0"})),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:p.variant,className:"gap-1",children:[e.jsx(f,{className:`h-3 w-3 ${p.label==="Publishing"?"animate-spin":""}`}),p.label]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:zqt(g,h.timezone||o)})]}),e.jsx("p",{className:"text-sm line-clamp-2 whitespace-pre-wrap",children:h.caption||"Media only post"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:h.social_post_targets.map(b=>{const w=rC(b.platform),S=w.icon,C=c(b.social_account_id),E=b.status==="published",P=b.status==="failed";return e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs ${P?"border-destructive/30 bg-destructive/5 text-destructive":w.chip}`,children:[e.jsxs(ja,{className:"h-4 w-4",children:[e.jsx(xi,{src:(C==null?void 0:C.profile_picture_url)??void 0}),e.jsx(Na,{className:"text-[8px]",children:e.jsx(S,{className:"h-2.5 w-2.5"})})]}),e.jsx("span",{className:"max-w-[140px] truncate",children:(C==null?void 0:C.page_name)||(C==null?void 0:C.platform_username)||w.label}),E&&b.permalink&&e.jsx("a",{href:b.permalink,target:"_blank",rel:"noopener noreferrer","aria-label":"View post",children:e.jsx(mr,{className:"h-3 w-3"})}),P&&e.jsx(nl,{className:"h-3 w-3"})]},b.id)})}),h.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2",children:e.jsx("p",{className:"text-xs text-destructive",children:h.error_message})}),h.social_post_targets.some(b=>b.status==="failed")&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2 space-y-1",children:h.social_post_targets.filter(b=>b.status==="failed").map(b=>e.jsxs("p",{className:"text-xs text-destructive",children:[e.jsxs("span",{className:"font-medium",children:[rC(b.platform).label,":"]})," ",b.error_message||"Publishing failed."]},b.id))})]}),e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1",onClick:()=>n(h),children:[e.jsx(Wa,{className:"h-3.5 w-3.5"})," Edit"]}),h.status!=="published"&&e.jsxs(z,{size:"sm",className:"gap-1",disabled:i===h.id,onClick:()=>d(h),children:[i===h.id?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):h.status==="failed"||h.status==="partial"?e.jsx(Gi,{className:"h-3.5 w-3.5"}):e.jsx(Fr,{className:"h-3.5 w-3.5"}),h.status==="failed"||h.status==="partial"?"Retry":"Post now"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",disabled:i===h.id,onClick:()=>u(h),children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},h.id)})})}const Gtn=()=>{const[s,t]=_.useState("compose"),[n,r]=_.useState(null),[a,i]=_.useState(null);_.useEffect(()=>{const g=sessionStorage.getItem("social-studio-seed");if(g){sessionStorage.removeItem("social-studio-seed");try{const v=JSON.parse(g);(v!=null&&v.mediaUrl||v!=null&&v.caption)&&(r(v),t("compose"))}catch{}}},[]);const{data:l=[]}=Qtt(),{data:o=[],isLoading:c}=Itn(),d=Lqt(),u=_.useMemo(()=>o.filter(g=>g.status==="scheduled"||g.status==="draft"||g.status==="publishing").sort((g,v)=>new Date(g.scheduled_for??g.created_at).getTime()-new Date(v.scheduled_for??v.created_at).getTime()),[o]),h=_.useMemo(()=>o.filter(g=>["published","partial","failed","cancelled"].includes(g.status)),[o]),m=h.filter(g=>g.status==="failed"||g.status==="partial").length,p=(g,v=null)=>{r(g),i(v),t("compose")},f=g=>{p({mediaUrl:g.mediaUrl,mediaType:g.mediaType,caption:g.caption,source:"swag",sourceRef:g.swagItemId??g.reelId})};return e.jsx($s,{title:"Social Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Le,{className:"p-6 flex flex-col gap-5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," Social Studio"]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Post everywhere, from one place"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Write once, preview each network, and publish or schedule to every connected account."})]}),e.jsxs("div",{className:"flex flex-col items-start gap-3 md:items-end",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No accounts connected yet"}):e.jsx("div",{className:"flex -space-x-2",children:l.slice(0,6).map(g=>e.jsxs(ja,{className:"h-8 w-8 border-2 border-background",title:g.page_name??g.platform,children:[e.jsx(xi,{src:g.profile_picture_url??void 0}),e.jsx(Na,{className:"text-[10px]",children:rC(g.platform).label.slice(0,2)})]},g.id))}),e.jsx(z,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/social-connections",children:[e.jsx(vS,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs(z,{className:"gap-2",onClick:()=>p(null),children:[e.jsx(Cp,{className:"h-4 w-4"})," New post"]})]})]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{label:"Connected accounts",value:l.length,icon:X4},{label:"Scheduled & drafts",value:u.length,icon:gc},{label:"Published",value:h.filter(g=>g.status==="published").length,icon:Mr}].map(({label:g,value:v,icon:y})=>e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(y,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-semibold leading-none",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:g})]})]})},g))}),e.jsxs(Qr,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(Jr,{className:"flex-wrap h-auto",children:[e.jsxs(Wt,{value:"compose",className:"gap-2",children:[e.jsx(Cp,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Wt,{value:"calendar",className:"gap-2",children:[e.jsx(gc,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Wt,{value:"queue",className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Wt,{value:"history",className:"gap-2",children:[e.jsx(Mr,{className:"h-4 w-4"}),"History",m>0&&e.jsx(ze,{variant:"destructive",className:"ml-1",children:m})]}),e.jsxs(Wt,{value:"gallery",className:"gap-2",children:[e.jsx(un,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Kt,{value:"compose",children:e.jsx(Utn,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Kt,{value:"calendar",children:e.jsx(Vtn,{posts:o,onCreateAt:g=>p({scheduledFor:g}),onOpenPost:g=>p(null,g)})}),e.jsx(Kt,{value:"queue",children:e.jsx(hvt,{posts:u,accounts:l,onEdit:g=>p(null,g),onChanged:d,emptyLabel:c?"Loading your posts…":"Nothing scheduled yet. Compose a post to get started."})}),e.jsx(Kt,{value:"history",children:e.jsx(hvt,{posts:h,accounts:l,onEdit:g=>p(null,g),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Kt,{value:"gallery",children:e.jsx(Eqt,{embedded:!0,onCompose:f})})]})]})})},Wtn=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:nc,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:sa,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:Oo,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:wl,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Hf,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:aj,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:XA,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function Ktn(){return e.jsx($s,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(dl,{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(z,{variant:"outline",asChild:!0,children:e.jsxs(or,{to:"/marketing-studio/brand-kit",children:[e.jsx(yc,{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:Wtn.map(s=>{const t=s.icon,n=e.jsxs(be,{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(Le,{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(or,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function Eae(){const s=ha();return rt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 Ytn(){const{data:s,...t}=Eae();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function Ztn(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await U.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await U.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 U.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 Xtn(){const s=ha(),t=$t();return mt({mutationFn:async n=>{const{error:r}=await U.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function Qtn(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 U.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await U.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function Jtn({preset:s,onSaved:t,onCancel:n}){var g;const r=ha(),a=Ztn(),i=Xtn(),l=_.useRef(null),o=_.useRef(null),[c,d]=_.useState(null),[u,h]=_.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"});_.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:v}=await Fa(async()=>{const{supabase:b}=await Promise.resolve().then(()=>yjs);return{supabase:b}},void 0),{data:y}=await v.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();y&&h(b=>({...b,display_name:b.display_name||(y.name??""),email:b.email||(y.email??""),phone:b.phone||(y.phone??""),headshot_url:b.headshot_url||(y.avatar_url??""),website_url:b.website_url||(y.website_url??""),tagline:b.tagline||(y.title??"")}))})()},[r]);const m=async(v,y)=>{if(r){d(v);try{const b=await Qtn(r,y,v);h(w=>({...w,[v==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){ne.error(b.message||"Upload failed")}finally{d(null)}}},p=async()=>{try{const v=await a.mutateAsync({id:s==null?void 0:s.id,...u});ne.success("Brand preset saved"),t==null||t(v)}catch(v){ne.error(v.message||"Save failed")}},f=async()=>{s!=null&&s.id&&await Qi("Delete this brand preset?")&&(await i.mutateAsync(s.id),ne.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(ee,{children:"Preset name"}),e.jsx(pe,{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(mn,{checked:u.is_default,onCheckedChange:v=>h({...u,is_default:v})}),e.jsx(ee,{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(ee,{children:"Display name"}),e.jsx(pe,{value:u.display_name,onChange:v=>h({...u,display_name:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:u.phone,onChange:v=>h({...u,phone:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:u.email,onChange:v=>h({...u,email:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:u.license_number,onChange:v=>h({...u,license_number:v.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{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(ee,{children:"Website"}),e.jsx(pe,{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(ee,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-16 w-16",children:[e.jsx(xi,{src:u.headshot_url||void 0}),e.jsx(Na,{children:((g=u.display_name)==null?void 0:g[0])??"A"})]}),e.jsxs(z,{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(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var y;return((y=v.target.files)==null?void 0:y[0])&&m("headshot",v.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(z,{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(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var y;return((y=v.target.files)==null?void 0:y[0])&&m("logo",v.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{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(z,{variant:"ghost",size:"sm",onClick:f,className:"text-destructive",children:[e.jsx(Cn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(z,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(z,{onClick:p,disabled:a.isPending,children:[a.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function esn(){const{data:s,isLoading:t}=Eae(),[n,r]=_.useState(null);return e.jsx($s,{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(dl,{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(or,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(ka,{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(z,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(sn,{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(be,{className:"border-dashed",children:e.jsxs(Le,{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(z,{onClick:()=>r("new"),children:[e.jsx(sn,{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(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(_t,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Nt,{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(Ia,{className:"h-3 w-3"})," Default"]})]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(Wa,{className:"h-4 w-4"})})]}),e.jsx(En,{children:a.display_name})]}),e.jsxs(Le,{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(Is,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Os,{children:e.jsx(Rs,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(Jtn,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const OHe=[{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"}],tsn=s=>OHe.find(t=>t.id===s)??OHe[0];function ssn(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 nsn({value:s,onChange:t,mediaType:n}){const r=OHe.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:Ct("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(rsn,{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 rsn({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 asn=Math.PI/180;function isn(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const EF=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},bi={_global:EF,version:"10.2.5",isBrowser:isn(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return bi.angleDeg?s*asn: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 bi.DD.isDragging},isTransforming(){var s,t;return(t=(s=bi.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!bi.DD.node},releaseCanvasOnDestroy:!0,document:EF.document,_injectGlobal(s){typeof EF.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),EF.Konva=s}},sx=s=>{bi[s.prototype.getClassName()]=s};bi._injectGlobal(bi);const osn=`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"; `,mvt=()=>{if(typeof document>"u")throw new Error(osn)};class sj{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 sj(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=rr._getRotation(c.rotation),c}}const lsn="[object Array]",csn="[object Number]",dsn="[object String]",usn="[object Boolean]",hsn=Math.PI/180,msn=180/Math.PI,tZ="#",psn="",fsn="0",xsn="Konva warning: ",pvt="Konva error: ",gsn="rgb(",f9e={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]},ysn=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let mce=[],sZ=null;const vsn=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},rr={_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)===lsn},_isNumber(s){return Object.prototype.toString.call(s)===csn&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===dsn},_isBoolean(s){return Object.prototype.toString.call(s)===usn},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){mce.push(s),mce.length===1&&vsn(function(){const t=mce;mce=[],t.forEach(function(n){n()})})},createCanvasElement(){mvt();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return mvt(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=rr.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(tZ,psn);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=fsn+s;return tZ+s},isCanvasFarblingActive(){if(sZ!==null)return sZ;if(typeof document>"u")return sZ=!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 sZ=r,this.releaseCanvas(s),sZ},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),tZ+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return tZ+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 f9e?(t=f9e[s],{r:t[0],g:t[1],b:t[2]}):s[0]===tZ?this._hexToRgb(s.substring(1)):s.substr(0,4)===gsn?(t=ysn.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",rr._namedColorToRBA(s)||rr._hex3ColorToRGBA(s)||rr._hex4ColorToRGBA(s)||rr._hex6ColorToRGBA(s)||rr._hex8ColorToRGBA(s)||rr._rgbColorToRGBA(s)||rr._rgbaColorToRGBA(s)||rr._hslColorToRGBA(s)},_namedColorToRBA(s){const t=f9e[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=rr.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=rr._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+=_sn+d.join(fvt)+wsn)):(i+=o.property,t||(i+=Csn+o.val)),i+=ksn;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=Esn&&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=xvt.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=bsn(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 Du._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];Du._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=rr._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=[];Du._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")&&(Du.justDragged=!0,bi._mouseListenClick=!1,bi._touchListenClick=!1,bi._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof bi.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){Du._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&Du._dragElements.delete(n)})}};bi.isBrowser&&(window.addEventListener("mouseup",Du._endDragBefore,!0),window.addEventListener("touchend",Du._endDragBefore,!0),window.addEventListener("touchcancel",Du._endDragBefore,!0),window.addEventListener("mousemove",Du._drag),window.addEventListener("touchmove",Du._drag),window.addEventListener("mouseup",Du._endDragAfter,!1),window.addEventListener("touchend",Du._endDragAfter,!1),window.addEventListener("touchcancel",Du._endDragAfter,!1));function PL(s){return rr._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||rr._isBoolean(s)?s:Object.prototype.toString.call(s)}function Bqt(s){return s>255?255:s<0?0:Math.round(s)}function mi(){if(bi.isUnminified)return function(s,t){return rr._isNumber(s)||rr.warn(PL(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function sIe(s){if(bi.isUnminified)return function(t,n){let r=rr._isNumber(t),a=rr._isArray(t)&&t.length==s;return!r&&!a&&rr.warn(PL(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function sst(){if(bi.isUnminified)return function(s,t){return rr._isNumber(s)||s==="auto"||rr.warn(PL(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function tz(){if(bi.isUnminified)return function(s,t){return rr._isString(s)||rr.warn(PL(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function $qt(){if(bi.isUnminified)return function(s,t){const n=rr._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||rr.warn(PL(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Lsn(){if(bi.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(rr._isArray(s)?s.forEach(function(r){rr._isNumber(r)||rr.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):rr.warn(PL(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function $S(){if(bi.isUnminified)return function(s,t){return s===!0||s===!1||rr.warn(PL(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Isn(s){if(bi.isUnminified)return function(t,n){return t==null||rr.isObject(t)||rr.warn(PL(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const nZ="get",rZ="set",xn={addGetterSetter(s,t,n,r,a){xn.addGetter(s,t,n),xn.addSetter(s,t,r,a),xn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=nZ+rr._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=rZ+rr._capitalize(t);s.prototype[a]||xn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=rZ+rr._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=rr._capitalize,o=nZ+l(t),c=rZ+l(t);s.prototype[o]=function(){const u={};for(let h=0;h{this._setAttr(t+l(m),void 0)}),this._fireChangeEvent(t,h,u),a&&a.call(this),this},xn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=rr._capitalize(t),r=rZ+n,a=nZ+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){rr.error("Adding deprecated "+t);const a=nZ+rr._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){rr.error(i);const l=this.attrs[t];return l===void 0?n:l},xn.addSetter(s,t,r,function(){rr.error(i)}),xn.addOverloadedGetterSetter(s,t)},backCompat(s,t){rr.each(t,function(n,r){const a=s.prototype[r],i=nZ+rr._capitalize(n),l=rZ+rr._capitalize(n);function o(){a.apply(this,arguments),rr.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 Dsn(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=bi.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=bi.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=bi.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=bi.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=bi.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=bi.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:rr.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const rCe="absoluteOpacity",yvt="allEventListeners",B3="absoluteTransform",vvt="absoluteScale",PI="canvas",Rsn="Change",Fsn="children",Osn="konva",zHe="listening",zsn="mouseenter",Bsn="mouseleave",$sn="pointerenter",Usn="pointerleave",qsn="touchenter",Vsn="touchleave",bvt="set",_vt="Shape",aCe=" ",wvt="stage",n6="transform",Hsn="Stage",BHe="visible",Gsn=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(aCe);let Wsn=1,Ci=class EX{constructor(t){this._id=Wsn++,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===n6||t===B3)&&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===n6||t===B3)&&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(aCe);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(PI)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===B3&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(PI)){const{scene:t,filter:n,hit:r}=this._cache.get(PI);rr.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(PI)}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){rr.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const m=Math.abs(Math.round(r.x)-o)>.5?1:0,p=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+m,i+=d*2+p,o-=d,c-=d;const f=new F6({pixelRatio:l,width:a,height:i}),g=new F6({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),v=new tst({pixelRatio:h,width:a,height:i}),y=f.getContext(),b=v.getContext(),w=new F6({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(c),pixelRatio:f.pixelRatio}),S=w.getContext();return v.isCache=!0,f.isCache=!0,this._cache.delete(PI),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,g.getContext()._context.imageSmoothingEnabled=!1),y.save(),b.save(),S.save(),y.translate(-o,-c),b.translate(-o,-c),S.translate(-o,-c),w.x=o,w.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(rCe),this._clearSelfAndDescendantCache(vvt),this.drawScene(f,this,w),this.drawHit(v,this),this._isUnderCache=!1,y.restore(),b.restore(),u&&(y.save(),y.beginPath(),y.rect(0,0,a,i),y.closePath(),y.setAttr("strokeStyle","red"),y.setAttr("lineWidth",5),y.stroke(),y.restore()),rr.releaseCanvas(w._canvas),this._cache.set(PI,{scene:f,filter:g,hit:v,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(PI)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let a=1/0,i=1/0,l=-1/0,o=-1/0;const c=this.getAbsoluteTransform(n);return r.forEach(function(d){const u=c.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),{x:a,y:i,width:l-a,height:o-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),a=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/a,r.height/a),t.restore()}_drawCachedHitCanvas(t){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),n=this._getCanvasCache(),r=n.scene,a=n.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return r;if(this._filterUpToDate)return a;let u=!0;for(let m=0;m{this.isAncestorOf(t.node)&&Du._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(B3),this._clearSelfAndDescendantCache(rCe),this._clearSelfAndDescendantCache(vvt),this._clearSelfAndDescendantCache(wvt),this._clearSelfAndDescendantCache(BHe),this._clearSelfAndDescendantCache(zHe)}_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"+rr._capitalize(t);return rr._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!==Fsn&&(r=bvt+rr._capitalize(n),rr._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(zHe,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(BHe,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;Du._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!bi.hitOnDragEnabled&&(a||bi.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!==Hsn&&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(n6),this._clearSelfAndDescendantCache(B3)),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 sj,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(n6);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(n6),this._clearSelfAndDescendantCache(B3),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 rr.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 rr.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&rr.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(rCe,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=rr.isObject(r)&&!rr._isPlainObject(r)&&!rr._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 rr._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,rr._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():bi.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;Du._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=Du._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&Du._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 rr.haveIntersection(r,this.getClientRect())}static create(t,n){return rr._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=EX.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),bi[r]||(rr.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=bi[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=Ci.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=Ci.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 p=this.getAbsoluteTransform(r);let f=p.getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.beginPath();let g;if(d)g=d.call(this,l,this);else{const v=this.clipX(),y=this.clipY();l.rect(v||0,y||0,o,c)}l.clip.apply(l,g),f=p.copy().invert().getMatrix(),l.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const m=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";m&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(p){p[t](n,r,a)}),m&&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(p){if(!p.visible())return;const f=p.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});f.width===0&&f.height===0||(i===void 0?(i=f.x,l=f.y,o=f.x+f.width,c=f.y+f.height):(i=Math.min(i,f.x),l=Math.min(l,f.y),o=Math.max(o,f.x+f.width),c=Math.max(c,f.y+f.height)))});const h=this.find("Shape");let m=!1;for(let p=0;ps.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",FB=s=>{const t=IX(s);if(t==="pointer")return bi.pointerEventsEnabled&&g9e.pointer;if(t==="touch")return g9e.touch;if(t==="mouse")return g9e.mouse};function Nvt(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&rr.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const enn="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);",QJ=[];let nIe=class extends kj{constructor(t){super(Nvt(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),QJ.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Nvt(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||rr.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===Ysn){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&&QJ.splice(n,1),rr.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}:(rr.warn(enn),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 F6({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+jvt,this.content.style.height=n+jvt),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;aQsn&&rr.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(),bi.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return qqt(t,this)}setPointerCapture(t){Vqt(t,this)}releaseCapture(t){XJ(t)}getLayers(){return this.children}_bindContentEvents(){bi.isBrowser&&Jsn.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=FB(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=FB(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=FB(t.type),r=IX(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(bi.isDragging()||bi.isTransforming())||bi.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=FB(t.type),r=IX(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(Du.justDragged=!1,bi["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}bi.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=FB(t.type),r=IX(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(bi.isDragging()&&Du.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(bi.isDragging()||bi.isTransforming())||bi.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=x9e(d.id)||this.getIntersection(d),h=d.id,m={evt:t,pointerId:h},p=c!==u;if(p&&c&&(c._fireAndBubble(n.pointerout,{...m},u),c._fireAndBubble(n.pointerleave,{...m},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,p&&(u._fireAndBubble(n.pointerover,{...m},c),u._fireAndBubble(n.pointerenter,{...m},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...m})):c&&(this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=FB(t.type),r=IX(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=x9e(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const u=c.id,h={evt:t,pointerId:u};let m=!1;bi["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):Du.justDragged||(bi["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){bi["_"+r+"InDblClickWindow"]=!1},bi.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),bi["_"+r+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(n.pointerclick,{...h}),m&&i&&i===d&&d._fireAndBubble(n.pointerdblclick,{...h}))):(this[r+"ClickEndShape"]=null,o||(this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),bi["_"+r+"ListenClick"]&&this._fire(n.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),m&&this._fire(n.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:u}))}),o||this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),bi["_"+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($He,{evt:t}):this._fire($He,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(UHe,{evt:t}):this._fire(UHe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=x9e(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(uU,nst(t)),XJ(t.pointerId)}_lostpointercapture(t){XJ(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:rr._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:rr._getFirstPointerId(t)}])}_setPointerPosition(t){rr.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 F6({width:this.width(),height:this.height()}),this.bufferHitCanvas=new tst({pixelRatio:1,width:this.width(),height:this.height()}),!bi.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 rr.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}};nIe.prototype.nodeType=Ksn;sx(nIe);xn.addGetterSetter(nIe,"container");bi.isBrowser&&document.addEventListener("visibilitychange",()=>{QJ.forEach(s=>{s.batchDraw()})});const tVt="hasShadow",sVt="shadowRGBA",nVt="patternImage",rVt="linearGradient",aVt="radialGradient";let vce;function y9e(){return vce||(vce=rr.createCanvasElement().getContext("2d"),vce)}const JJ={};function tnn(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function snn(s){s.stroke()}function nnn(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function rnn(s){s.stroke()}function ann(){this._clearCache(tVt)}function inn(){this._clearCache(sVt)}function onn(){this._clearCache(nVt)}function lnn(){this._clearCache(rVt)}function cnn(){this._clearCache(aVt)}let ai=class extends Ci{constructor(t){super(t);let n,r=0;for(;n=rr.getHitColor(),!(n&&!(n in JJ));)if(r++,r>=1e4){rr.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=rr.getRandomColor();break}this.colorKey=n,JJ[n]=this}getContext(){return rr.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return rr.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(tVt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(nVt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=y9e().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new sj;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(bi.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(rVt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=y9e(),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 Ci.prototype.destroy.call(this),delete JJ[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){rr.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),m=h?this.shadowOffsetX():0,p=h?this.shadowOffsetY():0,f=d+Math.abs(m),g=u+Math.abs(p),v=h&&this.shadowBlur()||0,y=f+v*2,b=g+v*2,w={width:y,height:b,x:-(c/2+v)+Math.min(m,0)+l.x,y:-(c/2+v)+Math.min(p,0)+l.y};return a?w:this._transformedRect(w,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,m=n===this;if(!this.isVisible()&&!m)return this;if(o){l.save();const p=this.getAbsoluteTransform(n).getMatrix();return l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const p=r||u.bufferCanvas,f=p.getContext();r?(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,p.width,p.height),f.restore()):f.clear(),f.save(),f._applyLineJoin(this),f._applyMiterLimit(this);const g=this.getAbsoluteTransform(n).getMatrix();f.transform(g[0],g[1],g[2],g[3],g[4],g[5]),c.call(this,f,this),f.restore();const v=p.pixelRatio;d&&l._applyShadow(this),m||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(p._canvas,p.x||0,p.y||0,p.width/v,p.height/v)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!m){const p=this.getAbsoluteTransform(n).getMatrix();l.transform(p[0],p[1],p[2],p[3],p[4],p[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||rr.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=rr._hexToRgb(this.colorKey);for(let m=0;mt?(d[m]=h.r,d[m+1]=h.g,d[m+2]=h.b,d[m+3]=255):d[m+3]=0;i.putImageData(c,0,0)}catch(c){rr.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return qqt(t,this)}setPointerCapture(t){Vqt(t,this)}releaseCapture(t){XJ(t)}};ai.prototype._fillFunc=tnn;ai.prototype._strokeFunc=snn;ai.prototype._fillFuncHit=nnn;ai.prototype._strokeFuncHit=rnn;ai.prototype._centroid=!1;ai.prototype.nodeType="Shape";sx(ai);ai.prototype.eventListeners={};ai.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",ann);ai.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",inn);ai.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",onn);ai.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",lnn);ai.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",cnn);xn.addGetterSetter(ai,"stroke",void 0,$qt());xn.addGetterSetter(ai,"strokeWidth",2,mi());xn.addGetterSetter(ai,"fillAfterStrokeEnabled",!1);xn.addGetterSetter(ai,"hitStrokeWidth","auto",sst());xn.addGetterSetter(ai,"strokeHitEnabled",!0,$S());xn.addGetterSetter(ai,"perfectDrawEnabled",!0,$S());xn.addGetterSetter(ai,"shadowForStrokeEnabled",!0,$S());xn.addGetterSetter(ai,"lineJoin");xn.addGetterSetter(ai,"lineCap");xn.addGetterSetter(ai,"miterLimit");xn.addGetterSetter(ai,"sceneFunc");xn.addGetterSetter(ai,"hitFunc");xn.addGetterSetter(ai,"dash");xn.addGetterSetter(ai,"dashOffset",0,mi());xn.addGetterSetter(ai,"shadowColor",void 0,tz());xn.addGetterSetter(ai,"shadowBlur",0,mi());xn.addGetterSetter(ai,"shadowOpacity",1,mi());xn.addComponentsGetterSetter(ai,"shadowOffset",["x","y"]);xn.addGetterSetter(ai,"shadowOffsetX",0,mi());xn.addGetterSetter(ai,"shadowOffsetY",0,mi());xn.addGetterSetter(ai,"fillPatternImage");xn.addGetterSetter(ai,"fill",void 0,$qt());xn.addGetterSetter(ai,"fillPatternX",0,mi());xn.addGetterSetter(ai,"fillPatternY",0,mi());xn.addGetterSetter(ai,"fillLinearGradientColorStops");xn.addGetterSetter(ai,"strokeLinearGradientColorStops");xn.addGetterSetter(ai,"fillRadialGradientStartRadius",0);xn.addGetterSetter(ai,"fillRadialGradientEndRadius",0);xn.addGetterSetter(ai,"fillRadialGradientColorStops");xn.addGetterSetter(ai,"fillPatternRepeat","repeat");xn.addGetterSetter(ai,"fillEnabled",!0);xn.addGetterSetter(ai,"strokeEnabled",!0);xn.addGetterSetter(ai,"shadowEnabled",!0);xn.addGetterSetter(ai,"dashEnabled",!0);xn.addGetterSetter(ai,"strokeScaleEnabled",!0);xn.addGetterSetter(ai,"fillPriority","color");xn.addComponentsGetterSetter(ai,"fillPatternOffset",["x","y"]);xn.addGetterSetter(ai,"fillPatternOffsetX",0,mi());xn.addGetterSetter(ai,"fillPatternOffsetY",0,mi());xn.addComponentsGetterSetter(ai,"fillPatternScale",["x","y"]);xn.addGetterSetter(ai,"fillPatternScaleX",1,mi());xn.addGetterSetter(ai,"fillPatternScaleY",1,mi());xn.addComponentsGetterSetter(ai,"fillLinearGradientStartPoint",["x","y"]);xn.addComponentsGetterSetter(ai,"strokeLinearGradientStartPoint",["x","y"]);xn.addGetterSetter(ai,"fillLinearGradientStartPointX",0);xn.addGetterSetter(ai,"strokeLinearGradientStartPointX",0);xn.addGetterSetter(ai,"fillLinearGradientStartPointY",0);xn.addGetterSetter(ai,"strokeLinearGradientStartPointY",0);xn.addComponentsGetterSetter(ai,"fillLinearGradientEndPoint",["x","y"]);xn.addComponentsGetterSetter(ai,"strokeLinearGradientEndPoint",["x","y"]);xn.addGetterSetter(ai,"fillLinearGradientEndPointX",0);xn.addGetterSetter(ai,"strokeLinearGradientEndPointX",0);xn.addGetterSetter(ai,"fillLinearGradientEndPointY",0);xn.addGetterSetter(ai,"strokeLinearGradientEndPointY",0);xn.addComponentsGetterSetter(ai,"fillRadialGradientStartPoint",["x","y"]);xn.addGetterSetter(ai,"fillRadialGradientStartPointX",0);xn.addGetterSetter(ai,"fillRadialGradientStartPointY",0);xn.addComponentsGetterSetter(ai,"fillRadialGradientEndPoint",["x","y"]);xn.addGetterSetter(ai,"fillRadialGradientEndPointX",0);xn.addGetterSetter(ai,"fillRadialGradientEndPointY",0);xn.addGetterSetter(ai,"fillPatternRotation",0);xn.addGetterSetter(ai,"fillRule",void 0,tz());xn.backCompat(ai,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const dnn="beforeDraw",unn="draw",iVt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],hnn=iVt.length;let sz=class extends kj{constructor(t){super(t),this.canvas=new F6,this.hitCanvas=new tst({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(dnn,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),kj.prototype.drawScene.call(this,i,n,r),this._fire(unn,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),kj.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){rr.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return rr.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 rr.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};sz.prototype.nodeType="Layer";sx(sz);xn.addGetterSetter(sz,"imageSmoothingEnabled",!0);xn.addGetterSetter(sz,"clearBeforeDraw",!0);xn.addGetterSetter(sz,"hitGraphEnabled",!0,$S());class rst extends sz{constructor(t){super(t),this.listening(!1),rr.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}rst.prototype.nodeType="FastLayer";sx(rst);let YH=class extends kj{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&rr.throw("You may only add groups and shapes to groups.")}};YH.prototype.nodeType="Group";sx(YH);const v9e=function(){return EF.performance&&EF.performance.now?function(){return EF.performance.now()}:function(){return new Date().getTime()}}();class tN{constructor(t,n){this.id=tN.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:v9e(),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=kvt,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Svt,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===kvt?this.setTime(t):this.state===Svt&&this.setTime(this.duration-t)}pause(){this.state=pnn,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Xm{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||eee.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=fnn++;const d=r.getLayer()||(r instanceof bi.Stage?r.getLayers():null);d||rr.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new tN(function(){n.tween.onEnterFrame()},d),this.tween=new xnn(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Xm.attrs[a]||(Xm.attrs[a]={}),Xm.attrs[a][this._id]||(Xm.attrs[a][this._id]={}),Xm.tweens[a]||(Xm.tweens[a]={});for(c in t)mnn[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=Xm.tweens[a][t];u&&delete Xm.attrs[a][u][t];let h=r.getAttr(t);if(rr._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=rr._prepareArrayForTween(h,n,r.closed())):(o=n,n=rr._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let m=0;m{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=Xm.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=Xm.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=Xm.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Xm.tweens[t][a];delete Xm.attrs[t][n],Xm.tweens[t]&&(Object.keys(Xm.tweens[t]).length===0&&delete Xm.tweens[t],Object.keys(Xm.attrs[t]).length===0&&delete Xm.attrs[t])}}Xm.attrs={};Xm.tweens={};Ci.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Xm(s).play()};const eee={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),m=c*(c>0?n:t);return{x:d,y:r?-1*m:h,width:u-d,height:m-h}}}qE.prototype._centroid=!0;qE.prototype.className="Arc";qE.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];sx(qE);xn.addGetterSetter(qE,"innerRadius",0,mi());xn.addGetterSetter(qE,"outerRadius",0,mi());xn.addGetterSetter(qE,"angle",0,mi());xn.addGetterSetter(qE,"clockwise",!1,$S());function qHe(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),m=r-d*(i-t),p=n+u*(a-s),f=r+u*(i-t);return[h,m,p,f]}function Avt(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 VE=class extends ai{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*ynn[20][o]+l,r+=vnn[20][o]*_nn(s,t,a);return l*r},Tvt=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,m=n+u,p=h-u*u,f=m*m+p>0?Math.sqrt(m*m+p):0,g=u*u+p>0?Math.sqrt(u*u+p):0,v=u+Math.sqrt(u*u+p)!==0?p*Math.log(Math.abs((m+f)/(u+g))):0;return Math.sqrt(o)/2*(m*f-u*g+v)};function _nn(s,t,n){const r=VHe(1,n,s),a=VHe(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const VHe=(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+=bnn[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 sN=class l_ extends ai{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=l_.parsePathData(this.data()),this.pathLength=l_.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,y=d>u?u/d:1;t.translate(o,c),t.rotate(p),t.scale(v,y),t.arc(0,0,g,h,h+m,1-f),t.scale(1/v,1/y),t.rotate(-p),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let m=Math.PI/180;if(Math.abs(d-h)h;p-=m){const f=l_.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,0);t.push(f.x,f.y)}else for(let p=d+m;pn[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 l_.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return l_.getPointOnCubicBezier(Mvt(t,l_.getPathLength(n),g=>Evt([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],g)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return l_.getPointOnQuadraticBezier(Mvt(t,l_.getPathLength(n),g=>Tvt([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],g)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],m=o[5],p=o[6];let f=o[4];return f+=m*t/l.pathLength,l_.getPointOnEllipticalArc(c,d,u,h,f,p)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(g+=2,g>=7&&(g-=7));continue}if(g>=0){if(g===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(b)){f.push(parseInt(b[0],10)),f.push(parseInt(b[1],10)),f.push(parseFloat(b.slice(2))),g+=3,g>=7&&(g-=7);continue}if(b==="11"||b==="10"||b==="01"){f.push(parseInt(b[0],10)),f.push(parseInt(b[1],10)),g+=2,g>=7&&(g-=7);continue}if(b==="0"||b==="1"){f.push(parseInt(b,10)),g+=1,g>=7&&(g-=7);continue}}else if(g===4){if(/^[01]\d+(?:\.\d+)?$/.test(b)){f.push(parseInt(b[0],10)),f.push(parseFloat(b.slice(1))),g+=2,g>=7&&(g-=7);continue}if(b==="0"||b==="1"){f.push(parseInt(b,10)),g+=1,g>=7&&(g-=7);continue}}const w=parseFloat(b);isNaN(w)?f.push(0):f.push(w),g+=1,g>=7&&(g-=7)}else{const w=parseFloat(b);isNaN(w)?f.push(0):f.push(w)}}for(;f.length>0&&!isNaN(f[0]);){let v="",y=[];const b=o,w=c;let S,C,E,P,M,I,D,F,q,G;switch(p){case"l":o+=f.shift(),c+=f.shift(),v="L",y.push(o,c);break;case"L":o=f.shift(),c=f.shift(),y.push(o,c);break;case"m":const V=f.shift(),H=f.shift();if(o+=V,c+=H,v="M",i.length>2&&i[i.length-1].command==="z"){for(let K=i.length-2;K>=0;K--)if(i[K].command==="M"){o=i[K].points[0]+V,c=i[K].points[1]+H;break}}y.push(o,c),p="l";break;case"M":o=f.shift(),c=f.shift(),v="M",y.push(o,c),p="L";break;case"h":o+=f.shift(),v="L",y.push(o,c);break;case"H":o=f.shift(),v="L",y.push(o,c);break;case"v":c+=f.shift(),v="L",y.push(o,c);break;case"V":c=f.shift(),v="L",y.push(o,c);break;case"C":y.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),c=f.shift(),y.push(o,c);break;case"c":y.push(o+f.shift(),c+f.shift(),o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),v="C",y.push(o,c);break;case"S":C=o,E=c,S=i[i.length-1],S.command==="C"&&(C=o+(o-S.points[2]),E=c+(c-S.points[3])),y.push(C,E,f.shift(),f.shift()),o=f.shift(),c=f.shift(),v="C",y.push(o,c);break;case"s":C=o,E=c,S=i[i.length-1],S.command==="C"&&(C=o+(o-S.points[2]),E=c+(c-S.points[3])),y.push(C,E,o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),v="C",y.push(o,c);break;case"Q":y.push(f.shift(),f.shift()),o=f.shift(),c=f.shift(),y.push(o,c);break;case"q":y.push(o+f.shift(),c+f.shift()),o+=f.shift(),c+=f.shift(),v="Q",y.push(o,c);break;case"T":C=o,E=c,S=i[i.length-1],S.command==="Q"&&(C=o+(o-S.points[0]),E=c+(c-S.points[1])),o=f.shift(),c=f.shift(),v="Q",y.push(C,E,o,c);break;case"t":C=o,E=c,S=i[i.length-1],S.command==="Q"&&(C=o+(o-S.points[0]),E=c+(c-S.points[1])),o+=f.shift(),c+=f.shift(),v="Q",y.push(C,E,o,c);break;case"A":P=f.shift(),M=f.shift(),I=f.shift(),D=f.shift(),F=f.shift(),q=o,G=c,o=f.shift(),c=f.shift(),v="A",y=this.convertEndpointToCenterParameterization(q,G,o,c,D,F,P,M,I);break;case"a":P=f.shift(),M=f.shift(),I=f.shift(),D=f.shift(),F=f.shift(),q=o,G=c,o+=f.shift(),c+=f.shift(),v="A",y=this.convertEndpointToCenterParameterization(q,G,o,c,D,F,P,M,I);break}i.push({command:v||p,points:y,start:{x:b,y:w},pathLength:this.calcLength(b,w,v||p,y)})}(p==="z"||p==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=l_;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return Evt([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return Tvt([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],m=a[4]+h;let p=Math.PI/180;if(Math.abs(u-m)m;c-=p)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+p;c1&&(o*=Math.sqrt(p),c*=Math.sqrt(p));let f=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(f*=-1),isNaN(f)&&(f=0);const g=f*o*m/c,v=f*-c*h/o,y=(t+r)/2+Math.cos(u)*g-Math.sin(u)*v,b=(n+a)/2+Math.sin(u)*g+Math.cos(u)*v,w=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},S=function(D,F){return(D[0]*F[0]+D[1]*F[1])/(w(D)*w(F))},C=function(D,F){return(D[0]*F[1]=1&&(I=0),l===0&&I>0&&(I=I-2*Math.PI),l===1&&I<0&&(I=I+2*Math.PI),[y,b,o,c,E,I,u,l]}};sN.prototype.className="Path";sN.prototype._attrsAffectingSize=["data"];sx(sN);xn.addGetterSetter(sN,"data");class nz extends VE{_sceneFunc(t){super._sceneFunc(t);const n=Math.PI*2,r=this.points();let a=r;const i=this.tension()!==0&&r.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=r.length;let c,d;if(i){const m=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],p=sN.calcLength(a[a.length-4],a[a.length-3],"C",m),f=sN.getPointOnQuadraticBezier(Math.min(1,1-l/p),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-f.x,d=r[o-1]-f.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}}}nz.prototype.className="Arrow";sx(nz);xn.addGetterSetter(nz,"pointerLength",10,mi());xn.addGetterSetter(nz,"pointerWidth",10,mi());xn.addGetterSetter(nz,"pointerAtBeginning",!1);xn.addGetterSetter(nz,"pointerAtEnding",!0);class PW extends ai{_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)}}PW.prototype._centroid=!0;PW.prototype.className="Circle";PW.prototype._attrsAffectingSize=["radius"];sx(PW);xn.addGetterSetter(PW,"radius",0,mi());class LL extends ai{_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)}}LL.prototype.className="Ellipse";LL.prototype._centroid=!0;LL.prototype._attrsAffectingSize=["radiusX","radiusY"];sx(LL);xn.addComponentsGetterSetter(LL,"radius",["x","y"]);xn.addGetterSetter(LL,"radiusX",0,mi());xn.addGetterSetter(LL,"radiusY",0,mi());let US=class oVt extends ai{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?rr.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?rr.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=rr.createImageElement();a.onload=function(){const i=new oVt({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};US.prototype.className="Image";US.prototype._attrsAffectingSize=["image"];sx(US);xn.addGetterSetter(US,"cornerRadius",0,sIe(4));xn.addGetterSetter(US,"image");xn.addComponentsGetterSetter(US,"crop",["x","y","width","height"]);xn.addGetterSetter(US,"cropX",0,mi());xn.addGetterSetter(US,"cropY",0,mi());xn.addGetterSetter(US,"cropWidth",0,mi());xn.addGetterSetter(US,"cropHeight",0,mi());const lVt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],wnn="Change.konva",jnn="none",HHe="up",GHe="right",WHe="down",KHe="left",Nnn=lVt.length;let ast=class extends YH{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)}}IL.prototype.className="RegularPolygon";IL.prototype._centroid=!0;IL.prototype._attrsAffectingSize=["radius"];sx(IL);xn.addGetterSetter(IL,"radius",0,mi());xn.addGetterSetter(IL,"sides",0,mi());xn.addGetterSetter(IL,"cornerRadius",0,sIe(4));const Pvt=Math.PI*2;class az extends ai{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,Pvt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),Pvt,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)}}az.prototype.className="Ring";az.prototype._centroid=!0;az.prototype._attrsAffectingSize=["innerRadius","outerRadius"];sx(az);xn.addGetterSetter(az,"innerRadius",0,mi());xn.addGetterSetter(az,"outerRadius",0,mi());class MC extends ai{constructor(t){super(t),this._updated=!0,this.anim=new tN(()=>{const n=this._updated;return this._updated=!1,n}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],h=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),h)if(l){const m=l[n],p=r*2;t.drawImage(h,o,c,d,u,m[p+0],m[p+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const OB="auto",knn="center",cVt="inherit",aZ="justify",Snn="Change.konva",dVt="2d",Lvt="-",uVt="left",Cnn="text",Ann="Text",Enn="top",Tnn="bottom",Ivt="middle",hVt="normal",Mnn="px ",bce=" ",Pnn="right",Dvt="rtl",Lnn="word",Inn="char",Rvt="none",b9e="…",mVt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Dnn=mVt.length;let iZ=null;function Rnn(){if(iZ!==null)return iZ;iZ=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(dVt);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){iZ=!0;break}}}catch{}return iZ}function Fnn(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 _ce;function _9e(){return _ce||(_ce=rr.createCanvasElement().getContext(dVt),_ce)}function Onn(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function znn(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Bnn(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let dp=class extends ai{constructor(t){super(Bnn(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nte+r6(ce.text).length,0),J=Z+ae;g({char:oe,index:J,x:M,y:E+I,lineIndex:C,column:Z,isLastInLine:G,width:this.measureSize(oe).width,context:t})}t.fillStrokeShape(this),g&&t.restore(),M+=this.measureSize(oe).width+f}}else f!==0&&t.setAttr("letterSpacing",`${f}px`),this._partialTextX=M,this._partialTextY=E+I,this._partialText=F,t.fillStrokeShape(this);if(S){t.save(),t.beginPath();const H=bi.legacyTextRendering?0:-Math.round(o/4),K=V;t.moveTo(K,E+I+H);const Z=m===aZ&&!G?p-l*2:q;t.lineTo(K+Math.round(Z),E+I+H),t.lineWidth=o/15;const oe=this._getLinearGradient();t.strokeStyle=oe||v,t.stroke(),t.restore()}t.restore(),i>1&&(E+=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=rr._isString(t)?t:t==null?"":t+"";return this._setAttr(Cnn,n),this}getWidth(){return this.attrs.width===OB||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===OB||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return rr.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,m;let p=_9e(),f=this.fontSize(),g;p.save(),p.font=this._getContextFont(),g=p.measureText(t),p.restore();const v=f/100;return{actualBoundingBoxAscent:(n=g.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*v,actualBoundingBoxDescent:(r=g.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=g.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*v,actualBoundingBoxRight:(i=g.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*v,alphabeticBaseline:(l=g.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=g.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(c=g.emHeightDescent)!==null&&c!==void 0?c:-20*v,fontBoundingBoxAscent:(d=g.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*v,fontBoundingBoxDescent:(u=g.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(h=g.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*v,ideographicBaseline:(m=g.ideographicBaseline)!==null&&m!==void 0?m:-21*v,width:g.width,height:f}}_getContextFont(){return this.fontStyle()+bce+this.fontVariant()+bce+(this.fontSize()+Mnn)+Fnn(this.fontFamily())}_addTextLine(t){this.align()===aZ&&(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 _9e().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!==OB&&i!==void 0,c=l!==OB&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,p=this.wrap(),f=p!==Rvt,g=p!==Inn&&f,v=this.ellipsis();this.textArr=[],_9e().font=this._getContextFont();const y=v?this._getTextWidth(b9e):0;for(let b=0,w=t.length;bu)for(;S.length>0;){let E=0,P=r6(S).length,M="",I=0;for(;E>>1,F=r6(S),q=F.slice(0,D+1).join(""),G=this._getTextWidth(q);(v&&c&&m+a>h?G+y:G)<=u?(E=D+1,M=q,I=G):P=D}if(M){if(g){const q=r6(S),G=r6(M),V=q[G.length],H=V===bce||V===Lvt;let K;if(H&&I<=u)K=G.length;else{const Z=G.lastIndexOf(bce),oe=G.lastIndexOf(Lvt);K=Math.max(Z,oe)+1}K>0&&(E=K,M=q.slice(0,E).join(""),I=this._getTextWidth(M))}if(M=M.trimRight(),this._addTextLine(M),r=Math.max(r,I),m+=a,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(S=r6(S).slice(E).join("").trimLeft(),S.length>0&&(C=this._getTextWidth(S),C<=u)){this._addTextLine(S),m+=a,r=Math.max(r,C);break}}else break}else this._addTextLine(S),m+=a,r=Math.max(r,C),this._shouldHandleEllipsis(m)&&bh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==OB&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==Rvt)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==OB&&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+b9e)n?null:sN.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=sN.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&&y-this.pathLength<=d?this.pathLength:y);if(!b)return;const w=sN.getLineLength(f.x,f.y,b.x,b.y);let S=0;if(c)try{S=c(n[p-1].char,g)*this.fontSize()}catch{S=0}f.x+=S,b.x+=S,this.textWidth+=S;const C=sN.getPointOnLine(S+w/2,f.x,f.y,b.x,b.y),E=Math.atan2(b.y-f.y,b.x-f.x);this.glyphInfo.push({transposeX:C.x,transposeY:C.y,text:t[p],rotation:E,p0:f,p1:b,width:w}),m+=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+`.${gVt}`).join(" "),Fvt="nodesRect",qnn=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Vnn={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Hnn="ontouchstart"in bi._global;function Gnn(s,t,n){if(s==="rotater")return n;t+=rr.degToRad(Vnn[s]||0);const r=(rr.radToDeg(t)%360+360)%360;return rr._inRange(r,315+22.5,360)||rr._inRange(r,0,22.5)?"ns-resize":rr._inRange(r,45-22.5,45+22.5)?"nesw-resize":rr._inRange(r,90-22.5,90+22.5)?"ew-resize":rr._inRange(r,135-22.5,135+22.5)?"nwse-resize":rr._inRange(r,180-22.5,180+22.5)?"ns-resize":rr._inRange(r,225-22.5,225+22.5)?"nesw-resize":rr._inRange(r,270-22.5,270+22.5)?"ew-resize":rr._inRange(r,315-22.5,315+22.5)?"nwse-resize":(rr.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const FEe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],Ovt=1e8;function Wnn(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 yVt(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 Knn(s,t){const n=Wnn(s);return yVt(s,t,n)}function Ynn(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(rr.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(qnn.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(Fvt),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Fvt,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=(bi.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 yVt(u,-bi.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-Ovt,y:-Ovt,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],m=d.getAbsoluteTransform();h.forEach(function(p){const f=m.point(p);n.push(f)})});const r=new sj;r.rotate(-bi.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:bi.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(),FEe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new Tae({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Hnn?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=bi.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=Gnn(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 ai({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=rr.degToRad(c),h=Math.sin(u),m=-Math.cos(u),p=l/2,f=o/2;let g=1/0;m<0?g=Math.min(g,-f/m):m>0&&(g=Math.min(g,(o-f)/m)),h<0?g=Math.min(g,-p/h):h>0&&(g=Math.min(g,(l-p)/h));const v=p+h*g,y=f+m*g,b=rr._sign(o),w=v+h*d*b,S=y+m*d*b;n.moveTo(v,y),n.lineTo(w,S)}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},YHe++,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 b=this._getNodeRect();n=i.x()-b.width/2,r=-i.y()+b.height/2;const w=bi.getAngle(this.rotateAnchorAngle());let S=Math.atan2(-r,n)+Math.PI/2-w;b.height<0&&(S-=Math.PI);const E=bi.getAngle(this.rotation())+S,P=bi.getAngle(this.rotationSnapTolerance()),I=Ynn(this.rotationSnaps(),E,P)-b.rotation,D=Knn(b,I);this._fitNodesInto(D,t);return}const h=this.shiftBehavior();let m;h==="inverted"?m=this.keepRatio()&&!t.shiftKey:h==="none"?m=this.keepRatio():m=this.keepRatio()||t.shiftKey;let p=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(b.y-i.y(),2));const w=this.findOne(".top-left").x()>b.x?-1:1,S=this.findOne(".top-left").y()>b.y?-1:1;n=a*this.cos*w,r=a*this.sin*S,this.findOne(".top-left").x(b.x-n),this.findOne(".top-left").y(b.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-b.x,2)+Math.pow(b.y-i.y(),2));const w=this.findOne(".top-right").x()b.y?-1:1;n=a*this.cos*w,r=a*this.sin*S,this.findOne(".top-right").x(b.x+n),this.findOne(".top-right").y(b.y-r)}var f=i.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){const b=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(b.x-i.x(),2)+Math.pow(i.y()-b.y,2));const w=b.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(rr._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(rr._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new sj;if(i.rotate(bi.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const m=i.point({x:-this.padding()*2,y:0});t.x+=m.x,t.y+=m.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const m=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const m=i.point({x:0,y:-this.padding()*2});t.x+=m.x,t.y+=m.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const m=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const m=this.boundBoxFunc()(r,t);m?t=m:rr.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new sj;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new sj,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(m=>{var p;if(!m.getStage())return;const f=m.getParent().getAbsoluteTransform(),g=m.getTransform().copy();g.translate(m.offsetX(),m.offsetY());const v=new sj;v.multiply(f.copy().invert()).multiply(h).multiply(f).multiply(g);const y=v.decompose();m.setAttrs(y),(p=m.getLayer())===null||p===void 0||p.batchDraw()}),this.rotation(rr._getRotation(t.rotation)),this._nodes.forEach(m=>{this._fire("transform",{evt:n,target:m}),m._fire("transform",{evt:n,target:m})}),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(rr._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(E=>{E.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),h=this.rotateAnchorOffset(),m=rr.degToRad(u),p=Math.sin(m),f=-Math.cos(m),g=r/2,v=a/2;let y=1/0;f<0?y=Math.min(y,-v/f):f>0&&(y=Math.min(y,(a-v)/f)),p<0?y=Math.min(y,-g/p):p>0&&(y=Math.min(y,(r-g)/p));const b=g+p*y,w=v+f*y,S=rr._sign(a);this._batchChangeChild(".rotater",{x:b+p*h*S,y:w+f*h*S-o*f,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(E=>E.draggable()),x:0,y:0});const C=this.anchorStyleFunc();C&&d.forEach(E=>{C(E)}),(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=""),YH.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(rr.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return Ci.prototype.toObject.call(this)}clone(t){return Ci.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};ou.isTransforming=()=>YHe>0;function Znn(s){return s instanceof Array||rr.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){FEe.indexOf(t)===-1&&rr.warn("Unknown anchor name: "+t+". Available names are: "+FEe.join(", "))}),s||[]}ou.prototype.className="Transformer";sx(ou);xn.addGetterSetter(ou,"enabledAnchors",FEe,Znn);xn.addGetterSetter(ou,"flipEnabled",!0,$S());xn.addGetterSetter(ou,"resizeEnabled",!0);xn.addGetterSetter(ou,"anchorSize",10,mi());xn.addGetterSetter(ou,"rotateEnabled",!0);xn.addGetterSetter(ou,"rotateLineVisible",!0);xn.addGetterSetter(ou,"rotationSnaps",[]);xn.addGetterSetter(ou,"rotateAnchorOffset",50,mi());xn.addGetterSetter(ou,"rotateAnchorAngle",0,mi());xn.addGetterSetter(ou,"rotateAnchorCursor","crosshair");xn.addGetterSetter(ou,"rotationSnapTolerance",5,mi());xn.addGetterSetter(ou,"borderEnabled",!0);xn.addGetterSetter(ou,"anchorStroke","rgb(0, 161, 255)");xn.addGetterSetter(ou,"anchorStrokeWidth",1,mi());xn.addGetterSetter(ou,"anchorFill","white");xn.addGetterSetter(ou,"anchorCornerRadius",0,mi());xn.addGetterSetter(ou,"borderStroke","rgb(0, 161, 255)");xn.addGetterSetter(ou,"borderStrokeWidth",1,mi());xn.addGetterSetter(ou,"borderDash");xn.addGetterSetter(ou,"keepRatio",!0);xn.addGetterSetter(ou,"shiftBehavior","default");xn.addGetterSetter(ou,"centeredScaling",!1);xn.addGetterSetter(ou,"ignoreStroke",!1);xn.addGetterSetter(ou,"padding",0,mi());xn.addGetterSetter(ou,"nodes");xn.addGetterSetter(ou,"node");xn.addGetterSetter(ou,"boundBoxFunc");xn.addGetterSetter(ou,"anchorDragBoundFunc");xn.addGetterSetter(ou,"anchorStyleFunc");xn.addGetterSetter(ou,"shouldOverdrawWholeArea",!1);xn.addGetterSetter(ou,"useSingleNodeRotation",!0);xn.backCompat(ou,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class HE extends ai{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,bi.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)}}HE.prototype.className="Wedge";HE.prototype._centroid=!0;HE.prototype._attrsAffectingSize=["radius"];sx(HE);xn.addGetterSetter(HE,"radius",0,mi());xn.addGetterSetter(HE,"angle",0,mi());xn.addGetterSetter(HE,"clockwise",!1);xn.backCompat(HE,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function zvt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Xnn=[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],Qnn=[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 Jnn(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,p,f,g,v,y,b,w,S,C,E,P,M;const I=t+t+1,D=r-1,F=a-1,q=t+1,G=q*(q+1)/2,V=new zvt,H=Xnn[t],K=Qnn[t];let Z=null,oe=V,re=null,ae=null;for(let J=1;J>K,P!==0?(P=255/P,n[l]=(c*H>>K)*P,n[l+1]=(d*H>>K)*P,n[l+2]=(u*H>>K)*P):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=p,u-=f,h-=g,m-=re.r,p-=re.g,f-=re.b,g-=re.a,i=o+((i=te+t+1)>K,P>0?(P=255/P,n[i]=(c*H>>K)*P,n[i+1]=(d*H>>K)*P,n[i+2]=(u*H>>K)*P):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=p,u-=f,h-=g,m-=re.r,p-=re.g,f-=re.b,g-=re.a,i=J+((i=ce+q)0&&Jnn(t,n)};xn.addGetterSetter(Ci,"blurRadius",0,mi(),xn.afterSetFilter);const trn=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};xn.addGetterSetter(Ci,"contrast",0,mi(),xn.afterSetFilter);const rrn=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,p=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),f=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,y=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),b=p*10,w=f*255,S=v*Math.PI/180,C=Math.cos(S),E=Math.sin(S),P=128/1020*b,M=new Uint8ClampedArray(u),I=new Float32Array(h*m);for(let V=0,H=0;HV<0?0:V>255?255:V;for(let V=1;Va&&(a=i),c=t[w+1],co&&(o=c),h=t[w+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let p,f,g,v,y,b;if(m>0)p=a+m*(255-a),f=r-m*(r-0),g=o+m*(255-o),v=l-m*(l-0),y=u+m*(255-u),b=d-m*(d-0);else{const w=(a+r)*.5;p=a+m*(a-w),f=r+m*(r-w);const S=(o+l)*.5;g=o+m*(o-S),v=l+m*(l-S);const C=(u+d)*.5;y=u+m*(u-C),b=d+m*(d-C)}for(let w=0;wd?m:d;const p=l,f=i,g=360/f*Math.PI/180;for(let v=0;vd?m:d;const p=l,f=i,g=0;let v,y;for(u=0;ut&&(S=w,C=0,E=-1),a=0;a=0&&p=0&&f=0&&p=0&&f=255*4?255:0}return l}function yrn(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&p=0&&f=n))for(let w=g;w=r)continue;const S=(n*w+b)*4;d+=l[S+0],u+=l[S+1],h+=l[S+2],m+=l[S+3],y+=1}d=d/y,u=u/y,h=h/y,m=m/y;for(let b=p;b=n))for(let w=g;w=r)continue;const S=(n*w+b)*4;l[S+0]=d,l[S+1]=u,l[S+2]=h,l[S+3]=m}}};xn.addGetterSetter(Ci,"pixelSize",8,mi(),xn.afterSetFilter);const wrn=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)});xn.addGetterSetter(Ci,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});xn.addGetterSetter(Ci,"blue",0,Bqt,xn.afterSetFilter);const Nrn=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)});xn.addGetterSetter(Ci,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});xn.addGetterSetter(Ci,"blue",0,Bqt,xn.afterSetFilter);xn.addGetterSetter(Ci,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const krn=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},Crn=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aQn||dt[Hs]!==Pt[Qn]){var Br=` `+dt[Hs].replace(" at new "," at ");return ie.displayName&&Br.includes("")&&(Br=Br.replace("",ie.displayName)),Br}while(1<=Hs&&0<=Qn);break}}}finally{Kr=!1,Error.prepareStackTrace=Re}return(ie=ie?ie.displayName||ie.name:"")?aa(ie):""}var Hr=Object.prototype.hasOwnProperty,Ba=[],Ja=-1;function Ro(ie){return{current:ie}}function ji(ie){0>Ja||(ie.current=Ba[Ja],Ba[Ja]=null,Ja--)}function Oa(ie,de){Ja++,Ba[Ja]=ie.current,ie.current=de}var Ao={},uo=Ro(Ao),Ua=Ro(!1),Eo=Ao;function Ji(ie,de){var Re=ie.type.contextTypes;if(!Re)return Ao;var st=ie.stateNode;if(st&&st.__reactInternalMemoizedUnmaskedChildContext===de)return st.__reactInternalMemoizedMaskedChildContext;var dt={},Pt;for(Pt in Re)dt[Pt]=de[Pt];return st&&(ie=ie.stateNode,ie.__reactInternalMemoizedUnmaskedChildContext=de,ie.__reactInternalMemoizedMaskedChildContext=dt),dt}function qa(ie){return ie=ie.childContextTypes,ie!=null}function ar(){ji(Ua),ji(uo)}function ui(ie,de,Re){if(uo.current!==Ao)throw Error(l(168));Oa(uo,de),Oa(Ua,Re)}function zo(ie,de,Re){var st=ie.stateNode;if(de=de.childContextTypes,typeof st.getChildContext!="function")return Re;st=st.getChildContext();for(var dt in st)if(!(dt in de))throw Error(l(108,M(ie)||"Unknown",dt));return i({},Re,st)}function gl(ie){return ie=(ie=ie.stateNode)&&ie.__reactInternalMemoizedMergedChildContext||Ao,Eo=uo.current,Oa(uo,ie),Oa(Ua,Ua.current),!0}function tl(ie,de,Re){var st=ie.stateNode;if(!st)throw Error(l(169));Re?(ie=zo(ie,de,Eo),st.__reactInternalMemoizedMergedChildContext=ie,ji(Ua),ji(uo),Oa(uo,ie)):ji(Ua),Oa(Ua,Re)}var Ll=Math.clz32?Math.clz32:ym,Ku=Math.log,uh=Math.LN2;function ym(ie){return ie>>>=0,ie===0?32:31-(Ku(ie)/uh|0)|0}var Ld=64,Bm=4194304;function Sl(ie){switch(ie&-ie){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 ie&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return ie&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return ie}}function wu(ie,de){var Re=ie.pendingLanes;if(Re===0)return 0;var st=0,dt=ie.suspendedLanes,Pt=ie.pingedLanes,Hs=Re&268435455;if(Hs!==0){var Qn=Hs&~dt;Qn!==0?st=Sl(Qn):(Pt&=Hs,Pt!==0&&(st=Sl(Pt)))}else Hs=Re&~dt,Hs!==0?st=Sl(Hs):Pt!==0&&(st=Sl(Pt));if(st===0)return 0;if(de!==0&&de!==st&&!(de&dt)&&(dt=st&-st,Pt=de&-de,dt>=Pt||dt===16&&(Pt&4194240)!==0))return de;if(st&4&&(st|=Re&16),de=ie.entangledLanes,de!==0)for(ie=ie.entanglements,de&=st;0Re;Re++)de.push(ie);return de}function ho(ie,de,Re){ie.pendingLanes|=de,de!==536870912&&(ie.suspendedLanes=0,ie.pingedLanes=0),ie=ie.eventTimes,de=31-Ll(de),ie[de]=Re}function pi(ie,de){var Re=ie.pendingLanes&~de;ie.pendingLanes=de,ie.suspendedLanes=0,ie.pingedLanes=0,ie.expiredLanes&=de,ie.mutableReadLanes&=de,ie.entangledLanes&=de,de=ie.entanglements;var st=ie.eventTimes;for(ie=ie.expirationTimes;0>=Hs,dt-=Hs,lu=1<<32-Ll(de)+dt|Re<Jl?(qp=bo,bo=null):qp=bo.sibling;var Ad=Ri(Ir,bo,Wn[Jl],Hi);if(Ad===null){bo===null&&(bo=qp);break}ie&&bo&&Ad.alternate===null&&de(Ir,bo),Ln=Pt(Ad,Ln,Jl),xl===null?ao=Ad:xl.sibling=Ad,xl=Ad,bo=qp}if(Jl===Wn.length)return Re(Ir,bo),Mn&&Um(Ir,Jl),ao;if(bo===null){for(;JlJl?(qp=bo,bo=null):qp=bo.sibling;var Zb=Ri(Ir,bo,Ad.value,Hi);if(Zb===null){bo===null&&(bo=qp);break}ie&&bo&&Zb.alternate===null&&de(Ir,bo),Ln=Pt(Zb,Ln,Jl),xl===null?ao=Zb:xl.sibling=Zb,xl=Zb,bo=qp}if(Ad.done)return Re(Ir,bo),Mn&&Um(Ir,Jl),ao;if(bo===null){for(;!Ad.done;Jl++,Ad=Wn.next())Ad=ic(Ir,Ad.value,Hi),Ad!==null&&(Ln=Pt(Ad,Ln,Jl),xl===null?ao=Ad:xl.sibling=Ad,xl=Ad);return Mn&&Um(Ir,Jl),ao}for(bo=st(Ir,bo);!Ad.done;Jl++,Ad=Wn.next())Ad=Ih(bo,Ir,Jl,Ad.value,Hi),Ad!==null&&(ie&&Ad.alternate!==null&&bo.delete(Ad.key===null?Jl:Ad.key),Ln=Pt(Ad,Ln,Jl),xl===null?ao=Ad:xl.sibling=Ad,xl=Ad);return ie&&bo.forEach(function(nI){return de(Ir,nI)}),Mn&&Um(Ir,Jl),ao}function K0(Ir,Ln,Wn,Hi){if(typeof Wn=="object"&&Wn!==null&&Wn.type===u&&Wn.key===null&&(Wn=Wn.props.children),typeof Wn=="object"&&Wn!==null){switch(Wn.$$typeof){case c:e:{for(var ao=Wn.key,xl=Ln;xl!==null;){if(xl.key===ao){if(ao=Wn.type,ao===u){if(xl.tag===7){Re(Ir,xl.sibling),Ln=dt(xl,Wn.props.children),Ln.return=Ir,Ir=Ln;break e}}else if(xl.elementType===ao||typeof ao=="object"&&ao!==null&&ao.$$typeof===w&&An(ao)===xl.type){Re(Ir,xl.sibling),Ln=dt(xl,Wn.props),Ln.ref=em(Ir,xl,Wn),Ln.return=Ir,Ir=Ln;break e}Re(Ir,xl);break}else de(Ir,xl);xl=xl.sibling}Wn.type===u?(Ln=Ws(Wn.props.children,Ir.mode,Hi,Wn.key),Ln.return=Ir,Ir=Ln):(Hi=ld(Wn.type,Wn.key,Wn.props,null,Ir.mode,Hi),Hi.ref=em(Ir,Ln,Wn),Hi.return=Ir,Ir=Hi)}return Hs(Ir);case d:e:{for(xl=Wn.key;Ln!==null;){if(Ln.key===xl)if(Ln.tag===4&&Ln.stateNode.containerInfo===Wn.containerInfo&&Ln.stateNode.implementation===Wn.implementation){Re(Ir,Ln.sibling),Ln=dt(Ln,Wn.children||[]),Ln.return=Ir,Ir=Ln;break e}else{Re(Ir,Ln);break}else de(Ir,Ln);Ln=Ln.sibling}Ln=n3(Wn,Ir.mode,Hi),Ln.return=Ir,Ir=Ln}return Hs(Ir);case w:return xl=Wn._init,K0(Ir,Ln,xl(Wn._payload),Hi)}if(H(Wn))return oc(Ir,Ln,Wn,Hi);if(E(Wn))return Kx(Ir,Ln,Wn,Hi);Gt(Ir,Wn)}return typeof Wn=="string"&&Wn!==""||typeof Wn=="number"?(Wn=""+Wn,Ln!==null&&Ln.tag===6?(Re(Ir,Ln.sibling),Ln=dt(Ln,Wn),Ln.return=Ir,Ir=Ln):(Re(Ir,Ln),Ln=d5(Wn,Ir.mode,Hi),Ln.return=Ir,Ir=Ln),Hs(Ir)):Re(Ir,Ln)}return K0}var qr=qn(!0),Pa=qn(!1),vi=Ro(null),Li=null,wi=null,rd=null;function Au(){rd=wi=Li=null}function pp(ie,de,Re){Pe?(Oa(vi,de._currentValue),de._currentValue=Re):(Oa(vi,de._currentValue2),de._currentValue2=Re)}function gd(ie){var de=vi.current;ji(vi),Pe?ie._currentValue=de:ie._currentValue2=de}function Hd(ie,de,Re){for(;ie!==null;){var st=ie.alternate;if((ie.childLanes&de)!==de?(ie.childLanes|=de,st!==null&&(st.childLanes|=de)):st!==null&&(st.childLanes&de)!==de&&(st.childLanes|=de),ie===Re)break;ie=ie.return}}function Th(ie,de){Li=ie,rd=wi=null,ie=ie.dependencies,ie!==null&&ie.firstContext!==null&&(ie.lanes&de&&(ox=!0),ie.firstContext=null)}function Rp(ie){var de=Pe?ie._currentValue:ie._currentValue2;if(rd!==ie)if(ie={context:ie,memoizedValue:de,next:null},wi===null){if(Li===null)throw Error(l(308));wi=ie,Li.dependencies={lanes:0,firstContext:ie}}else wi=wi.next=ie;return de}var qx=null;function ac(ie){qx===null?qx=[ie]:qx.push(ie)}function $a(ie,de,Re,st){var dt=de.interleaved;return dt===null?(Re.next=Re,ac(de)):(Re.next=dt.next,dt.next=Re),de.interleaved=Re,Yr(ie,st)}function Yr(ie,de){ie.lanes|=de;var Re=ie.alternate;for(Re!==null&&(Re.lanes|=de),Re=ie,ie=ie.return;ie!==null;)ie.childLanes|=de,Re=ie.alternate,Re!==null&&(Re.childLanes|=de),Re=ie,ie=ie.return;return Re.tag===3?Re.stateNode:null}var Tc=!1;function Va(ie){ie.updateQueue={baseState:ie.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Fp(ie,de){ie=ie.updateQueue,de.updateQueue===ie&&(de.updateQueue={baseState:ie.baseState,firstBaseUpdate:ie.firstBaseUpdate,lastBaseUpdate:ie.lastBaseUpdate,shared:ie.shared,effects:ie.effects})}function cu(ie,de){return{eventTime:ie,lane:de,tag:0,payload:null,callback:null,next:null}}function ba(ie,de,Re){var st=ie.updateQueue;if(st===null)return null;if(st=st.shared,$o&2){var dt=st.pending;return dt===null?de.next=de:(de.next=dt.next,dt.next=de),st.pending=de,Yr(ie,Re)}return dt=st.interleaved,dt===null?(de.next=de,ac(st)):(de.next=dt.next,dt.next=de),st.interleaved=de,Yr(ie,Re)}function Zg(ie,de,Re){if(de=de.updateQueue,de!==null&&(de=de.shared,(Re&4194240)!==0)){var st=de.lanes;st&=ie.pendingLanes,Re|=st,de.lanes=Re,$m(ie,Re)}}function qy(ie,de){var Re=ie.updateQueue,st=ie.alternate;if(st!==null&&(st=st.updateQueue,Re===st)){var dt=null,Pt=null;if(Re=Re.firstBaseUpdate,Re!==null){do{var Hs={eventTime:Re.eventTime,lane:Re.lane,tag:Re.tag,payload:Re.payload,callback:Re.callback,next:null};Pt===null?dt=Pt=Hs:Pt=Pt.next=Hs,Re=Re.next}while(Re!==null);Pt===null?dt=Pt=de:Pt=Pt.next=de}else dt=Pt=de;Re={baseState:st.baseState,firstBaseUpdate:dt,lastBaseUpdate:Pt,shared:st.shared,effects:st.effects},ie.updateQueue=Re;return}ie=Re.lastBaseUpdate,ie===null?Re.firstBaseUpdate=de:ie.next=de,Re.lastBaseUpdate=de}function wg(ie,de,Re,st){var dt=ie.updateQueue;Tc=!1;var Pt=dt.firstBaseUpdate,Hs=dt.lastBaseUpdate,Qn=dt.shared.pending;if(Qn!==null){dt.shared.pending=null;var Br=Qn,Ka=Br.next;Br.next=null,Hs===null?Pt=Ka:Hs.next=Ka,Hs=Br;var no=ie.alternate;no!==null&&(no=no.updateQueue,Qn=no.lastBaseUpdate,Qn!==Hs&&(Qn===null?no.firstBaseUpdate=Ka:Qn.next=Ka,no.lastBaseUpdate=Br))}if(Pt!==null){var ic=dt.baseState;Hs=0,no=Ka=Br=null,Qn=Pt;do{var Ri=Qn.lane,Ih=Qn.eventTime;if((st&Ri)===Ri){no!==null&&(no=no.next={eventTime:Ih,lane:0,tag:Qn.tag,payload:Qn.payload,callback:Qn.callback,next:null});e:{var oc=ie,Kx=Qn;switch(Ri=de,Ih=Re,Kx.tag){case 1:if(oc=Kx.payload,typeof oc=="function"){ic=oc.call(Ih,ic,Ri);break e}ic=oc;break e;case 3:oc.flags=oc.flags&-65537|128;case 0:if(oc=Kx.payload,Ri=typeof oc=="function"?oc.call(Ih,ic,Ri):oc,Ri==null)break e;ic=i({},ic,Ri);break e;case 2:Tc=!0}}Qn.callback!==null&&Qn.lane!==0&&(ie.flags|=64,Ri=dt.effects,Ri===null?dt.effects=[Qn]:Ri.push(Qn))}else Ih={eventTime:Ih,lane:Ri,tag:Qn.tag,payload:Qn.payload,callback:Qn.callback,next:null},no===null?(Ka=no=Ih,Br=ic):no=no.next=Ih,Hs|=Ri;if(Qn=Qn.next,Qn===null){if(Qn=dt.shared.pending,Qn===null)break;Ri=Qn,Qn=Ri.next,Ri.next=null,dt.lastBaseUpdate=Ri,dt.shared.pending=null}}while(!0);if(no===null&&(Br=ic),dt.baseState=Br,dt.firstBaseUpdate=Ka,dt.lastBaseUpdate=no,de=dt.shared.interleaved,de!==null){dt=de;do Hs|=dt.lane,dt=dt.next;while(dt!==de)}else Pt===null&&(dt.shared.lanes=0);I1|=Hs,ie.lanes=Hs,ie.memoizedState=ic}}function F0(ie,de,Re){if(ie=de.effects,de.effects=null,ie!==null)for(de=0;deRe?Re:4,ie(!0);var st=Fb.transition;Fb.transition={};try{ie(!1),de()}finally{al=Re,Fb.transition=st}}function XS(){return xh().memoizedState}function WC(ie,de,Re){var st=H0(ie);if(Re={lane:st,action:Re,hasEagerState:!1,eagerState:null,next:null},KC(ie))tT(de,Re);else if(Re=$a(ie,de,Re,st),Re!==null){var dt=yh();Wx(Re,ie,st,dt),vd(Re,de,st)}}function XL(ie,de,Re){var st=H0(ie),dt={lane:st,action:Re,hasEagerState:!1,eagerState:null,next:null};if(KC(ie))tT(de,dt);else{var Pt=ie.alternate;if(ie.lanes===0&&(Pt===null||Pt.lanes===0)&&(Pt=de.lastRenderedReducer,Pt!==null))try{var Hs=de.lastRenderedState,Qn=Pt(Hs,Re);if(dt.hasEagerState=!0,dt.eagerState=Qn,hh(Qn,Hs)){var Br=de.interleaved;Br===null?(dt.next=dt,ac(de)):(dt.next=Br.next,Br.next=dt),de.interleaved=dt;return}}catch{}finally{}Re=$a(ie,de,dt,st),Re!==null&&(dt=yh(),Wx(Re,ie,st,dt),vd(Re,de,st))}}function KC(ie){var de=ie.alternate;return ie===Mc||de!==null&&de===Mc}function tT(ie,de){Wd=qu=!0;var Re=ie.pending;Re===null?de.next=de:(de.next=Re.next,Re.next=de),ie.pending=de}function vd(ie,de,Re){if(Re&4194240){var st=de.lanes;st&=ie.pendingLanes,Re|=st,de.lanes=Re,$m(ie,Re)}}var lw={readContext:Rp,useCallback:wm,useContext:wm,useEffect:wm,useImperativeHandle:wm,useInsertionEffect:wm,useLayoutEffect:wm,useMemo:wm,useReducer:wm,useRef:wm,useState:wm,useDebugValue:wm,useDeferredValue:wm,useTransition:wm,useMutableSource:wm,useSyncExternalStore:wm,useId:wm,unstable_isNewReconciler:!1},YC={readContext:Rp,useCallback:function(ie,de){return Jg().memoizedState=[ie,de===void 0?null:de],ie},useContext:Rp,useEffect:P1,useImperativeHandle:function(ie,de,Re){return Re=Re!=null?Re.concat([ie]):null,Bb(4194308,4,ow.bind(null,de,ie),Re)},useLayoutEffect:function(ie,de){return Bb(4194308,4,ie,de)},useInsertionEffect:function(ie,de){return Bb(4,2,ie,de)},useMemo:function(ie,de){var Re=Jg();return de=de===void 0?null:de,ie=ie(),Re.memoizedState=[ie,de],ie},useReducer:function(ie,de,Re){var st=Jg();return de=Re!==void 0?Re(de):de,st.memoizedState=st.baseState=de,ie={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ie,lastRenderedState:de},st.queue=ie,ie=ie.dispatch=WC.bind(null,Mc,ie),[st.memoizedState,ie]},useRef:function(ie){var de=Jg();return ie={current:ie},de.memoizedState=ie},useState:gf,useDebugValue:sk,useDeferredValue:function(ie){return Jg().memoizedState=ie},useTransition:function(){var ie=gf(!1),de=ie[0];return ie=Mo.bind(null,ie[1]),Jg().memoizedState=ie,[de,ie]},useMutableSource:function(){},useSyncExternalStore:function(ie,de,Re){var st=Mc,dt=Jg();if(Mn){if(Re===void 0)throw Error(l(407));Re=Re()}else{if(Re=de(),Cd===null)throw Error(l(349));fh&30||ek(st,de,Re)}dt.memoizedState=Re;var Pt={value:Re,getSnapshot:de};return dt.queue=Pt,P1(zb.bind(null,st,Pt,ie),[ie]),st.flags|=2048,jm(9,Ob.bind(null,st,Pt,Re,de),void 0,null),Re},useId:function(){var ie=Jg(),de=Cd.identifierPrefix;if(Mn){var Re=mp,st=lu;Re=(st&~(1<<32-Ll(st)-1)).toString(32)+Re,de=":"+de+"R"+Re,Re=Qg++,0Wy&&(de.flags|=128,st=!0,Dn(dt,!1),de.lanes=4194304)}else{if(!st)if(ie=Xg(Pt),ie!==null){if(de.flags|=128,st=!0,ie=ie.updateQueue,ie!==null&&(de.updateQueue=ie,de.flags|=4),Dn(dt,!0),dt.tail===null&&dt.tailMode==="hidden"&&!Pt.alternate&&!Mn)return Jn(de),null}else 2*zc()-dt.renderingStartTime>Wy&&Re!==1073741824&&(de.flags|=128,st=!0,Dn(dt,!1),de.lanes=4194304);dt.isBackwards?(Pt.sibling=de.child,de.child=Pt):(ie=dt.last,ie!==null?ie.sibling=Pt:de.child=Pt,dt.last=Pt)}return dt.tail!==null?(de=dt.tail,dt.rendering=de,dt.tail=de.sibling,dt.renderingStartTime=zc(),de.sibling=null,ie=yd.current,Oa(yd,st?ie&1|2:ie&1),de):(Jn(de),null);case 22:case 23:return O1(),Re=de.memoizedState!==null,ie!==null&&ie.memoizedState!==null!==Re&&(de.flags|=8192),Re&&de.mode&1?xp&1073741824&&(Jn(de),Oe&&de.subtreeFlags&6&&(de.flags|=8192)):Jn(de),null;case 24:return null;case 25:return null}throw Error(l(156,de.tag))}function Hn(ie,de){switch(ts(de),de.tag){case 1:return qa(de.type)&&ar(),ie=de.flags,ie&65536?(de.flags=ie&-65537|128,de):null;case 3:return xf(),ji(Ua),ji(uo),_m(),ie=de.flags,ie&65536&&!(ie&128)?(de.flags=ie&-65537|128,de):null;case 5:return M1(de),null;case 13:if(ji(yd),ie=de.memoizedState,ie!==null&&ie.dehydrated!==null){if(de.alternate===null)throw Error(l(340));gi()}return ie=de.flags,ie&65536?(de.flags=ie&-65537|128,de):null;case 19:return ji(yd),null;case 4:return xf(),null;case 10:return gd(de.type._context),null;case 22:case 23:return O1(),null;case 24:return null;default:return null}}var ir=!1,Dr=!1,Nr=typeof WeakSet=="function"?WeakSet:Set,Gn=null;function Gr(ie,de){var Re=ie.ref;if(Re!==null)if(typeof Re=="function")try{Re(null)}catch(st){Vi(ie,de,st)}else Re.current=null}function Ca(ie,de,Re){try{Re()}catch(st){Vi(ie,de,st)}}var _a=!1;function ro(ie,de){for(re(ie.containerInfo),Gn=de;Gn!==null;)if(ie=Gn,de=ie.child,(ie.subtreeFlags&1028)!==0&&de!==null)de.return=ie,Gn=de;else for(;Gn!==null;){ie=Gn;try{var Re=ie.alternate;if(ie.flags&1024)switch(ie.tag){case 0:case 11:case 15:break;case 1:if(Re!==null){var st=Re.memoizedProps,dt=Re.memoizedState,Pt=ie.stateNode,Hs=Pt.getSnapshotBeforeUpdate(ie.elementType===ie.type?st:Hy(ie.type,st),dt);Pt.__reactInternalSnapshotBeforeUpdate=Hs}break;case 3:Oe&&Fs(ie.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(Qn){Vi(ie,ie.return,Qn)}if(de=ie.sibling,de!==null){de.return=ie.return,Gn=de;break}Gn=ie.return}return Re=_a,_a=!1,Re}function Oi(ie,de,Re){var st=de.updateQueue;if(st=st!==null?st.lastEffect:null,st!==null){var dt=st=st.next;do{if((dt.tag&ie)===ie){var Pt=dt.destroy;dt.destroy=void 0,Pt!==void 0&&Ca(de,Re,Pt)}dt=dt.next}while(dt!==st)}}function Al(ie,de){if(de=de.updateQueue,de=de!==null?de.lastEffect:null,de!==null){var Re=de=de.next;do{if((Re.tag&ie)===ie){var st=Re.create;Re.destroy=st()}Re=Re.next}while(Re!==de)}}function Yi(ie){var de=ie.ref;if(de!==null){var Re=ie.stateNode;switch(ie.tag){case 5:ie=K(Re);break;default:ie=Re}typeof de=="function"?de(ie):de.current=ie}}function bc(ie){var de=ie.alternate;de!==null&&(ie.alternate=null,bc(de)),ie.child=null,ie.deletions=null,ie.sibling=null,ie.tag===5&&(de=ie.stateNode,de!==null&&We(de)),ie.stateNode=null,ie.return=null,ie.dependencies=null,ie.memoizedProps=null,ie.memoizedState=null,ie.pendingProps=null,ie.stateNode=null,ie.updateQueue=null}function Eu(ie){return ie.tag===5||ie.tag===3||ie.tag===4}function El(ie){e:for(;;){for(;ie.sibling===null;){if(ie.return===null||Eu(ie.return))return null;ie=ie.return}for(ie.sibling.return=ie.return,ie=ie.sibling;ie.tag!==5&&ie.tag!==6&&ie.tag!==18;){if(ie.flags&2||ie.child===null||ie.tag===4)continue e;ie.child.return=ie,ie=ie.child}if(!(ie.flags&2))return ie.stateNode}}function eo(ie,de,Re){var st=ie.tag;if(st===5||st===6)ie=ie.stateNode,de?qs(Re,ie,de):zt(Re,ie);else if(st!==4&&(ie=ie.child,ie!==null))for(eo(ie,de,Re),ie=ie.sibling;ie!==null;)eo(ie,de,Re),ie=ie.sibling}function fi(ie,de,Re){var st=ie.tag;if(st===5||st===6)ie=ie.stateNode,de?It(Re,ie,de):qt(Re,ie);else if(st!==4&&(ie=ie.child,ie!==null))for(fi(ie,de,Re),ie=ie.sibling;ie!==null;)fi(ie,de,Re),ie=ie.sibling}var Il=null,To=!1;function vl(ie,de,Re){for(Re=Re.child;Re!==null;)ju(ie,de,Re),Re=Re.sibling}function ju(ie,de,Re){if(Pi&&typeof Pi.onCommitFiberUnmount=="function")try{Pi.onCommitFiberUnmount(nx,Re)}catch{}switch(Re.tag){case 5:Dr||Gr(Re,de);case 6:if(Oe){var st=Il,dt=To;Il=null,vl(ie,de,Re),Il=st,To=dt,Il!==null&&(To?Us(Il,Re.stateNode):wt(Il,Re.stateNode))}else vl(ie,de,Re);break;case 18:Oe&&Il!==null&&(To?Vs(Il,Re.stateNode):Vt(Il,Re.stateNode));break;case 4:Oe?(st=Il,dt=To,Il=Re.stateNode.containerInfo,To=!0,vl(ie,de,Re),Il=st,To=dt):(ke&&(st=Re.stateNode.containerInfo,dt=lr(st),fs(st,dt)),vl(ie,de,Re));break;case 0:case 11:case 14:case 15:if(!Dr&&(st=Re.updateQueue,st!==null&&(st=st.lastEffect,st!==null))){dt=st=st.next;do{var Pt=dt,Hs=Pt.destroy;Pt=Pt.tag,Hs!==void 0&&(Pt&2||Pt&4)&&Ca(Re,de,Hs),dt=dt.next}while(dt!==st)}vl(ie,de,Re);break;case 1:if(!Dr&&(Gr(Re,de),st=Re.stateNode,typeof st.componentWillUnmount=="function"))try{st.props=Re.memoizedProps,st.state=Re.memoizedState,st.componentWillUnmount()}catch(Qn){Vi(Re,de,Qn)}vl(ie,de,Re);break;case 21:vl(ie,de,Re);break;case 22:Re.mode&1?(Dr=(st=Dr)||Re.memoizedState!==null,vl(ie,de,Re),Dr=st):vl(ie,de,Re);break;default:vl(ie,de,Re)}}function Vm(ie){var de=ie.updateQueue;if(de!==null){ie.updateQueue=null;var Re=ie.stateNode;Re===null&&(Re=ie.stateNode=new Nr),de.forEach(function(st){var dt=c5.bind(null,ie,st);Re.has(st)||(Re.add(st),st.then(dt,dt))})}}function Nu(ie,de){var Re=de.deletions;if(Re!==null)for(var st=0;st";case Mh:return":has("+(Tu(ie)||"")+")";case Op:return'[role="'+ie.value+'"]';case tm:return'"'+ie.value+'"';case Dd:return'[data-testname="'+ie.value+'"]';default:throw Error(l(365))}}function cx(ie,de){var Re=[];ie=[ie,0];for(var st=0;stdt&&(dt=Hs),st&=~Pt}if(st=dt,st=zc()-st,st=(120>st?120:480>st?480:1080>st?1080:1920>st?1920:3e3>st?3e3:4320>st?4320:1960*Bp(st/1960))-st,10ie?16:ie,kg===null)var st=!1;else{if(ie=kg,kg=null,mw=0,$o&6)throw Error(l(331));var dt=$o;for($o|=4,Gn=ie.current;Gn!==null;){var Pt=Gn,Hs=Pt.child;if(Gn.flags&16){var Qn=Pt.deletions;if(Qn!==null){for(var Br=0;Brzc()-l2?Ky(ie,0):D1|=Re),hx(ie,de)}function t3(ie,de){de===0&&(ie.mode&1?(de=Bm,Bm<<=1,!(Bm&130023424)&&(Bm=4194304)):de=1);var Re=yh();ie=Yr(ie,de),ie!==null&&(ho(ie,de,Re),hx(ie,Re))}function nT(ie){var de=ie.memoizedState,Re=0;de!==null&&(Re=de.retryLane),t3(ie,Re)}function c5(ie,de){var Re=0;switch(ie.tag){case 13:var st=ie.stateNode,dt=ie.memoizedState;dt!==null&&(Re=dt.retryLane);break;case 19:st=ie.stateNode;break;default:throw Error(l(314))}st!==null&&st.delete(de),t3(ie,Re)}var rT;rT=function(ie,de,Re){if(ie!==null)if(ie.memoizedProps!==de.pendingProps||Ua.current)ox=!0;else{if(!(ie.lanes&Re)&&!(de.flags&128))return ox=!1,xt(ie,de,Re);ox=!!(ie.flags&131072)}else ox=!1,Mn&&de.flags&1048576&&qm(de,R0,de.index);switch(de.lanes=0,de.tag){case 2:var st=de.type;Me(ie,de),ie=de.pendingProps;var dt=Ji(de,uo.current);Th(de,Re),dt=Zj(null,de,st,ie,dt,Re);var Pt=rw();return de.flags|=1,typeof dt=="object"&&dt!==null&&typeof dt.render=="function"&&dt.$$typeof===void 0?(de.tag=1,de.memoizedState=null,de.updateQueue=null,qa(st)?(Pt=!0,gl(de)):Pt=!1,de.memoizedState=dt.state!==null&&dt.state!==void 0?dt.state:null,Va(de),dt.updater=cw,de.stateNode=dt,dt._reactInternals=de,Gx(de,st,ie,Re),de=r2(null,de,st,!0,Pt,Re)):(de.tag=0,Mn&&Pt&&ot(de),yf(null,de,dt,Re),de=de.child),de;case 16:st=de.elementType;e:{switch(Me(ie,de),ie=de.pendingProps,dt=st._init,st=dt(st._payload),de.type=st,dt=de.tag=dr(st),ie=Hy(st,ie),dt){case 0:de=t5(null,de,st,ie,Re);break e;case 1:de=s5(null,de,st,ie,Re);break e;case 11:de=XC(null,de,st,ie,Re);break e;case 14:de=Fv(null,de,st,Hy(st.type,ie),Re);break e}throw Error(l(306,st,""))}return de;case 0:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:Hy(st,dt),t5(ie,de,st,dt,Re);case 1:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:Hy(st,dt),s5(ie,de,st,dt,Re);case 3:e:{if(a2(de),ie===null)throw Error(l(387));st=de.pendingProps,Pt=de.memoizedState,dt=Pt.element,Fp(ie,de),wg(de,st,null,Re);var Hs=de.memoizedState;if(st=Hs.element,Ve&&Pt.isDehydrated)if(Pt={element:st,isDehydrated:!1,cache:Hs.cache,pendingSuspenseBoundaries:Hs.pendingSuspenseBoundaries,transitions:Hs.transitions},de.updateQueue.baseState=Pt,de.memoizedState=Pt,de.flags&256){dt=Yu(Error(l(423)),de),de=dw(ie,de,st,Re,dt);break e}else if(st!==dt){dt=Yu(Error(l(424)),de),de=dw(ie,de,st,Re,dt);break e}else for(Ve&&(Js=it(de.stateNode.containerInfo),Ks=de,Mn=!0,ea=null,Ur=!1),Re=Pa(de,null,st,Re),de.child=Re;Re;)Re.flags=Re.flags&-3|4096,Re=Re.sibling;else{if(gi(),st===dt){de=Ue(ie,de,Re);break e}yf(ie,de,st,Re)}de=de.child}return de;case 5:return T1(de),ie===null&&wo(de),st=de.type,dt=de.pendingProps,Pt=ie!==null?ie.memoizedProps:null,Hs=dt.children,me(st,dt)?Hs=null:Pt!==null&&me(st,Pt)&&(de.flags|=32),e5(ie,de),yf(ie,de,Hs,Re),de.child;case 6:return ie===null&&wo(de),null;case 13:return sT(ie,de,Re);case 4:return Gd(de,de.stateNode.containerInfo),st=de.pendingProps,ie===null?de.child=qr(de,null,st,Re):yf(ie,de,st,Re),de.child;case 11:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:Hy(st,dt),XC(ie,de,st,dt,Re);case 7:return yf(ie,de,de.pendingProps,Re),de.child;case 8:return yf(ie,de,de.pendingProps.children,Re),de.child;case 12:return yf(ie,de,de.pendingProps.children,Re),de.child;case 10:e:{if(st=de.type._context,dt=de.pendingProps,Pt=de.memoizedProps,Hs=dt.value,pp(de,st,Hs),Pt!==null)if(hh(Pt.value,Hs)){if(Pt.children===dt.children&&!Ua.current){de=Ue(ie,de,Re);break e}}else for(Pt=de.child,Pt!==null&&(Pt.return=de);Pt!==null;){var Qn=Pt.dependencies;if(Qn!==null){Hs=Pt.child;for(var Br=Qn.firstContext;Br!==null;){if(Br.context===st){if(Pt.tag===1){Br=cu(-1,Re&-Re),Br.tag=2;var Ka=Pt.updateQueue;if(Ka!==null){Ka=Ka.shared;var no=Ka.pending;no===null?Br.next=Br:(Br.next=no.next,no.next=Br),Ka.pending=Br}}Pt.lanes|=Re,Br=Pt.alternate,Br!==null&&(Br.lanes|=Re),Hd(Pt.return,Re,de),Qn.lanes|=Re;break}Br=Br.next}}else if(Pt.tag===10)Hs=Pt.type===de.type?null:Pt.child;else if(Pt.tag===18){if(Hs=Pt.return,Hs===null)throw Error(l(341));Hs.lanes|=Re,Qn=Hs.alternate,Qn!==null&&(Qn.lanes|=Re),Hd(Hs,Re,de),Hs=Pt.sibling}else Hs=Pt.child;if(Hs!==null)Hs.return=Pt;else for(Hs=Pt;Hs!==null;){if(Hs===de){Hs=null;break}if(Pt=Hs.sibling,Pt!==null){Pt.return=Hs.return,Hs=Pt;break}Hs=Hs.return}Pt=Hs}yf(ie,de,dt.children,Re),de=de.child}return de;case 9:return dt=de.type,st=de.pendingProps.children,Th(de,Re),dt=Rp(dt),st=st(dt),de.flags|=1,yf(ie,de,st,Re),de.child;case 14:return st=de.type,dt=Hy(st,de.pendingProps),dt=Hy(st.type,dt),Fv(ie,de,st,dt,Re);case 15:return s2(ie,de,de.type,de.pendingProps,Re);case 17:return st=de.type,dt=de.pendingProps,dt=de.elementType===st?dt:Hy(st,dt),Me(ie,de),de.tag=1,qa(st)?(ie=!0,gl(de)):ie=!1,Th(de,Re),qb(de,st,dt),Gx(de,st,dt,Re),r2(null,de,st,!0,ie,Re);case 19:return hw(ie,de,Re);case 22:return n2(ie,de,Re)}throw Error(l(156,de.tag))};function aT(ie,de){return $x(ie,de)}function lk(ie,de,Re,st){this.tag=ie,this.key=Re,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=de,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=st,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Up(ie,de,Re,st){return new lk(ie,de,Re,st)}function ur(ie){return ie=ie.prototype,!(!ie||!ie.isReactComponent)}function dr(ie){if(typeof ie=="function")return ur(ie)?1:0;if(ie!=null){if(ie=ie.$$typeof,ie===g)return 11;if(ie===b)return 14}return 2}function W0(ie,de){var Re=ie.alternate;return Re===null?(Re=Up(ie.tag,de,ie.key,ie.mode),Re.elementType=ie.elementType,Re.type=ie.type,Re.stateNode=ie.stateNode,Re.alternate=ie,ie.alternate=Re):(Re.pendingProps=de,Re.type=ie.type,Re.flags=0,Re.subtreeFlags=0,Re.deletions=null),Re.flags=ie.flags&14680064,Re.childLanes=ie.childLanes,Re.lanes=ie.lanes,Re.child=ie.child,Re.memoizedProps=ie.memoizedProps,Re.memoizedState=ie.memoizedState,Re.updateQueue=ie.updateQueue,de=ie.dependencies,Re.dependencies=de===null?null:{lanes:de.lanes,firstContext:de.firstContext},Re.sibling=ie.sibling,Re.index=ie.index,Re.ref=ie.ref,Re}function ld(ie,de,Re,st,dt,Pt){var Hs=2;if(st=ie,typeof ie=="function")ur(ie)&&(Hs=1);else if(typeof ie=="string")Hs=5;else e:switch(ie){case u:return Ws(Re.children,dt,Pt,de);case h:Hs=8,dt|=8;break;case m:return ie=Up(12,Re,de,dt|2),ie.elementType=m,ie.lanes=Pt,ie;case v:return ie=Up(13,Re,de,dt),ie.elementType=v,ie.lanes=Pt,ie;case y:return ie=Up(19,Re,de,dt),ie.elementType=y,ie.lanes=Pt,ie;case S:return s3(Re,dt,Pt,de);default:if(typeof ie=="object"&&ie!==null)switch(ie.$$typeof){case p:Hs=10;break e;case f:Hs=9;break e;case g:Hs=11;break e;case b:Hs=14;break e;case w:Hs=16,st=null;break e}throw Error(l(130,ie==null?ie:typeof ie,""))}return de=Up(Hs,Re,de,dt),de.elementType=ie,de.type=st,de.lanes=Pt,de}function Ws(ie,de,Re,st){return ie=Up(7,ie,st,de),ie.lanes=Re,ie}function s3(ie,de,Re,st){return ie=Up(22,ie,st,de),ie.elementType=S,ie.lanes=Re,ie.stateNode={isHidden:!1},ie}function d5(ie,de,Re){return ie=Up(6,ie,null,de),ie.lanes=Re,ie}function n3(ie,de,Re){return de=Up(4,ie.children!==null?ie.children:[],ie.key,de),de.lanes=Re,de.stateNode={containerInfo:ie.containerInfo,pendingChildren:null,implementation:ie.implementation},de}function iT(ie,de,Re,st,dt){this.tag=de,this.containerInfo=ie,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Ne,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=so(0),this.expirationTimes=so(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=so(0),this.identifierPrefix=st,this.onRecoverableError=dt,Ve&&(this.mutableSourceEagerHydrationData=null)}function eI(ie,de,Re,st,dt,Pt,Hs,Qn,Br){return ie=new iT(ie,de,Re,Qn,Br),de===1?(de=1,Pt===!0&&(de|=8)):de=0,Pt=Up(3,null,null,de),ie.current=Pt,Pt.stateNode=ie,Pt.memoizedState={element:st,isDehydrated:Re,cache:null,transitions:null,pendingSuspenseBoundaries:null},Va(Pt),ie}function tI(ie){if(!ie)return Ao;ie=ie._reactInternals;e:{if(I(ie)!==ie||ie.tag!==1)throw Error(l(170));var de=ie;do{switch(de.tag){case 3:de=de.stateNode.context;break e;case 1:if(qa(de.type)){de=de.stateNode.__reactInternalMemoizedMergedChildContext;break e}}de=de.return}while(de!==null);throw Error(l(171))}if(ie.tag===1){var Re=ie.type;if(qa(Re))return zo(ie,Re,de)}return de}function ck(ie){var de=ie._reactInternals;if(de===void 0)throw typeof ie.render=="function"?Error(l(188)):(ie=Object.keys(ie).join(","),Error(l(268,ie)));return ie=q(de),ie===null?null:ie.stateNode}function sI(ie,de){if(ie=ie.memoizedState,ie!==null&&ie.dehydrated!==null){var Re=ie.retryLane;ie.retryLane=Re!==0&&Re=Ka&&Pt>=ic&&dt<=no&&Hs<=Ri){ie.splice(de,1);break}else if(st!==Ka||Re.width!==Br.width||RiHs){if(!(Pt!==ic||Re.height!==Br.height||nodt)){Ka>st&&(Br.width+=Ka-st,Br.x=st),noPt&&(Br.height+=ic-Pt,Br.y=Pt),RiRe&&(Re=Hs)),Hs ")+` No matching component was found for: `)+ie.join(" > ")}return null},n.getPublicRootInstance=function(ie){if(ie=ie.current,!ie.child)return null;switch(ie.child.tag){case 5:return K(ie.child.stateNode);default:return ie.child.stateNode}},n.injectIntoDevTools=function(ie){if(ie={bundleType:ie.bundleType,version:ie.version,rendererPackageName:ie.rendererPackageName,rendererConfig:ie.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:Dz,findFiberByHostInstance:ie.findFiberByHostInstance||lT,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")ie=!1;else{var de=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(de.isDisabled||!de.supportsFiber)ie=!0;else{try{nx=de.inject(ie),Pi=de}catch{}ie=!!de.checkDCE}}return ie},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(ie,de,Re,st){if(!Ze)throw Error(l(363));ie=dx(ie,de);var dt=lt(ie,Re,st).disconnect;return{disconnect:function(){dt()}}},n.registerMutableSourceForHydration=function(ie,de){var Re=de._getVersion;Re=Re(de._source),ie.mutableSourceEagerHydrationData==null?ie.mutableSourceEagerHydrationData=[de,Re]:ie.mutableSourceEagerHydrationData.push(de,Re)},n.runWithPriority=function(ie,de){var Re=al;try{return al=ie,de()}finally{al=Re}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(ie,de,Re,st){var dt=de.current,Pt=yh(),Hs=H0(dt);return Re=tI(Re),de.context===null?de.context=Re:de.pendingContext=Re,de=cu(Pt,Hs),de.payload={element:ie},st=st===void 0?null:st,st!==null&&(de.callback=st),ie=ba(dt,de,Hs),ie!==null&&(Wx(ie,dt,Hs,Pt),Zg(ie,dt,Hs)),Hs},n};vVt.exports=Arn;var Ern=vVt.exports;const Trn=kd(Ern);var bVt={exports:{}},iz={};/** * @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. */iz.ConcurrentRoot=1;iz.ContinuousEventPriority=4;iz.DefaultEventPriority=16;iz.DiscreteEventPriority=1;iz.IdleEventPriority=536870912;iz.LegacyRoot=0;bVt.exports=iz;var _Vt=bVt.exports;const Bvt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let $vt=!1,Uvt=!1;const ist=".react-konva-event",Mrn=`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 `,Prn=`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 `,Lrn={};function rIe(s,t,n=Lrn){if(!$vt&&"zIndex"in t&&(console.warn(Prn),$vt=!0),!Uvt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(Mrn),Uvt=!0)}for(var i in n)if(!Bvt[i]){var l=i.slice(0,2)==="on",o=n[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},m=!1;const p={};for(var i in t)if(!Bvt[i]){var l=i.slice(0,2)==="on",f=n[i]!==t[i];if(l&&f){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(p[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),RL(s));for(var c in p)s.on(c+ist,p[c])}function RL(s){if(!bi.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const wVt={},Irn={};x9.Node.prototype._applyProps=rIe;function Drn(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),RL(s)}function Rrn(s,t,n){let r=x9[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=x9.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 rIe(c,i),c}function Frn(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function Orn(s,t,n){return!1}function zrn(s){return s}function Brn(){return null}function $rn(){return null}function Urn(s,t,n,r){return Irn}function qrn(){}function Vrn(s){}function Hrn(s,t){return!1}function Grn(){return wVt}function Wrn(){return wVt}const Krn=setTimeout,Yrn=clearTimeout,Zrn=-1;function Xrn(s,t){return!1}const Qrn=!1,Jrn=!0,ean=!0;function tan(s,t){t.parent===s?t.moveToTop():s.add(t),RL(s)}function san(s,t){t.parent===s?t.moveToTop():s.add(t),RL(s)}function jVt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),RL(s)}function nan(s,t,n){jVt(s,t,n)}function ran(s,t){t.destroy(),t.off(ist),RL(s)}function aan(s,t){t.destroy(),t.off(ist),RL(s)}function ian(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function oan(s,t,n){}function lan(s,t,n,r,a){rIe(s,a,r)}function can(s){s.hide(),RL(s)}function dan(s){}function uan(s,t){(t.visible==null||t.visible)&&s.show()}function han(s,t){}function man(s){}function pan(){}const fan=()=>_Vt.DefaultEventPriority,xan=Object.freeze(Object.defineProperty({__proto__:null,appendChild:tan,appendChildToContainer:san,appendInitialChild:Drn,cancelTimeout:Yrn,clearContainer:man,commitMount:oan,commitTextUpdate:ian,commitUpdate:lan,createInstance:Rrn,createTextInstance:Frn,detachDeletedInstance:pan,finalizeInitialChildren:Orn,getChildHostContext:Wrn,getCurrentEventPriority:fan,getPublicInstance:zrn,getRootHostContext:Grn,hideInstance:can,hideTextInstance:dan,idlePriority:xQ.unstable_IdlePriority,insertBefore:jVt,insertInContainerBefore:nan,isPrimaryRenderer:Qrn,noTimeout:Zrn,now:xQ.unstable_now,prepareForCommit:Brn,preparePortalMount:$rn,prepareUpdate:Urn,removeChild:ran,removeChildFromContainer:aan,resetAfterCommit:qrn,resetTextContent:Vrn,run:xQ.unstable_runWithPriority,scheduleTimeout:Krn,shouldDeprioritizeSubtree:Hrn,shouldSetTextContent:Xrn,supportsMutation:ean,unhideInstance:uan,unhideTextInstance:han,warnsIfNotActing:Jrn},Symbol.toStringTag,{value:"Module"}));var gan=Object.defineProperty,yan=Object.defineProperties,van=Object.getOwnPropertyDescriptors,qvt=Object.getOwnPropertySymbols,ban=Object.prototype.hasOwnProperty,_an=Object.prototype.propertyIsEnumerable,Vvt=(s,t,n)=>t in s?gan(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Hvt=(s,t)=>{for(var n in t||(t={}))ban.call(t,n)&&Vvt(s,n,t[n]);if(qvt)for(var n of qvt(t))_an.call(t,n)&&Vvt(s,n,t[n]);return s},wan=(s,t)=>yan(s,van(t)),Gvt,Wvt;typeof window<"u"&&((Gvt=window.document)!=null&&Gvt.createElement||((Wvt=window.navigator)==null?void 0:Wvt.product)==="ReactNative")?_.useLayoutEffect:_.useEffect;function NVt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=NVt(r,t,n);if(a)return a;r=r.sibling}}function kVt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const Kvt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=Kvt;return}return Kvt.apply(this,arguments)};const ost=kVt(_.createContext(null));class SVt extends _.Component{render(){return _.createElement(ost.Provider,{value:this._reactInternals},this.props.children)}}function jan(){const s=_.useContext(ost);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=_.useId();return _.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=NVt(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 Nan(){const s=jan(),[t]=_.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!==ost&&!t.has(a)&&t.set(a,_.useContext(kVt(a)))}n=n.return}return t}function kan(){const s=Nan();return _.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>_.createElement(t,null,_.createElement(n.Provider,wan(Hvt({},r),{value:s.get(n)}))),t=>_.createElement(SVt,Hvt({},t))),[s])}function San(s){const t=Ft.useRef({});return Ft.useLayoutEffect(()=>{t.current=s}),Ft.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Can=s=>{const t=Ft.useRef(null),n=Ft.useRef(null),r=Ft.useRef(null),a=San(s),i=kan(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Ft.useLayoutEffect(()=>(n.current=new x9.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=DX.createContainer(n.current,_Vt.LegacyRoot,!1,null),DX.updateContainer(Ft.createElement(i,{},s.children),r.current),()=>{x9.isBrowser&&(l(null),DX.updateContainer(null,r.current,null),n.current.destroy())}),[]),Ft.useLayoutEffect(()=>{l(n.current),rIe(n.current,s,a),DX.updateContainer(Ft.createElement(i,{},s.children),r.current,null)}),Ft.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})},Aan="Layer",LM="Group",z5="Rect",hU="Image",zB="Text",Uwr="Transformer",DX=Trn(xan);DX.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Ft.version,rendererPackageName:"react-konva"});const Ean=Ft.forwardRef((s,t)=>Ft.createElement(SVt,{},Ft.createElement(Can,{...s,forwardedRef:t})));function Tan({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=_.useRef(null),[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState(null),p=(t==null?void 0:t.headshot_url)??"",f=(t==null?void 0:t.brokerage_logo_url)??"";_.useEffect(()=>{if(!s){c(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>c(G),G.onerror=()=>c(null),G.src=s},[s]),_.useEffect(()=>{if(!p){u(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>u(G),G.onerror=()=>u(null),G.src=p},[p]),_.useEffect(()=>{if(!f){m(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>m(G),G.onerror=()=>m(null),G.src=f},[f]);const g=tsn(n),v=(o==null?void 0:o.naturalWidth)??1080,y=(o==null?void 0:o.naturalHeight)??1080,b=_.useMemo(()=>Math.min(1,a/v),[v,a]),w=v*b,S=y*b,C=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",E=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",P=(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)??"",I=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",D=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",F=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),q=G=>g.fields.includes(G)&&!F.has(G);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(Ean,{ref:G=>{l.current=G,i&&(i.current=G)},width:w,height:S,scaleX:b,scaleY:b,children:e.jsxs(Aan,{children:[o&&e.jsx(hU,{image:o,width:v,height:y,listening:!1}),!o&&e.jsx(z5,{x:0,y:0,width:v,height:y,fill:"#e2e8f0"}),e.jsx(Man,{style:g,canvasW:v,canvasH:y,brandColor:C,accentColor:E,name:P,phone:M,email:I,tagline:D,headshot:d,logo:h,hidden:F,has:q})]})})})}function Man({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const m=n*s.heightRatio,p=m*.18,f=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":ssn(r),g=f==="#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-m:0;return e.jsxs(LM,{children:[e.jsx(z5,{x:0,y:v,width:t,height:m,fill:r}),e.jsx(z5,{x:0,y:s.position==="bottom"?v:m-4,width:t,height:4,fill:a}),e.jsx(jce,{x:p,y:v+p,width:t-p*2,height:m-p*2,textColor:f,subTextColor:g,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,y=m,b=t-v-n*.025,w=n-y-n*.025;return e.jsxs(LM,{children:[e.jsx(z5,{x:b,y:w,width:v,height:y,fill:r,cornerRadius:y*.12,opacity:.92}),e.jsx(z5,{x:b,y:w+y-4,width:v,height:4,fill:a,cornerRadius:2}),e.jsx(jce,{x:b+p,y:w+p,width:v-p*2,height:y-p*2,textColor:f,subTextColor:g,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)),y=v*.12;return e.jsxs(LM,{children:[e.jsx(z5,{x:t-v,y:0,width:v,height:n,fill:r}),e.jsx(z5,{x:t-v,y:0,width:4,height:n,fill:a}),e.jsx(jce,{x:t-v+y,y:n*.08,width:v-y*2,height:n*.84,textColor:f,subTextColor:g,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(LM,{children:[e.jsx(z5,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(z5,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(z5,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(jce,{x:p,y:n-m+p,width:t-p*2,height:m-p*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(hU,{image:u,x:t-p-m*.7,y:p,height:m-p*2,width:m*.7})]}):null}function jce({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:p,vertical:f,railWidth:g}){if(f){const G=g??n,V=Math.min(n,G*.7),H=Math.max(14,G*.13),K=Math.max(11,G*.085),Z=G*.08,oe=G*.35;let re=t;const ae=re;re+=V+Z;const J=re,te=l.length>12?2:1;re+=H*1.15*te+Z*.5;const ce=re;m("phone")&&o&&(re+=K*1.3+Z*.4);const ve=re;m("email")&&c&&(re+=K*1.3+Z*.4);const me=re+Z*.5;return e.jsxs(LM,{children:[m("headshot")&&u&&e.jsx(LM,{clipFunc:p?he=>{he.beginPath(),he.arc(s+n/2,ae+V/2,V/2,0,Math.PI*2),he.closePath()}:void 0,children:e.jsx(hU,{image:u,x:s+(n-V)/2,y:ae,width:V,height:V})}),m("name")&&l&&e.jsx(zB,{text:l,x:s,y:J,width:n,align:"center",fontSize:H,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(zB,{text:o,x:s,y:ce,width:n,align:"center",fontSize:K,fill:i}),m("email")&&c&&e.jsx(zB,{text:c,x:s,y:ve,width:n,align:"center",fontSize:K,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(hU,{image:h,x:s,y:me,width:n,height:oe})]})}const v=r*.95,y=u&&m("headshot")?s+v+r*.18:s,b=n-(y-s)-(h&&m("logo")?r*1.6:0),w=Math.max(20,r*.34),S=Math.max(13,r*.22),C=r*.06,E=m("tagline")&&d?1:0,P=m("phone")&&o?1:0,M=m("email")&&c?1:0,I=1+E+(P||M?1:0),D=I*w+(I-1)*C;let q=t+(r-D)/2;return e.jsxs(LM,{children:[m("headshot")&&u&&e.jsx(LM,{clipFunc:p?G=>{G.beginPath(),G.arc(s+v/2,t+v/2,v/2,0,Math.PI*2),G.closePath()}:void 0,children:e.jsx(hU,{image:u,x:s,y:t+(r-v)/2,width:v,height:v})}),m("name")&&l&&e.jsx(zB,{text:l,x:y,y:q,width:b,fontSize:w,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(q+=w+C,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(zB,{text:d,x:y,y:q,width:b,fontSize:S*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(q+=S*1.1+C,null)]}),P||M?e.jsx(zB,{text:[o,c].filter(Boolean).join(" • "),x:y,y:q,width:b,fontSize:S,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(hU,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function Pan(){const{data:s}=Eae(),t=(s==null?void 0:s.find(q=>q.is_default))??(s==null?void 0:s[0])??null,[n,r]=_.useState(void 0),a=(s==null?void 0:s.find(q=>q.id===n))??t,[i,l]=_.useState([]),[o,c]=_.useState(0),[d,u]=_.useState("minimal-stripe"),[h,m]=_.useState({}),[p,f]=_.useState(!1),g=_.useRef(null),[v,y]=_.useState(780),b=_.useRef(null),w=q=>{if(b.current&&(b.current.disconnect(),b.current=null),!q)return;const G=()=>{const H=q.clientWidth;H>0&&y(Math.min(780,H-16))};G();const V=new ResizeObserver(G);V.observe(q),b.current=V};_.useEffect(()=>()=>{var q;(q=b.current)==null||q.disconnect()},[]);const S=_.useRef(null),C=q=>{if(!q)return;const G=[];Array.from(q).forEach(V=>{V.type.startsWith("image/")&&G.push({id:crypto.randomUUID(),url:URL.createObjectURL(V),file:V,name:V.name})}),l(V=>[...V,...G])},E=q=>{l(G=>{const V=G.find(H=>H.id===q);return V&&URL.revokeObjectURL(V.url),G.filter(H=>H.id!==q)}),c(0)},P=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=q=>{var oe;const[G,V]=q.split(","),H=((oe=G.match(/:(.*?);/))==null?void 0:oe[1])??"image/jpeg",K=atob(V),Z=new Uint8Array(K.length);for(let re=0;re{var q;if(S.current){f(!0);try{const G=S.current,V=G.toDataURL({pixelRatio:1/(G.scaleX()||1),mimeType:"image/jpeg",quality:.95}),K=`${((q=i[o])==null?void 0:q.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,Z=M(V),oe=URL.createObjectURL(Z);if(P)window.open(oe,"_blank")||(window.location.href=oe),ne.success('Long-press the image and tap "Save to Photos"');else{const re=document.createElement("a");re.href=oe,re.download=K,document.body.appendChild(re),re.click(),re.remove(),ne.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(oe),6e4)}catch(G){ne.error(G.message||"Export failed")}finally{f(!1)}}},D=async()=>{if(i.length){f(!0);try{const q=new Aqt,G=i.length,V=o;for(let Z=0;ZsetTimeout(te,600)),!S.current)continue;const oe=S.current,ae=oe.toDataURL({pixelRatio:1/(oe.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],J=i[Z].name.replace(/\.[^.]+$/,"")||`image-${Z+1}`;q.file(`${J}-branded.jpg`,ae,{base64:!0})}c(V);const H=await q.generateAsync({type:"blob"}),K=document.createElement("a");K.href=URL.createObjectURL(H),K.download=`branded-images-${Date.now()}.zip`,K.click(),URL.revokeObjectURL(K.href),ne.success(`${G} images exported`)}catch(q){ne.error(q.message||"Batch export failed")}finally{f(!1)}}},F=i[o];return e.jsx($s,{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(dl,{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(or,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(ka,{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(z,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(or,{to:"/marketing-studio/brand-kit",children:[e.jsx(yc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(be,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Le,{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(z,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(or,{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(be,{className:"overflow-hidden",children:e.jsxs(Le,{className:"p-4",children:[F?e.jsx("div",{ref:w,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(Tan,{imageUrl:F.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:v,stageRef:S})}):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 q;return(q=g.current)==null?void 0:q.click()},onDragOver:q=>q.preventDefault(),onDrop:q=>{q.preventDefault(),C(q.dataTransfer.files)},children:[e.jsx(nc,{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(z,{type:"button",children:[e.jsx(Ra,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:g,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:q=>C(q.target.files)})]})}),i.length>0&&e.jsx(be,{className:"overflow-hidden",children:e.jsx(Le,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((q,G)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(G),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${G===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:q.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>E(q.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(er,{className:"h-3 w-3"})})]},q.id)),e.jsx("button",{onClick:()=>{var q;return(q=g.current)==null?void 0:q.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(sn,{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(z,{variant:"outline",onClick:()=>{i.forEach(q=>URL.revokeObjectURL(q.url)),l([])},children:"Clear all"}),e.jsxs(z,{onClick:I,disabled:p||!F,children:[p?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(z,{onClick:D,disabled:p,children:[p?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ga,{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(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-base",children:"Brand preset"})}),e.jsx(Le,{children:e.jsxs(ls,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose preset"})}),e.jsx(as,{children:s==null?void 0:s.map(q=>e.jsxs(He,{value:q.id,children:[q.name," ",q.is_default?"(default)":""]},q.id))})]})})]}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-base",children:"Bar style"})}),e.jsx(Le,{children:e.jsx(nsn,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-base",children:"Tweak this design"})}),e.jsx(Le,{children:e.jsxs(Qr,{defaultValue:"text",children:[e.jsxs(Jr,{className:"grid grid-cols-2 w-full",children:[e.jsx(Wt,{value:"text",children:"Text"}),e.jsx(Wt,{value:"colors",children:"Colors"})]}),e.jsxs(Kt,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Display name"}),e.jsx(pe,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:q=>m({...h,display_name:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:q=>m({...h,phone:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email??(a==null?void 0:a.email)??"",onChange:q=>m({...h,email:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:q=>m({...h,tagline:q.target.value})})]})]}),e.jsxs(Kt,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{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:q=>m({...h,brand_color:q.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(pe,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:q=>m({...h,brand_color:q.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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:q=>m({...h,accent_color:q.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(pe,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:q=>m({...h,accent_color:q.target.value})})]})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function Lan(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 Ian=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function SP(s){const t=[];for(let n=0,r=s.length;nvw||s.height>vw)&&(s.width>vw&&s.height>vw?s.width>s.height?(s.height*=vw/s.width,s.width=vw):(s.width*=vw/s.height,s.height=vw):s.width>vw?(s.height*=vw/s.width,s.width=vw):(s.width*=vw/s.height,s.height=vw))}function zEe(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 zan(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Ban(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),zan(a)}const U_=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||U_(n,t)};function $an(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function Uan(s,t){return CVt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function qan(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?$an(n):Uan(n,r);return document.createTextNode(`${a}{${i}}`)}function Yvt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Ian();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(qan(l,n,a,r)),t.appendChild(o)}function Van(s,t,n){Yvt(s,t,":before",n),Yvt(s,t,":after",n)}const Zvt="application/font-woff",Xvt="image/jpeg",Han={woff:Zvt,woff2:Zvt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Xvt,jpeg:Xvt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Gan(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function lst(s){const t=Gan(s).toLowerCase();return Han[t]||""}function Wan(s){return s.split(/,/)[1]}function ZHe(s){return s.search(/^(data:)/)!==-1}function Kan(s,t){return`data:${t};base64,${s}`}async function EVt(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 j9e={};function Yan(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 cst(s,t,n){const r=Yan(s,t,n.includeQueryParams);if(j9e[r]!=null)return j9e[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await EVt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),Wan(o)));a=Kan(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 j9e[r]=a,a}async function Zan(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):zEe(t)}async function Xan(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 zEe(o)}const n=s.poster,r=lst(n),a=await cst(n,r,t);return zEe(a)}async function Qan(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await aIe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function Jan(s,t){return U_(s,HTMLCanvasElement)?Zan(s):U_(s,HTMLVideoElement)?Xan(s,t):U_(s,HTMLIFrameElement)?Qan(s,t):s.cloneNode(TVt(s))}const ein=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",TVt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function tin(s,t,n){var r,a;if(TVt(t))return t;let i=[];return ein(s)&&s.assignedNodes?i=SP(s.assignedNodes()):U_(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=SP(s.contentDocument.body.childNodes):i=SP(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||U_(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>aIe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function sin(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):CVt(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`),U_(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 nin(s,t){U_(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),U_(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function rin(s,t){if(U_(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function ain(s,t,n){return U_(t,Element)&&(sin(s,t,n),Van(s,t,n),nin(s,t),rin(s,t)),t}async function iin(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iJan(r,t)).then(r=>tin(s,r,t)).then(r=>ain(s,r,t)).then(r=>iin(r,t))}const MVt=/url\((['"]?)([^'"]+?)\1\)/g,oin=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,lin=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function cin(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function din(s){const t=[];return s.replace(MVt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!ZHe(n))}async function uin(s,t,n,r,a){try{const i=n?Lan(t,n):t,l=lst(t);let o;return a||(o=await cst(i,l,r)),s.replace(cin(t),`$1${o}$3`)}catch{}return s}function hin(s,{preferredFontFormat:t}){return t?s.replace(lin,n=>{for(;;){const[r,,a]=oin.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function PVt(s){return s.search(MVt)!==-1}async function LVt(s,t,n){if(!PVt(s))return s;const r=hin(s,n);return din(r).reduce((i,l)=>i.then(o=>uin(o,l,t,n)),Promise.resolve(r))}async function $B(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await LVt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function min(s,t){await $B("background",s,t)||await $B("background-image",s,t),await $B("mask",s,t)||await $B("-webkit-mask",s,t)||await $B("mask-image",s,t)||await $B("-webkit-mask-image",s,t)}async function pin(s,t){const n=U_(s,HTMLImageElement);if(!(n&&!ZHe(s.src))&&!(U_(s,SVGImageElement)&&!ZHe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await cst(r,lst(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 fin(s,t){const r=SP(s.childNodes).map(a=>IVt(a,t));await Promise.all(r).then(()=>s)}async function IVt(s,t){U_(s,Element)&&(await min(s,t),await pin(s,t),await fin(s,t))}function xin(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 Qvt={};async function Jvt(s){let t=Qvt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},Qvt[s]=t,t}async function e1t(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),EVt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function t1t(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 gin(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{SP(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Jvt(c).then(u=>e1t(u,t)).then(u=>t1t(u).forEach(h=>{try{a.insertRule(h,h.startsWith("@import")?o+=1:a.cssRules.length)}catch(m){console.error("Error inserting rule from remote css",{rule:h,error:m})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&r.push(Jvt(a.href).then(o=>e1t(o,t)).then(o=>t1t(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{SP(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function yin(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>PVt(t.style.getPropertyValue("src")))}async function vin(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=SP(s.ownerDocument.styleSheets),r=await gin(n,t);return yin(r)}function DVt(s){return s.trim().replace(/["']/g,"")}function bin(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(DVt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function _in(s,t){const n=await vin(s,t),r=bin(s);return(await Promise.all(n.filter(i=>r.has(DVt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return LVt(i.cssText,l,t)}))).join(` `)}async function win(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await _in(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 RVt(s,t={}){const{width:n,height:r}=AVt(s,t),a=await aIe(s,t,!0);return await win(a,t),await IVt(a,t),xin(a,t),await Ban(a,n,r)}async function FVt(s,t={}){const{width:n,height:r}=AVt(s,t),a=await RVt(s,t),i=await zEe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||Fan(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||Oan(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 ZH(s,t={}){return(await FVt(s,t)).toDataURL()}const OVt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:FVt,toPng:ZH,toSvg:RVt},Symbol.toStringTag,{value:"Module"})),XH=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),iIe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},IM={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},jin=({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})]})]}),dst=Ft.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=iIe[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:XH(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",XH(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(jin,{branding:r,dim:l})]})]})]})});dst.displayName="LuxuryDarkTemplate";const Nin=({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})]})]}),ust=Ft.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=iIe[t],u=n==="instagram-story",h=n==="facebook-post",m=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:h?"row":"column"},children:[e.jsxs("div",{style:{width:h?"55%":"100%",height:h?"100%":u?"50%":"52%",position:"relative",overflow:"hidden",flexShrink:0},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",top:l.w*.04,left:0,background:m,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(h?.055:.065),fontWeight:800,lineHeight:1.1,color:m,marginBottom:l.w*.012},children:XH(s.price)}),e.jsx("div",{style:{fontSize:l.w*.026,fontWeight:600,marginBottom:l.w*.006},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.02,color:"#6B7280",marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsxs("div",{style:{display:"flex",gap:l.w*.03,marginBottom:l.w*.02},children:[s.bedrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bedrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Beds"})]}),s.bathrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bathrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Baths"})]}),s.sqft>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.sqft.toLocaleString()}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Sq Ft"})]})]}),t==="open-house"&&e.jsx("div",{style:{background:`${m}10`,border:`2px solid ${m}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:m,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(Nin,{branding:r,dim:l,accentColor:m})]})]})});ust.displayName="ModernCleanTemplate";const kin=({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})]})]}),hst=Ft.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var m;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=iIe[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:XH(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(kin,{branding:r,dim:l})]})]})]})});hst.displayName="BoldColorfulTemplate";const Sin=({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})]})]}),mst=Ft.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=iIe[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:XH(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",XH(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(Sin,{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"}})]})]})})});mst.displayName="EditorialTemplate";const Cin=[{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:"📉"}],s1t=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(Fm,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(Fm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(of,{className:"h-4 w-4"})}],Ain=[{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:"📰"}],n1t={"luxury-dark":dst,"modern-clean":ust,"bold-colorful":hst,editorial:mst},N9e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function Ein(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;oEe.is_default))??(s==null?void 0:s[0])??null,[n,r]=_.useState(void 0),a=(s==null?void 0:s.find(Ee=>Ee.id===n))??t,i=ha(),[l,o]=_.useState("mine"),[c,d]=_.useState(""),[u,h]=_.useState("address"),[m,p]=_.useState(!1),[f,g]=_.useState([]),[v,y]=_.useState(null),[b,w]=_.useState(0),[S,C]=_.useState("just-listed"),[E,P]=_.useState(["instagram-square"]),[M,I]=_.useState("luxury-dark"),[D,F]=_.useState(!0),[q,G]=_.useState(!1),[V,H]=_.useState([]),[K,Z]=_.useState("search"),oe=_.useRef({}),{data:re=[],isLoading:ae}=rt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ee,error:Ne}=await U.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Ne)throw Ne;return(Ee||[]).map(Pe=>{const Oe=(Pe.listing_photos||[]).slice().sort((Ve,_e)=>(_e.is_primary?1:0)-(Ve.is_primary?1:0)||(Ve.sort_order??0)-(_e.sort_order??0)).map(Ve=>Ve.photo_url).filter(Boolean),ke=String(Pe.status||"");return{mlsNumber:Pe.id,address:Pe.property_address||"",city:Pe.city||"",state:Pe.state||"",zip:"",price:Number(Pe.price||0),status:ke,bedrooms:Number(Pe.bedrooms||0),bathrooms:Number(Pe.bathrooms||0),sqft:Number(Pe.square_footage||0),lotSize:"",yearBuilt:Pe.year_built??null,propertyType:Pe.property_type||"",description:Pe.description||"",photos:Oe,listDate:Pe.created_at,soldDate:ke.toLowerCase().includes("sold")?Pe.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),J=_.useMemo(()=>!D||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[D,a]),te=async()=>{if(c.trim()){p(!0),g([]);try{const{data:Ee,error:Ne}=await U.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Ne)throw Ne;if(Ee!=null&&Ee.error)throw new Error(Ee.error);g((Ee==null?void 0:Ee.listings)||[]),((Ee==null?void 0:Ee.listings)||[]).length===0&&ne.info("No listings found. Try a different search.")}catch(Ee){ne.error(Ee.message||"Search failed")}finally{p(!1)}}},ce=Ee=>{var Ne;y(Ee),w(0),Z("customize"),Ee.soldDate||(Ne=Ee.status)!=null&&Ne.toLowerCase().includes("sold")?C("just-sold"):C("just-listed")},ve=Ee=>P(Ne=>Ne.includes(Ee)?Ne.filter(Pe=>Pe!==Ee):[...Ne,Ee]),me=v?{listing:v,postType:S,format:"instagram-square",branding:J,selectedPhotoIndex:b}:null,he=_.useCallback(async()=>{if(!(!v||E.length===0)){G(!0),H([]),Z("generate");try{await new Promise(Ne=>setTimeout(Ne,600));const Ee=[];for(const Ne of E){const Pe=`${M}-${Ne}`,Oe=oe.current[Pe];if(!Oe)continue;const ke=IM[Ne],Ve=await ZH(Oe,{width:ke.width,height:ke.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:Ne,url:Ve})}H(Ee),ne.success(`Generated ${Ee.length} design${Ee.length>1?"s":""}!`)}catch(Ee){ne.error(Ee.message||"Generation failed")}finally{G(!1)}}},[v,E,M]),ge=(Ee,Ne)=>{const Pe=`${((v==null?void 0:v.address)||"listing").replace(/\s+/g,"-")}-${S}-${Ne}.png`;try{const Oe=Ein(Ee),ke=URL.createObjectURL(Oe);if(Tin)window.open(ke,"_blank"),ne.message("Long-press the image to save to Photos");else{const Ve=document.createElement("a");Ve.href=ke,Ve.download=Pe,document.body.appendChild(Ve),Ve.click(),document.body.removeChild(Ve)}setTimeout(()=>URL.revokeObjectURL(ke),6e4)}catch{const Oe=document.createElement("a");Oe.href=Ee,Oe.download=Pe,Oe.click()}};return _.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx($s,{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(dl,{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(z,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(or,{to:"/marketing-studio",children:[e.jsx(ka,{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(ee,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Default"})}),e.jsx(as,{children:s.map(Ee=>e.jsxs(He,{value:Ee.id,children:[Ee.name,Ee.is_default?" (default)":""]},Ee.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:()=>Z("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${K==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Rr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>v&&Z("customize"),disabled:!v,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${K==="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(yi,{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 ${K==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),K==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qr,{value:l,onValueChange:Ee=>o(Ee),children:e.jsxs(Jr,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Wt,{value:"mine",children:[e.jsx(sa,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Wt,{value:"mls",children:[e.jsx(Rr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:ae?e.jsx(be,{children:e.jsx(Le,{className:"py-12 flex items-center justify-center",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):re.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-10 text-center space-y-2",children:[e.jsx(sa,{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(z,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(or,{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:[re.length," listing",re.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:re.map((Ee,Ne)=>{var Pe;return e.jsx(be,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Le,{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:(Pe=Ee.photos)!=null&&Pe[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(sa,{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:Ee.price>0?N9e(Ee.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,Ee.state?`, ${Ee.state}`:""]}),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(W4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ey,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d7,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),Ee.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ee.status})})]})]})})},Ee.mlsNumber||Ne)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Rr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(En,{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(Le,{className:"space-y-3",children:[e.jsx(Qr,{value:u,onValueChange:Ee=>h(Ee),children:e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"address",children:[e.jsx(Ha,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Wt,{value:"mls",children:[e.jsx(Ip,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{value:c,onChange:Ee=>d(Ee.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&te()}),e.jsxs(z,{onClick:te,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Rr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),f.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[f.length," listing",f.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:f.map((Ee,Ne)=>{var Pe;return e.jsx(be,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Le,{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:(Pe=Ee.photos)!=null&&Pe[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(sa,{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:N9e(Ee.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",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(W4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ey,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d7,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Ee.mlsNumber&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),Ee.status&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||Ne)})})]})]})]}),K==="customize"&&v&&me&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(be,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"Selected listing"})}),e.jsxs(Le,{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[b],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(z,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.max(0,Ee-1)),disabled:b===0,children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",v.photos.length]}),e.jsx(z,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.min(v.photos.length-1,Ee+1)),disabled:b===v.photos.length-1,children:e.jsx(yi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:N9e(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(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Z("search"),y(null)},children:[e.jsx(Dx,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(be,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(En,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Ain.map(Ee=>e.jsxs("button",{onClick:()=>I(Ee.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===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(ee,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Cin.map(Ee=>e.jsxs("button",{onClick:()=>C(Ee.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${S===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ee.icon})," ",e.jsx("span",{className:"truncate",children:Ee.label})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:s1t.map(Ee=>e.jsxs("button",{onClick:()=>ve(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${E.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Oo,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(mn,{checked:D,onCheckedChange:F})]}),D&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(or,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),D&&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(ee,{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*(IM[E[0]||"instagram-square"].height/IM[E[0]||"instagram-square"].width)},children:(()=>{const Ee=n1t[M],Ne=E[0]||"instagram-square";return e.jsx(Ee,{...me,format:Ne})})()})})]}),e.jsx(z,{onClick:he,disabled:E.length===0||q,size:"lg",className:"w-full gap-2",children:q?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-5 w-5"})," Generate ",E.length," design",E.length>1?"s":""]})})]})]})]}),K==="generate"&&e.jsxs("div",{className:"space-y-4",children:[q&&e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(bt,{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."})]})}),V.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(z,{variant:"outline",size:"sm",onClick:()=>Z("customize"),children:[e.jsx(Dx,{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:V.map((Ee,Ne)=>{const Pe=s1t.find(Oe=>Oe.value===Ee.format);return e.jsxs(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ee.url,alt:"",className:"w-full rounded"})}),e.jsxs(Le,{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:[Pe==null?void 0:Pe.icon,e.jsx("span",{className:"text-sm font-medium",children:Pe==null?void 0:Pe.label})]}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Pe==null?void 0:Pe.dimensions})]}),e.jsxs(z,{size:"sm",className:"w-full gap-1.5",onClick:()=>ge(Ee.url,Ee.format),children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ne)})})]})]}),K==="generate"&&v&&me&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:E.map(Ee=>{const Ne=n1t[M],Pe=IM[Ee];return e.jsx("div",{style:{width:Pe.width,height:Pe.height},children:e.jsx(Ne,{ref:Oe=>{oe.current[`${M}-${Ee}`]=Oe},...me,format:Ee})},`${M}-${Ee}`)})})]})})}var zVt="Toggle",pst=_.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=Gg({prop:n,onChange:a,defaultProp:r??!1,caller:zVt});return e.jsx(ci.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:wa(s.onClick,()=>{s.disabled||o(!l)})})});pst.displayName=zVt;var BVt=pst,FL="ToggleGroup",[$Vt,qwr]=uf(FL,[xL]),UVt=xL(),fst=Ft.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(Pin,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(Lin,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${FL}\``)});fst.displayName=FL;var[qVt,VVt]=$Vt(FL),Pin=Ft.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Gg({prop:n,defaultProp:r??"",onChange:a,caller:FL});return e.jsx(qVt,{scope:s.__scopeToggleGroup,type:"single",value:Ft.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Ft.useCallback(()=>o(""),[o]),children:e.jsx(HVt,{...i,ref:t})})}),Lin=Ft.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Gg({prop:n,defaultProp:r??[],onChange:a,caller:FL}),c=Ft.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Ft.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(qVt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(HVt,{...i,ref:t})})});fst.displayName=FL;var[Iin,Din]=$Vt(FL),HVt=Ft.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=UVt(n),u=$E(l),h={role:"group",dir:u,...c};return e.jsx(Iin,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(oPe,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(ci.div,{...h,ref:t})}):e.jsx(ci.div,{...h,ref:t})})}),BEe="ToggleGroupItem",GVt=Ft.forwardRef((s,t)=>{const n=VVt(BEe,s.__scopeToggleGroup),r=Din(BEe,s.__scopeToggleGroup),a=UVt(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Ft.useRef(null);return r.rovingFocus?e.jsx(lPe,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(r1t,{...o,ref:t})}):e.jsx(r1t,{...o,ref:t})});GVt.displayName=BEe;var r1t=Ft.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=VVt(BEe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(pst,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),WVt=fst,KVt=GVt;const YVt=G9("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"}}),Rin=_.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(BVt,{ref:a,className:Ct(YVt({variant:t,size:n,className:s})),...r}));Rin.displayName=BVt.displayName;const ZVt=_.createContext({size:"default",variant:"default"}),Oq=_.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(WVt,{ref:i,className:Ct("flex items-center justify-center gap-1",s),...a,children:e.jsx(ZVt.Provider,{value:{variant:t,size:n},children:r})}));Oq.displayName=WVt.displayName;const L7=_.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=_.useContext(ZVt);return e.jsx(KVt,{ref:i,className:Ct(YVt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});L7.displayName=KVt.displayName;const Fin=[{id:"meet",label:"Meet Your Agent",icon:Oo,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:wj,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:jl,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:yS,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:Nh,description:"Personal philosophy, mantra, or rallying call."}],k9e={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"}},Oin=[{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."}],a1t={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 zin(){const{data:s}=Ytn(),{data:t}=Eae(),[n,r]=_.useState(void 0),a=_.useMemo(()=>(t==null?void 0:t.find(f=>f.id===n))??s??null,[t,n,s]),[i,l]=_.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...a1t.meet}),o=f=>l(g=>({...g,...f})),c=f=>l(g=>({...g,template:f,...a1t[f]})),d=_.useRef(null),[u,h]=_.useState(!1),m=async()=>{if(!d.current)return;h(!0);const f=d.current,g=f.style.transform;try{f.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const v=await ZH(f,{cacheBust:!0,pixelRatio:2,width:f.offsetWidth,height:f.offsetHeight,backgroundColor:"#ffffff"}),y=document.createElement("a");y.href=v,y.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(y),y.click(),y.remove(),ne.success("Downloaded to your device")}catch(v){ne.error((v==null?void 0:v.message)||"Export failed")}finally{f.style.transform=g,h(!1)}},p=k9e[i.aspect];return e.jsx($s,{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(dl,{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(or,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(ka,{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(z,{variant:"outline",asChild:!0,children:e.jsxs(or,{to:"/marketing-studio/brand-kit",children:[e.jsx(yc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(z,{onClick:m,disabled:u,children:[e.jsx(Ga,{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(be,{children:e.jsxs(Le,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Fin.map(f=>{const g=f.icon,v=i.template===f.id;return e.jsxs("button",{onClick:()=>c(f.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(g,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:f.label})]},f.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(Oq,{type:"single",value:i.style,onValueChange:f=>f&&o({style:f}),className:"grid grid-cols-2 gap-1",children:Oin.map(f=>e.jsx(L7,{value:f.id,className:"text-xs h-9",children:f.label},f.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(Oq,{type:"single",value:i.aspect,onValueChange:f=>f&&o({aspect:f}),className:"grid grid-cols-3 gap-1",children:Object.keys(k9e).map(f=>e.jsx(L7,{value:f,className:"text-xs h-9",children:k9e[f].label},f))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(ls,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose preset"})}),e.jsx(as,{children:t.map(f=>e.jsx(He,{value:f.id,children:f.name},f.id))})]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ps,{id:"headline",value:i.headline,onChange:f=>o({headline:f.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(pe,{id:"subline",value:i.subline,onChange:f=>o({subline:f.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ps,{id:"body",value:i.body,onChange:f=>o({body:f.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(pe,{id:"attribution",value:i.attribution,onChange:f=>o({attribution:f.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Rating"}),e.jsx(Oq,{type:"single",value:String(i.rating),onValueChange:f=>f&&o({rating:Number(f)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(f=>e.jsxs(L7,{value:String(f),className:"text-xs h-9",children:[f,"★"]},f))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(pe,{id:"badge",value:i.badgeText,onChange:f=>o({badgeText:f.target.value})})]})]})})]}),e.jsx(Bin,{aspect:p,canvasRef:d,children:e.jsx($in,{form:i,preset:a,width:p.w,height:p.h})})]})]})})}function Bin({aspect:s,canvasRef:t,children:n}){const r=_.useRef(null),[a,i]=_.useState(.5);return _.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 $in({form:s,preset:t,width:n,height:r}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",m=(t==null?void 0:t.website_url)||"",p={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:m,width:n,height:r};return s.style==="editorial"?e.jsx(Uin,{...p}):s.style==="bold"?e.jsx(qin,{...p}):s.style==="luxury"?e.jsx(Hin,{...p}):e.jsx(Vin,{...p})}function XVt({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 oIe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(Ia,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:m,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:n},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:h-128,height:p?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(oIe,{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(XVt,{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 qin(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%, ${Gin(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(oIe,{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(XVt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function Vin(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(oIe,{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 Hin(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(oIe,{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 Gin(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 Win=()=>{const{swagId:s}=Mi(),{user:t}=hs(),{toast:n}=_i(),r=$t(),{trackEngagement:a}=CW(),[i,l]=_.useState(""),{data:o,isLoading:c}=rt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:y,error:b}=await U.from("social_swag").select("*").eq("id",s).single();if(b)throw b;const{data:w}=await U.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...y,links:w||[]}},enabled:!!s});_.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=rt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:y,error:b}=await U.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return y},enabled:!!s}),{data:u=[]}=rt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:y,error:b}=await U.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(b)throw b;const w=[...new Set(y.map(E=>E.user_id))],{data:S}=await U.from("profiles").select("id, name").in("id",w),C=new Map((S==null?void 0:S.map(E=>[E.id,E.name]))||[]);return y.map(E=>({...E,user_name:C.get(E.user_id)||"Unknown User"}))},enabled:!!s}),h=mt({mutationFn:async y=>{const{error:b}=await U.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:y});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:y=>{n({title:"Error adding comment",description:y.message,variant:"destructive"})}}),m=mt({mutationFn:async y=>{const{error:b}=await U.from("social_swag_comments").delete().eq("id",y);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),p=mt({mutationFn:async()=>{const y=d.find(b=>b.user_id===(t==null?void 0:t.id));if(y){const{error:b}=await U.from("social_swag_likes").delete().eq("id",y.id);if(b)throw b}else{const{error:b}=await U.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(b)throw b}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),f=d.some(y=>y.user_id===(t==null?void 0:t.id)),g=y=>y.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),v=y=>{y.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx($s,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx($s,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/social-swag",children:[e.jsx(ka,{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(TW,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(z,{variant:f?"default":"outline",className:"gap-2 w-fit",onClick:()=>p.mutate(),disabled:!t||p.isPending,children:[e.jsx(Ug,{className:`h-4 w-4 ${f?"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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Kc,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(y=>e.jsxs(z,{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(y.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:y.title}),e.jsx(mr,{className:"h-4 w-4 text-muted-foreground"})]},y.id))})]})}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Bu,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Ps,{placeholder:"Add a comment...",value:i,onChange:y=>l(y.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(z,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(Fr,{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(be,{children:e.jsx(Le,{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(y=>e.jsx(be,{children:e.jsx(Le,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Na,{className:"text-sm",children:g(y.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:y.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Md(new Date(y.created_at),{addSuffix:!0})}),y.user_id===(t==null?void 0:t.id)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(y.id),children:e.jsx(Cn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:y.content})]})]})})},y.id))})]})]})}):e.jsx($s,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Kc,{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(z,{asChild:!0,className:"mt-4",children:e.jsx(or,{to:"/social-swag",children:"Back to Social Swag"})})]})})},Kin=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=_.useState(!0),[o,c]=_.useState(!0),[d,u]=_.useState(!0),h=m=>m.split(" ").map(p=>p[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(z,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(aP,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(f1,{open:i,onOpenChange:l,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{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(cl,{className:"h-4 w-4"}):e.jsx(yi,{className:"h-4 w-4"})]})}),e.jsx(g1,{className:"space-y-1 pl-2",children:s.map(m=>e.jsxs(z,{variant:n===m.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(m.id),children:[e.jsx("span",{className:"mr-2",children:m.icon||"📂"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),t.length>0&&e.jsxs(f1,{open:o,onOpenChange:c,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{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(Hl,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(cl,{className:"h-4 w-4"}):e.jsx(yi,{className:"h-4 w-4"})]})}),e.jsx(g1,{className:"space-y-1 pl-2",children:t.map(m=>e.jsxs(z,{variant:n===`group:${m.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${m.id}`),children:[e.jsx("span",{className:"mr-2",children:m.icon||"🔒"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),e.jsxs(f1,{open:d,onOpenChange:u,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{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(On,{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(cl,{className:"h-4 w-4"}):e.jsx(yi,{className:"h-4 w-4"})]})}),e.jsx(g1,{className:"pl-2 space-y-1",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2 px-2",children:"No one else online right now"}):a.map(m=>e.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(xi,{src:m.avatarUrl}),e.jsx(Na,{className:"text-xs",children:h(m.name)})]}),e.jsx(Gf,{className:"h-2.5 w-2.5 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"text-sm truncate",children:m.name})]},m.id))})]})]})})})},Yin=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=_.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(m=>m.id===u);return h?`🔒 ${h.name}`:"Private Group"}const d=s.find(u=>u.id===n);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(cl,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(qd,{className:"w-56 bg-background border",children:[e.jsxs(ua,{onClick:()=>r("all"),children:[e.jsx(aP,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(Iy,{}),e.jsx(qP,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(ua,{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(Iy,{}),e.jsxs(qP,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Hl,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(ua,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(Wg,{open:i,onOpenChange:l,children:[e.jsx(Yre,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(On,{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(gg,{children:[e.jsx(Dy,{children:e.jsxs(Ry,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Ki,{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(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:d.avatarUrl}),e.jsx(Na,{children:o(d.name)})]}),e.jsx(Gf,{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 S9e,lIe="HoverCard",[QVt,Vwr]=uf(lIe,[CC]),cIe=CC(),[Zin,xst]=QVt(lIe),JVt=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=cIe(t),d=_.useRef(0),u=_.useRef(0),h=_.useRef(!1),m=_.useRef(!1),[p,f]=Gg({prop:r,defaultProp:a??!1,onChange:i,caller:lIe}),g=_.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>f(!0),l)},[l,f]),v=_.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>f(!1),o))},[o,f]),y=_.useCallback(()=>f(!1),[f]);return _.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(Zin,{scope:t,open:p,onOpenChange:f,onOpen:g,onClose:v,onDismiss:y,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(Fre,{...c,children:n})})};JVt.displayName=lIe;var eHt="HoverCardTrigger",tHt=_.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=xst(eHt,n),i=cIe(n);return e.jsx(lW,{asChild:!0,...i,children:e.jsx(ci.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:wa(s.onPointerEnter,UEe(a.onOpen)),onPointerLeave:wa(s.onPointerLeave,UEe(a.onClose)),onFocus:wa(s.onFocus,a.onOpen),onBlur:wa(s.onBlur,a.onClose),onTouchStart:wa(s.onTouchStart,l=>l.preventDefault())})})});tHt.displayName=eHt;var Xin="HoverCardPortal",[Hwr,Qin]=QVt(Xin,{forceMount:void 0}),$Ee="HoverCardContent",sHt=_.forwardRef((s,t)=>{const n=Qin($Ee,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=xst($Ee,s.__scopeHoverCard);return e.jsx(vg,{present:r||i.open,children:e.jsx(Jin,{"data-state":i.open?"open":"closed",...a,onPointerEnter:wa(s.onPointerEnter,UEe(i.onOpen)),onPointerLeave:wa(s.onPointerLeave,UEe(i.onClose)),ref:t})})});sHt.displayName=$Ee;var Jin=_.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=xst($Ee,n),d=cIe(n),u=_.useRef(null),h=el(t,u),[m,p]=_.useState(!1);return _.useEffect(()=>{if(m){const f=document.body;return S9e=f.style.userSelect||f.style.webkitUserSelect,f.style.userSelect="none",f.style.webkitUserSelect="none",()=>{f.style.userSelect=S9e,f.style.webkitUserSelect=S9e}}},[m]),_.useEffect(()=>{if(u.current){const f=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",f),()=>{document.removeEventListener("pointerup",f),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),_.useEffect(()=>{u.current&&son(u.current).forEach(g=>g.setAttribute("tabindex","-1"))}),e.jsx(pL,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:wa(i,f=>{f.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(Ore,{...d,...o,onPointerDown:wa(o.onPointerDown,f=>{f.currentTarget.contains(f.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:m?"text":void 0,WebkitUserSelect:m?"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)"}})})}),eon="HoverCardArrow",ton=_.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=cIe(n);return e.jsx(zre,{...a,...r,ref:t})});ton.displayName=eon;function UEe(s){return t=>t.pointerType==="touch"?void 0:s()}function son(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 non=JVt,ron=tHt,nHt=sHt;const aon=non,ion=ron,rHt=_.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(nHt,{ref:a,align:t,sideOffset:n,className:Ct("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}));rHt.displayName=nHt.displayName;const oon=[{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"}],lon=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),aHt=({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(aon,{openDelay:200,closeDelay:100,children:[e.jsx(ion,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(rHt,{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=oon.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(ja,{className:"h-6 w-6",children:[e.jsx(xi,{src:l.user_avatar||void 0}),e.jsx(Na,{className:"text-[10px]",children:lon(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 con({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=_.useState(t),[l,o]=_.useState(!1);_.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(m=>m>0?m-1:s.length-1),o(!1)},d=()=>{i(m=>m{n&&(m.key==="ArrowLeft"&&c(),m.key==="ArrowRight"&&d(),m.key==="Escape"&&r(!1))},[n,s.length]);_.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(Is,{open:n,onOpenChange:r,children:e.jsxs(Ls,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(z,{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(er,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(z,{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(Wc,{className:"h-8 w-8"})}),e.jsx(z,{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(yi,{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(z,{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(Nq,{className:"h-5 w-5"}):e.jsx(fP,{className:"h-5 w-5"})}),e.jsx("div",{className:Ct("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(h==null?void 0:h.type)==="image"&&o(!l),children:(h==null?void 0:h.type)==="video"?e.jsx("video",{src:h.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:m=>m.stopPropagation()}):e.jsx("img",{src:h==null?void 0:h.url,alt:"",className:Ct("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((m,p)=>e.jsx("button",{onClick:()=>{i(p),o(!1)},className:Ct("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===p?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:m.type==="video"?e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:m.url,alt:"",className:"w-full h-full object-cover"})},p))})]})})}const Nce=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],don=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=$t(),[a,i]=_.useState(!1),l=t.find(h=>h.user_id===n),o=mt({mutationFn:async h=>{l?l.reaction_type===h?await U.from("community_comment_reactions").delete().eq("id",l.id):await U.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await U.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(aHt,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(h=>{var m;return e.jsx("span",{className:"text-sm",children:(m=Nce.find(p=>p.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(hd,{open:a,onOpenChange:i,children:[e.jsx(md,{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=Nce.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=Nce.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fo,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(nd,{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:Nce.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 gst({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(or,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Ct("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(_.Fragment,{children:o},c))})}function qEe({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=_.useRef(null),h=_.useRef(null),[m,p]=_.useState(!1),[f,g]=_.useState("user"),[v,y]=_.useState(""),[b,w]=_.useState(null),[S,C]=_.useState(0),[E,P]=_.useState({top:0,left:0,width:0}),M=_.useRef(new Map),I=_.useRef(new Map),D=te=>{if(c==="plain"){const he=[];return M.current.forEach((Ee,Ne)=>{te.includes(`@${Ne}`)&&he.push(Ee)}),[...new Set(he)]}const ce=/@\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let me;for(;(me=ce.exec(te))!==null;)ve.push(me[2]);return[...new Set(ve)]},F=te=>{if(c==="plain"){const he=[];return I.current.forEach((Ee,Ne)=>{te.includes(`#${Ne}`)&&he.push(Ee)}),[...new Set(he)]}const ce=/#\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let me;for(;(me=ce.exec(te))!==null;)ve.push(me[2]);return[...new Set(ve)]};_.useEffect(()=>{if(i){const te=D(s);i(te)}if(l){const te=F(s);l(te)}},[s,i,l,c]);const{data:q=[],isLoading:G}=rt({queryKey:["mention-users",v],queryFn:async()=>{const te=U.from("profiles").select("id, name").limit(8),ce=v.length>=1?te.ilike("name",`%${v}%`):te.order("name"),{data:ve,error:me}=await ce;if(me)throw me;const he=ve.map(Ee=>Ee.id),ge=await D8t(he);return ve.map(Ee=>({id:Ee.id,name:Ee.name||"Unknown",avatar_url:ge.get(Ee.id)}))},enabled:m&&f==="user",staleTime:3e4}),{data:V=[],isLoading:H}=rt({queryKey:["mention-templates",v],queryFn:async()=>{let te=U.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&&(te=te.ilike("name",`%${v}%`));const{data:ce,error:ve}=await te;if(ve)throw ve;return ce||[]},enabled:m&&f==="template"&&d,staleTime:3e4}),K=f==="user"?G:H,Z=f==="user"?q:V,oe=te=>te.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),re=te=>{const ce=te.target.value,ve=te.target.selectionStart;t(ce);const me=ce.substring(0,ve),he=me.lastIndexOf("@"),ge=d?me.lastIndexOf("#"):-1;let Ee=-1,Ne="user";if(he>ge?(Ee=he,Ne="user"):ge>he&&d&&(Ee=ge,Ne="template"),Ee!==-1){const Pe=me.substring(Ee+1),Oe=Pe.includes(" "),ke=Pe.includes(` `);if(!Oe&&!ke&&Pe.length<=30){w(Ee),y(Pe),g(Ne),p(!0),C(0);return}}p(!1),w(null)},ae=te=>{if(b===null)return;const ce=s.substring(0,b),ve=s.substring(b+v.length+1),me=f==="user"?"@":"#",he=c==="plain"?`${me}${te.name} `:`${me}[${te.name}](${te.id}) `;c==="plain"&&(f==="user"?M.current.set(te.name,te.id):I.current.set(te.name,te.id));const ge=ce+he+ve;t(ge),p(!1),w(null),y(""),setTimeout(()=>{if(u.current){const Ee=ce.length+he.length;u.current.focus(),u.current.setSelectionRange(Ee,Ee)}},0)},J=te=>{if(!(!m||Z.length===0))switch(te.key){case"ArrowDown":te.preventDefault(),C(ce=>(ce+1)%Z.length);break;case"ArrowUp":te.preventDefault(),C(ce=>(ce-1+Z.length)%Z.length);break;case"Enter":Z[S]&&(te.preventDefault(),ae(Z[S]));break;case"Escape":te.preventDefault(),p(!1);break;case"Tab":Z[S]&&(te.preventDefault(),ae(Z[S]));break}};return _.useEffect(()=>{const te=ce=>{h.current&&!h.current.contains(ce.target)&&u.current&&!u.current.contains(ce.target)&&p(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[]),_.useEffect(()=>{if(!m)return;const te=()=>{const ce=u.current;if(!ce)return;const ve=ce.getBoundingClientRect();P({top:ve.bottom+4,left:ve.left,width:ve.width})};return te(),window.addEventListener("resize",te),window.addEventListener("scroll",te,!0),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ps,{ref:u,value:s,onChange:re,onKeyDown:te=>{J(te),te.defaultPrevented||o==null||o(te)},placeholder:n,className:Ct("resize-none",r),style:{minHeight:a}}),m&&pv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:E.top,left:E.left,width:E.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:f==="user"?"👤 Mention a person":"📋 Link a template"}),K?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):Z.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:v.length<1?`Type to search ${f==="user"?"people":"templates"}...`:`No ${f==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:Z.map((te,ce)=>e.jsx("li",{className:Ct("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ce===S?"bg-accent":"hover:bg-accent/50"),onClick:()=>ae(te),onMouseEnter:()=>C(ce),children:f==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(xi,{src:te.avatar_url}),e.jsx(Na,{className:"text-xs",children:oe(te.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:te.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:te.preview_image_url?e.jsx("img",{src:te.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(yc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:te.name})]})},te.id))})]}),document.body)]})}function uon(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const i1t=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function iHt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=$t(),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState([]),f=mt({mutationFn:async({content:b,parentCommentId:w})=>{const{data:S,error:C}=await U.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:w}).select("id").single();if(C)throw C;const E=m;if(E.length>0&&S){const P=E.filter(M=>M!==n).map(M=>({comment_id:S.id,mentioned_user_id:M,mentioned_by_user_id:n}));P.length>0&&await U.from("community_comment_mentions").insert(P)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),p([]),d(!1)}}),g=mt({mutationFn:async b=>{const{error:w}=await U.from("community_comments").delete().eq("id",b);if(w)throw w},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),v=()=>{u.trim()&&f.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(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:s.user_avatar||void 0}),e.jsx(Na,{className:"text-xs",children:i1t(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(gst,{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:Md(new Date(s.created_at),{addSuffix:!0})}),e.jsx(don,{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(oq,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>g.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(ja,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(xi,{src:r||void 0}),e.jsx(Na,{className:"text-xs",children:i1t((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(qEe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:p,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:v,disabled:!u.trim()||f.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Fr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(b=>e.jsx(iHt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const kce=[{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"}],hon=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=hs(),{avatarUrl:a}=I8t(s==null?void 0:s.id),{onlineUsers:i}=bIt(),{toast:l}=_i(),o=$t(),c=_.useRef(null),[d,u]=_.useState("all"),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState([]),[w,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState(!1),[I,D]=_.useState(null),[F,q]=_.useState(""),[G,V]=_.useState(new Set),[H,K]=_.useState({}),[Z,oe]=_.useState({}),[re,ae]=_.useState([]),[J,te]=_.useState([]),[ce,ve]=_.useState({open:!1,images:[],index:0});_.useEffect(()=>{if(d.startsWith("group:")){const lt=d.replace("group:","");v(lt),f("")}else d!=="all"?(f(d),v("")):(f(""),v(""))},[d]);const{data:me=[]}=rt({queryKey:["community-categories"],queryFn:async()=>{const{data:lt,error:qt}=await U.from("community_categories").select("*").order("sort_order");if(qt)throw qt;return lt}}),{data:he=[]}=rt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:lt,error:qt}=await U.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(qt)throw qt;return lt}}),ge=20,{data:Ee,isLoading:Ne,hasNextPage:Pe,fetchNextPage:Oe,isFetchingNextPage:ke}=TLt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:lt})=>{var gt;const qt=lt*ge,zt=qt+ge;let Zt=U.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(qt,zt);if(d.startsWith("group:")){const ft=d.replace("group:","");Zt=Zt.eq("private_group_id",ft)}else d==="all"||(Zt=Zt.eq("category_id",d).is("private_group_id",null));const{data:ms,error:Dt}=await Zt;if(Dt)throw Dt;const It=((ms==null?void 0:ms.length)||0)>ge,qs=(ms||[]).slice(0,ge);if(qs.length===0)return{posts:[],hasMore:!1,nextPage:lt+1};const wt=qs.map(ft=>ft.id),Us=[...new Set(qs.filter(ft=>ft.category_id).map(ft=>ft.category_id))].filter(Boolean),[Es,kn,Sn,bn,cr]=await Promise.all([Us.length?U.from("community_categories").select("*").in("id",Us):Promise.resolve({data:[]}),U.from("community_post_media").select("*").in("post_id",wt).order("sort_order"),U.from("community_reactions").select("*").in("post_id",wt),U.from("community_comments").select("*").in("post_id",wt).order("created_at",{ascending:!0}),U.from("community_post_resources").select("*").in("post_id",wt)]),Fs=Es==null?void 0:Es.data,cn=kn==null?void 0:kn.data,lr=Sn==null?void 0:Sn.data,Tn=bn==null?void 0:bn.data,Yn=cr==null?void 0:cr.data,fs=(Tn||[]).map(ft=>ft.id),[wn,As]=await Promise.all([fs.length?U.from("community_comment_reactions").select("*").in("comment_id",fs):Promise.resolve({data:[]}),(()=>{const ft=(Yn||[]).filter(Lt=>Lt.resource_type==="template").map(Lt=>Lt.resource_id);return ft.length===0?Promise.resolve({data:[]}):U.from("canva_templates").select("id, name, preview_image_url").in("id",ft)})()]),Ss=(wn==null?void 0:wn.data)||[],pr=(As==null?void 0:As.data)||[],hn=new Map(pr.map(ft=>[ft.id,{name:ft.name,preview_image_url:ft.preview_image_url}])),Pn=Array.from(new Set([...qs.map(ft=>ft.user_id),...(lr||[]).map(ft=>ft.user_id),...(Tn||[]).map(ft=>ft.user_id),...Ss.map(ft=>ft.user_id)])),[Gs,an]=await Promise.all([Pn.length?U.from("profiles").select("id, name").in("id",Pn):Promise.resolve({data:[]}),D8t(Pn)]),tr=new Map(((gt=Gs==null?void 0:Gs.data)==null?void 0:gt.map(ft=>[ft.id,ft.name]))||[]),Lr=new Map((Fs||[]).map(ft=>[ft.id,ft])),Yt=ft=>{const Lt=new Map,Mt=[];return ft.forEach(Qt=>{Lt.set(Qt.id,{...Qt,user_name:tr.get(Qt.user_id)||"Unknown User",user_avatar:an.get(Qt.user_id),reactions:Ss.filter(ks=>ks.comment_id===Qt.id).map(ks=>({...ks,user_name:tr.get(ks.user_id)||"Unknown User",user_avatar:an.get(ks.user_id)})),replies:[]})}),ft.forEach(Qt=>{const ks=Lt.get(Qt.id);if(Qt.parent_comment_id&&Lt.has(Qt.parent_comment_id)){const gs=Lt.get(Qt.parent_comment_id);gs.replies=gs.replies||[],gs.replies.push(ks)}else Mt.push(ks)}),Mt};return{posts:qs.map(ft=>{const Lt=(Yn||[]).filter(Mt=>Mt.post_id===ft.id).map(Mt=>{let Qt="",ks=null;if(Mt.resource_type==="template"){const gs=hn.get(Mt.resource_id);Qt=(gs==null?void 0:gs.name)||"Unknown Template",ks=(gs==null?void 0:gs.preview_image_url)||null}return{id:Mt.id,resource_type:Mt.resource_type,resource_id:Mt.resource_id,resource_name:Qt,resource_preview_url:ks}});return{...ft,user_name:tr.get(ft.user_id)||"Unknown User",user_avatar:an.get(ft.user_id),category:ft.category_id?Lr.get(ft.category_id):null,media:(cn||[]).filter(Mt=>Mt.post_id===ft.id),reactions:((lr||[]).filter(Mt=>Mt.post_id===ft.id)||[]).map(Mt=>({...Mt,user_name:tr.get(Mt.user_id)||"Unknown User",user_avatar:an.get(Mt.user_id)})),comments:Yt((Tn||[]).filter(Mt=>Mt.post_id===ft.id)),resources:Lt}}),hasMore:It,nextPage:lt+1}},getNextPageParam:lt=>lt.hasMore?lt.nextPage:void 0}),Ve=_.useMemo(()=>(Ee==null?void 0:Ee.pages.flatMap(lt=>lt.posts))??[],[Ee]),_e=mt({mutationFn:async()=>{M(!0);const{data:lt,error:qt}=await U.from("community_posts").insert({user_id:s.id,category_id:g?null:p||null,private_group_id:g||null,content:h,link_url:C||null}).select().single();if(qt)throw qt;for(let Zt=0;Zt0){const Zt=re.filter(ms=>ms!==s.id).map(ms=>({post_id:lt.id,mentioned_user_id:ms,mentioned_by_user_id:s.id}));Zt.length>0&&await U.from("community_post_mentions").insert(Zt)}const zt=uon(h);if(zt.length>0){const Zt=zt.map(ms=>({post_id:lt.id,resource_type:"template",resource_id:ms}));await U.from("community_post_resources").insert(Zt)}return lt},onSuccess:async lt=>{var qt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),ae([]),te([]),f(""),v(""),b([]),S([]),E(""),l({title:"Post created!"});try{const zt=((qt=s==null?void 0:s.user_metadata)==null?void 0:qt.name)||"Someone",Zt=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),ms=Zt.length>50?Zt.substring(0,50)+"...":Zt;await U.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${zt}: ${ms}`,url:"/community"}})}catch(zt){console.error("Failed to send push notification:",zt)}},onError:lt=>{l({title:"Error creating post",description:lt.message,variant:"destructive"})},onSettled:()=>M(!1)}),Ae=mt({mutationFn:async({postId:lt,content:qt})=>{const{error:zt}=await U.from("community_posts").update({content:qt}).eq("id",lt);if(zt)throw zt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),D(null),q(""),l({title:"Post updated!"})}}),Se=mt({mutationFn:async lt=>{const{error:qt}=await U.from("community_posts").delete().eq("id",lt);if(qt)throw qt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),We=mt({mutationFn:async({postId:lt,isPinned:qt})=>{const{error:zt}=await U.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",lt);if(zt)throw zt},onSuccess:(lt,{isPinned:qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:qt?"Post unpinned":"Post pinned to top"})}}),qe=mt({mutationFn:async({postId:lt,reactionType:qt})=>{var Zt;const zt=(Zt=Ve.find(ms=>ms.id===lt))==null?void 0:Zt.reactions.find(ms=>ms.user_id===(s==null?void 0:s.id));zt?zt.reaction_type===qt?await U.from("community_reactions").delete().eq("id",zt.id):await U.from("community_reactions").update({reaction_type:qt}).eq("id",zt.id):await U.from("community_reactions").insert({post_id:lt,user_id:s.id,reaction_type:qt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Be=mt({mutationFn:async({postId:lt,content:qt})=>{const{data:zt,error:Zt}=await U.from("community_comments").insert({post_id:lt,user_id:s.id,content:qt}).select("id").single();if(Zt)throw Zt;const ms=Z[lt]||[];if(ms.length>0&&zt){const Dt=ms.filter(It=>It!==s.id).map(It=>({comment_id:zt.id,mentioned_user_id:It,mentioned_by_user_id:s.id}));Dt.length>0&&await U.from("community_comment_mentions").insert(Dt)}},onSuccess:(lt,{postId:qt})=>{o.invalidateQueries({queryKey:["community-posts"]}),K(zt=>({...zt,[qt]:""})),oe(zt=>({...zt,[qt]:[]}))}});mt({mutationFn:async lt=>{const{error:qt}=await U.from("community_comments").delete().eq("id",lt);if(qt)throw qt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Ze=lt=>{const qt=Array.from(lt.target.files||[]);if(qt.length+y.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(zt=>[...zt,...qt]),qt.forEach(zt=>{const Zt=new FileReader;Zt.onloadend=()=>{S(ms=>[...ms,Zt.result])},Zt.readAsDataURL(zt)})},$e=lt=>{b(qt=>qt.filter((zt,Zt)=>Zt!==lt)),S(qt=>qt.filter((zt,Zt)=>Zt!==lt))},Xe=lt=>lt.split(" ").map(qt=>qt[0]).join("").toUpperCase().slice(0,2),nt=lt=>{const qt={};return lt.forEach(zt=>{qt[zt.reaction_type]=(qt[zt.reaction_type]||0)+1}),qt},Ge=lt=>{var qt;return(qt=lt.find(zt=>zt.user_id===(s==null?void 0:s.id)))==null?void 0:qt.reaction_type},Je=lt=>lt.reduce((qt,zt)=>qt+1+(zt.replies?Je(zt.replies):0),0),ut=lt=>{if(r)return!0;if(!t||!lt.private_group_id)return!1;const qt=he.find(zt=>zt.id===lt.private_group_id);return qt!=null&&qt.brokerage_id?n.some(zt=>zt.id===qt.brokerage_id):!1};return e.jsx($s,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(Kin,{categories:me,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(Yin,{categories:me,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:a||void 0}),e.jsx(Na,{children:s!=null&&s.email?Xe(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(qEe,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:m,onMentionsChange:ae,onTemplatesChange:te,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),w.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:w.map((lt,qt)=>{var zt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(zt=y[qt])!=null&&zt.type.startsWith("video/")?e.jsx("video",{src:lt,className:"w-full h-full object-cover"}):e.jsx("img",{src:lt,alt:"",className:"w-full h-full object-cover"}),e.jsx(z,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>$e(qt),children:e.jsx(er,{className:"h-3 w-3"})})]},qt)})}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:C,onChange:lt=>E(lt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>E(""),children:e.jsx(er,{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:Ze,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>{var lt;return(lt=c.current)==null?void 0:lt.click()},children:[e.jsx(nc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>{var lt;return(lt=c.current)==null?void 0:lt.click()},children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>E("https://"),children:[e.jsx(Kc,{className:"h-4 w-4 mr-1"}),"Link"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[he.length>0?e.jsxs(ls,{value:g||p||"none",onValueChange:lt=>{lt==="none"?(f(""),v("")):lt.startsWith("group:")?(v(lt.replace("group:","")),f("")):(f(lt),v(""))},children:[e.jsx(rs,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(cs,{placeholder:"Select..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No category"}),me.map(lt=>e.jsxs(He,{value:lt.id,children:[lt.icon," ",lt.name]},lt.id)),he.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),he.map(lt=>e.jsxs(He,{value:`group:${lt.id}`,children:[lt.icon||"🔒"," ",lt.name]},lt.id))]})]})]}):e.jsxs(ls,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(cs,{placeholder:"Category"})}),e.jsx(as,{children:me.map(lt=>e.jsxs(He,{value:lt.id,children:[lt.icon," ",lt.name]},lt.id))})]}),e.jsxs(z,{size:"sm",onClick:()=>_e.mutate(),disabled:!h.trim()||P,children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Ne?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((lt,qt)=>e.jsx(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ln,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ln,{className:"h-4 w-32"}),e.jsx(ln,{className:"h-4 w-full"}),e.jsx(ln,{className:"h-4 w-3/4"})]})]})})},qt))}):Ve.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Bu,{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:[Ve.map(lt=>{var qt,zt,Zt,ms;return e.jsx(be,{children:e.jsxs(Le,{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(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:lt.user_avatar||void 0}),e.jsx(Na,{children:Xe(lt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:lt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Md(new Date(lt.created_at),{addSuffix:!0})}),lt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[lt.category.icon," ",lt.category.name]})]})]})]})]}),(lt.user_id===(s==null?void 0:s.id)||ut(lt))&&e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(lb,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[ut(lt)&<.private_group_id&&e.jsx(ua,{onClick:()=>We.mutate({postId:lt.id,isPinned:lt.is_pinned}),children:lt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(cJ,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(JA,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),lt.user_id===(s==null?void 0:s.id)&&e.jsxs(ua,{onClick:()=>{D(lt),q(lt.content)},children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ua,{className:"text-destructive",onClick:()=>Se.mutate(lt.id),children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),lt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),lt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(JA,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(gst,{content:lt.content})}),lt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${lt.media.length===1?"grid-cols-1":lt.media.length===2?"grid-cols-2":lt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:lt.media.slice(0,4).map((Dt,It)=>{const qs=It===3&<.media.length>4,wt=lt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${lt.media.length===1?"max-h-[500px]":lt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>ve({open:!0,images:lt.media.map(Us=>({url:Us.media_url,type:Us.media_type==="video"?"video":"image"})),index:It}),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"})})})}),qs&&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:["+",wt]})})]},Dt.id)})}),lt.link_url&&e.jsxs("a",{href:lt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[lt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:lt.link_image,alt:lt.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:lt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:lt.link_title}),lt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:lt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(lt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Kc,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:lt.link_url})]})})]}),lt.reactions.length>0&&e.jsx(aHt,{reactions:lt.reactions,children:e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[e.jsx("div",{className:"flex -space-x-1",children:Object.entries(nt(lt.reactions)).slice(0,3).map(([Dt])=>{var It;return e.jsx("span",{className:"text-base",children:(It=kce.find(qs=>qs.type===Dt))==null?void 0:It.emoji},Dt)})}),e.jsx("span",{children:lt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:"flex-1",children:[Ge(lt.reactions)?e.jsx("span",{className:"mr-1",children:(qt=kce.find(Dt=>Dt.type===Ge(lt.reactions)))==null?void 0:qt.emoji}):e.jsx(Ug,{className:"h-4 w-4 mr-1"}),Ge(lt.reactions)?(zt=kce.find(Dt=>Dt.type===Ge(lt.reactions)))==null?void 0:zt.label:"Like"]})}),e.jsx(nd,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:kce.map(Dt=>e.jsx("button",{onClick:()=>qe.mutate({postId:lt.id,reactionType:Dt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Dt.label,children:Dt.emoji},Dt.type))})})]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>V(Dt=>{const It=new Set(Dt);return It.has(lt.id)?It.delete(lt.id):It.add(lt.id),It}),children:[e.jsx(Bu,{className:"h-4 w-4 mr-1"}),(()=>{const Dt=Je(lt.comments);return Dt>0?`Comment (${Dt})`:"Comment"})()]})]}),G.has(lt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[lt.comments.map(Dt=>e.jsx(iHt,{comment:Dt,postId:lt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:ut(lt)},Dt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:a||void 0}),e.jsx(Na,{className:"text-xs",children:Xe(((Zt=s.email)==null?void 0:Zt.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(qEe,{placeholder:"Write a comment... (use @ to mention)",value:H[lt.id]||"",onChange:Dt=>K(It=>({...It,[lt.id]:Dt})),onMentionsChange:Dt=>oe(It=>({...It,[lt.id]:Dt})),mentionFormat:"plain",onKeyDown:Dt=>{var It;Dt.defaultPrevented||Dt.key==="Enter"&&!Dt.shiftKey&&((It=H[lt.id])!=null&&It.trim())&&(Dt.preventDefault(),Be.mutate({postId:lt.id,content:H[lt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>{var Dt;(Dt=H[lt.id])!=null&&Dt.trim()&&Be.mutate({postId:lt.id,content:H[lt.id]})},disabled:!((ms=H[lt.id])!=null&&ms.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Fr,{className:"h-4 w-4"})})]})]})]})]})},lt.id)}),Pe&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(z,{variant:"outline",onClick:()=>Oe(),disabled:ke,children:ke?"Loading…":"Load more posts"})})]}),e.jsx(Is,{open:!!I,onOpenChange:()=>D(null),children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Edit Post"})}),e.jsx(Ps,{value:F,onChange:lt=>q(lt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>D(null),children:"Cancel"}),e.jsx(z,{onClick:()=>{I&&Ae.mutate({postId:I.id,content:F})},disabled:!F.trim(),children:"Save Changes"})]})]})}),e.jsx(con,{images:ce.images,initialIndex:ce.index,open:ce.open,onOpenChange:lt=>ve(qt=>({...qt,open:lt}))})]})]})})},mon=50*1024*1024;function oHt({value:s,onChange:t,disabled:n}){const{user:r}=hs(),a=_.useRef(null),[i,l]=_.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/")){ne.error(`${h.name}: only images and videos allowed`);continue}if(h.size>mon){ne.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",p=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:f}=await U.storage.from("support-attachments").upload(p,h,{contentType:h.type,upsert:!1});if(f){ne.error(`${h.name}: ${f.message}`);continue}u.push({path:p,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await U.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(zQ,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(rP,{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(er,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(z,{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(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(dP,{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 lHt({attachments:s}){const[t,n]=_.useState({}),[r,a]=_.useState(!0);return _.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await U.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),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(bt,{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 UB={open:{label:"Open",icon:Zr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Bu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Xl,color:"bg-green-500"},closed:{label:"Closed",icon:Bd,color:"bg-muted-foreground"}},o1t={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function pon(){const{user:s}=hs(),t=$t(),[n,r]=_.useState(null),[a,i]=_.useState(""),[l,o]=_.useState([]),{data:c=[],isLoading:d}=rt({queryKey:["support-tickets"],queryFn:async()=>{const{data:p,error:f}=await U.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(f)throw f;return p},enabled:!!s}),{data:u=[]}=rt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:p,error:f}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(f)throw f;return p},enabled:!!n}),h=mt({mutationFn:async({content:p,attachments:f})=>{if(!n||!s)throw new Error("Missing data");const{error:g}=await U.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:p,is_admin_reply:!1,attachments:f});if(g)throw g},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ne.success("Reply sent!")},onError:()=>{ne.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const p=UB[n.status].icon;return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(ka,{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:o1t[n.category]}),e.jsxs(ze,{className:UB[n.status].color,children:[e.jsx(p,{className:"h-3 w-3 mr-1"}),UB[n.status].label]})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(En,{children:["Created on ",Ys(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Le,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Le,{children:[e.jsx(Ki,{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(f=>{var g;return e.jsxs("div",{className:`p-4 rounded-lg ${f.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:f.is_admin_reply?"Support Team":((g=f.profiles)==null?void 0:g.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(f.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:f.content}),f.attachments&&f.attachments.length>0&&e.jsx(lHt,{attachments:f.attachments})]},f.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(fc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ps,{placeholder:"Type your reply...",value:a,onChange:f=>i(f.target.value),className:"min-h-[80px]"}),e.jsx(z,{onClick:m,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(Fr,{className:"h-4 w-4"})})]}),e.jsx(oHt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Le,{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(v4,{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(nVe,{trigger:e.jsxs(z,{size:"lg",className:"gap-2",children:[e.jsx(sn,{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(va,{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(nVe,{trigger:e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(sn,{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(be,{className:"border-dashed",children:e.jsxs(Le,{className:"text-center py-12",children:[e.jsx(Bu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(p=>{const f=UB[p.status].icon;return e.jsx(be,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(p),children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:p.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"outline",className:"text-xs",children:o1t[p.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(p.created_at),"MMM d, yyyy")})]})]}),e.jsxs(ze,{className:UB[p.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),UB[p.status].label]})]})})},p.id)})})]})})}function fon({open:s,onOpenChange:t}){return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Os,{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(ya,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rs,{children:"Schedule Agent Onboarding"}),e.jsx(_r,{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 xon({open:s,onOpenChange:t}){const{brokerageId:n}=hs(),[r,a]=_.useState(""),[i,l]=_.useState([]),[o,c]=_.useState(!1),{data:d,isLoading:u}=rt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:g,error:v}=await U.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(v)throw v;return g},enabled:s&&!!n}),h=d==null?void 0:d.filter(g=>g.name.toLowerCase().includes(r.toLowerCase())||g.email.toLowerCase().includes(r.toLowerCase())),m=g=>{l(v=>v.includes(g)?v.filter(y=>y!==g):[...v,g])},p=async()=>{if(i.length===0){ne.error("Please select at least one agent");return}c(!0);try{const{data:g,error:v}=await U.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(v)throw v;ne.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(g){console.error("Error sending onboarding link:",g),ne.error(g.message||"Failed to send onboarding link")}finally{c(!1)}},f=g=>{g||(l([]),a("")),t(g)};return e.jsx(Is,{open:s,onOpenChange:f,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Fr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rs,{children:"Send Onboarding Link"}),e.jsx(_r,{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(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:r,onChange:g=>a(g.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{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(On,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Ki,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(g=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>m(g.id),children:[e.jsx(za,{checked:i.includes(g.id),onCheckedChange:()=>m(g.id)}),e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{className:"text-xs",children:g.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:g.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:g.email})]})]},g.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(z,{onClick:p,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function gon(){const[s,t]=_.useState(!1),[n,r]=_.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"mb-8",children:[e.jsx(_t,{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(On,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Nt,{children:"Agent Onboarding"}),e.jsx(En,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Le,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(z,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(z,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(fon,{open:s,onOpenChange:t}),e.jsx(xon,{open:n,onOpenChange:r})]})}function yon({open:s,onOpenChange:t}){return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Os,{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(Xf,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rs,{children:"Schedule Launch Meeting"}),e.jsx(_r,{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 von(){const[s,t]=_.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"mb-8",children:[e.jsx(_t,{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(Xf,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Nt,{children:"Launch or ReLaunch Meeting"}),e.jsx(En,{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(Le,{children:e.jsxs(z,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(Xf,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(yon,{open:s,onOpenChange:t})]})}function bon(){const s=zn(),[t,n]=_.useState(""),[r,a]=_.useState(null),{data:i,isLoading:l}=rt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:g,error:v}=await U.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return g}}),{data:o}=rt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:g,error:v}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(v)throw v;return g}}),{data:c}=rt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:g,error:v}=await U.from("brokerage_resource_pdfs").select("resource_id");if(v)throw v;return g}}),{data:d}=rt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:g,error:v}=await U.from("brokerage_resource_videos").select("resource_id");if(v)throw v;return g}}),{data:u}=rt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:g,error:v}=await U.from("brokerage_resource_links").select("resource_id");if(v)throw v;return g}}),h=i==null?void 0:i.filter(g=>{var b;const v=g.title.toLowerCase().includes(t.toLowerCase())||((b=g.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),y=!r||g.category_id===r;return v&&y}),m=o==null?void 0:o.filter(g=>i==null?void 0:i.some(v=>v.category_id===g.id)),p=g=>{const v=(c==null?void 0:c.filter(w=>w.resource_id===g).length)||0,y=(d==null?void 0:d.filter(w=>w.resource_id===g).length)||0,b=(u==null?void 0:u.filter(w=>w.resource_id===g).length)||0;return{pdfCount:v,videoCount:y,linkCount:b}},f=g=>{s(`/brokerage-resources/${g}`)};return e.jsx($s,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gon,{}),e.jsx(von,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search resources...",value:t,onChange:g=>n(g.target.value),className:"pl-10"})]}),m&&m.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"}),m.map(g=>e.jsx(ze,{variant:r===g.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(g.id),children:g.name},g.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((g,v)=>e.jsxs(be,{children:[e.jsx(ln,{className:"h-40 w-full"}),e.jsx(_t,{children:e.jsx(ln,{className:"h-5 w-3/4"})}),e.jsxs(Le,{children:[e.jsx(ln,{className:"h-4 w-full mb-2"}),e.jsx(ln,{className:"h-4 w-2/3"})]})]},v))}):(h==null?void 0:h.length)===0?e.jsxs(be,{className:"p-12 text-center",children:[e.jsx(Px,{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(g=>{const{pdfCount:v,videoCount:y,linkCount:b}=p(g.id),w=o==null?void 0:o.find(S=>S.id===g.category_id);return e.jsxs(be,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>f(g.id),children:[g.preview_image_url?e.jsx("img",{src:g.preview_image_url,alt:g.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(Px,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(_t,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Nt,{className:"text-lg line-clamp-1",children:g.title}),w&&e.jsx(ze,{variant:"secondary",className:"shrink-0 text-xs",children:w.name})]})}),e.jsxs(Le,{children:[g.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:g.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($r,{className:"h-4 w-4"}),v]}),y>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-4 w-4"}),y]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Kc,{className:"h-4 w-4"}),b]})]})]})]},g.id)})})]})})}const _on=()=>{const{resourceId:s}=Mi(),{data:t,isLoading:n}=rt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await U.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await U.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await U.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await U.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),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($s,{title:"Brokerage Resources",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):t?e.jsx($s,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/brokerage-resources",children:[e.jsx(ka,{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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Xr,{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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{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($r,{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(Ga,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(mr,{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(mr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(mr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx($s,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Px,{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(z,{asChild:!0,className:"mt-4",children:e.jsx(or,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function won(){const{onlineUsers:s,totalOnline:t}=bIt(),{user:n}=hs();return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(ze,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Gf,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Le,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No users online right now"}):e.jsx(Ki,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var a;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(xi,{src:r.avatarUrl,alt:r.name}),e.jsx(Na,{className:"text-xs",children:(a=r.name)==null?void 0:a.split(" ").map(i=>i[0]).join("").slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-background"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[r.name,r.id===(n==null?void 0:n.id)?" (You)":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",Md(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const l1t={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:Nh,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:On,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:Ko,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:v7,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:j0,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:LQ,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:Ip,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:sd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:On,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:bu,path:"/admin/prospector",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Recruiting",description:"Manage agent recruit pipeline and outreach",icon:Pl,path:"/admin/recruiting",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Coaching",description:"Promote coaches and manage agent coaching assignments",icon:jl,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Blog",description:"Write founder articles, moderate comments, publish to /blog",icon:vN,path:"/admin/blog",color:"bg-amber-500/10 text-amber-600"},{title:"Manage Templates",description:"Upload and organize Canva templates",icon:yc,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:fm,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:fm,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:eC,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:vN,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:vN,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:gc,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:Nv,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Px,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Px,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:on,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:Nh,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:oP,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Vw,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:on,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:Nh,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:fN,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:J4,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:Ko,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:jl,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:Oc,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:On,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:Nh,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:qi,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:ZU,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:yS,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Ia,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:on,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:wl,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:ip,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:C0,path:"/admin/music-videos",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"},{title:"Video Lab (Beta)",description:"Admin-only Higgsfield AI: describe a 5–10s clip or animate a listing photo",icon:C0,path:"/admin/video-lab",color:"bg-primary/10 text-primary"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:fm,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:Fo,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:sa,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Listing Leads",description:"View all leads from the public listings site with property & agent assignment",icon:Pl,path:"/admin/listing-leads",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Public Site Leads",description:"Alerts signups, exit-intent captures & saved-home leads from listings.relevelup.com",icon:Pl,path:"/admin/public-site-leads",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:C0,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Listing Presentation Studio",description:"Track every listing presentation agents build, generate, and send",icon:$r,path:"/admin/listing-presentation-studio",color:"bg-gradient-to-br from-slate-500/20 to-zinc-500/10 text-slate-600"},{title:"Listing Revival",description:"Track expired-listing campaigns, seller leads, and manage who has access",icon:un,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Staging Studio",description:"Member conversions gallery, credits, subscriptions, and credit pack pricing",icon:nc,path:"/admin/staging-studio",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:Yh,path:"/admin/weekly-reels",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"},{title:"Guest Book Analytics",description:"Track open house sign-in usage, visitors, and lead generation",icon:ip,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:nc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Mail Studio Designs",description:"Upload postcard designs for the Mail Studio template library",icon:on,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:Z4,path:"/admin/beta/homereel",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Video Lab",description:"Higgsfield AI: describe a 5–10s cinematic clip or bring a listing photo to life",icon:Yh,path:"/admin/video-lab",color:"bg-gradient-to-br from-cyan-500/20 to-blue-500/10 text-cyan-600"}]},"lead-sites":{label:"Lead Sites",sections:[{title:"All Sites",description:"Overview of all agent websites with status and quick actions",icon:Wo,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:zU,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Free Website Offers",description:"Choose which brokerages get a free luxury website, and set their default template",icon:Ko,path:"/admin/lead-sites/offers",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon:kl,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Beta Website Requests",description:"Member requests for free beta (non-IDX) agent websites — review, build and launch",icon:$r,path:"/admin/website-requests",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:$r,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:$r,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:Nd,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function c1t(){const s=zn();return console.log("[AdminDashboard] render"),e.jsx($s,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage all aspects of your platform"})]}),e.jsxs(Qr,{defaultValue:"users",className:"w-full",children:[e.jsx(Jr,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(l1t).map(([t,n])=>e.jsx(Wt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(l1t).map(([t,n])=>e.jsx(Kt,{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(be,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(_t,{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(Nt,{className:"text-base",children:r.title})]}),e.jsx(Le,{className:"pt-0",children:e.jsx(En,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(won,{})]})})}const jon=()=>{const{isAdmin:s}=hs(),t=zn(),[n,r]=_.useState([]),[a,i]=_.useState(!0),[l,o]=_.useState(!1),[c,d]=_.useState(null);_.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:g,error:v}=await U.from("app_tiles").select("*").order("name");if(v)throw v;r(g||[])}catch(g){console.error("Error loading apps:",g),ne.error("Failed to load apps")}finally{i(!1)}},h=async g=>{g.preventDefault();const v=new FormData(g.currentTarget),y={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(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await U.from("app_tiles").update(y).eq("id",c.id);if(b)throw b;ne.success("App updated successfully")}else{const{error:b}=await U.from("app_tiles").insert([y]);if(b)throw b;ne.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),ne.error("Failed to save app")}},m=async g=>{if(await Qi("Are you sure you want to delete this app?"))try{const{error:v}=await U.from("app_tiles").delete().eq("id",g);if(v)throw v;ne.success("App deleted successfully"),u()}catch(v){console.error("Error deleting app:",v),ne.error("Failed to delete app")}},p=g=>{d(g),o(!0)},f=()=>{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(z,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(ka,{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(Is,{open:l,onOpenChange:o,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{onClick:f,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:c?"Edit App":"Create New App"}),e.jsx(_r,{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(ee,{htmlFor:"name",children:"App Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"app_id",children:"App ID"}),e.jsx(pe,{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(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{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(ee,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(pe,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"target_url",children:"Target URL"}),e.jsx(pe,{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(ee,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(pe,{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(z,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(z,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Application Tiles"}),e.jsx(En,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Le,{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(z,{onClick:f,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"App ID"}),e.jsx(Tt,{children:"Target URL"}),e.jsx(Tt,{children:"Tags"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:n.map(g=>e.jsxs(fn,{children:[e.jsx(yt,{className:"text-2xl",children:g.icon}),e.jsx(yt,{className:"font-medium",children:g.name}),e.jsx(yt,{className:"font-mono text-sm",children:g.app_id}),e.jsx(yt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:g.target_url}),e.jsx(yt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:g.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(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>p(g),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>m(g.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},g.id))})]})})]})})]})};function Xh({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(or,{to:"/admin",children:e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(ka,{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 d1t=({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:Ct("gap-1",t),children:[e.jsx(nl,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(ze,{variant:"destructive",className:Ct("gap-1",t),children:[e.jsx(Zr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(ze,{className:Ct("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Zr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(ze,{variant:"secondary",className:Ct("gap-1",t),children:[e.jsx(Zr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},cHt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=_i(),l=_.useRef(null),[o,c]=_.useState([]),[d,u]=_.useState(""),[h,m]=_.useState(!1),[p,f]=_.useState("upload"),[g,v]=_.useState(null),y=()=>{c([]),u(""),f("upload"),v(null),l.current&&(l.current.value="")},b=()=>{y(),t(!1)},w=M=>{const I=M.split(` `).map(V=>V.trim()).filter(V=>V);if(I.length===0)return[];const D=I[0].toLowerCase(),q=D.includes("first")||D.includes("last")||D.includes("email")||D.includes("name")||D.includes("phone")||D.includes("sms")||D.includes("consent")?I.slice(1):I,G=[];for(const V of q){const K=(V.includes(" ")?V.split(" "):V.split(",")).map(Z=>Z.trim().replace(/^["']|["']$/g,""));if(K.length>=2){let Z="",oe="",re="",ae="",J;if(K.length===2){const ve=K[0].split(" ");Z=ve[0]||"",oe=ve.slice(1).join(" ")||"",re=K[1]}else if(K.length===3)Z=K[0],oe=K[1],re=K[2];else if(K.length===4)Z=K[0],oe=K[1],re=K[2],ae=K[3];else if(K.length>=5){Z=K[0],oe=K[1],re=K[2],ae=K[3];const ve=K[4].toLowerCase();J=ve==="true"||ve==="yes"||ve==="1"||ve==="y"}const ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(re);G.push({firstName:Z.trim(),lastName:oe.trim(),email:re.trim().toLowerCase(),phone:ae.trim()||void 0,smsConsent:J,isValid:ce&&Z.trim().length>0,error:ce?Z.trim()?void 0:"Missing name":"Invalid email"})}}return G},S=M=>{var F;const I=(F=M.target.files)==null?void 0:F[0];if(!I)return;const D=new FileReader;D.onload=q=>{var H;const G=(H=q.target)==null?void 0:H.result,V=w(G);if(V.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(V),f("preview")},D.readAsText(I)},C=async()=>{const M=o.filter(D=>D.isValid);if(M.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const I=r||d||null;m(!0);try{const{data:{session:D}}=await U.auth.getSession(),F=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({users:M.map(G=>({firstName:G.firstName,lastName:G.lastName,email:G.email,phone:G.phone,smsConsent:G.smsConsent})),brokerageId:I})}),q=await F.json();if(!F.ok)throw new Error(q.error||"Failed to import users");v(q),f("result"),q.created>0&&a(),i({title:"Import Complete",description:`${q.created} user(s) created successfully.${q.failed>0?` ${q.failed} failed.`:""}`})}catch(D){console.error("Import error:",D),i({title:"Import Failed",description:D.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},E=o.filter(M=>M.isValid).length,P=o.filter(M=>!M.isValid).length;return e.jsx(Is,{open:s,onOpenChange:b,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(xN,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(_r,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),p==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:S,className:"hidden"}),e.jsx(Ra,{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(z,{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."})]})]}),p==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Assign to Brokerage (optional)"}),e.jsxs(ls,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a brokerage..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(He,{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(Mr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[E," valid"]})]}),P>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs("span",{children:[P," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"SMS"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Qa,{children:o.slice(0,100).map((M,I)=>e.jsxs(fn,{children:[e.jsx(yt,{children:M.firstName}),e.jsx(yt,{children:M.lastName}),e.jsx(yt,{children:M.email}),e.jsx(yt,{className:"text-muted-foreground",children:M.phone||"-"}),e.jsx(yt,{className:"text-muted-foreground",children:M.smsConsent===!0?"✓":M.smsConsent===!1?"✗":"-"}),e.jsx(yt,{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"})})]},I))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),p==="result"&&g&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Mr,{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:[g.created," agent(s) created and invited"]}),g.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[g.failed," failed to create"]})]}),g.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:[g.errors.slice(0,10).map((M,I)=>e.jsxs("li",{children:["• ",M]},I)),g.errors.length>10&&e.jsxs("li",{children:["...and ",g.errors.length-10," more"]})]})]})]}),e.jsxs(hr,{children:[p==="upload"&&e.jsx(z,{variant:"outline",onClick:b,children:"Cancel"}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"outline",onClick:y,children:"Back"}),e.jsx(z,{onClick:C,disabled:h||E===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${E} Agent${E!==1?"s":""}`})]}),p==="result"&&e.jsx(z,{onClick:b,children:"Done"})]})]})})};function Hh({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Tt,{className:Ct("cursor-pointer select-none",i),...l,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 font-semibold hover:text-foreground transition-colors w-full text-left",onClick:()=>r(s),children:[a,o?n==="asc"?e.jsx(ap,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Vf,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Og,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function Mae(s=null,t=null){const[n,r]=_.useState(s),[a,i]=_.useState(t),l=_.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=_.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,m)=>{const p=u(h),f=u(m);if(p==null&&f==null)return 0;if(p==null)return 1;if(f==null)return-1;let g;return typeof p=="string"&&typeof f=="string"?g=p.localeCompare(f,void 0,{sensitivity:"base"}):g=p-f,a==="asc"?g:-g})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const Non=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Ia},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:jl},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:Ix}];function dHt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=_.useState("custom"),[l,o]=_.useState(""),[c,d]=_.useState(""),u=V6s(),h=p=>{i(p.type),o(p.title),d(p.message)},m=async p=>{if(p.preventDefault(),!l.trim()){la({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}),la({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{la({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Ix,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(_r,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(ee,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Non.map((p,f)=>e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>h(p),className:"text-xs",children:[e.jsx(p.icon,{className:"h-3 w-3 mr-1"}),p.title]},f))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(ls,{value:a,onValueChange:p=>i(p),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"})," Custom"]})}),e.jsx(He,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(He,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(He,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:l,onChange:p=>o(p.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ps,{id:"message",value:c,onChange:p=>d(p.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:u.isPending,children:[e.jsx(Ix,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const C9e={points_earned:{label:"Points Earned",icon:jl,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:sa,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Nd,color:"bg-green-500"},custom:{label:"Custom",icon:un,color:"bg-purple-500"}};function kon(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),{data:l=[],isLoading:o}=rt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await U.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const m=[...new Set([...u.map(g=>g.user_id),...u.map(g=>g.created_by).filter(Boolean)])],{data:p}=await U.from("profiles").select("id, name, email").in("id",m),f=new Map((p==null?void 0:p.map(g=>[g.id,g]))||[]);return u.map(g=>{var v,y,b;return{...g,user_name:((v=f.get(g.user_id))==null?void 0:v.name)||"Unknown",user_email:((y=f.get(g.user_id))==null?void 0:y.email)||"",creator_name:g.created_by?((b=f.get(g.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var f,g;const h=((f=u.user_name)==null?void 0:f.toLowerCase().includes(s.toLowerCase()))||((g=u.user_email)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),m=n==="all"||u.celebration_type===n,p=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&p}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(C9e).reduce((u,h)=>(u[h]=l.filter(m=>m.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Ix,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(En,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"Filter by type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),Object.entries(C9e).map(([u,h])=>e.jsx(He,{value:u,children:h.label},u))]})]}),e.jsxs(ls,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(cs,{placeholder:"Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"seen",children:"Seen"}),e.jsx(He,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Points"}),e.jsx(Tt,{children:"Created By"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Qa,{children:c.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=C9e[u.celebration_type],m=h.icon;return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(m,{className:"h-3 w-3"}),h.label]})}),e.jsx(yt,{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(yt,{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(yt,{children:u.points_amount?e.jsxs(ze,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(yt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(yt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ys(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(yt,{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 Son=()=>{const{user:s}=hs(),{toast:t}=_i(),[n,r]=_.useState([]),[a,i]=_.useState(!0),[l,o]=_.useState(!1),[c,d]=_.useState("all"),[u,h]=_.useState("all"),[m,p]=_.useState("new"),[f,g]=_.useState(new Set),v=_.useCallback(async()=>{try{i(!0);const{data:G,error:V}=await U.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(V)throw V;const{data:H,error:K}=await U.from("trial_email_exports").select("user_id");if(K)throw K;const Z=new Set((H||[]).map(re=>re.user_id)),oe=(G||[]).map(re=>({...re,converted_from_trial_at:re.converted_from_trial_at??null,already_exported:Z.has(re.id)}));oe.sort((re,ae)=>new Date(ae.created_at).getTime()-new Date(re.created_at).getTime()),r(oe)}catch(G){console.error("Error loading trial users:",G),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);_.useEffect(()=>{v()},[v]);const y=G=>G.trial_started_at?"ghl":"stripe",b=G=>G.trial_expires_at?G.trial_expires_at:G.subscription_end_date?G.subscription_end_date:null,w=G=>G.converted_from_trial_at!==null,S=G=>{if(w(G))return!1;const V=b(G);return V?new Date(V).getTime()<=Date.now():!1},C=n.filter(G=>!(c!=="all"&&y(G)!==c||u==="active"&&(S(G)||w(G))||u==="expired"&&!S(G)||u==="converted"&&!w(G)||m==="new"&&G.already_exported||m==="exported"&&!G.already_exported)),E=()=>{f.size===C.length?g(new Set):g(new Set(C.map(G=>G.id)))},P=G=>{const V=new Set(f);V.has(G)?V.delete(G):V.add(G),g(V)},M=async()=>{if(f.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const G=n.filter(J=>f.has(J.id)),V="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",H=G.map(J=>{const te=(J.name||"").split(" "),ce=te[0]||"",ve=te.slice(1).join(" ")||"",me=y(J)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",he=w(J)?"Converted":S(J)?"Expired":"Active",ge=J.created_at?new Date(J.created_at).toLocaleDateString():"",Ee=b(J)?new Date(b(J)).toLocaleDateString():"";return`"${ce}","${ve}","${J.email}","${J.phone||""}","${me}","${he}","${ge}","${Ee}"`}),K=[V,...H].join(` `),Z=new Blob([K],{type:"text/csv"}),oe=URL.createObjectURL(Z),re=document.createElement("a");re.href=oe,re.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,re.click(),URL.revokeObjectURL(oe);const ae=G.filter(J=>!J.already_exported).map(J=>({user_id:J.id,exported_by:s.id}));if(ae.length>0){const{error:J}=await U.from("trial_email_exports").upsert(ae,{onConflict:"user_id"});J&&console.error("Error marking exports:",J)}t({title:"Export complete",description:`Downloaded ${G.length} trial user(s). ${ae.length} newly marked as exported.`}),g(new Set),v()}catch(G){console.error("Export error:",G),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},I=n.filter(G=>!G.already_exported).length,D=n.filter(G=>G.already_exported).length,F=n.filter(G=>w(G)).length,q=n.filter(G=>!S(G)&&!w(G)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{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(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Total"}),e.jsx(Nt,{className:"text-2xl",children:n.length})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"New (Not Exported)"}),e.jsx(Nt,{className:"text-2xl text-green-600",children:I})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Active Trials"}),e.jsx(Nt,{className:"text-2xl",children:q})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Converted 🎉"}),e.jsx(Nt,{className:"text-2xl text-primary",children:F})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Already Exported"}),e.jsx(Nt,{className:"text-2xl text-muted-foreground",children:D})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(ls,{value:m,onValueChange:G=>p(G),children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Users"}),e.jsx(He,{value:"new",children:"New Only"}),e.jsx(He,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(ls,{value:c,onValueChange:G=>d(G),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Trial Types"}),e.jsx(He,{value:"stripe",children:"Credit Card Trial"}),e.jsx(He,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(ls,{value:u,onValueChange:G=>h(G),children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"active",children:"Active Trial"}),e.jsx(He,{value:"expired",children:"Expired"}),e.jsx(He,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(z,{onClick:M,disabled:l||f.size===0,children:[l?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Export Selected (",f.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(za,{checked:C.length>0&&f.size===C.length,onCheckedChange:E})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Trial Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Last Login"}),e.jsx(Tt,{children:"Expires / Renews"}),e.jsx(Tt,{children:"Exported"})]})}),e.jsx(Qa,{children:C.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):C.map(G=>{const V=y(G),H=w(G),K=S(G),Z=b(G);return e.jsxs(fn,{className:`hover:bg-muted/30 ${H?"bg-primary/5":""}`,children:[e.jsx(yt,{children:e.jsx(za,{checked:f.has(G.id),onCheckedChange:()=>P(G.id)})}),e.jsx(yt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[G.name,H&&e.jsx(kl,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(yt,{className:"text-muted-foreground",children:G.email}),e.jsx(yt,{children:V==="stripe"?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(j0,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(yt,{children:H?e.jsxs(ze,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(kl,{className:"h-3 w-3"}),"Converted"]}):K?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(yt,{className:"text-sm",children:G.created_at?new Date(G.created_at).toLocaleDateString():"—"}),e.jsx(yt,{className:"text-sm",children:G.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(G.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(G.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(yt,{className:"text-sm",children:H&&Z?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(Z).toLocaleDateString()]}):Z?new Date(Z).toLocaleDateString():"—"}),e.jsx(yt,{children:G.already_exported?e.jsx(Mr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ze,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},G.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",C.length," of ",n.length," trial users · ",F," converted to paid"]})]})},Con=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,Aon=()=>{const[s,t]=_.useState([]),[n,r]=_.useState(!0);_.useEffect(()=>{(async()=>{const{data:l,error:o}=await U.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ne.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Ys(new Date(h.created_at),"MMM d, yyyy h:mm a"),h.deleted_user_name||"—",h.deleted_user_email||"—",h.brokerage_name||"—",h.deletion_type==="deleted"?"Account Deleted":"Removed",h.deleted_by_name||h.deleted_by_email||"—"]),o=[i.join(","),...l.map(h=>h.map(Con).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),ne.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Cn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{className:"text-lg",children:"User Deletion History"}),e.jsxs(z,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Le,{children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Deleted By"})]})}),e.jsx(Qa,{children:s.map(i=>e.jsxs(fn,{children:[e.jsx(yt,{className:"whitespace-nowrap text-sm",children:Ys(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(yt,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(yt,{children:i.brokerage_name||"—"}),e.jsx(yt,{children:e.jsx(ze,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(yt,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},PC=s=>{const{user:t}=hs(),n=$t(),r=rt({queryKey:["teams",s],queryFn:async()=>{let h=U.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:m,error:p}=await h;if(p)throw p;return m||[]},enabled:!!t}),a=h=>rt({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:p}=await U.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(p)throw p;const f=(m||[]).map(y=>y.user_id),{data:g}=await U.from("profiles").select("id, name, email, avatar_url").in("id",f),v=new Map((g||[]).map(y=>[y.id,y]));return(m||[]).map(y=>({...y,profile:v.get(y.user_id)||null}))},enabled:!!h}),i=mt({mutationFn:async h=>{const m={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(m.brokerage_id=h.brokerage_id);const{data:p,error:f}=await U.from("teams").insert(m).select().single();if(f)throw f;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ne.success("Team created!")},onError:h=>{ne.error("Failed to create team: "+h.message)}}),l=mt({mutationFn:async({id:h,...m})=>{const{data:p,error:f}=await U.from("teams").update(m).eq("id",h).select().single();if(f)throw f;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ne.success("Team updated")},onError:h=>{ne.error("Failed to update team: "+h.message)}}),o=mt({mutationFn:async h=>{const{error:m}=await U.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ne.success("Team deleted")},onError:h=>{ne.error("Failed to delete team: "+h.message)}}),c=mt({mutationFn:async h=>{const{data:m,error:p}=await U.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(p)throw p.message.includes("duplicate")||p.message.includes("unique")?new Error("This agent is already on this team."):p;return m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ne.success("Member added to team")},onError:h=>{ne.error(h.message)}}),d=mt({mutationFn:async h=>{const{error:m}=await U.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ne.success("Member removed from team")},onError:h=>{ne.error("Failed to remove member: "+h.message)}}),u=mt({mutationFn:async h=>{const{error:m}=await U.from("team_members").update({role:h.role}).eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ne.success("Member role updated")},onError:h=>{ne.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}},yst=s=>{const t=$t(),n=rt({queryKey:["team-ponds",s],queryFn:async()=>{const{data:o,error:c}=await U.rpc("get_team_ponds",{_team_id:s});if(c)throw c;return o||[]},enabled:!!s}),r=()=>{t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},a=mt({mutationFn:async o=>{const{data:c,error:d}=await U.from("team_ponds").insert({team_id:s,name:o.name,description:o.description||null}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ne.success("Pond created")},onError:o=>ne.error(o.message)}),i=mt({mutationFn:async({id:o,...c})=>{const{error:d}=await U.from("team_ponds").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ne.success("Pond updated")},onError:o=>ne.error(o.message)}),l=mt({mutationFn:async o=>{const{error:c}=await U.from("team_ponds").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ne.success("Pond deleted")},onError:o=>ne.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},Eon=s=>{const t=$t(),n=rt({queryKey:["pond-assignments",s],queryFn:async()=>{const{data:a,error:i}=await U.from("team_pond_members").select("id, user_id").eq("pond_id",s);if(i)throw i;return a||[]},enabled:!!s}),r=mt({mutationFn:async a=>{if(a.assigned){const{error:i}=await U.from("team_pond_members").insert({pond_id:s,user_id:a.user_id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await U.from("team_pond_members").delete().eq("pond_id",s).eq("user_id",a.user_id);if(i)throw i}},onSuccess:()=>{t.invalidateQueries({queryKey:["pond-assignments",s]}),t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},onError:a=>ne.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},Ton=({pond:s,teamId:t})=>{const{useTeamMembers:n}=PC(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=Eon(s.id);return a||l?e.jsx(ln,{className:"h-16 w-full"}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(On,{className:"h-3.5 w-3.5"}),i.length===0?"Open to everyone on the team (no agents assigned)":`${i.length} agent${i.length===1?"":"s"} assigned`]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:r.map(c=>{var u,h;const d=i.includes(c.user_id);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded-md border p-2 text-sm",children:[e.jsx(za,{checked:d,onCheckedChange:m=>o.mutate({user_id:c.user_id,assigned:!!m})}),e.jsx("span",{className:"truncate",children:((u=c.profile)==null?void 0:u.name)||((h=c.profile)==null?void 0:h.email)||"Unknown"}),c.role==="team_leader"&&e.jsx(ze,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},uHt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=yst(s),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,g]=_.useState(null),v=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Lead Ponds"}),e.jsx(En,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs(z,{size:"sm",onClick:()=>o(!0),children:[e.jsx(sn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(Le,{className:"space-y-3",children:[n&&e.jsx(ln,{className:"h-20 w-full"}),!n&&t.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No ponds yet. Create your first pond to start sharing leads with the team."}),t.map(y=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(m1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:y.name}),y.is_default&&e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[y.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[y.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>g(f===y.id?null:y.id),children:[e.jsx(On,{className:"mr-1 h-3.5 w-3.5"}),f===y.id?"Hide agents":"Assign agents"]}),e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>p(y),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${y.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(y.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),f===y.id&&e.jsx(Ton,{pond:y,teamId:s})]},y.id))]}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"New Lead Pond"}),e.jsx(_r,{children:"Leave agents unassigned to make the pond open to the whole team."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Pond name"}),e.jsx(pe,{value:c,onChange:y=>d(y.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description (optional)"}),e.jsx(pe,{value:u,onChange:y=>h(y.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(z,{onClick:v,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(Is,{open:!!m,onOpenChange:y=>!y&&p(null),children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Pond name"}),e.jsx(pe,{value:m.name,onChange:y=>p({...m,name:y.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:m.description||"",onChange:y=>p({...m,description:y.target.value})})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>p(null),children:"Cancel"}),e.jsx(z,{onClick:async()=>{m&&(await a.mutateAsync({id:m.id,name:m.name,description:m.description||""}),p(null))},disabled:a.isPending,children:"Save"})]})]})})]})},Mon=(s,t=!0)=>rt({queryKey:["lead-pond-activity",s],queryFn:async()=>{const{data:n,error:r}=await U.rpc("get_lead_pond_activity",{_lead_pond_id:s});if(r)throw r;return n||[]},enabled:!!s&&t}),Pon=()=>{const{user:s}=hs();return rt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},hHt=(s,t)=>{const{user:n}=hs(),r=$t(),a=rt({queryKey:["lead-pond",s,t||"all"],queryFn:async()=>{const{data:c,error:d}=await U.rpc("get_team_lead_pond",{_team_id:s,_pond_id:t||null});if(d)throw d;return(c||[]).map(u=>({id:u.id,team_id:u.team_id,pond_id:u.pond_id,pond_name:u.pond_name,contact_id:u.contact_id,added_by:u.added_by,claimed_by:u.claimed_by,claimed_at:u.claimed_at,returned_at:u.returned_at,notes:u.notes,created_at:u.created_at,status:u.claimed_by?"claimed":"available",contact:{first_name:u.first_name,last_name:u.last_name,email:u.email,phone:u.phone,address:u.address,lead_source:u.lead_source,notes:u.contact_notes},contributor:{name:u.contributor_name,avatar_url:u.contributor_avatar_url},claimer:u.claimed_by?{name:u.claimer_name,avatar_url:u.claimer_avatar_url}:null,touch_count:u.touch_count??0,last_activity_at:u.last_activity_at,can_view_activity:!!u.can_view_activity}))},enabled:!!s&&!!n}),i=mt({mutationFn:async c=>{const{data:d,error:u}=await U.rpc("add_to_lead_pond",{_contact_id:c.contact_id,_team_id:c.team_id,_notes:c.notes||null,_pond_id:c.pond_id||null});if(u)throw u;return d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ne.success("Contact added to Lead Pond")},onError:c=>{ne.error(c.message)}}),l=mt({mutationFn:async c=>{const{error:d}=await U.rpc("claim_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),r.invalidateQueries({queryKey:["innercircle-contacts"]}),r.invalidateQueries({queryKey:["contacts"]}),r.invalidateQueries({queryKey:["contact-custom-tags"]}),ne.success("Lead claimed and added to your contacts, tagged with the pond name. Your notes and follow-ups stay visible to your team leader and the agent who shared it.")},onError:c=>{ne.error(c.message)}}),o=mt({mutationFn:async c=>{const{error:d}=await U.rpc("return_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ne.success("Lead returned to pond")},onError:c=>{ne.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},Lon=(s,t,n=100)=>rt({queryKey:["team-pond-history",s,t||"all",n],queryFn:async()=>{const{data:r,error:a}=await U.rpc("get_team_pond_history",{_team_id:s,_pond_id:t||null,_limit:n});if(a)throw a;return r||[]},enabled:!!s}),Ion=()=>{const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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"]}),ne.success("Contact transferred successfully")},onError:t=>{ne.error(t.message||"Failed to transfer contact")}})};function mHt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var C;const{user:i}=hs(),{data:l}=K_(),{useTeamMembers:o}=PC(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Ion(),[u,h]=_.useState(null),[m,p]=_.useState(""),[f,g]=_.useState(!1),v=c.filter(E=>E.user_id!==(i==null?void 0:i.id)),y=async()=>{if(u){g(!0);try{for(const E of n)await d.mutateAsync({contactId:E,toUserId:u,notes:m||void 0});t(!1),h(null),p(""),a==null||a()}catch{}finally{g(!1)}}},b=v.find(E=>E.user_id===u),w=n.length>1,S=r.length>0?w?`${r.length} contacts`:r[0]:w?`${n.length} contacts`:"this contact";return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(G4,{className:"h-5 w-5"}),"Transfer ",S]}),e.jsxs(_r,{children:["Select a team member to transfer ",w?"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(ee,{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(E=>{var P,M,I;return e.jsxs("button",{onClick:()=>h(E.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===E.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:((P=E.profile)==null?void 0:P.avatar_url)||""}),e.jsx(Na,{className:"text-xs",children:(((M=E.profile)==null?void 0:M.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((I=E.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:E.role.replace("_"," ")})]})]},E.user_id)})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ps,{id:"transfer-notes",value:m,onChange:E=>p(E.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:y,disabled:!u||f,children:[f?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(G4,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(C=b.profile)==null?void 0:C.name}`:""]})]})]})})}const dIe=()=>{const s=zn(),{data:t,isLoading:n}=Pon(),{data:r}=K_(),[a,i]=_.useState(""),[l,o]=_.useState("all"),[c,d]=_.useState(null),[u,h]=_.useState(""),m=(r==null?void 0:r.role)==="team_leader",p=_.useMemo(()=>{if(!t)return[];const g=new Map;return t.forEach(v=>{g.has(v.owner_user_id)||g.set(v.owner_user_id,{id:v.owner_user_id,name:v.owner_name||"Unknown",avatar:v.owner_avatar_url})}),Array.from(g.values())},[t]),f=_.useMemo(()=>{if(!t)return[];let g=t;if(l!=="all"&&(g=g.filter(v=>v.owner_user_id===l)),a.trim()){const v=a.toLowerCase();g=g.filter(y=>{var b,w,S;return(y.first_name+" "+(y.last_name||"")).toLowerCase().includes(v)||((b=y.email)==null?void 0:b.toLowerCase().includes(v))||((w=y.phone)==null?void 0:w.includes(v))||((S=y.owner_name)==null?void 0:S.toLowerCase().includes(v))})}return g},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(ln,{className:"h-10 w-full"}),e.jsx(ln,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(On,{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(be,{children:e.jsx(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(cs,{placeholder:"Filter by agent"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Team Members"}),p.map(g=>e.jsx(He,{value:g.id,children:g.name},g.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.length," contact",f.length!==1?"s":""," from ",p.length," teammate",p.length!==1?"s":""]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0 overflow-x-auto",children:e.jsxs(Za,{className:"min-w-[800px]",children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Contact Info"}),e.jsx(Tt,{children:"Address"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Date Added"}),m&&e.jsx(Tt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(Qa,{children:f.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:m?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):f.map(g=>e.jsxs(fn,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${g.id}`):void 0,children:[e.jsx(yt,{className:"font-medium",children:e.jsxs("span",{className:m?"hover:text-primary hover:underline transition-colors":"",children:[g.first_name," ",g.last_name||""]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ja,{className:"h-6 w-6",children:[e.jsx(xi,{src:g.owner_avatar_url||""}),e.jsx(Na,{className:"text-[10px]",children:(g.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:g.owner_name||"Unknown"})]})}),e.jsx(yt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[g.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(on,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:g.email})]}),g.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(va,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:g.phone})]}),!g.email&&!g.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(yt,{children:g.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Ha,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:g.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(yt,{children:g.lead_source?e.jsx(ze,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:g.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(yt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ys(new Date(g.created_at),"MMM d, yyyy")})}),m&&e.jsx(yt,{children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:v=>{v.stopPropagation(),d(g.id),h(`${g.first_name} ${g.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(G4,{className:"h-4 w-4"})})})]},g.id))})]})})}),e.jsx(mHt,{open:!!c,onOpenChange:g=>{g||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},Don=s=>{if(!s)return"";const t=new Date(s);return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}).format(t)},Ron=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=Mon(s);return n?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(ln,{className:"h-4 w-2/3"}),e.jsx(ln,{className:"h-4 w-1/2"})]}):r?e.jsx("p",{className:"pt-2 text-xs text-muted-foreground",children:"Activity isn't available for this lead."}):!t||t.length===0?e.jsx("p",{className:"pt-2 text-xs text-muted-foreground",children:"No notes or logged follow-ups yet."}):e.jsx("div",{className:"space-y-3 pt-2",children:t.map((a,i)=>e.jsxs("div",{className:"flex gap-2 border-l-2 border-muted pl-3",children:[a.kind==="note"?e.jsx(y7,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(pm,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"text-xs font-medium",children:[a.label,a.actor_name?e.jsxs("span",{className:"font-normal text-muted-foreground",children:[" · ",a.actor_name]}):null]}),a.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-xs text-muted-foreground",children:a.notes}),a.occurred_at&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Don(a.occurred_at)})]})]},i))})},Fon=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(s)):"",Oon=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:HU,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," claimed"," ",e.jsx("span",{className:"font-medium",children:t})]})};case"returned":return{icon:Dx,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," returned"," ",e.jsx("span",{className:"font-medium",children:t})," to the pond"]})};default:return{icon:m1,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," added"," ",e.jsx("span",{className:"font-medium",children:t})," to the pond"]})}}},u1t=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=Lon(s,t),[a,i]=_.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-sm",children:[e.jsx(O_,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(Le,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(ln,{className:"h-8 w-full"},c))}):l.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No pond activity yet. Adding, claiming, and returning leads will show up here."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3",children:o.map((c,d)=>{const u=Oon(c),h=u.icon;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(ja,{className:"h-6 w-6 shrink-0",children:[e.jsx(xi,{src:c.actor_avatar_url||""}),e.jsx(Na,{className:"text-[9px]",children:(c.actor_name||"?").charAt(0)})]}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(h,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{children:u.text})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Fon(c.occurred_at)}),c.pond_name&&e.jsx(ze,{variant:"secondary",className:"text-[9px]",children:c.pond_name})]}),c.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-muted-foreground",children:c.notes})]})]},`${c.lead_pond_id}-${c.event_type}-${d}`)})}),l.length>8&&e.jsxs(z,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(c=>!c),children:[a?e.jsx(h1,{className:"mr-1 h-3 w-3"}):e.jsx(cl,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},zon=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,Bon=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=_.useState(!1),l=zon(s.last_activity_at);return e.jsx(be,{children:e.jsxs(Le,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"text-sm font-medium",children:[(o=s.contact)==null?void 0:o.first_name," ",((c=s.contact)==null?void 0:c.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[s.touch_count||0," follow-up",(s.touch_count||0)===1?"":"s"]}),e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Zr,{className:"h-3 w-3"}),l?`Last activity ${l}`:"No activity yet"]})]}),t&&e.jsxs("p",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),"Your notes and follow-ups on this lead are visible to the team leader and the agent who shared it."]})]}),t&&e.jsxs(z,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(Dx,{className:"mr-1 h-3 w-3"}),"Return"]})]}),s.can_view_activity&&e.jsxs("div",{className:"border-t pt-2",children:[e.jsxs(z,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(u=>!u),children:[a?e.jsx(h1,{className:"mr-1 h-3 w-3"}):e.jsx(cl,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(Ron,{leadPondId:s.id})]})]})})},uIe=({teamId:s})=>{const{user:t}=hs(),[n,r]=_.useState(null),{ponds:a,isLoading:i}=yst(s),l=a.filter(f=>f.has_access),{leadPondItems:o,isLoading:c,claimLead:d,returnLead:u}=hHt(s,n),h=l.length>1?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{size:"sm",variant:n===null?"default":"outline",onClick:()=>r(null),children:"All Ponds"}),l.map(f=>e.jsxs(z,{size:"sm",variant:n===f.id?"default":"outline",onClick:()=>r(f.id),children:[e.jsx(m1,{className:"mr-1 h-3 w-3"}),f.name,e.jsx(ze,{variant:"secondary",className:"ml-2 text-[10px]",children:f.available_count})]},f.id))]}):null;if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",o.length,"loading:",c),c)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(ln,{className:"h-20 w-full"},f))});if(o.length===0)return e.jsxs("div",{className:"space-y-4",children:[h,e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(m1,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Lead Pond is Empty"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team members can contribute contacts here for others to claim and follow up with."})]})}),e.jsx(u1t,{teamId:s,pondId:n})]});const m=o.filter(f=>f.status==="available"),p=o.filter(f=>f.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[h,e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",m.length,")"]}),m.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:m.map(f=>{var g,v,y,b,w,S,C,E,P,M,I;return e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"font-medium text-sm",children:[((g=f.contact)==null?void 0:g.first_name)||"Unnamed"," ",((v=f.contact)==null?void 0:v.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((y=f.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"})," ",f.contact.email]}),((b=f.contact)==null?void 0:b.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"})," ",f.contact.phone]}),((w=f.contact)==null?void 0:w.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ha,{className:"h-3 w-3"})," ",f.contact.address]})]}),f.pond_name&&n===null&&l.length>1&&e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[e.jsx(m1,{className:"mr-1 h-2.5 w-2.5"})," ",f.pond_name]}),((S=f.contact)==null?void 0:S.lead_source)&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:["Source: ",f.contact.lead_source]}),(f.notes||((C=f.contact)==null?void 0:C.notes))&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-1 max-w-xl",children:[e.jsx(y7,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:f.notes||((E=f.contact)==null?void 0:E.notes)})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsxs(ja,{className:"h-4 w-4",children:[e.jsx(xi,{src:((P=f.contributor)==null?void 0:P.avatar_url)||""}),e.jsx(Na,{className:"text-[8px]",children:(((M=f.contributor)==null?void 0:M.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((I=f.contributor)==null?void 0:I.name)||"Unknown"]})]})]}),e.jsxs(z,{size:"sm",className:"shrink-0",onClick:()=>d.mutate(f.id),disabled:d.isPending,children:[e.jsx(HU,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},f.id)})})]}),p.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",p.length,")"]}),e.jsx("div",{className:"space-y-2",children:p.map(f=>e.jsx(Bon,{item:f,isClaimer:f.claimed_by===(t==null?void 0:t.id),onReturn:()=>u.mutate(f.id),returning:u.isPending},f.id))})]}),e.jsx(u1t,{teamId:s,pondId:n})]})},vst=({teamId:s})=>{const{useTeamMembers:t}=PC(),{data:n=[]}=t(s),r=n.map(p=>p.user_id),a=new Map(n.map(p=>[p.user_id,p.profile])),{data:i=[],isLoading:l}=rt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=await U.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(f)throw f;return p||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=rt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=await U.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(f)throw f;return p||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=rt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:f}=await U.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(f)throw f;return p||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(ln,{className:"h-20 w-full"},p))});const m=p=>{const f=a.get(p);return{name:(f==null?void 0:f.name)||"Unknown",avatar:(f==null?void 0:f.avatar_url)||"",initials:((f==null?void 0:f.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(be,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(C0,{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(be,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(sa,{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(be,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(Xr,{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(Qr,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Wt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Wt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Kt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(A9e,{icon:e.jsx(C0,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(p=>{const f=m(p.owner_user_id);return e.jsx(be,{children:e.jsxs(Le,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:f.avatar}),e.jsx(Na,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Ys(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(ze,{variant:p.status==="published"?"default":"secondary",className:"text-xs capitalize",children:p.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})}),e.jsx(Kt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(A9e,{icon:e.jsx(sa,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(p=>{const f=m(p.agent_id);return e.jsx(be,{children:e.jsxs(Le,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:f.avatar}),e.jsx(Na,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Ys(new Date(p.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[p.is_active?e.jsx(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(On,{className:"h-3 w-3"}),p.visitor_count||0]})]})]})},p.id)})}),e.jsx(Kt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(A9e,{icon:e.jsx(Xr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(p=>{const f=m(p.owner_user_id);return e.jsx(be,{children:e.jsxs(Le,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:f.avatar}),e.jsx(Na,{className:"text-xs",children:f.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||p.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.name," · ",Ys(new Date(p.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:p.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})})]})]})},A9e=({icon:s,label:t})=>e.jsx(be,{children:e.jsxs(Le,{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})]})}),pHt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var P,M;const{useTeamMembers:u}=PC(),{data:h=[],isLoading:m}=u(s.id),[p,f]=_.useState(!1),[g,v]=_.useState(""),[y,b]=_.useState("team_member"),{data:w}=rt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:I}=await U.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),D=new Map;return(I||[]).forEach(F=>{var G;const q=D.get(F.user_id)||[];q.push(((G=F.teams)==null?void 0:G.name)||"another team"),D.set(F.user_id,q)}),D}}),S=new Set(h.map(I=>I.user_id)),C=t.filter(I=>!S.has(I.id)),E=async()=>{g&&(await a(g,y),v(""),b("team_member"),f(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(z,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(Qr,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"members",children:"Members"}),e.jsxs(Wt,{value:"contacts",children:[e.jsx(nP,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Wt,{value:"lead-pond",children:[e.jsx(m1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Wt,{value:"shared-assets",children:[e.jsx(wv,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Wt,{value:"settings",children:"Settings"})]}),e.jsxs(Kt,{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(Is,{open:p,onOpenChange:f,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add Team Member"}),e.jsxs(_r,{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(ee,{children:"Agent"}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[g&&(((P=C.find(I=>I.id===g))==null?void 0:P.name)||((M=C.find(I=>I.id===g))==null?void 0:M.email))||"Select an agent",e.jsx(R_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search agents..."}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:"No agents found."}),e.jsx(G_,{children:C.map(I=>{const D=w==null?void 0:w.get(I.id);return e.jsxs(c1,{value:I.name||I.email||I.id,onSelect:()=>v(I.id),children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",g===I.id?"opacity-100":"opacity-0")}),I.name||I.email,D!=null&&D.length?e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(also on ",D.join(", "),")"]}):null]},I.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Role"}),e.jsxs(ls,{value:y,onValueChange:b,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"team_leader",children:"Team Leader"}),e.jsx(He,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(z,{onClick:E,disabled:!g||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(I=>e.jsx(ln,{className:"h-16 w-full"},I))}):h.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(On,{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(I=>{var D,F,q,G,V;return e.jsx(be,{children:e.jsxs(Le,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:((D=I.profile)==null?void 0:D.avatar_url)||""}),e.jsx(Na,{children:(((F=I.profile)==null?void 0:F.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((q=I.profile)==null?void 0:q.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(G=I.profile)==null?void 0:G.email})]}),I.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(Kf,{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(ls,{value:I.role,onValueChange:H=>l(I.id,H),children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"team_leader",children:"Team Leader"}),e.jsx(He,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(vq,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Remove Member?"}),e.jsxs(ql,{children:["Remove ",((V=I.profile)==null?void 0:V.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>i(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},I.id)})})]}),e.jsx(Kt,{value:"contacts",className:"space-y-4",children:e.jsx(dIe,{})}),s.lead_pond_enabled&&e.jsx(Kt,{value:"lead-pond",className:"space-y-4",children:e.jsx(uIe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Kt,{value:"shared-assets",className:"space-y-4",children:e.jsx(vst,{teamId:s.id})}),e.jsxs(Kt,{value:"settings",className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-lg",children:"Team Settings"}),e.jsx(En,{children:"Configure how this team operates."})]}),e.jsxs(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Team Name"}),e.jsx(pe,{defaultValue:s.name,onBlur:I=>{I.target.value!==s.name&&r({name:I.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{defaultValue:s.description||"",onBlur:I=>{I.target.value!==(s.description||"")&&r({description:I.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact Visibility"}),e.jsxs(ls,{defaultValue:s.contact_visibility,onValueChange:I=>r({contact_visibility:I}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(He,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(He,{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(ee,{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(mn,{checked:s.lead_pond_enabled,onCheckedChange:I=>r({lead_pond_enabled:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:s.shared_assets_enabled,onCheckedChange:I=>r({shared_assets_enabled:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:s.shared_videos_enabled??!1,onCheckedChange:I=>r({shared_videos_enabled:I})})]})]})]}),s.lead_pond_enabled&&e.jsx(uHt,{teamId:s.id}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{variant:"destructive",size:"sm",children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Team?"}),e.jsxs(ql,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},fHt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=_.useState(1),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(""),[v,y]=_.useState(""),[b,w]=_.useState([]),S=()=>{d(1),h(""),p(""),g(""),y(""),w([])},C=I=>{I||S(),t(I)},E=async()=>{const I=f&&f!=="none"?f:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:I,leaderId:v||void 0,memberIds:b.length>0?b:void 0}),S()},P=I=>{I!==v&&w(D=>D.includes(I)?D.filter(F=>F!==I):[...D,I])},M=a.filter(I=>I.id!==v);return e.jsx(Is,{open:s,onOpenChange:C,children:e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(_r,{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:Ct("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Ct("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(ee,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(pe,{id:"team-name",value:u,onChange:I=>h(I.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ps,{id:"team-desc",value:m,onChange:I=>p(I.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(ee,{children:"Brokerage"}),e.jsxs(ls,{value:f,onValueChange:g,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No brokerage (independent)"}),l.map(I=>e.jsx(He,{value:I.id,children:I.name},I.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Kf,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(ls,{value:v,onValueChange:I=>{y(I),w(D=>D.filter(F=>F!==I))},children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No leader for now"}),a.map(I=>e.jsx(He,{value:I.id,children:I.name||I.email||"Unknown"},I.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs(ze,{variant:"secondary",className:"ml-1 text-xs",children:[b.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(On,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(I=>{const D=b.includes(I.id);return e.jsxs("button",{type:"button",className:Ct("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",D&&"bg-primary/5"),onClick:()=>P(I.id),children:[e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:I.avatar_url||""}),e.jsx(Na,{className:"text-xs",children:(I.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:I.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:I.email})]}),e.jsx("div",{className:Ct("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",D?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:D&&e.jsx(Wr,{className:"h-3 w-3"})})]},I.id)})})]})]})}),e.jsx(hr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(Da,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",onClick:()=>d(1),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(z,{onClick:E,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},$on=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=PC(),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(""),{data:f}=rt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:C,error:E}=await U.from("brokerages").select("id, name").order("name");if(E)throw E;return C||[]}}),{data:g}=rt({queryKey:["admin-team-member-info",s.map(C=>C.id).join(",")],queryFn:async()=>{var I;if(s.length===0)return{};const{data:C}=await U.from("team_members").select("team_id, user_id, role").in("team_id",s.map(D=>D.id));if(!C)return{};const E=C.filter(D=>D.role==="team_leader").map(D=>D.user_id);let P={};if(E.length>0){const{data:D}=await U.from("profiles").select("id, name").in("id",E);D&&(P=Object.fromEntries(D.map(F=>[F.id,{name:F.name}])))}const M={};for(const D of s){const F=C.filter(G=>G.team_id===D.id),q=F.find(G=>G.role==="team_leader");M[D.id]={count:F.length,leaderName:q&&((I=P[q.user_id])==null?void 0:I.name)||null}}return M},enabled:s.length>0}),v=(u==null?void 0:u.brokerage_id)||null,{data:y}=rt({queryKey:["brokerage-agents-for-teams",v],queryFn:async()=>{let C=U.from("profiles").select("id, name, email, avatar_url").order("name");v&&(C=C.eq("brokerage_id",v));const{data:E,error:P}=await C;if(P)throw P;return E||[]},enabled:!!u}),b=Object.fromEntries((f||[]).map(C=>[C.id,C.name])),w=async C=>{const E=await n.mutateAsync({name:C.name,brokerage_id:C.brokerage_id||null,description:C.description});if(C.leaderId&&C.leaderId!=="none"&&await i.mutateAsync({team_id:E.id,user_id:C.leaderId,role:"team_leader"}),C.memberIds)for(const P of C.memberIds)await i.mutateAsync({team_id:E.id,user_id:P,role:"team_member"});d(!1)};if(u)return e.jsx(pHt,{team:u,brokerageAgents:y||[],onBack:()=>h(null),onUpdate:C=>r.mutateAsync({id:u.id,...C}).then(E=>h(E)),onAddMember:(C,E)=>i.mutateAsync({team_id:u.id,user_id:C,role:E}),onRemoveMember:C=>l.mutateAsync({team_id:u.id,member_id:C}),onUpdateRole:(C,E)=>o.mutateAsync({team_id:u.id,member_id:C,role:E}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const S=s.filter(C=>C.name.toLowerCase().includes(m.toLowerCase())||(C.description||"").toLowerCase().includes(m.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search teams...",value:m,onChange:C=>p(C.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[S.length," of ",s.length," teams"]})]}),e.jsxs(z,{size:"sm",onClick:()=>d(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(fHt,{open:c,onOpenChange:d,onCreateTeam:w,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:f,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Team Name"}),e.jsx(Tt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Tt,{className:"font-semibold",children:"Leader"}),e.jsx(Tt,{className:"font-semibold",children:"Members"}),e.jsx(Tt,{className:"font-semibold",children:"Visibility"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(Qa,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(C=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx(ln,{className:"h-4 w-32"})}),e.jsx(yt,{children:e.jsx(ln,{className:"h-4 w-24"})}),e.jsx(yt,{children:e.jsx(ln,{className:"h-4 w-28"})}),e.jsx(yt,{children:e.jsx(ln,{className:"h-4 w-12"})}),e.jsx(yt,{children:e.jsx(ln,{className:"h-4 w-20"})}),e.jsx(yt,{children:e.jsx(ln,{className:"h-4 w-16"})})]},C))}):S.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:m?"No teams match your search":"No teams found. Create one to get started."})}):S.map(C=>{const E=g==null?void 0:g[C.id];return e.jsxs(fn,{className:"hover:bg-muted/30",children:[e.jsxs(yt,{children:[e.jsx("button",{onClick:()=>h(C),className:"text-primary hover:underline font-medium",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:C.description})]}),e.jsx(yt,{children:C.brokerage_id?e.jsx("span",{className:"text-sm",children:b[C.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(yt,{children:E!=null&&E.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Kf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),E.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(yt,{children:e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(On,{className:"h-3 w-3 mr-1"}),(E==null?void 0:E.count)??0]})}),e.jsx(yt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Om,{className:"h-3 w-3"}),C.contact_visibility.replace("_"," ")]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(C),title:"Edit team",children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await Qi(`Delete team "${C.name}"? This cannot be undone.`)&&a.mutate(C.id)},title:"Delete team",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})})]},C.id)})})]})})]})};function h1t(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 Uon({open:s,onOpenChange:t,recipients:n}){const{toast:r}=_i(),[a,i]=_.useState([]),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(!1),[v,y]=_.useState(!1),b=_.useMemo(()=>a.find(E=>E.id===c)||null,[a,c]);_.useEffect(()=>{s&&(o(!0),(async()=>{const E=new Date().toISOString(),{data:P,error:M}=await U.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",E).order("event_date",{ascending:!0}).limit(50);M?r({title:"Could not load events",description:M.message,variant:"destructive"}):i(P||[]),o(!1)})())},[s,r]);const w=_.useMemo(()=>n.filter(E=>E.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E.email)),[n]),S=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(w.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}y(!0)},C=async()=>{if(b){y(!1),g(!0);try{const{data:{session:E}}=await U.auth.getSession(),P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E==null?void 0:E.access_token}`},body:JSON.stringify({event_id:b.id,recipients:w.map(q=>({email:q.email,name:q.name,user_id:q.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),M=await P.json().catch(()=>({}));if(!P.ok)throw new Error((M==null?void 0:M.error)||"Failed to send event invite");const I=(M==null?void 0:M.sent)??0,D=(M==null?void 0:M.failed)??0,F=(M==null?void 0:M.already_invited)??0;r({title:"Invites sent",description:`Sent: ${I}${F?` · Skipped (already invited): ${F}`:""}${D?` · Failed: ${D}`:""}`}),t(!1),p(""),h(""),d("")}catch(E){const P=E instanceof Error?E.message:"Send failed";r({title:"Send failed",description:P,variant:"destructive"})}finally{g(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(_r,{children:["Send a beautiful event invitation to ",w.length," selected member",w.length===1?"":"s",".",n.length!==w.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-w.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{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(bt,{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(ls,{value:c,onValueChange:d,children:[e.jsx(rs,{id:"event-select",children:e.jsx(cs,{placeholder:"Pick an upcoming event..."})}),e.jsx(as,{children:a.map(E=>e.jsx(He,{value:E.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:E.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h1t(E.event_date),!E.is_published&&" · (Draft)"]})]})},E.id))})]})]}),b&&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(ya,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h1t(b.event_date)}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b.description})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(pe,{id:"subject",placeholder:b?`You're invited: ${b.title}`:"You're invited to...",value:u,onChange:E=>h(E.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(ee,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ps,{id:"intro",placeholder:"Add a custom intro message... e.g. 'As a new member, we'd love to have you at our weekly onboarding event!'",value:m,onChange:E=>p(E.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 (",w.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[w.slice(0,30).map(E=>e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:E.name||E.email},E.id)),w.length>30&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:["+",w.length-30," more"]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:f,children:"Cancel"}),e.jsx(z,{onClick:S,disabled:f||!c||w.length===0,children:f?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"})," Send to ",w.length]})})]})]})}),e.jsx(Ql,{open:v,onOpenChange:y,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Send event invite?"}),e.jsx(ql,{children:b?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',b.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[w.length," member",w.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsxs(Ml,{onClick:C,children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const qon=()=>{var em;const s=zn(),{user:t,isAdmin:n}=hs(),{startImpersonation:r,isLoading:a}=iPe(),{toast:i}=_i(),[l,o]=_.useState([]),[c,d]=_.useState([]),[u,h]=_.useState([]),[m,p]=_.useState({}),[f,g]=_.useState(!0);_.useState({});const[v,y]=_.useState(!1),[b,w]=_.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[S,C]=_.useState(!1),[E,P]=_.useState(""),[M,I]=_.useState(1),[D,F]=_.useState(50),[q,G]=_.useState("all"),[V,H]=_.useState(!1),[K,Z]=_.useState(!1),[oe,re]=_.useState({done:0,total:0}),[ae,J]=_.useState(null),[te,ce]=_.useState("all"),[ve,me]=_.useState("all"),[he,ge]=_.useState("all"),[Ee,Ne]=_.useState("all"),[Pe,Oe]=_.useState(!1),[ke,Ve]=_.useState(!1),[_e,Ae]=_.useState(!1),[Se,We]=_.useState(""),[qe,Be]=_.useState(!1),[Ze,$e]=_.useState(null),[Xe,nt]=_.useState(null),[Ge,Je]=_.useState(!1),[ut,lt]=_.useState({name:"",email:"",brokerage_id:"",phone:""}),[qt,zt]=_.useState(null),[Zt,ms]=_.useState(!1),[Dt,It]=_.useState(""),[qs,wt]=_.useState(!1),[Us,Es]=_.useState(!1),[kn,Sn]=_.useState(null),[bn,cr]=_.useState(""),[Fs,cn]=_.useState(!1),[lr,Tn]=_.useState(!1),[Yn,fs]=_.useState(null),[wn,As]=_.useState(!1),[Ss,pr]=_.useState(!1),[hn,Pn]=_.useState(null),[Gs,an]=_.useState(""),[tr,Lr]=_.useState(!1),[Yt,it]=_.useState({email:"",name:"",password:"",phone:""}),[gt,ft]=_.useState(!1),[Lt,Mt]=_.useState(null),[Qt,ks]=_.useState([]),[gs,Vt]=_.useState("none"),[Vs,Zs]=_.useState(!1),[Zn,Or]=_.useState(""),[oa,aa]=_.useState(!1),[Kr,Tr]=_.useState(!1),[Hr,Ba]=_.useState(""),[Ja,Ro]=_.useState(new Set),[ji,Oa]=_.useState(!1),[Ao,uo]=_.useState(!1),[Ua,Eo]=_.useState(null),[Ji,qa]=_.useState(!1),[ar,ui]=_.useState(null),[zo,gl]=_.useState([]),[tl,Ll]=_.useState([]),[Ku,uh]=_.useState(!1),[ym,Ld]=_.useState({});_.useEffect(()=>{if(!t||!n){t&&!n&&g(!1);return}Sl(),wu()},[t,n]);const Bm=async()=>{try{const{data:Gt,error:An}=await U.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(An)throw An;const qn={};for(const qr of Gt??[])qn[qr.brokerage_id]||(qn[qr.brokerage_id]=[]),qn[qr.brokerage_id].push(qr.user_id);p(qn)}catch(Gt){console.error("Error loading brokerage manager assignments:",Gt)}},Sl=async()=>{try{g(!0);const{data:Gt,error:An}=await U.functions.invoke("get-user-details");if(An)throw An;const qn=Gt.users||[];o(qn),h(Gt.brokerages||[]),await Bm();const qr=qn.filter(Pa=>Pa.roles.includes("assistant"));if(qr.length>0){const Pa=qr.map(Li=>Li.id),{data:vi}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Pa);if(vi&&vi.length>0){const Li=[...new Set(vi.map(Au=>Au.agent_id))],{data:wi}=await U.from("profiles").select("id, name, email").in("id",Li),rd={};for(const Au of vi){const pp=wi==null?void 0:wi.find(gd=>gd.id===Au.agent_id);pp&&(rd[Au.assistant_id]={agent_name:pp.name||"",agent_email:pp.email||""})}Ld(rd)}}}catch(Gt){console.error("Error loading members:",Gt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{g(!1)}},wu=async()=>{try{const{data:Gt,error:An}=await U.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(An)throw An;d(Gt||[])}catch(Gt){console.error("Error loading apps:",Gt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},js=async Gt=>{if(!ut.name.trim()||!ut.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ut.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:qn}=await U.from("profiles").update({name:ut.name.trim(),email:ut.email.trim(),brokerage_id:ut.brokerage_id||null,phone:ut.phone.trim()||null}).eq("id",Gt);if(qn)throw qn;i({title:"Success",description:"Member details updated successfully"}),$e(null),Sl()}catch(qn){console.error("Error updating member:",qn),i({title:"Error",description:qn.message||"Failed to update member",variant:"destructive"})}},Ma=async Gt=>{try{const{data:{session:An}}=await U.auth.getSession(),qn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${An==null?void 0:An.access_token}`},body:JSON.stringify({userId:Gt})}),qr=await qn.json();if(!qn.ok)throw new Error(qr.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(An){console.error("Error resending welcome email:",An),i({title:"Error",description:An.message||"Failed to resend welcome email",variant:"destructive"})}},to=async(Gt,An)=>{try{const{error:qn}=await U.functions.invoke("send-password-reset",{body:{email:Gt,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(qn)throw qn;i({title:"Password Reset Sent",description:`Password reset email sent to ${An}`})}catch(qn){console.error("Error sending password reset:",qn),i({title:"Error",description:qn.message||"Failed to send password reset email",variant:"destructive"})}},Ta=async(Gt,An)=>{if(await Qi(`Are you sure you want to delete ${An}? This action cannot be undone.`))try{const{data:{session:qn}}=await U.auth.getSession(),qr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qn==null?void 0:qn.access_token}`},body:JSON.stringify({userId:Gt})}),Pa=await qr.json();if(!qr.ok)throw new Error(Pa.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),Sl()}catch(qn){console.error("Error deleting user:",qn),i({title:"Error",description:qn.message||"Failed to delete user",variant:"destructive"})}},so=async()=>{if(!b.email||!b.name||!b.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(b.role==="brokerage_manager"&&!b.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}y(!0);try{const{data:{session:Gt}}=await U.auth.getSession(),An=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gt==null?void 0:Gt.access_token}`},body:JSON.stringify(b)}),qn=await An.json();if(!An.ok)throw new Error(qn.error||"Failed to create user");if(b.role&&b.role!=="user"&&qn.userId){const qr=b.role==="brokerage_manager"?b.brokerage_id:void 0;await ho(qn.userId,b.role,"add",qr)}i({title:"Success",description:`User ${b.email} created successfully`}),w({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),C(!1),Sl()}catch(Gt){console.error("Error creating user:",Gt),i({title:"Error",description:Gt.message||"Failed to create user",variant:"destructive"})}finally{y(!1)}},ho=async(Gt,An,qn,qr)=>{try{const{data:{session:Pa}}=await U.auth.getSession(),vi={userId:Gt,role:An,action:qn};if(An==="brokerage_manager"){if(!qr){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}vi.brokerageId=qr}const Li=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pa==null?void 0:Pa.access_token}`},body:JSON.stringify(vi)}),wi=await Li.json();if(!Li.ok)throw new Error(wi.error||"Failed to manage user role");i({title:"Success",description:`Role ${qn==="add"?"added":"removed"} successfully`}),Sl()}catch(Pa){console.error("Error managing user role:",Pa),i({title:"Error",description:Pa.message||"Failed to manage user role",variant:"destructive"})}},pi=(Gt,An)=>An.length===0?!0:An.some(qn=>Gt.includes(qn)),$m=async(Gt,An,qn)=>{const qr=`${Gt}-${An.id}`;zt(qr);try{if(qn){const Pa=l.find(Li=>Li.id===Gt),vi=An.required_tags.filter(Li=>Pa==null?void 0:Pa.tags.includes(Li));for(const Li of vi){const{error:wi}=await U.from("user_tags").delete().eq("user_id",Gt).eq("tag",Li);if(wi)throw wi}i({title:"Access Removed",description:`Removed access to ${An.name}`})}else if(An.required_tags.length>0){const{error:Pa}=await U.from("user_tags").insert({user_id:Gt,tag:An.required_tags[0]});if(Pa)throw Pa;i({title:"Access Granted",description:`Granted access to ${An.name}`})}await Sl()}catch(Pa){console.error("Error toggling access:",Pa),i({title:"Error",description:Pa.message||"Failed to update access",variant:"destructive"})}finally{zt(null)}},al=async()=>{const Gt=Dt.trim();if(!Gt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Gt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(qn=>qn.name.toLowerCase()===Gt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}wt(!0);try{const{error:qn}=await U.from("brokerages").insert({name:Gt});if(qn)throw qn;i({title:"Success",description:`Brokerage "${Gt}" created successfully`}),It(""),ms(!1),Sl()}catch(qn){console.error("Error creating brokerage:",qn),i({title:"Error",description:qn.message||"Failed to create brokerage",variant:"destructive"})}finally{wt(!1)}},vo=Gt=>{Sn(Gt),cr(Gt.name),Es(!0)},$x=()=>{Sn(null),cr(""),Es(!1)},il=async()=>{if(!kn)return;const Gt=bn.trim();if(!Gt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Gt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}cn(!0);try{const{error:An}=await U.from("brokerages").update({name:Gt}).eq("id",kn.id);if(An)throw An;i({title:"Success",description:"Brokerage updated successfully"}),$x(),Sl()}catch(An){console.error("Error updating brokerage:",An),i({title:"Error",description:An.message||"Failed to update brokerage",variant:"destructive"})}finally{cn(!1)}},yl=async(Gt,An)=>{var qn;if(!An||typeof An!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const qr={userId:Gt,role:"brokerage_manager",action:"add",brokerageId:An};console.debug("[assignManagerToBrokerage] payload",qr);const{data:{session:Pa}}=await U.auth.getSession(),vi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pa==null?void 0:Pa.access_token}`},body:JSON.stringify(qr)}),Li=await vi.json();if(!vi.ok&&!((qn=Li.error)!=null&&qn.includes("duplicate")))throw new Error(Li.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await Sl()}catch(qr){console.error("Error assigning manager:",qr),i({title:"Error",description:qr.message||"Failed to assign manager",variant:"destructive"})}},E1=Gt=>{fs(Gt),Tn(!0)},zc=async()=>{if(Yn){As(!0);try{const Gt=l.filter(qr=>qr.brokerage_id===Yn.id),{data:{session:An}}=await U.auth.getSession();for(const qr of Gt){const Pa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${An==null?void 0:An.access_token}`},body:JSON.stringify({userId:qr.id})});if(!Pa.ok){const vi=await Pa.json();console.error(`Failed to delete user ${qr.email}:`,vi.error)}}const{error:qn}=await U.from("brokerages").delete().eq("id",Yn.id);if(qn)throw qn;i({title:"Success",description:`Brokerage "${Yn.name}" and ${Gt.length} member(s) deleted`}),Tn(!1),fs(null),Sl()}catch(Gt){console.error("Error deleting brokerage:",Gt),i({title:"Error",description:Gt.message||"Failed to delete brokerage",variant:"destructive"})}finally{As(!1)}}},Dp=Gt=>{Pn(Gt),an(""),pr(!0)},hp=()=>{Pn(null),an(""),pr(!1)},_g=async Gt=>{try{const{error:An}=await U.from("profiles").update({brokerage_id:null}).eq("id",Gt);if(An)throw An;i({title:"Success",description:"User removed from brokerage"}),Sl()}catch(An){console.error("Error removing user from brokerage:",An),i({title:"Error",description:An.message||"Failed to remove user",variant:"destructive"})}},Dv=async(Gt,An)=>{try{const{error:qn}=await U.from("profiles").update({brokerage_id:An}).eq("id",Gt);if(qn)throw qn;i({title:"Success",description:"User added to brokerage"}),Sl()}catch(qn){console.error("Error adding user to brokerage:",qn),i({title:"Error",description:qn.message||"Failed to add user",variant:"destructive"})}};_.useEffect(()=>{(async()=>{var An;if(!(hn!=null&&hn.id)){Mt(null),ks([]),Vt("none");return}try{const{data:qn}=await U.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",hn.id).maybeSingle();if(!qn||!qn.enabled){Mt(null),ks([]),Vt("none");return}const{data:qr}=await U.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",qn.id).order("sort_order",{ascending:!0});Mt({id:qn.id,name:qn.name}),ks(qr||[]),Vt(((An=qr==null?void 0:qr[0])==null?void 0:An.id)||"none")}catch(qn){console.error("Error loading partnership packages:",qn)}})()},[hn==null?void 0:hn.id]);const nx=async()=>{if(!hn||!Yt.email||!Yt.name||!Yt.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}ft(!0);try{const{data:{session:Gt}}=await U.auth.getSession(),An=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gt==null?void 0:Gt.access_token}`},body:JSON.stringify({...Yt,brokerage_id:hn.id,role:"user",partnershipPackageId:Lt&&gs!=="none"?gs:void 0})}),qn=await An.json();if(!An.ok)throw new Error(qn.error||"Failed to create agent");i({title:"Success",description:`Agent ${Yt.email} created successfully`}),it({email:"",name:"",password:"",phone:""}),Lr(!1),Sl()}catch(Gt){console.error("Error creating agent:",Gt),i({title:"Error",description:Gt.message||"Failed to create agent",variant:"destructive"})}finally{ft(!1)}},Pi=Gt=>l.filter(An=>An.brokerage_id===Gt),vm=Gt=>{const An=Pi(Gt);if(!Gs)return An;const qn=Gs.toLowerCase();return An.filter(qr=>qr.name.toLowerCase().includes(qn)||qr.email.toLowerCase().includes(qn))},Yg=Gt=>l.filter(An=>An.brokerage_id!==Gt),hh=l.filter(Gt=>{var qn;if(E){const qr=E.toLowerCase();if(!(Gt.name.toLowerCase().includes(qr)||Gt.email.toLowerCase().includes(qr)||((qn=Gt.brokerage_name)==null?void 0:qn.toLowerCase().includes(qr))))return!1}if(q==="claimed"&&!Gt.claimed||q==="unclaimed"&&Gt.claimed||te!=="all"&&!Gt.roles.includes(te))return!1;const An=Gt.is_trial||Gt.subscription_status==="trialing";if(ve==="trial"&&!An||ve==="non-trial"&&An||he==="none"&&Gt.brokerage_id||he!=="all"&&he!=="none"&&Gt.brokerage_id!==he)return!1;if(Ee!=="all"){if(!Gt.created_at)return!1;const qr=parseInt(Ee,10),Pa=Date.now()-qr*24*60*60*1e3;if(new Date(Gt.created_at).getTime(){var An;return((An=Gt.name)==null?void 0:An.toLowerCase())||""},brokerage:Gt=>{var An;return((An=Gt.brokerage_name)==null?void 0:An.toLowerCase())||""},status:Gt=>Gt.claimed?"active":"pending",role:Gt=>Gt.roles[0]||"",last_login:Gt=>Gt.last_sign_in_at?new Date(Gt.last_sign_in_at).getTime():null,created_at:Gt=>Gt.created_at?new Date(Gt.created_at).getTime():null}),Eh=Ah.length,Jh=D===0,Uu=Jh?1:Math.ceil(Eh/D),rx=Jh?0:(M-1)*D,R0=Jh?Eh:rx+D,mc=Ah.slice(rx,R0),Sd=Gt=>{P(Gt),I(1)},pf=Gt=>{F(Gt),I(1)},lu=(Gt,An)=>{Gt(An),I(1)},mp=async(Gt,An)=>{Ve(!0);try{const qn=l.find(Li=>Li.id===Gt);if(!qn)return;const qr=qn.trial_expires_at?new Date(qn.trial_expires_at):new Date,Pa=new Date(qr.getTime()+An*24*60*60*1e3),{error:vi}=await U.from("profiles").update({trial_expires_at:Pa.toISOString()}).eq("id",Gt);if(vi)throw vi;i({title:"Trial Extended",description:`Trial extended by ${An} days`}),Sl()}catch(qn){console.error("Error extending trial:",qn),i({title:"Error",description:qn.message||"Failed to extend trial",variant:"destructive"})}finally{Ve(!1)}},Um=async(Gt,An,qn)=>{Ae(!0);try{const{error:qr}=await U.from("profiles").update({is_paused:An,paused_at:An?new Date().toISOString():null,paused_reason:An&&(qn==null?void 0:qn.trim())||null}).eq("id",Gt);if(qr)throw qr;o(Pa=>Pa.map(vi=>vi.id===Gt?{...vi,is_paused:An,paused_reason:An&&(qn==null?void 0:qn.trim())||null,paused_at:An?new Date().toISOString():null}:vi)),nt(Pa=>Pa&&Pa.id===Gt?{...Pa,is_paused:An,paused_reason:An&&(qn==null?void 0:qn.trim())||null}:Pa),i({title:An?"Account paused":"Account reactivated",description:An?"This member can no longer sign in and will see a paused message.":"This member can sign in again."})}catch(qr){console.error("Error updating pause state:",qr),i({title:"Error",description:qr.message||"Failed to update account",variant:"destructive"})}finally{Ae(!1)}},qm=async Gt=>{Be(!0);try{const{error:An}=await U.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Gt);if(An)throw An;i({title:"Account Converted",description:"User has been converted to a full account"}),Sl(),Ur()}catch(An){console.error("Error converting trial:",An),i({title:"Error",description:An.message||"Failed to convert account",variant:"destructive"})}finally{Be(!1)}},[ot,ts]=_.useState(!1),Ks=async(Gt,An)=>{if(await Qi(`Revert this user to a ${An}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){ts(!0);try{const qn=new Date,qr=new Date(qn.getTime()+An*24*60*60*1e3),{error:Pa}=await U.from("profiles").update({is_trial:!0,trial_started_at:qn.toISOString(),trial_expires_at:qr.toISOString(),trial_claimed_at:qn.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",Gt);if(Pa)throw Pa;i({title:"Reverted to Trial",description:`User is now on a ${An}-day free trial.`}),Sl()}catch(qn){console.error("Error reverting to trial:",qn),i({title:"Error",description:qn.message||"Failed to revert to trial",variant:"destructive"})}finally{ts(!1)}}},Js=async Gt=>{uh(!0);try{const{data:An}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Gt);if(An&&An.length>0){const qr=An.map(vi=>vi.assistant_id),{data:Pa}=await U.from("profiles").select("id, name, email").in("id",qr);gl(An.map(vi=>{const Li=Pa==null?void 0:Pa.find(wi=>wi.id===vi.assistant_id);return{id:vi.id,assistant_id:vi.assistant_id,assistant_name:(Li==null?void 0:Li.name)||"Unknown",assistant_email:(Li==null?void 0:Li.email)||"",permissions:vi.permissions||{}}}))}else gl([]);const{data:qn}=await U.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Gt);if(qn&&qn.length>0){const qr=qn.map(vi=>vi.agent_id),{data:Pa}=await U.from("profiles").select("id, name, email").in("id",qr);Ll(qn.map(vi=>{const Li=Pa==null?void 0:Pa.find(wi=>wi.id===vi.agent_id);return{id:vi.id,agent_id:vi.agent_id,agent_name:(Li==null?void 0:Li.name)||"Unknown",agent_email:(Li==null?void 0:Li.email)||"",permissions:vi.permissions||{}}}))}else Ll([])}catch(An){console.error("Error loading assistant data:",An)}finally{uh(!1)}},Mn=Gt=>{nt(Gt),lt({name:Gt.name,email:Gt.email,brokerage_id:Gt.brokerage_id||"",phone:Gt.phone||""}),Je(!0),Js(Gt.id)},Ur=()=>{nt(null),Je(!1),lt({name:"",email:"",brokerage_id:"",phone:""})},ea=async()=>{Xe&&(await js(Xe.id),Ur())},Pr=Gt=>{Ro(An=>{const qn=new Set(An);return qn.has(Gt)?qn.delete(Gt):qn.add(Gt),qn})},Ni=()=>{if(Ja.size===mc.length&&mc.every(Gt=>Ja.has(Gt.id))){const Gt=new Set(Ja);mc.forEach(An=>Gt.delete(An.id)),Ro(Gt)}else{const Gt=new Set(Ja);mc.forEach(An=>Gt.add(An.id)),Ro(Gt)}},Lo=()=>{Ro(new Set)},wo=async()=>{if(Ja.size===0)return;Oa(!0);let Gt=0,An=0;try{const{data:{session:qn}}=await U.auth.getSession();for(const qr of Ja)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qn==null?void 0:qn.access_token}`},body:JSON.stringify({userId:qr,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"})})).ok?Gt++:An++}catch{An++}i({title:"Bulk Email Complete",description:`Sent ${Gt} emails${An>0?`, ${An} failed`:""}`}),Lo()}catch(qn){i({title:"Error",description:qn.message||"Failed to send emails",variant:"destructive"})}finally{Oa(!1)}},Wl=async()=>{if(Ja.size===0)return;Oa(!0);let Gt=0,An=0;try{const{data:{session:qn}}=await U.auth.getSession();for(const qr of Ja)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qn==null?void 0:qn.access_token}`},body:JSON.stringify({userId:qr})})).ok?Gt++:An++}catch{An++}i({title:"Bulk Password Reset Complete",description:`Sent ${Gt} reset emails${An>0?`, ${An} failed`:""}`}),Lo()}catch(qn){i({title:"Error",description:qn.message||"Failed to send password reset emails",variant:"destructive"})}finally{Oa(!1)}},xd=async Gt=>{Z(!0),re({done:0,total:Gt.length});const An=[];try{const{data:{session:qn}}=await U.auth.getSession(),qr=5;for(let vi=0;vi{try{const rd=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qn==null?void 0:qn.access_token}`},body:JSON.stringify({userId:wi.id,variant:"activation"})}),Au=await rd.json().catch(()=>({}));rd.ok&&(Au==null?void 0:Au.sent)!==!1?An.push({email:wi.email,ok:!0}):An.push({email:wi.email,ok:!1,reason:(Au==null?void 0:Au.reason)||`HTTP ${rd.status}`})}catch(rd){An.push({email:wi.email,ok:!1,reason:(rd==null?void 0:rd.message)||"Network error"})}})),re({done:Math.min(vi+qr,Gt.length),total:Gt.length}),vi+qrsetTimeout(wi,1200))}J(An);const Pa=An.filter(vi=>vi.ok).length;i({title:"Activation emails sent",description:`${Pa} of ${Gt.length} sent successfully`})}finally{Z(!1)}},Vr=async()=>{if(Ja.size===0)return;const Gt=l.filter(Pa=>Ja.has(Pa.id)).map(Pa=>Pa.name).slice(0,5).join(", "),An=Ja.size>5?` and ${Ja.size-5} more`:"";if(!await Qi(`Are you sure you want to delete ${Ja.size} users (${Gt}${An})? This action cannot be undone.`))return;Oa(!0);let qn=0,qr=0;try{const{data:{session:Pa}}=await U.auth.getSession();for(const vi of Ja)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pa==null?void 0:Pa.access_token}`},body:JSON.stringify({userId:vi})})).ok?qn++:qr++}catch{qr++}i({title:"Bulk Delete Complete",description:`Deleted ${qn} users${qr>0?`, ${qr} failed`:""}`}),Lo(),Sl()}catch(Pa){i({title:"Error",description:Pa.message||"Failed to delete users",variant:"destructive"})}finally{Oa(!1)}},gi=async()=>{uo(!0);try{const{data:{session:Gt}}=await U.auth.getSession(),An=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gt==null?void 0:Gt.access_token}`}});if(!An.ok){const qr=await An.json();throw new Error(qr.error||"Failed to sync phones")}const qn=await An.json();i({title:"Phone Sync Complete",description:`Pulled ${qn.summary.pulledFromGHL} from GHL, pushed ${qn.summary.pushedToGHL} to GHL, ${qn.summary.alreadySynced} already synced`}),Sl()}catch(Gt){i({title:"Error",description:Gt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{uo(!1)}},Ai=async(Gt,An)=>{Eo(Gt);try{const{data:{session:qn}}=await U.auth.getSession(),{data:qr}=await U.from("profiles").select("phone").eq("id",Gt).single(),Pa=(qr==null?void 0:qr.phone)||"",vi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qn==null?void 0:qn.access_token}`},body:JSON.stringify({email:An,action:"update",phone:Pa||void 0})});if(!vi.ok){const wi=await vi.json();throw new Error(wi.error||"Failed to sync with GHL")}const Li=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(An)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Pa?`Phone ${Pa} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),Sl()}catch(qn){i({title:"Error",description:qn.message||"Failed to sync phone",variant:"destructive"})}finally{Eo(null)}},rc=async Gt=>{await r(Gt)},Yc=()=>{if(Ja.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Gt=l.filter(wi=>Ja.has(wi.id)),An=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],qn=Gt.map(wi=>[wi.name,wi.email,wi.phone||"",wi.brokerage_name||"",wi.roles.join("; "),wi.claimed?"Claimed":"Unclaimed",new Date(wi.created_at).toLocaleDateString()]),qr=[An.join(","),...qn.map(wi=>wi.map(rd=>`"${(rd||"").replace(/"/g,'""')}"`).join(","))].join(` `),Pa=new Blob([qr],{type:"text/csv"}),vi=URL.createObjectURL(Pa),Li=document.createElement("a");Li.href=vi,Li.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Li.click(),URL.revokeObjectURL(vi),i({title:"Export complete",description:`Exported ${Gt.length} member(s)`})},mo=()=>{if(hh.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Gt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],An=hh.map(wi=>[wi.name,wi.email,wi.phone||"",wi.brokerage_name||"",wi.roles.join("; "),wi.claimed?"Claimed":"Unclaimed",wi.created_at?new Date(wi.created_at).toLocaleDateString():""]),qn=[Gt.join(","),...An.map(wi=>wi.map(rd=>`"${(rd||"").replace(/"/g,'""')}"`).join(","))].join(` `),qr=new Blob([qn],{type:"text/csv"}),Pa=URL.createObjectURL(qr),vi=document.createElement("a"),Li=Ee!=="all"?`-last-${Ee}days`:"";vi.href=Pa,vi.download=`members-export${Li}-${new Date().toISOString().split("T")[0]}.csv`,vi.click(),URL.revokeObjectURL(Pa),i({title:"Export complete",description:`Exported ${hh.length} member(s)`})};return f?e.jsx($s,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs($s,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(nl,{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(z,{size:"sm",variant:"outline",onClick:gi,disabled:Ao,children:[Ao?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(va,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Ao?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:Ao?"Syncing...":"Sync GHL"})]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>Zs(!0),children:[e.jsx(xN,{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(Is,{open:S,onOpenChange:C,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create New User"}),e.jsx(_r,{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(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",placeholder:"John Doe",value:b.name,onChange:Gt=>w({...b,name:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",placeholder:"john@example.com",value:b.email,onChange:Gt=>w({...b,email:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"password",children:"Password"}),e.jsx(pe,{id:"password",type:"password",placeholder:"Min 6 characters",value:b.password,onChange:Gt=>w({...b,password:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(pe,{id:"phone",type:"tel",placeholder:"555-123-4567",value:b.phone,onChange:Gt=>w({...b,phone:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"brokerage",children:["Brokerage",b.role==="brokerage_manager"?" (required)":""]}),e.jsxs(ls,{value:b.brokerage_id||"none",onValueChange:Gt=>w({...b,brokerage_id:Gt==="none"?"":Gt}),children:[e.jsx(rs,{id:"brokerage",children:e.jsx(cs,{placeholder:b.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),u.map(Gt=>e.jsx(He,{value:Gt.id,children:Gt.name},Gt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"role",children:"Role"}),e.jsxs(ls,{value:b.role,onValueChange:Gt=>w({...b,role:Gt}),children:[e.jsx(rs,{id:"role",children:e.jsx(cs,{placeholder:"Select role"})}),e.jsxs(as,{children:[e.jsx(He,{value:"user",children:"User"}),e.jsx(He,{value:"moderator",children:"Moderator"}),e.jsx(He,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(He,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(ls,{value:b.trial_days||"none",onValueChange:Gt=>w({...b,trial_days:Gt==="none"?"":Gt}),children:[e.jsx(rs,{id:"trial_days",children:e.jsx(cs,{placeholder:"No trial (full access)"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No trial (full access)"}),e.jsx(He,{value:"7",children:"7-day trial"}),e.jsx(He,{value:"30",children:"30-day trial"}),e.jsx(He,{value:"60",children:"60-day trial"}),e.jsx(He,{value:"90",children:"90-day trial"}),e.jsx(He,{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(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsx(z,{onClick:so,disabled:v,children:v?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(Qr,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"members",children:"Members"}),e.jsx(Wt,{value:"brokerages",children:"Brokerages"}),e.jsx(Wt,{value:"teams",children:"Teams"}),e.jsx(Wt,{value:"trials",children:"Trial Users"}),e.jsx(Wt,{value:"access",children:"Access Matrix"}),e.jsx(Wt,{value:"celebrations",children:"Celebrations"}),e.jsx(Wt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Kt,{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(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search members...",value:E,onChange:Gt=>Sd(Gt.target.value),className:"pl-10 h-9"})]}),e.jsxs(ls,{value:q,onValueChange:Gt=>lu(G,Gt),children:[e.jsx(rs,{className:"w-[130px] h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"claimed",children:"Active"}),e.jsx(He,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(ls,{value:te,onValueChange:Gt=>lu(ce,Gt),children:[e.jsx(rs,{className:"w-[130px] h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Roles"}),e.jsx(He,{value:"admin",children:"Admin"}),e.jsx(He,{value:"brokerage_manager",children:"Manager"}),e.jsx(He,{value:"assistant",children:"Assistant"}),e.jsx(He,{value:"user",children:"User"})]})]}),e.jsxs(ls,{value:ve,onValueChange:Gt=>lu(me,Gt),children:[e.jsx(rs,{className:"w-[130px] h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Users"}),e.jsx(He,{value:"trial",children:"Trial Only"}),e.jsx(He,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(ls,{value:he,onValueChange:Gt=>lu(ge,Gt),children:[e.jsx(rs,{className:"w-[150px] h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Brokerages"}),e.jsx(He,{value:"none",children:"No Brokerage"}),u.map(Gt=>e.jsx(He,{value:Gt.id,children:Gt.name},Gt.id))]})]}),e.jsxs(ls,{value:Ee,onValueChange:Gt=>lu(Ne,Gt),children:[e.jsx(rs,{className:"w-[150px] h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any Join Date"}),e.jsx(He,{value:"30",children:"Joined Last 30 Days"}),e.jsx(He,{value:"60",children:"Joined Last 60 Days"}),e.jsx(He,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(z,{size:"sm",variant:"outline",className:"h-9",onClick:mo,title:"Export currently filtered members to CSV",children:[e.jsx(Ga,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),e.jsxs(z,{size:"sm",variant:"outline",className:"h-9",disabled:Ah.filter(Gt=>!Gt.claimed&&Gt.email).length===0,onClick:()=>{J(null),H(!0)},title:"Email every pending (never signed in) member a link to set their password",children:[e.jsx(on,{className:"h-4 w-4 mr-1"}),"Email Pending (",Ah.filter(Gt=>!Gt.claimed&&Gt.email).length,")"]}),e.jsx(Is,{open:V,onOpenChange:Gt=>{K||H(Gt)},children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Email pending members"}),e.jsx(_r,{children:'Sends the branded "Activate your account" email with a set-password link to every member in the current filter who has never signed in. Sent in small batches, so this can take a few minutes.'})]}),K&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sending… ",oe.done," of ",oe.total]}),ae&&!K&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm",children:[ae.filter(Gt=>Gt.ok).length," sent",ae.some(Gt=>!Gt.ok)&&`, ${ae.filter(Gt=>!Gt.ok).length} failed`]}),ae.some(Gt=>!Gt.ok)&&e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border p-2 text-xs space-y-1",children:ae.filter(Gt=>!Gt.ok).map(Gt=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:Gt.email}),e.jsx("span",{className:"text-muted-foreground truncate",children:Gt.reason})]},Gt.email))})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",disabled:K,onClick:()=>H(!1),children:"Close"}),!ae&&e.jsx(z,{disabled:K,onClick:()=>xd(Ah.filter(Gt=>!Gt.claimed&&Gt.email).map(Gt=>({id:Gt.id,email:Gt.email,name:Gt.name}))),children:K?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}),"Sending…"]}):`Send to ${Ah.filter(Gt=>!Gt.claimed&&Gt.email).length} members`})]})]})}),(E||q!=="all"||te!=="all"||ve!=="all"||he!=="all"||Ee!=="all")&&e.jsxs(z,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{P(""),G("all"),ce("all"),me("all"),ge("all"),Ne("all"),I(1)},children:[e.jsx(er,{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:Jh?`Showing all ${Eh} members`:`Showing ${rx+1}-${Math.min(R0,Eh)} of ${Eh} members`}),e.jsxs(ls,{value:D.toString(),onValueChange:Gt=>pf(Number(Gt)),children:[e.jsx(rs,{className:"h-9 w-[110px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"50",children:"50 / page"}),e.jsx(He,{value:"100",children:"100 / page"}),e.jsx(He,{value:"250",children:"250 / page"}),e.jsx(He,{value:"0",children:"All"})]})]})]})]}),Ja.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[mc.length>0&&mc.every(Gt=>Ja.has(Gt.id))&&Ah.length>Ja.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 ",Ja.size," on this page are selected."]}),e.jsxs(z,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>Ro(new Set(Ah.map(Gt=>Gt.id))),children:["Select all ",Ah.length," filtered members"]})]}),Ah.length>0&&Ja.size===Ah.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Ah.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(Zw,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Ja.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:wo,disabled:ji,children:[ji?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(on,{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(z,{size:"sm",variant:"outline",onClick:Wl,disabled:ji,children:[ji?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(wb,{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(z,{size:"sm",variant:"outline",onClick:()=>Oe(!0),disabled:ji,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(xS,{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(z,{size:"sm",variant:"outline",onClick:Yc,children:[e.jsx(Ga,{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(z,{size:"sm",variant:"destructive",onClick:Vr,disabled:ji,children:[ji?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Cn,{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(z,{size:"sm",variant:"ghost",onClick:Lo,disabled:ji,children:e.jsx(er,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"w-[50px]",children:e.jsx(za,{checked:mc.length>0&&mc.every(Gt=>Ja.has(Gt.id)),onCheckedChange:Ni,"aria-label":"Select all on page"})}),e.jsx(Hh,{sortKey:"name",currentSortKey:mh,currentDirection:pd,onSort:fd,children:"Name"}),e.jsx(Hh,{sortKey:"brokerage",currentSortKey:mh,currentDirection:pd,onSort:fd,children:"Brokerage"}),e.jsx(Hh,{sortKey:"status",currentSortKey:mh,currentDirection:pd,onSort:fd,children:"Status"}),e.jsx(Hh,{sortKey:"role",currentSortKey:mh,currentDirection:pd,onSort:fd,children:"Role"}),e.jsx(Hh,{sortKey:"last_login",currentSortKey:mh,currentDirection:pd,onSort:fd,children:"Last Login"}),e.jsx(Hh,{sortKey:"created_at",currentSortKey:mh,currentDirection:pd,onSort:fd,children:"Member Since"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(Qa,{children:mc.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):mc.map(Gt=>e.jsxs(fn,{className:`hover:bg-muted/30 ${Ja.has(Gt.id)?"bg-primary/5":""}`,children:[e.jsx(yt,{children:e.jsx(za,{checked:Ja.has(Gt.id),onCheckedChange:()=>Pr(Gt.id),"aria-label":`Select ${Gt.name}`})}),e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>Mn(Gt),className:"text-primary hover:underline font-medium text-left",children:Gt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Gt.email})]})}),e.jsx(yt,{className:"text-muted-foreground",children:Gt.brokerage_name||"—"}),e.jsx(yt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const An=Gt.trial_expires_at||Gt.subscription_end_date;if((Gt.is_trial||Gt.subscription_status==="trialing")&&An){const qr=Math.ceil((new Date(An).getTime()-Date.now())/864e5),Pa=qr<=0,vi=qr<=3;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ze,{variant:"outline",className:Ct("w-fit",Pa?"border-destructive text-destructive":vi?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Pa?"Trial Expired":`Trial · ${qr}d left`}),e.jsx("button",{type:"button",title:"Copy upgrade link — paste into an email so this agent can sign in and pay on their existing account",className:"text-muted-foreground hover:text-primary transition-colors",onClick:async()=>{const Li="https://dashboard.relevelup.com/upgrade";try{await navigator.clipboard.writeText(Li),i({title:"Upgrade link copied",description:Li})}catch{window.prompt("Copy this upgrade link:",Li)}},children:e.jsx(Sa,{className:"h-3.5 w-3.5"})})]})}return e.jsx(ze,{variant:Gt.claimed?"default":"secondary",className:Gt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Gt.claimed?"Active":"Pending"})})()})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex flex-col",children:[Gt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Gt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Gt.roles.includes("assistant")&&ym[Gt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",ym[Gt.id].agent_name||ym[Gt.id].agent_email]})]})}),e.jsx(yt,{className:"text-muted-foreground",children:Gt.last_sign_in_at?new Date(Gt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(yt,{className:"text-muted-foreground",children:Gt.created_at?new Date(Gt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{ui(Gt),qa(!0)},title:"Send celebration",children:e.jsx(Ix,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Mn(Gt),title:"Edit member",children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ai(Gt.id,Gt.email),disabled:Ua===Gt.id,title:"Sync phone with GHL",children:Ua===Gt.id?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(va,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ma(Gt.id),title:"Resend welcome email",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>to(Gt.email,Gt.name),title:"Send password reset",children:e.jsx(iP,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>rc(Gt.id),disabled:a||Gt.id===(t==null?void 0:t.id),title:Gt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Gt.name}`,children:a?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(lP,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Ta(Gt.id,Gt.name),title:"Delete user",children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},Gt.id))})]})}),Uu>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 ",Uu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>I(1),disabled:M===1,children:"First"}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Gt=>Math.max(1,Gt-1)),disabled:M===1,children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Uu)},(Gt,An)=>{let qn;return Uu<=5||M<=3?qn=An+1:M>=Uu-2?qn=Uu-4+An:qn=M-2+An,e.jsx(z,{variant:M===qn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>I(qn),children:qn},qn)})}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Gt=>Math.min(Uu,Gt+1)),disabled:M===Uu,children:e.jsx(yi,{className:"h-4 w-4"})}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>I(Uu),disabled:M===Uu,children:"Last"})]})]})]}),e.jsx(Is,{open:Ge,onOpenChange:Je,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Edit Member"}),e.jsx(_r,{children:"Update member details, roles, and app access"})]}),Xe&&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(ee,{htmlFor:"edit-name",children:"Name"}),e.jsx(pe,{id:"edit-name",value:ut.name,onChange:Gt=>lt({...ut,name:Gt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-email",children:"Email"}),e.jsx(pe,{id:"edit-email",type:"email",value:ut.email,onChange:Gt=>lt({...ut,email:Gt.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(ee,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(pe,{id:"edit-phone",type:"tel",value:ut.phone,onChange:Gt=>lt({...ut,phone:Gt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(ls,{value:ut.brokerage_id||"none",onValueChange:Gt=>lt({...ut,brokerage_id:Gt==="none"?"":Gt}),children:[e.jsx(rs,{id:"edit-brokerage",children:e.jsx(cs,{placeholder:"Select brokerage"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),u.map(Gt=>e.jsx(He,{value:Gt.id,children:Gt.name},Gt.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:[Xe.roles.map(Gt=>e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(Om,{className:"h-3 w-3"}),Gt,Gt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>ho(Xe.id,Gt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(er,{className:"h-3 w-3"})})]},Gt)),Xe.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(ls,{onValueChange:Gt=>ho(Xe.id,Gt,"add"),children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(cs,{placeholder:"Add role..."})}),e.jsxs(as,{children:[!Xe.roles.includes("admin")&&e.jsx(He,{value:"admin",children:"Admin"}),!Xe.roles.includes("user")&&e.jsx(He,{value:"user",children:"User"})]})]}),!Xe.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"})]}),(zo.length>0||tl.length>0||Xe.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(On,{className:"h-4 w-4"}),"Assistant Relationships"]}),Ku?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[zo.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:"}),zo.map(Gt=>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:Gt.assistant_name}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Gt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Gt.permissions).filter(([,An])=>An).map(([An])=>e.jsx(ze,{variant:"secondary",className:"text-[10px] capitalize",children:An},An))})]},Gt.id))]}),tl.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:"}),tl.map(Gt=>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:Gt.agent_name}),e.jsx(ze,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Gt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Gt.permissions).filter(([,An])=>An).map(([An])=>e.jsx(ze,{variant:"secondary",className:"text-[10px] capitalize",children:An},An))})]},Gt.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(Gt=>{const An=pi(Xe.tags,Gt.required_tags),qn=`${Xe.id}-${Gt.id}`,qr=qt===qn,Pa=Gt.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:Gt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Gt.name}),Pa&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:qr?e.jsx(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Pa?e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(mn,{checked:An,onCheckedChange:()=>$m(Xe.id,Gt,An)})})]},Gt.id)})})]}),e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Account Access"}),Xe.is_paused?e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"This account is paused"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["They cannot sign in and see a paused message on the login page.",Xe.paused_reason?` Reason shown: “${Xe.paused_reason}”`:""]})]}),e.jsx(z,{size:"sm",onClick:()=>Um(Xe.id,!1),disabled:_e,children:"Reactivate account"})]}):e.jsxs("div",{className:"p-4 rounded-lg border bg-muted/30 space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pausing blocks sign-in and shows this member a message explaining their account is paused."}),e.jsx(pe,{placeholder:"Optional message shown to them (e.g. Payment is past due.)",value:Se,onChange:Gt=>We(Gt.target.value)}),e.jsx(z,{size:"sm",variant:"destructive",onClick:async()=>{await Um(Xe.id,!0,Se),We("")},disabled:_e,children:"Pause account"})]})]}),(Xe.is_trial||Xe.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(Zr,{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:[Xe.trial_expires_at&&e.jsx(d1t,{expiresAt:Xe.trial_expires_at}),!Xe.trial_expires_at&&Xe.subscription_status==="trialing"&&Xe.subscription_end_date&&e.jsx(d1t,{expiresAt:Xe.subscription_end_date})]}),(Xe.trial_expires_at||Xe.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Xe.trial_expires_at||Xe.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>mp(Xe.id,7),disabled:ke,children:[e.jsx(v0,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>mp(Xe.id,14),disabled:ke,children:[e.jsx(v0,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>mp(Xe.id,30),disabled:ke,children:[e.jsx(v0,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(z,{size:"sm",variant:"default",onClick:()=>qm(Xe.id),disabled:qe,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(jj,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Xe.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Xe.trial_started_at).toLocaleDateString(),Xe.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Xe.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Xe.is_trial||Xe.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(Zr,{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(Gt=>e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>Ks(Xe.id,Gt),disabled:ot,children:[e.jsx(v0,{className:"h-4 w-4 mr-1"}),Gt,"-day trial"]},Gt))})]})]}),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:[Xe.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Xe.email_confirmed_at).toLocaleString()]}),Xe.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Xe.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Xe.created_at).toLocaleString()]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:Ur,children:"Cancel"}),e.jsx(z,{onClick:ea,children:"Save Changes"})]})]})}),e.jsxs(Kt,{value:"access",children:[c.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(z,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Member Access Matrix"}),e.jsx(En,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents by name or email...",value:E,onChange:Gt=>{P(Gt.target.value),I(1)},className:"pl-9"})]})]}),e.jsxs(Le,{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(Gt=>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:Gt.icon}),e.jsx("span",{className:"text-sm",children:Gt.name})]})},Gt.id))]})}),e.jsxs("tbody",{children:[mc.map(Gt=>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:Gt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Gt.email})]})}),c.map(An=>{const qn=pi(Gt.tags,An.required_tags),qr=`${Gt.id}-${An.id}`,Pa=qt===qr;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Pa?e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(mn,{checked:qn,onCheckedChange:()=>$m(Gt.id,An,qn),disabled:An.required_tags.length===0})})},An.id)})]},Gt.id)),mc.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"})})]})]})}),Uu>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 ",rx+1,"-",Math.min(R0,Eh)," of ",Eh," • Page ",M," of ",Uu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Gt=>Math.max(1,Gt-1)),disabled:M===1,children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Gt=>Math.min(Uu,Gt+1)),disabled:M===Uu,children:e.jsx(yi,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(z,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(Kt,{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(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:Zn,onChange:Gt=>Or(Gt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Gt=>Gt.name.toLowerCase().includes(Zn.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{const Gt=[];for(const Li of u){const wi=m[Li.id]??[];for(const rd of wi){const Au=l.find(pp=>pp.id===rd);if(Au){const pp=(Au.name||"").trim().split(/\s+/),gd=pp[0]||"",Hd=pp.slice(1).join(" ")||"";Gt.push({firstName:gd,lastName:Hd,email:Au.email,brokerageName:Li.name})}}}if(Gt.length===0){i({title:"No managers found to export"});return}const qn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Gt.map(Li=>[Li.firstName,Li.lastName,Li.email,Li.brokerageName].map(wi=>`"${(wi||"").replace(/"/g,'""')}"`).join(","))].join(` `),qr=new Blob([qn],{type:"text/csv"}),Pa=URL.createObjectURL(qr),vi=document.createElement("a");vi.href=Pa,vi.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,vi.click(),URL.revokeObjectURL(Pa),i({title:`Exported ${Gt.length} managers`})},children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(Is,{open:Zt,onOpenChange:ms,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create New Brokerage"}),e.jsx(_r,{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(ee,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Dt,onChange:Gt=>It(Gt.target.value),maxLength:100})]})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>ms(!1),children:"Cancel"}),e.jsx(z,{onClick:al,disabled:qs,children:qs?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Tt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Tt,{className:"font-semibold",children:"Agents"}),e.jsx(Tt,{className:"w-[150px]"})]})}),e.jsx(Qa,{children:(()=>{const Gt=u.filter(An=>An.name.toLowerCase().includes(Zn.toLowerCase()));return Gt.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Zn?"No brokerages match your search":"No brokerages found"})}):Gt.map(An=>{const qn=l.filter(Li=>Li.brokerage_id===An.id),Pa=(m[An.id]??[]).map(Li=>l.find(wi=>wi.id===Li)).filter(Boolean),vi=qn.length;return e.jsxs(fn,{className:"hover:bg-muted/30",children:[e.jsx(yt,{children:e.jsx("button",{onClick:()=>vo(An),className:"text-primary hover:underline font-medium",children:An.name})}),e.jsx(yt,{children:Pa.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Pa.map(Li=>e.jsx(ze,{variant:"secondary",className:"text-xs",children:Li.name},Li.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(yt,{children:[vi," member",vi!==1?"s":""]}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(z,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Dp(An),children:[e.jsx(On,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>vo(An),title:"Edit brokerage",children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>E1(An),title:"Delete brokerage",children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},An.id)})})()})]})}),e.jsx(Is,{open:Us,onOpenChange:Es,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Edit Brokerage"}),e.jsx(_r,{children:"Update brokerage details and manage managers"})]}),kn&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"edit-brokerage-name",value:bn,onChange:Gt=>cr(Gt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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 An=(m[kn.id]??[]).map(qn=>l.find(qr=>qr.id===qn)).filter(Boolean);return An.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):An.map(qn=>e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(Om,{className:"h-3 w-3"}),qn.name,e.jsx("button",{onClick:()=>ho(qn.id,"brokerage_manager","remove",kn.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(er,{className:"h-3 w-3"})})]},qn.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(hd,{open:oa,onOpenChange:aa,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox","aria-expanded":oa,className:"w-full justify-between",children:["Search for a member...",e.jsx(Rr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-full p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search by name or email..."}),e.jsxs(Rj,{className:"max-h-[200px]",children:[e.jsx(Fj,{children:"No members found."}),e.jsx(G_,{children:(()=>{const Gt=new Set(m[kn.id]??[]);return l.filter(An=>!Gt.has(An.id)&&(n||An.brokerage_id===kn.id)).map(An=>e.jsxs(c1,{value:`${An.name} ${An.email}`,onSelect:()=>{yl(An.id,kn.id),aa(!1)},children:[An.name," (",An.email,")"]},An.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Gt=>Gt.brokerage_id===kn.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Gt=>Gt.brokerage_id===kn.id).map(Gt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Gt.name}),Gt.roles.includes("brokerage_manager")&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Manager"})]},Gt.id))})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:$x,children:"Cancel"}),e.jsx(z,{onClick:il,disabled:Fs,children:Fs?"Saving...":"Save Changes"})]})]})}),e.jsx(Is,{open:lr,onOpenChange:Tn,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(_r,{children:['Are you sure you want to delete "',Yn==null?void 0:Yn.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 "',Yn==null?void 0:Yn.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Gt=>Gt.brokerage_id===(Yn==null?void 0:Yn.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>Tn(!1),children:"Cancel"}),e.jsx(z,{variant:"destructive",onClick:zc,disabled:wn,children:wn?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(Is,{open:Ss,onOpenChange:pr,children:e.jsxs(Ls,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-5 w-5"}),"Manage ",hn==null?void 0:hn.name]}),e.jsx(_r,{children:"Add, remove, or manage users in this brokerage"})]}),hn&&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(Rr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search members...",value:Gs,onChange:Gt=>an(Gt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Is,{open:tr,onOpenChange:Lr,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add New Agent"}),e.jsxs(_r,{children:["Create a new agent for ",hn.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-name",children:"Name"}),e.jsx(pe,{id:"agent-name",placeholder:"John Doe",value:Yt.name,onChange:Gt=>it({...Yt,name:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-email",children:"Email"}),e.jsx(pe,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Yt.email,onChange:Gt=>it({...Yt,email:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-password",children:"Password"}),e.jsx(pe,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Yt.password,onChange:Gt=>it({...Yt,password:Gt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(pe,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Yt.phone,onChange:Gt=>it({...Yt,phone:Gt.target.value})})]}),Lt&&Qt.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"agent-package",children:[Lt.name," Package"]}),e.jsxs(ls,{value:gs,onValueChange:Vt,children:[e.jsx(rs,{id:"agent-package",children:e.jsx(cs,{placeholder:"Select a package"})}),e.jsxs(as,{children:[Qt.map(Gt=>e.jsx(He,{value:Gt.id,children:Gt.name},Gt.id)),e.jsx(He,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:gs==="none"?"Agent gets unrestricted access; welcome email has no package block.":((em=Qt.find(Gt=>Gt.id===gs))==null?void 0:em.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>Lr(!1),children:"Cancel"}),e.jsx(z,{onClick:nx,disabled:gt,children:gt?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(hd,{open:Kr,onOpenChange:Tr,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox","aria-expanded":Kr,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Rr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search users...",value:Hr,onValueChange:Ba}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:"No users found."}),e.jsx(G_,{children:Yg(hn.id).filter(Gt=>Hr===""||Gt.name.toLowerCase().includes(Hr.toLowerCase())||Gt.email.toLowerCase().includes(Hr.toLowerCase())).map(Gt=>e.jsxs(c1,{value:`${Gt.name} ${Gt.email}`,onSelect:()=>{Dv(Gt.id,hn.id),Tr(!1),Ba("")},children:[Gt.name," (",Gt.email,")"]},Gt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Name"}),e.jsx(Tt,{className:"font-semibold",children:"Email"}),e.jsx(Tt,{className:"font-semibold",children:"Status"}),e.jsx(Tt,{className:"font-semibold",children:"Role"}),e.jsx(Tt,{className:"w-[120px]"})]})}),e.jsx(Qa,{children:vm(hn.id).length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Gs?"No matching members found":"No members in this brokerage"})}):vm(hn.id).map(Gt=>e.jsxs(fn,{className:"hover:bg-muted/30",children:[e.jsx(yt,{className:"font-medium",children:Gt.name}),e.jsx(yt,{className:"text-muted-foreground",children:Gt.email}),e.jsx(yt,{children:Gt.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(yt,{children:Gt.roles.includes("brokerage_manager")?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Om,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Gt.claimed&&e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ma(Gt.id),title:"Resend welcome email",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>_g(Gt.id),title:"Remove from brokerage",children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>rc(Gt.id),disabled:a||Gt.id===(t==null?void 0:t.id),title:Gt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Gt.name}`,children:a?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(lP,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Ta(Gt.id,Gt.name),title:"Delete user",children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},Gt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Pi(hn.id).length," total member",Pi(hn.id).length!==1?"s":""," •",Pi(hn.id).filter(Gt=>Gt.roles.includes("brokerage_manager")).length," manager",Pi(hn.id).filter(Gt=>Gt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(hr,{children:e.jsx(z,{variant:"outline",onClick:hp,children:"Close"})})]})})]}),e.jsx(Kt,{value:"teams",children:e.jsx($on,{})}),e.jsx(Kt,{value:"trials",children:e.jsx(Son,{})}),e.jsx(Kt,{value:"celebrations",children:e.jsx(kon,{})}),e.jsx(Kt,{value:"deletions",children:e.jsx(Aon,{})})]})]}),e.jsx(cHt,{open:Vs,onOpenChange:Zs,brokerages:u,onSuccess:Sl}),ar&&e.jsx(dHt,{open:Ji,onOpenChange:Gt=>{qa(Gt),Gt||ui(null)},userId:ar.id,userName:ar.name}),e.jsx(Uon,{open:Pe,onOpenChange:Oe,recipients:l.filter(Gt=>Ja.has(Gt.id)).map(Gt=>({id:Gt.id,name:Gt.name,email:Gt.email}))})]})};function Von(){const{toast:s}=_i(),t=$t(),[n,r]=_.useState(""),[a,i]=_.useState(new Set),[l,o]=_.useState({}),[c,d]=_.useState({}),[u,h]=_.useState(""),[m,p]=_.useState(!1),{data:f=[],isLoading:g}=rt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:I}=await U.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(I)throw I;return M||[]}}),{data:v=[]}=rt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:I}=await U.from("brokerages").select("id, name").order("name");if(I)throw I;return M||[]}}),y=_.useMemo(()=>{const M=n.toLowerCase().trim();return M?f.filter(I=>(I.name||"").toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M)||(I.phone||"").toLowerCase().includes(M)):f},[f,n]),b=_.useMemo(()=>{var I;const M=new Map;for(const D of f){const F=(I=(D.email||"").split("@")[1])==null?void 0:I.toLowerCase();F&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(F)||M.set(F,(M.get(F)||0)+1))}return Array.from(M.entries()).sort((D,F)=>F[1]-D[1]).slice(0,10)},[f]),w=M=>{i(I=>{const D=new Set(I);return D.has(M)?D.delete(M):D.add(M),D})},S=()=>{a.size===y.length?i(new Set):i(new Set(y.map(M=>M.id)))},C=async(M,I)=>{if(I){d(D=>({...D,[M]:!0}));try{const{data:D,error:F}=await U.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:I}});if(F)throw F;if(D!=null&&D.error)throw new Error(D.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(q=>{const G=new Set(q);return G.delete(M),G})}catch(D){s({title:"Failed",description:D.message,variant:"destructive"})}finally{d(D=>({...D,[M]:!1}))}}},E=async()=>{if(!u||a.size===0)return;p(!0);let M=0,I=0;for(const D of a)try{const{data:F,error:q}=await U.functions.invoke("assign-brokerage",{body:{userId:D,brokerageId:u}});if(q||F!=null&&F.error)throw new Error((q==null?void 0:q.message)||F.error);M++}catch{I++}p(!1),s({title:`Assigned ${M}${I?`, ${I} failed`:""}`,description:"Bulk assignment complete.",variant:I?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},P=(M,I)=>{const D={...l};for(const F of f)(F.email||"").toLowerCase().endsWith(`@${M}`)&&(D[F.id]=I);o(D),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Le,{children:e.jsx("div",{className:"text-3xl font-bold",children:f.length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(oi,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Le,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{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(Le,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Le,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([M,I])=>{const D=v.find(F=>F.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:I}),e.jsxs(ls,{onValueChange:F=>P(M,F),defaultValue:D==null?void 0:D.id,children:[e.jsx(rs,{className:"h-8 w-[220px]",children:e.jsx(cs,{placeholder:"Apply brokerage…"})}),e.jsx(as,{children:v.map(F=>e.jsx(He,{value:F.id,children:F.name},F.id))})]})]},M)})})})]}),e.jsxs(be,{children:[e.jsxs(_t,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{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(ls,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"w-[240px]",children:e.jsx(cs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(as,{children:v.map(M=>e.jsx(He,{value:M.id,children:M.name},M.id))})]}),e.jsxs(z,{onClick:E,disabled:!u||a.size===0||m,children:[m&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Le,{children:g?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-10",children:e.jsx(za,{checked:a.size===y.length&&y.length>0,onCheckedChange:S})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Signed up"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Assign to brokerage"}),e.jsx(Tt,{className:"w-24"})]})}),e.jsx(Qa,{children:y.map(M=>{const I=l[M.id]||"";return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx(za,{checked:a.has(M.id),onCheckedChange:()=>w(M.id)})}),e.jsx(yt,{className:"font-medium",children:M.name||"—"}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:M.email}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Md(new Date(M.created_at),{addSuffix:!0})}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(yt,{children:e.jsxs(ls,{value:I,onValueChange:D=>o(F=>({...F,[M.id]:D})),children:[e.jsx(rs,{className:"h-9 w-[240px]",children:e.jsx(cs,{placeholder:"Pick brokerage…"})}),e.jsx(as,{children:v.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))})]})}),e.jsx(yt,{children:e.jsx(z,{size:"sm",disabled:!I||c[M.id],onClick:()=>C(M.id,I),children:c[M.id]?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const Hon=()=>{const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("");_.useEffect(()=>{f()},[]);const f=async()=>{const{data:C,error:E}=await U.from("invite_codes").select("*").order("created_at",{ascending:!1});E?(ne.error("Failed to load invite codes"),console.error(E)):t(C||[]),r(!1)},g=async C=>{if(C.preventDefault(),!l.trim()){ne.error("Please enter a code");return}i(!0);const{error:E}=await U.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});E?E.code==="23505"?ne.error("This code already exists"):(ne.error("Failed to create invite code"),console.error(E)):(ne.success("Invite code created"),o(""),d(""),h(""),p(""),f()),i(!1)},v=async(C,E)=>{const{error:P}=await U.from("invite_codes").update({is_active:!E}).eq("id",C);P?ne.error("Failed to update code"):t(s.map(M=>M.id===C?{...M,is_active:!E}:M))},y=async C=>{const{error:E}=await U.from("invite_codes").delete().eq("id",C);E?ne.error("Failed to delete code"):(ne.success("Code deleted"),t(s.filter(P=>P.id!==C)))},b="https://dashboard.relevelup.com",w=C=>{const E=`${b}/join?code=${C}`;navigator.clipboard.writeText(E),ne.success("Link copied to clipboard")},S=`${b}/join`;return e.jsx($s,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Create New Code"}),e.jsxs(En,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:S})]})]}),e.jsx(Le,{children:e.jsxs("form",{onSubmit:g,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"code",children:"Code"}),e.jsx(pe,{id:"code",placeholder:"WELCOME2024",value:l,onChange:C=>o(C.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(ee,{htmlFor:"description",children:"Description (optional)"}),e.jsx(pe,{id:"description",placeholder:"For marketing campaign",value:c,onChange:C=>d(C.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(pe,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:C=>h(C.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(pe,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:C=>p(C.target.value),className:"w-28"})]}),e.jsxs(z,{type:"submit",disabled:a,children:[a?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Active Codes"})}),e.jsx(Le,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Code"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Uses"}),e.jsx(Tt,{children:"Trial"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Active"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(C=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-mono font-medium",children:C.code}),e.jsx(yt,{className:"text-muted-foreground",children:C.description||"—"}),e.jsxs(yt,{children:[C.uses_count,C.max_uses&&` / ${C.max_uses}`]}),e.jsx(yt,{children:C.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[C.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(yt,{className:"text-muted-foreground",children:Ys(new Date(C.created_at),"MMM d, yyyy")}),e.jsx(yt,{children:e.jsx(mn,{checked:C.is_active,onCheckedChange:()=>v(C.id,C.is_active)})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>w(C.code),title:"Copy invite link",children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>y(C.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},C.id))})]})})]})]})})},BA=U;function Gwr(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 Gon(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const Won="https://dashboard.relevelup.com";function Wwr(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:Won}/live/${s}`;return t?`${r}?i=${t}`:r}function Kwr(){const s=$t(),t=rt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await BA.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=mt({mutationFn:async i=>{var d;const{data:l}=await U.auth.getUser(),{data:o,error:c}=await BA.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"]}),ne.success("Live event created")},onError:i=>ne.error((i==null?void 0:i.message)||"Could not create event")}),r=mt({mutationFn:async({id:i,...l})=>{const{error:o}=await BA.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]}),ne.success("Saved")},onError:i=>ne.error((i==null?void 0:i.message)||"Could not save")}),a=mt({mutationFn:async i=>{const{error:l}=await BA.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ne.success("Event deleted")},onError:i=>ne.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function Ywr(s){return rt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await BA.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function Zwr(s){return rt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await BA.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function Xwr(s){const t=$t(),n=rt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await BA.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=mt({mutationFn:async i=>{const{data:l}=await U.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 BA.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ne.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ne.error((i==null?void 0:i.message)||"Could not create invites")}),a=mt({mutationFn:async i=>{const{error:l}=await BA.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 Pae=async s=>{try{const{data:t,error:n}=await U.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}},LW=async s=>{try{const{data:t,error:n}=await U.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}}},Kon=async(s,t)=>await Pae("new_templates")?LW({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}),Yon=async(s,t)=>LW({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),Zon=async(s,t)=>await Pae("new_events")?LW({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),Xon=async(s,t)=>await Pae("new_toolbox")?LW({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),XHe=async(s,t)=>await Pae("new_social_swag")?LW({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}),Qon=async(s,t)=>await Pae("new_newsletters")?LW({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),E9e=400;function Jon(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 eln(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await U.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 K=!1;return(async()=>{h(!0);try{const[Z,oe,re]=await Promise.all([eln(),m1t("event_registrations",n.id),m1t("event_attendees",n.id)]);if(K)return;p(Z),g(oe),y(re)}catch(Z){K||r({title:"Could not load audience",description:Z instanceof Error?Z.message:"Unknown error",variant:"destructive"})}finally{K||h(!1)}})(),()=>{K=!0}},[s,n,r]),_.useEffect(()=>{s||(C(null),d(""),o(""),i("not_registered"))},[s]);const D=_.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(K=>!f.has(K.id)):m.filter(K=>f.has(K.id)&&!v.has(K.id)),[a,m,f,v]),F={all:m.length,not_registered:m.filter(K=>!f.has(K.id)).length,registered_never_attended:m.filter(K=>f.has(K.id)&&!v.has(K.id)).length},q=async(K,Z=!1)=>{const{data:{session:oe}}=await U.auth.getSession(),re=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:K.map(J=>({email:J.email,name:J.name,user_id:J.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:Z||void 0})}),ae=await re.json().catch(()=>({}));if(!re.ok)throw new Error((ae==null?void 0:ae.error)||`HTTP ${re.status}`);return{sent:(ae==null?void 0:ae.sent)??0,failed:(ae==null?void 0:ae.failed)??0,alreadyInvited:(ae==null?void 0:ae.already_invited)??0}},G=async()=>{var K;if(n){I(!0);try{const{data:{session:Z}}=await U.auth.getSession(),oe=Z==null?void 0:Z.user;if(!(oe!=null&&oe.email))throw new Error("No signed-in email found");const re=await q([{id:oe.id,name:((K=oe.user_metadata)==null?void 0:K.name)||"",email:oe.email}],!0);r({title:"Test sent",description:`Sent to ${oe.email} · Sent: ${re.sent} · Failed: ${re.failed}`})}catch(Z){r({title:"Test failed",description:Z instanceof Error?Z.message:"Unknown error",variant:"destructive"})}finally{I(!1)}}},V=async()=>{if(!(!n||D.length===0)){P(!1),w(!0),C({done:0,total:D.length,sent:0,failed:0});try{let K=0,Z=0,oe=0;for(let re=0;re!b&&t(K),children:e.jsxs(Ls,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(_r,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ud,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Jon(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(ee,{className:"flex items-center gap-2",children:[e.jsx(On,{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(bt,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(C_,{value:a,onValueChange:K=>i(K),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(am,{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:F.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(am,{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:F.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(am,{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:F.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(pe,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:K=>o(K.target.value),disabled:b}),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(ee,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ps,{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:K=>d(K.target.value),rows:4,disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),S&&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 ",S.done.toLocaleString()," / ",S.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",S.sent.toLocaleString(),S.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",S.failed.toLocaleString()]})]})]}),e.jsx(Di,{value:H})]})]}),e.jsxs(hr,{className:"gap-2 sm:gap-2",children:[e.jsx(z,{variant:"outline",onClick:G,disabled:b||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(on,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(z,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx(z,{onClick:()=>P(!0),disabled:b||u||D.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"})," Send to ",D.length.toLocaleString()]})})]})]})}),e.jsx(Ql,{open:E,onOpenChange:P,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Send event invite?"}),e.jsxs(ql,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[D.length.toLocaleString()," member",D.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($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsxs(Ml,{onClick:V,children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const Sce={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 sln(){const s=zn(),t=$t(),[n,r]=_.useState(!1),[a,i]=_.useState(null),[l,o]=_.useState(Sce),[c,d]=_.useState(null),[u,h]=_.useState(null),[m,p]=_.useState(!1),f=_.useRef(null),[g,v]=_.useState(!1),[y,b]=_.useState(null),[w,S]=_.useState(!1),[C,E]=_.useState(null),[P,M]=_.useState(null),[I,D]=_.useState(!0),[F,q]=_.useState(""),[G,V]=_.useState(!1),[H,K]=_.useState(null),{data:Z,isLoading:oe}=rt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ge,error:Je}=await U.from("events").select("*").order("event_date",{ascending:!0});if(Je)throw Je;return Ge}}),{data:re}=rt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ge=[],Je=0;const ut=1e3;for(;;){const{data:qt,error:zt}=await U.from("event_registrations").select("event_id").range(Je,Je+ut-1);if(zt)throw zt;if(!qt||qt.length===0||(Ge=Ge.concat(qt),qt.length{lt[qt.event_id]=(lt[qt.event_id]||0)+1}),lt}}),{data:ae,isLoading:J}=rt({queryKey:["event-registrations-details",y==null?void 0:y.id],queryFn:async()=>{if(!y)return[];const{data:Ge,error:Je}=await U.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",y.id).order("registered_at",{ascending:!1});if(Je)throw Je;if(!Ge||Ge.length===0)return[];const ut=Ge.map(zt=>zt.user_id).filter(Boolean);let lt=[];if(ut.length>0){const{data:zt,error:Zt}=await U.from("profiles").select("id, name, email").in("id",ut);if(Zt)throw Zt;lt=zt||[]}const qt=new Map((lt==null?void 0:lt.map(zt=>[zt.id,zt]))||[]);return Ge.map(zt=>({...zt,profiles:zt.user_id&&qt.get(zt.user_id)||null}))},enabled:!!y}),{data:te,isLoading:ce}=rt({queryKey:["event-attendees-details",y==null?void 0:y.id],queryFn:async()=>{if(!y)return[];const{data:Ge,error:Je}=await U.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",y.id).order("created_at",{ascending:!1});if(Je)throw Je;if(!Ge||Ge.length===0)return[];const ut=Ge.map(ms=>ms.user_id).filter(Boolean);let lt=[];if(ut.length>0){const{data:ms,error:Dt}=await U.from("profiles").select("id, name, email").in("id",ut);if(Dt)throw Dt;lt=ms||[]}const{data:qt}=await U.from("agent_points").select("user_id").eq("event_id",y.id),zt=new Set((qt==null?void 0:qt.map(ms=>ms.user_id))||[]),Zt=new Map((lt==null?void 0:lt.map(ms=>[ms.id,ms]))||[]);return Ge.map(ms=>({...ms,profiles:ms.user_id&&Zt.get(ms.user_id)||null,points_awarded:ms.user_id?zt.has(ms.user_id):!1}))},enabled:!!y}),ve=Ge=>{b(Ge),v(!0)},me=mt({mutationFn:async Ge=>{const{data:{session:Je}}=await U.auth.getSession();if(!Je)throw new Error("Not authenticated");const ut=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Je.access_token}`},body:JSON.stringify({event_id:Ge})}),lt=await ut.json();if(!ut.ok){const qt=new Error(lt.error||"Failed to sync");throw qt.scopeError=!!lt.scope_error,qt.details=lt.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 lt},onSuccess:Ge=>{if(t.invalidateQueries({queryKey:["event-registrations-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ge!=null&&Ge.scope_error||(Ge==null?void 0:Ge.success)===!1){ne.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}ne.success(Ge.message)},onError:Ge=>{ne.error("Failed to sync Zoom registrations",{description:Ge.scopeError&&Ge.details||Ge.message,duration:Ge.scopeError?2e4:5e3})}}),he=mt({mutationFn:async Ge=>{const{data:{session:Je}}=await U.auth.getSession();if(!Je)throw new Error("Not authenticated");const ut=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Je.access_token}`},body:JSON.stringify({event_id:Ge})}),lt=await ut.json();if(!ut.ok)throw new Error(lt.error||"Failed to sync attendees");return lt},onSuccess:Ge=>{if(t.invalidateQueries({queryKey:["event-attendees-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ge!=null&&Ge.scope_error||(Ge==null?void 0:Ge.success)===!1){ne.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?ne.success(Ge.message):ne.success(`Synced ${Ge.synced||0} attendees. ${Ge.points_awarded||0} points awarded!`)},onError:Ge=>{ne.error("Failed to sync attendees: "+Ge.message)}}),ge=mt({mutationFn:async()=>{const{data:Ge,error:Je}=await U.functions.invoke("zoom-retry-registrations",{body:{}});if(Je)throw Je;return Ge},onSuccess:Ge=>{t.invalidateQueries({queryKey:["event-registrations-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ne.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=>{ne.error("Retry failed: "+Ge.message)}}),Ee=mt({mutationFn:async({eventId:Ge,testMode:Je})=>{const{data:{session:ut}}=await U.auth.getSession();if(!ut)throw new Error("Not authenticated");const lt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ut.access_token}`},body:JSON.stringify({event_id:Ge,test_mode:Je})}),qt=await lt.json();if(!lt.ok)throw new Error(qt.error||"Failed to send reminders");return qt},onSuccess:Ge=>{Ge.test?ne.success(Ge.message||"Test email sent!"):ne.success(Ge.message||`Reminder emails sent to ${Ge.sent} registrants!`)},onError:Ge=>{ne.error("Failed to send reminders: "+Ge.message)}}),{data:Ne}=rt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ge=[],Je=0;const ut=1e3;for(;;){const{data:lt,error:qt}=await U.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(Je,Je+ut-1);if(qt)throw qt;if(!lt||lt.length===0||(Ge=[...Ge,...lt],lt.length{const{error:qt}=await U.from("event_attendees").update({user_id:Je}).eq("id",Ge);if(qt)throw qt;if(lt&&ut){const{error:Zt}=await U.from("zoom_email_aliases").upsert({user_id:Je,zoom_email:ut.toLowerCase()},{onConflict:"zoom_email"});Zt&&console.error("Failed to save alias:",Zt)}const zt=y==null?void 0:y.id;if(zt){const{data:Zt}=await U.from("user_roles").select("id").eq("user_id",Je).eq("role","admin").single();if(!Zt){const{data:ms}=await U.from("agent_points").select("id").eq("user_id",Je).eq("event_id",zt).single();ms||(await U.rpc("award_attendance_points",{p_user_id:Je,p_event_id:zt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await U.rpc("check_and_award_badges",{p_user_id:Je}))}}return{userId:Je,zoomEmail:ut,shouldSaveAlias:lt}},onSuccess:Ge=>{t.invalidateQueries({queryKey:["event-attendees-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let Je="Attendee linked and points awarded!";Ge.shouldSaveAlias&&Ge.zoomEmail&&(Je+=` Email "${Ge.zoomEmail}" will be auto-matched in the future.`),ne.success(Je),S(!1),E(null),M(null),q("")},onError:Ge=>{ne.error("Failed to link attendee: "+Ge.message)}}),Oe=Ge=>{E(Ge),M(null),D(!0),q(""),S(!0)},ke=()=>{!C||!P||Pe.mutate({attendeeId:C.id,userId:P,zoomEmail:C.zoom_email,shouldSaveAlias:I})},Ve=(Ne==null?void 0:Ne.filter(Ge=>{var ut,lt;if(!F)return!0;const Je=F.toLowerCase();return((ut=Ge.name)==null?void 0:ut.toLowerCase().includes(Je))||((lt=Ge.email)==null?void 0:lt.toLowerCase().includes(Je))}))||[],_e=async Ge=>{const Je=Ge.name.split(".").pop(),lt=`${`${crypto.randomUUID()}.${Je}`}`,{error:qt}=await U.storage.from("event-images").upload(lt,Ge);if(qt)throw qt;const{data:{publicUrl:zt}}=U.storage.from("event-images").getPublicUrl(lt);return zt},Ae=Ge=>{var ut;const Je=(ut=Ge.target.files)==null?void 0:ut[0];if(Je){if(Je.size>5*1024*1024){ne.error("Image must be less than 5MB");return}d(Je),h(URL.createObjectURL(Je))}},Se=()=>{d(null),h(null),o({...l,image_url:""}),f.current&&(f.current.value="")},We=mt({mutationFn:async Ge=>{p(!0);let Je=Ge.image_url;c&&(Je=await _e(c)||"");const ut=new Date(Ge.event_date),[lt,qt]=Ge.event_time.split(":");ut.setHours(parseInt(lt),parseInt(qt));const zt=[new Date(ut)];if(Ge.is_recurring&&Ge.recurrence_end_date){let It=new Date(ut);for(;Ge.recurrence_pattern==="weekly"?It=bF(It,1):Ge.recurrence_pattern==="biweekly"?It=bF(It,2):It=A0(It,1),!(It>Ge.recurrence_end_date);)zt.push(new Date(It))}const Zt=zt.map(It=>({title:Ge.title,description:Ge.description||null,image_url:Je||null,video_url:Ge.video_url||null,event_date:It.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:ms,error:Dt}=await U.from("events").insert(Zt).select();if(Dt)throw Dt;return ms&&ms.length>0&&Zon(Ge.title,ms[0].id),zt.length},onSuccess:Ge=>{t.invalidateQueries({queryKey:["admin-events"]}),ne.success(Ge>1?`${Ge} recurring events created successfully`:"Event created successfully"),r(!1),o(Sce),d(null),h(null),p(!1)},onError:Ge=>{ne.error("Failed to create event: "+Ge.message),p(!1)}}),qe=mt({mutationFn:async({id:Ge,data:Je})=>{p(!0);let ut=Je.image_url;c&&(ut=await _e(c)||"");const lt=new Date(Je.event_date),[qt,zt]=Je.event_time.split(":");lt.setHours(parseInt(qt),parseInt(zt));const{error:Zt}=await U.from("events").update({title:Je.title,description:Je.description||null,image_url:ut||null,video_url:Je.video_url||null,event_date:lt.toISOString(),zoom_link:Je.zoom_link,zoom_meeting_id:Je.zoom_meeting_id||null,capacity:Je.capacity?parseInt(Je.capacity):null,is_published:Je.is_published}).eq("id",Ge);if(Zt)throw Zt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ne.success("Event updated successfully"),r(!1),i(null),o(Sce),d(null),h(null),p(!1)},onError:Ge=>{ne.error("Failed to update event: "+Ge.message),p(!1)}}),Be=mt({mutationFn:async Ge=>{const{error:Je}=await U.from("events").delete().eq("id",Ge);if(Je)throw Je},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ne.success("Event deleted successfully")},onError:Ge=>{ne.error("Failed to delete event: "+Ge.message)}}),Ze=mt({mutationFn:async Ge=>{var It;const{data:Je}=await U.auth.getUser(),ut=new Date(Ge.event_date),lt=new Date(ut.getTime()+60*60*1e3),qt=Gon(Ge.title),zt=Math.random().toString(36).slice(2,7),Zt=`${qt}-${zt}`,{data:ms,error:Dt}=await U.from("live_events").insert({slug:Zt,title:Ge.title,description:Ge.description||null,hero_image_url:Ge.image_url||null,starts_at:Ge.event_date,ends_at:lt.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:(It=Je.user)==null?void 0:It.id,agenda:[],offer_bullets:[]}).select().single();if(Dt)throw Dt;return ms},onSuccess:Ge=>{t.invalidateQueries({queryKey:["live-events"]}),ne.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ge.id}`)},onError:Ge=>{ne.error("Failed to clone to LevelUp Live: "+Ge.message)}}),$e=Ge=>{var ut;const Je=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:Je,event_time:Ys(Je,"HH:mm"),zoom_link:Ge.zoom_link,zoom_meeting_id:Ge.zoom_meeting_id||"",capacity:((ut=Ge.capacity)==null?void 0:ut.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)},Xe=Ge=>{if(Ge.preventDefault(),!l.event_date){ne.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ne.error("Please select an end date for recurring events");return}a?qe.mutate({id:a.id,data:l}):We.mutate(l)},nt=()=>{r(!1),i(null),o(Sce),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(Xh,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(be,{className:"mb-6",children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{children:"All Events"}),e.jsxs(Is,{open:n,onOpenChange:Ge=>!Ge&&nt(),children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{onClick:()=>r(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:Xe,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{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(ee,{children:"Description"}),e.jsx(GN,{content:l.description,onChange:Ge=>o({...l,description:Ge}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Event Image"}),e.jsx("input",{type:"file",ref:f,accept:"image/*",onChange:Ae,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(z,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:Se,children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs(z,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ge;return(Ge=f.current)==null?void 0:Ge.click()},children:[e.jsx(Ra,{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(ee,{children:"Date *"}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),l.event_date?Ys(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{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(ee,{htmlFor:"time",children:"Time *"}),e.jsx(pe,{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(ee,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(pe,{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(ee,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(pe,{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(ee,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(pe,{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(ee,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(pe,{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(sE,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(mn,{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(ee,{children:"Frequency"}),e.jsxs(ls,{value:l.recurrence_pattern,onValueChange:Ge=>o({...l,recurrence_pattern:Ge}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"weekly",children:"Weekly"}),e.jsx(He,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(He,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Repeat Until"}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Ys(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{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,Je=new Date(l.event_date);for(;Je=l.recurrence_pattern==="weekly"?bF(Je,1):l.recurrence_pattern==="biweekly"?bF(Je,2):A0(Je,1),!(Je>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(ee,{htmlFor:"is_published",children:"Published"}),e.jsx(mn,{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(z,{type:"button",variant:"outline",onClick:nt,className:"flex-1",children:"Cancel"}),e.jsx(z,{type:"submit",className:"flex-1",disabled:We.isPending||qe.isPending||m,children:m?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Le,{children:oe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(Z==null?void 0:Z.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,Je=[...Z||[]],ut=Je.filter(ms=>new Date(ms.event_date)>=Ge).sort((ms,Dt)=>new Date(ms.event_date).getTime()-new Date(Dt.event_date).getTime()),lt=Je.filter(ms=>new Date(ms.event_date)new Date(Dt.event_date).getTime()-new Date(ms.event_date).getTime()),qt=ut[0],zt=ms=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:ms.title}),e.jsx(yt,{className:"whitespace-nowrap",children:Ys(new Date(ms.event_date),"PPP p")}),e.jsx(yt,{children:e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>ve(ms),children:[e.jsx(On,{className:"h-4 w-4"}),(re==null?void 0:re[ms.id])||0,ms.capacity&&` / ${ms.capacity}`]})}),e.jsx(yt,{children:e.jsx("span",{className:Ct("px-2 py-1 rounded-full text-xs font-medium",ms.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:ms.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{K(ms),V(!0)},title:"Send invite email to members",children:[e.jsx(Fr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ze.mutate(ms),disabled:Ze.isPending,title:"Clone to LevelUp Live",children:[e.jsx(Nv,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>window.open(ms.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(mr,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>$e(ms),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi("Are you sure you want to delete this event?")&&Be.mutate(ms.id)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},ms.id),Zt=(ms,Dt)=>ms.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Dt}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Date & Time"}),e.jsx(Tt,{children:"Registrations"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:ms.map(zt)})]});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(Zr,{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:Ys(new Date(qt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(re==null?void 0:re[qt.id])||0," registered",qt.capacity?` of ${qt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(z,{size:"sm",className:"gap-1.5",onClick:()=>{K(qt),V(!0)},children:[e.jsx(Fr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(z,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>ve(qt),children:[e.jsx(On,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs(z,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ze.mutate(qt),disabled:Ze.isPending,children:[e.jsx(Nv,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(z,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(qt.zoom_link,"_blank"),children:[e.jsx(mr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(Qr,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"upcoming",className:"gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:ut.length})]}),e.jsxs(Wt,{value:"past",className:"gap-2",children:[e.jsx(Mr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:lt.length})]})]}),e.jsx(Kt,{value:"upcoming",className:"mt-4",children:Zt(ut,"No upcoming events scheduled.")}),e.jsx(Kt,{value:"past",className:"mt-4",children:Zt(lt,"No past events.")})]})]})})()})]}),e.jsx(tln,{open:G,onOpenChange:V,event:H}),e.jsx(Is,{open:g,onOpenChange:v,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),y==null?void 0:y.title]}),e.jsx(_r,{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(z,{variant:"ghost",size:"sm",onClick:()=>Ee.mutate({eventId:y.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(on,{className:Ct("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>Ee.mutate({eventId:y.id}),disabled:Ee.isPending||!(ae!=null&&ae.length),children:[e.jsx(on,{className:Ct("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(y==null?void 0:y.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>me.mutate(y.id),disabled:me.isPending,children:[e.jsx(Gi,{className:Ct("h-4 w-4 mr-2",me.isPending&&"animate-spin")}),me.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>ge.mutate(),disabled:ge.isPending,children:[e.jsx(Gi,{className:Ct("h-4 w-4 mr-2",ge.isPending&&"animate-spin")}),ge.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(z,{variant:"default",size:"sm",onClick:()=>he.mutate(y.id),disabled:he.isPending,children:[e.jsx(jl,{className:Ct("h-4 w-4 mr-2",he.isPending&&"animate-spin")}),he.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(Qr,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Wt,{value:"registrations",className:"gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),"Registrations (",(ae==null?void 0:ae.length)||0,")"]}),e.jsxs(Wt,{value:"attendees",className:"gap-2",children:[e.jsx(Mr,{className:"h-4 w-4"}),"Attendees (",(te==null?void 0:te.length)||0,")"]})]}),e.jsx(Kt,{value:"registrations",className:"mt-4",children:J?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ae==null?void 0:ae.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(y==null?void 0:y.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Registered"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Qa,{children:ae==null?void 0:ae.map(Ge=>{var qt,zt;const Je=((qt=Ge.profiles)==null?void 0:qt.name)||Ge.zoom_name||"Unknown",ut=((zt=Ge.profiles)==null?void 0:zt.email)||Ge.zoom_email||null,lt=!Ge.user_id;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Je,lt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(yt,{children:ut?e.jsxs("a",{href:`mailto:${ut}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(on,{className:"h-3 w-3"}),ut]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(yt,{className:"text-muted-foreground text-sm",children:Ys(new Date(Ge.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(yt,{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(Kt,{value:"attendees",className:"mt-4",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(te==null?void 0:te.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(y==null?void 0:y.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:[(te==null?void 0:te.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(Ho,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"}),e.jsxs("h4",{className:"font-medium text-amber-800 dark:text-amber-200",children:["Unmatched Attendees (",te==null?void 0:te.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:te==null?void 0:te.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(z,{variant:"outline",size:"sm",onClick:()=>Oe(Ge),className:"gap-1",children:[e.jsx(Oc,{className:"h-3 w-3"}),"Link to Profile"]})]},Ge.id))})]}),e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Points"})]})}),e.jsx(Qa,{children:te==null?void 0:te.filter(Ge=>Ge.user_id).map(Ge=>{var lt,qt;const Je=((lt=Ge.profiles)==null?void 0:lt.name)||Ge.zoom_name||"Unknown",ut=((qt=Ge.profiles)==null?void 0:qt.email)||Ge.zoom_email||null;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Je,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(yt,{children:ut?e.jsxs("a",{href:`mailto:${ut}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(on,{className:"h-3 w-3"}),ut]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(yt,{children:Ge.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Zr,{className:"h-3 w-3"}),Ge.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(yt,{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(jl,{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(Is,{open:w,onOpenChange:S,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(_r,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),C&&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:C.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:F,onChange:Ge=>q(Ge.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ve.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No profiles found"}):e.jsx("div",{className:"divide-y",children:Ve.slice(0,20).map(Ge=>e.jsxs("button",{type:"button",onClick:()=>M(Ge.id),className:Ct("w-full p-3 text-left hover:bg-muted/50 transition-colors",P===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))})}),C.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(za,{id:"save-alias",checked:I,onCheckedChange:Ge=>D(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(z,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(z,{onClick:ke,disabled:!P||Pe.isPending,children:Pe.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const nln={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 rln(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState("issues");async function l(){r(!0);let o=U.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 _.useEffect(()=>{l()},[a]),e.jsx($s,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(uq,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx(z,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(Gi,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Le,{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:nln[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 aln({selectedKitIds:s,onChange:t}){const[n,r]=_.useState(""),[a,i]=_.useState(!1),{data:l=[]}=rt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await U.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Sh,{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(er,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(hd,{open:a,onOpenChange:i,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Sh,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(nd,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Rr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{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(Sh,{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 iln=()=>{const{user:s}=hs(),{toast:t}=_i(),n=$t(),[r,a]=Gl(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,m]=_.useState(null),[p,f]=_.useState(0),[g,v]=_.useState(!1),[y,b]=_.useState(null),[w,S]=_.useState(""),[C,E]=_.useState([]),[P,M]=_.useState(""),[I,D]=_.useState(""),[F,q]=_.useState(!1),[G,V]=_.useState(!1),{data:H=[]}=rt({queryKey:["template-categories"],queryFn:async()=>{const{data:Se,error:We}=await U.from("template_categories").select("*").order("name");if(We)throw We;return Se}}),{data:K=[]}=rt({queryKey:["template-types"],queryFn:async()=>{const{data:Se,error:We}=await U.from("template_types").select("*").order("name");if(We)throw We;return Se}}),{data:Z=[],isLoading:oe}=rt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Se,error:We}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(We)throw We;const{data:qe,error:Be}=await U.from("template_links").select("*").order("sort_order");if(Be)throw Be;const{data:Ze,error:$e}=await U.from("template_guides").select("*").order("sort_order");if($e)throw $e;return Se.map(nt=>({...nt,links:(qe==null?void 0:qe.filter(Ge=>Ge.template_id===nt.id))||[],guides:(Ze==null?void 0:Ze.filter(Ge=>Ge.template_id===nt.id))||[]}))}});_.useEffect(()=>{const Se=r.get("edit");if(Se&&Z.length>0){const We=Z.find(qe=>qe.id===Se);We&&(me(We),a({},{replace:!0}))}},[Z,r]);const re=mt({mutationFn:async Se=>{const{data:We,error:qe}=await U.from("template_categories").insert({name:Se}).select().single();if(qe)throw qe;return We},onSuccess:Se=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Se.id}),M(""),q(!1),t({title:"Category added"})},onError:Se=>{t({title:"Error adding category",description:Se.message,variant:"destructive"})}}),ae=mt({mutationFn:async Se=>{const{data:We,error:qe}=await U.from("template_types").insert({name:Se}).select().single();if(qe)throw qe;return We},onSuccess:Se=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Se.id}),D(""),V(!1),t({title:"Type added"})},onError:Se=>{t({title:"Error adding type",description:Se.message,variant:"destructive"})}}),J=mt({mutationFn:async Se=>{var $e;let We=Se.existingImageUrl;if(Se.image){const Xe=Se.image.name.split(".").pop(),nt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Xe}`,{error:Ge}=await U.storage.from("template-previews").upload(nt,Se.image);if(Ge)throw Ge;const{data:Je}=U.storage.from("template-previews").getPublicUrl(nt);We=Je.publicUrl}const qe={name:Se.template.name,description:Se.template.description||null,category_id:Se.template.category_id||null,type_id:Se.template.type_id||null,preview_image_url:We,video_url:Se.videoUrl||null,publish_date:Se.template.publish_date?new Date(Se.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Be=Se.templateId;if(Be){const{error:Xe}=await U.from("canva_templates").update(qe).eq("id",Be);if(Xe)throw Xe;const{error:nt}=await U.from("template_links").delete().eq("template_id",Be);if(nt)throw nt;const Ge=(($e=Se.existingGuides)==null?void 0:$e.map(lt=>lt.id).filter(Boolean))||[],Je=Se.template.guides.map(lt=>lt.id).filter(Boolean),ut=Ge.filter(lt=>!Je.includes(lt));ut.length>0&&await U.from("template_guides").delete().in("id",ut)}else{const{data:Xe,error:nt}=await U.from("canva_templates").insert(qe).select().single();if(nt)throw nt;Be=Xe.id,Kon(Se.template.name,Xe.id)}const Ze=Se.template.links.filter(Xe=>Xe.title.trim()&&Xe.canva_share_link.trim());if(Ze.length>0){const Xe=Ze.map((Ge,Je)=>({template_id:Be,title:Ge.title.trim(),canva_share_link:Ge.canva_share_link.trim(),sort_order:Je})),{error:nt}=await U.from("template_links").insert(Xe);if(nt)throw nt}for(let Xe=0;Xe0)){const{error:Xe}=await U.from("resource_kit_templates").insert(Se.linkedKitIds.map(nt=>({template_id:Be,kit_id:nt})));if(Xe)throw Xe}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),ve(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Se=>{t({title:"Error saving template",description:Se.message,variant:"destructive"})}}),te=mt({mutationFn:async Se=>{const{error:We}=await U.from("canva_templates").delete().eq("id",Se);if(We)throw We},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Se=>{t({title:"Error deleting template",description:Se.message,variant:"destructive"})}}),ce=mt({mutationFn:async({id:Se,is_featured:We})=>{const{error:qe}=await U.from("canva_templates").update({is_featured:We}).eq("id",Se);if(qe)throw qe},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Se=>{t({title:"Error updating featured",description:Se.message,variant:"destructive"})}}),ve=()=>{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:""}),b(null),S(""),c(null),q(!1),V(!1),M(""),D(""),m(null),f(0),v(!1),E([])},me=async Se=>{var qe;c(Se),u({name:Se.name,description:Se.description||"",category_id:Se.category_id||"",type_id:Se.type_id||"",publish_date:Se.publish_date?new Date(Se.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Se.links&&Se.links.length>0?Se.links.map(Be=>({id:Be.id,title:Be.title,canva_share_link:Be.canva_share_link,sort_order:Be.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((qe=Se.guides)==null?void 0:qe.map(Be=>({id:Be.id,name:Be.name,file_url:Be.file_url,file_type:Be.file_type,file_size:Be.file_size,sort_order:Be.sort_order})))||[],video_url:Se.video_url||""}),S(Se.preview_image_url||""),m(null);const{data:We}=await U.from("resource_kit_templates").select("kit_id").eq("template_id",Se.id);E((We||[]).map(Be=>Be.kit_id)),l(!0)},he=Se=>{var qe;const We=(qe=Se.target.files)==null?void 0:qe[0];We&&(b(We),S(URL.createObjectURL(We)))},ge=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ee=Se=>{if(d.links.length<=1)return;const We=d.links.filter((qe,Be)=>Be!==Se);u({...d,links:We})},Ne=(Se,We,qe)=>{const Be=[...d.links];Be[Se]={...Be[Se],[We]:qe},u({...d,links:Be})},Pe=Se=>{const We=Se.target.files;if(!We)return;const qe=Array.from(We).map((Be,Ze)=>({name:Be.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Be.type,file_size:Be.size,sort_order:d.guides.length+Ze,file:Be}));u({...d,guides:[...d.guides,...qe]}),Se.target.value=""},Oe=Se=>{const We=d.guides.filter((qe,Be)=>Be!==Se);u({...d,guides:We})},ke=(Se,We)=>{const qe=[...d.guides];qe[Se]={...qe[Se],name:We},u({...d,guides:qe})},Ve=async()=>{if(!h)return null;v(!0),f(0);try{const{data:Se,error:We}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(We)throw new Error(We.message);const{videoId:qe,libraryId:Be}=Se,{data:Ze,error:$e}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:qe}});if($e)throw new Error($e.message);const Xe=new XMLHttpRequest;return await new Promise((Ge,Je)=>{Xe.upload.addEventListener("progress",ut=>{if(ut.lengthComputable){const lt=Math.round(ut.loaded/ut.total*100);f(lt)}}),Xe.addEventListener("load",()=>{Xe.status>=200&&Xe.status<300?Ge():Je(new Error(`Upload failed with status ${Xe.status}`))}),Xe.addEventListener("error",()=>Je(new Error("Upload failed"))),Xe.open("PUT",Ze.uploadUrl),Xe.setRequestHeader("AccessKey",Ze.apiKey),Xe.send(h)}),`https://player.mediadelivery.net/embed/${Be}/${qe}`}catch(Se){return console.error("Bunny upload error:",Se),t({title:"Video upload failed",description:Se instanceof Error?Se.message:"Unknown error",variant:"destructive"}),null}finally{v(!1)}},_e=Se=>{var qe;const We=(qe=Se.target.files)==null?void 0:qe[0];We&&m(We),Se.target.value=""},Ae=async Se=>{if(Se.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Be=>Be.title.trim()&&Be.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let qe=d.video_url;if(h){const Be=await Ve();if(!Be)return;qe=Be}J.mutate({template:d,image:y,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:qe,linkedKitIds:C})};return e.jsx($s,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:Z.length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:H.length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:K.length})})]})]}),e.jsxs(Is,{open:i,onOpenChange:Se=>{l(Se),Se||ve()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:d.name,onChange:Se=>u({...d,name:Se.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:d.description,onChange:Se=>u({...d,description:Se}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Canva Links *"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:ge,className:"gap-1",children:[e.jsx(sn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Se,We)=>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(pe,{value:Se.title,onChange:qe=>Ne(We,"title",qe.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(pe,{value:Se.canva_share_link,onChange:qe=>Ne(We,"canva_share_link",qe.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Ee(We),children:e.jsx(er,{className:"h-4 w-4"})})]},We))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Category"}),F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:P,onChange:Se=>M(Se.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(z,{type:"button",size:"sm",onClick:()=>P.trim()&&re.mutate(P.trim()),disabled:re.isPending,children:"Add"}),e.jsx(z,{type:"button",size:"sm",variant:"ghost",onClick:()=>{q(!1),M("")},children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:d.category_id,onValueChange:Se=>u({...d,category_id:Se}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(cs,{placeholder:"Select category"})}),e.jsx(as,{children:H.map(Se=>e.jsx(He,{value:Se.id,children:Se.name},Se.id))})]}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:()=>q(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Template Type"}),G?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:I,onChange:Se=>D(Se.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(z,{type:"button",size:"sm",onClick:()=>I.trim()&&ae.mutate(I.trim()),disabled:ae.isPending,children:"Add"}),e.jsx(z,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),D("")},children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:d.type_id,onValueChange:Se=>u({...d,type_id:Se}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(cs,{placeholder:"Select type"})}),e.jsx(as,{children:K.map(Se=>e.jsx(He,{value:Se.id,children:Se.name},Se.id))})]}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Se=>u({...d,publish_date:Se.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[w?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:w,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(z,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{b(null),S("")},children:e.jsx(er,{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(nc,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:he,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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(Xr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(z,{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})})]}):g?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(bt,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",p,"%"]})]}),e.jsx(Di,{value:p,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(Xr,{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(z,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>m(null),children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(pe,{type:"file",accept:"video/*",onChange:_e,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(Xr,{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(ee,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(pe,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Pe,className:"hidden"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Ra,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Se,We)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx($r,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(pe,{value:Se.name,onChange:qe=>ke(We,qe.target.value),placeholder:"Guide name",className:"flex-1"}),Se.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Se.file_size/1024).toFixed(0)," KB"]}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Oe(We),children:e.jsx(er,{className:"h-4 w-4"})})]},Se.id||We))}):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(aln,{selectedKitIds:C,onChange:E}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>{l(!1),ve()},children:"Cancel"}),e.jsx(z,{type:"submit",disabled:J.isPending,children:J.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:oe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):Z.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:Z.map(Se=>{var We,qe,Be,Ze,$e;return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Se.preview_image_url?e.jsx("img",{src:Se.preview_image_url,alt:Se.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(nc,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(yt,{className:"font-medium",children:Se.name}),e.jsx(yt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(ze,{variant:"secondary",children:[((We=Se.links)==null?void 0:We.length)||0," link",(((qe=Se.links)==null?void 0:qe.length)||0)!==1?"s":""]}),(((Be=Se.guides)==null?void 0:Be.length)||0)>0&&e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx($r,{className:"h-3 w-3"}),(Ze=Se.guides)==null?void 0:Ze.length," guide",((($e=Se.guides)==null?void 0:$e.length)||0)!==1?"s":""]})]})}),e.jsx(yt,{children:Se.category?e.jsx(ze,{variant:"secondary",children:Se.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(yt,{children:Se.type?e.jsx(ze,{variant:"outline",children:Se.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(yt,{className:"text-muted-foreground",children:new Date(Se.publish_date).toLocaleDateString()}),e.jsx(yt,{className:"text-center",children:e.jsx(z,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Se.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>ce.mutate({id:Se.id,is_featured:!Se.is_featured}),children:e.jsx(Ia,{className:`h-4 w-4 ${Se.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>me(Se),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await Qi("Delete this template?")&&te.mutate(Se.id)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},Se.id)})})]})})})]})})};function xHt({selectedTemplateIds:s,onChange:t}){const[n,r]=_.useState(""),[a,i]=_.useState(!1),{data:l=[]}=rt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await U.from("canva_templates").select("id, name, preview_image_url").order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(yj,{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(er,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(hd,{open:a,onOpenChange:i,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(yj,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(nd,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Rr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{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(yj,{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 oln=[{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"}],p1t=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),f1t=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},lln=()=>{const{user:s}=hs(),[t,n]=Gl(),{toast:r}=_i(),a=$t(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=_.useState(null),[p,f]=_.useState(""),[g,v]=_.useState([]),[y,b]=_.useState([]),[w,S]=_.useState([]),[C,E]=_.useState([]),[P,M]=_.useState(""),[I,D]=_.useState(!1),[F,q]=_.useState(null),[G,V]=_.useState(0),[H,K]=_.useState(!1),[Z,oe]=_.useState(null),{data:re=[]}=rt({queryKey:["academy-categories"],queryFn:async()=>{const{data:Se,error:We}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(We)throw We;return Se}}),{data:ae=[],isLoading:J}=rt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Se,error:We}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(We)throw We;const{data:qe,error:Be}=await U.from("academy_resources").select("*").order("sort_order");if(Be)throw Be;return Se.map($e=>({...$e,resources:(qe==null?void 0:qe.filter(Xe=>Xe.video_id===$e.id))||[]}))}});_.useEffect(()=>{const Se=t.get("edit");if(Se&&ae.length>0){const We=ae.find(qe=>qe.id===Se);We&&(Ne(We),n({},{replace:!0}))}},[ae,t]);const te=mt({mutationFn:async Se=>{const{data:We,error:qe}=await U.from("academy_categories").insert({name:Se,sort_order:re.length}).select().single();if(qe)throw qe;return We},onSuccess:Se=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Se.id}),M(""),D(!1),r({title:"Category added"})},onError:Se=>{r({title:"Error adding category",description:Se.message,variant:"destructive"})}}),ce=mt({mutationFn:async Se=>{let We=Se.existingThumbnailUrl;if(Se.thumbnail){const Ze=Se.thumbnail.name.split(".").pop(),$e=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Ze}`,{error:Xe}=await U.storage.from("academy-resources").upload($e,Se.thumbnail);if(Xe)throw Xe;const{data:nt}=U.storage.from("academy-resources").getPublicUrl($e);We=nt.publicUrl}const qe={title:Se.video.title,description:Se.video.description||null,video_url:Se.video.video_url,video_type:Se.video.video_type,duration:Se.video.duration||null,thumbnail_url:We,category_id:Se.video.category_id||null,publish_date:Se.video.publish_date?new Date(Se.video.publish_date).toISOString():new Date().toISOString(),is_published:Se.video.is_published,created_by:s==null?void 0:s.id};let Be=Se.videoId;if(Be){const{error:Ze}=await U.from("academy_videos").update(qe).eq("id",Be);if(Ze)throw Ze}else{const{data:Ze,error:$e}=await U.from("academy_videos").insert(qe).select().single();if($e)throw $e;Be=Ze.id,Yon(Se.video.title,Ze.id)}if(Se.resourcesToDelete.length>0){const{error:Ze}=await U.from("academy_resources").delete().in("id",Se.resourcesToDelete);if(Ze)throw Ze}for(let Ze=0;Ze0){const{error:Ze}=await U.from("academy_video_templates").insert(C.map($e=>({video_id:Be,template_id:$e})));if(Ze)throw Ze}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ee(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Se=>{r({title:"Error saving video",description:Se.message,variant:"destructive"})}}),ve=mt({mutationFn:async Se=>{const{error:We}=await U.from("academy_videos").delete().eq("id",Se);if(We)throw We},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Se=>{r({title:"Error deleting video",description:Se.message,variant:"destructive"})}}),me=mt({mutationFn:async({id:Se,is_published:We})=>{const{error:qe}=await U.from("academy_videos").update({is_published:We}).eq("id",Se);if(qe)throw qe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Se=>{r({title:"Error updating video",description:Se.message,variant:"destructive"})}}),he=async Se=>{try{let We=Se.public_slug||null,qe=!!Se.is_public;if(!We||!qe){const Ze=(Se.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!We){let Xe=Ze;const{data:nt}=await U.from("academy_videos").select("id").eq("public_slug",Xe).maybeSingle();nt&&nt.id!==Se.id&&(Xe=`${Ze}-${Se.id.slice(0,6)}`),We=Xe}const{error:$e}=await U.from("academy_videos").update({public_slug:We,is_public:!0}).eq("id",Se.id);if($e)throw $e;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Be=`${window.location.origin}/watch/${We}`;await navigator.clipboard.writeText(Be),r({title:"Public link copied",description:Be})}catch(We){r({title:"Could not copy link",description:We.message,variant:"destructive"})}},ge=async Se=>{if(!await Qi("Disable the public teaser link for this video?"))return;const{error:We}=await U.from("academy_videos").update({is_public:!1}).eq("id",Se.id);if(We){r({title:"Error",description:We.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Ee=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),f(""),v([]),b([]),S([]),c(null),E([]),M(""),q(null),V(0),K(!1),oe(null)},Ne=async Se=>{c(Se),u({title:Se.title,description:Se.description||"",video_url:Se.video_url,video_type:Se.video_type,duration:Se.duration||"",category_id:Se.category_id||"",publish_date:Se.publish_date?new Date(Se.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Se.is_published}),f(Se.thumbnail_url||""),b(Se.resources||[]),v([]),S([]);const{data:We}=await U.from("academy_video_templates").select("template_id").eq("video_id",Se.id);E((We||[]).map(qe=>qe.template_id)),l(!0)},Pe=Se=>{var qe;const We=(qe=Se.target.files)==null?void 0:qe[0];We&&(m(We),f(URL.createObjectURL(We)))},Oe=Se=>{const We=Se.target.files;if(We){const qe=Array.from(We).map(Be=>({file:Be,title:Be.name.replace(/\.[^/.]+$/,"")}));v([...g,...qe])}Se.target.value=""},ke=Se=>{v(g.filter((We,qe)=>qe!==Se))},Ve=Se=>{S([...w,Se]),b(y.filter(We=>We.id!==Se))},_e=async()=>{if(!F)return null;K(!0),V(0);try{const{data:Se,error:We}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||F.name}});if(We)throw new Error(We.message);const{videoId:qe,libraryId:Be}=Se;oe(qe);const{data:Ze,error:$e}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:qe}});if($e)throw new Error($e.message);const Xe=new XMLHttpRequest;return await new Promise((Ge,Je)=>{Xe.upload.addEventListener("progress",ut=>{if(ut.lengthComputable){const lt=Math.round(ut.loaded/ut.total*100);V(lt)}}),Xe.addEventListener("load",()=>{Xe.status>=200&&Xe.status<300?Ge():Je(new Error(`Upload failed with status ${Xe.status}`))}),Xe.addEventListener("error",()=>Je(new Error("Upload failed"))),Xe.open("PUT",Ze.uploadUrl),Xe.setRequestHeader("AccessKey",Ze.apiKey),Xe.send(F)}),`https://player.mediadelivery.net/embed/${Be}/${qe}`}catch(Se){return console.error("Bunny upload error:",Se),r({title:"Video upload failed",description:Se instanceof Error?Se.message:"Unknown error",variant:"destructive"}),null}finally{K(!1)}},Ae=async Se=>{if(Se.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let We=d.video_url;if(d.video_type==="bunny_stream"&&F&&!o){const qe=await _e();if(!qe)return;We=qe}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"&&!F&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}ce.mutate({video:{...d,video_url:We},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:g,resourcesToDelete:w})};return e.jsx($s,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:ae.length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:ae.filter(Se=>Se.is_published).length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:ae.filter(Se=>Se.is_public).length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:ae.reduce((Se,We)=>Se+(We.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(Is,{open:i,onOpenChange:Se=>{l(Se),Se||Ee()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:d.title,onChange:Se=>u({...d,title:Se.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:d.description,onChange:Se=>u({...d,description:Se}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video Type"}),e.jsxs(ls,{value:d.video_type,onValueChange:Se=>{u({...d,video_type:Se,video_url:""}),q(null)},disabled:H,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:oln.map(Se=>e.jsx(He,{value:Se.value,children:Se.label},Se.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ee,{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(pe,{type:"file",accept:"video/*",onChange:Se=>{var qe;const We=(qe=Se.target.files)==null?void 0:qe[0];We&&q(We)},disabled:H}),F&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Xr,{className:"h-4 w-4"}),F.name," (",(F.size/(1024*1024)).toFixed(1)," MB)"]}),H&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(Di,{value:G,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[G,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(pe,{id:"video_url",value:d.video_url,onChange:Se=>u({...d,video_url:Se.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"duration",children:"Duration"}),e.jsx(pe,{id:"duration",value:d.duration,onChange:Se=>u({...d,duration:Se.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date (go-live)"}),e.jsx(pe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Se=>u({...d,publish_date:Se.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see the video on or after this date."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Category"}),I?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:P,onChange:Se=>M(Se.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(z,{type:"button",size:"sm",onClick:()=>P.trim()&&te.mutate(P.trim()),disabled:te.isPending,children:"Add"}),e.jsx(z,{type:"button",size:"sm",variant:"ghost",onClick:()=>{D(!1),M("")},children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:d.category_id,onValueChange:Se=>u({...d,category_id:Se}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(cs,{placeholder:"Select category"})}),e.jsx(as,{children:re.map(Se=>e.jsx(He,{value:Se.id,children:Se.name},Se.id))})]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>D(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[p&&e.jsx("img",{src:p,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:Pe,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(ee,{children:"Resource Files"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(Ra,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Oe,className:"hidden"})]})})]}),(y.length>0||g.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[y.map(Se=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Se.title}),e.jsx(ze,{variant:"outline",className:"text-xs",children:Se.file_type}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ve(Se.id),className:"text-destructive hover:text-destructive",children:e.jsx(er,{className:"h-4 w-4"})})]},Se.id)),g.map((Se,We)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:Se.title,onChange:qe=>{const Be=[...g];Be[We].title=qe.target.value,v(Be)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(ze,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>ke(We),className:"text-destructive hover:text-destructive",children:e.jsx(er,{className:"h-4 w-4"})})]},We))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(xHt,{selectedTemplateIds:C,onChange:E}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"is_published",checked:d.is_published,onCheckedChange:Se=>u({...d,is_published:Se})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.is_published?d.publish_date>p1t?`Scheduled — goes live automatically on ${f1t(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(hr,{children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:H,children:"Cancel"}),e.jsx(z,{type:"submit",disabled:ce.isPending||H,children:H?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ce.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:J?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"})}):ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Xr,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Public Views"}),e.jsx(Tt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(Qa,{children:ae.map(Se=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Se.thumbnail_url?e.jsx("img",{src:Se.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):e.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:e.jsx(Xr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Se.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Se.video_type.replace("_"," ")})]})]})}),e.jsx(yt,{children:Se.category?e.jsx(ze,{variant:"outline",children:Se.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(yt,{children:Se.duration||"-"}),e.jsx(yt,{children:Se.resources&&Se.resources.length>0?e.jsxs(ze,{variant:"secondary",children:[Se.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(yt,{children:f1t(Se.publish_date)}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:Se.is_published,onCheckedChange:We=>me.mutate({id:Se.id,is_published:We})}),Se.is_published?Se.publish_date.slice(0,10)>p1t?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," Scheduled"]}):e.jsx(ze,{variant:"secondary",children:"Live"}):e.jsx(ze,{variant:"outline",className:"text-muted-foreground",children:"Draft"})]})}),e.jsx(yt,{children:Se.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Se.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"ghost",size:"sm",title:Se.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>he(Se),children:Se.is_public?e.jsx(Sa,{className:"h-4 w-4 text-primary"}):e.jsx(sd,{className:"h-4 w-4"})}),Se.is_public&&e.jsx(z,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>ge(Se),children:e.jsx(Wo,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>Ne(Se),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>ve.mutate(Se.id),className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]})})},lZ=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),x1t={public_enabled:!1,public_slug:"",public_headline:"",public_subheadline:"",public_cta_text:"",public_benefits:"",public_hero_image_url:""};function cln(){var ve,me,he;const s=$t(),[t,n]=Gl(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...x1t}),[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState([]),[g,v]=_.useState([]),[y,b]=_.useState([]),[w,S]=_.useState(null),{data:C,isLoading:E}=rt({queryKey:["resource-kits"],queryFn:async()=>{const{data:ge,error:Ee}=await U.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return ge}}),{data:P}=rt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:ge,error:Ee}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return ge}}),{data:M}=rt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:ge,error:Ee}=await U.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return ge}}),{data:I}=rt({queryKey:["resource-kit-leads"],queryFn:async()=>{const{data:ge,error:Ee}=await U.from("resource_kit_leads").select("id, kit_id, full_name, email, brokerage, created_at").order("created_at",{ascending:!1}).limit(500);if(Ee)throw Ee;return ge}});_.useEffect(()=>{const ge=t.get("edit");if(ge&&C&&C.length>0&&P&&M){const Ee=C.find(Ne=>Ne.id===ge);Ee&&(F(Ee),n({},{replace:!0}))}},[C,P,M,t]);const D=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...x1t}),u(null),m(""),f([]),v([]),b([]),l(null)},F=async ge=>{l(ge),c({name:ge.name,description:ge.description||"",publish_date:ge.publish_date.split("T")[0],is_published:ge.is_published,public_enabled:!!ge.public_enabled,public_slug:ge.public_slug||"",public_headline:ge.public_headline||"",public_subheadline:ge.public_subheadline||"",public_cta_text:ge.public_cta_text||"",public_benefits:Array.isArray(ge.public_benefits)?ge.public_benefits.join(` `):"",public_hero_image_url:ge.public_hero_image_url||""}),m(ge.featured_image_url||"");const Ee=(P==null?void 0:P.filter(Oe=>Oe.kit_id===ge.id))||[];f(Ee.map(Oe=>({id:Oe.id,name:Oe.name,file_url:Oe.file_url,file_type:Oe.file_type,file_size:Oe.file_size,sort_order:Oe.sort_order})));const Ne=(M==null?void 0:M.filter(Oe=>Oe.kit_id===ge.id))||[];v(Ne.map(Oe=>({id:Oe.id,title:Oe.title,canva_share_link:Oe.canva_share_link,sort_order:Oe.sort_order})));const{data:Pe}=await U.from("resource_kit_templates").select("template_id").eq("kit_id",ge.id);b((Pe||[]).map(Oe=>Oe.template_id)),a(!0)},q=ge=>{var Ne;const Ee=(Ne=ge.target.files)==null?void 0:Ne[0];Ee&&(u(Ee),m(URL.createObjectURL(Ee)))},G=()=>{f([...p,{name:"",file_url:"",sort_order:p.length}])},V=ge=>{f(p.filter((Ee,Ne)=>Ne!==ge))},H=(ge,Ee,Ne)=>{const Pe=[...p];Pe[ge]={...Pe[ge],[Ee]:Ne},f(Pe)},K=()=>{v([...g,{title:"",canva_share_link:"",sort_order:g.length}])},Z=ge=>{v(g.filter((Ee,Ne)=>Ne!==ge))},oe=(ge,Ee,Ne)=>{const Pe=[...g];Pe[ge]={...Pe[ge],[Ee]:Ne},v(Pe)},re=(ge,Ee)=>{var Pe;const Ne=(Pe=Ee.target.files)==null?void 0:Pe[0];if(Ne){const Oe=[...p],ke=Ne.name.replace(/\.[^/.]+$/,"");Oe[ge]={...Oe[ge],file:Ne,file_type:Ne.type,file_size:Ne.size,name:Oe[ge].name||ke},f(Oe)}},ae=mt({mutationFn:async()=>{let ge=(i==null?void 0:i.featured_image_url)||null;if(d){const Ve=d.name.split(".").pop(),_e=`${Date.now()}.${Ve}`,{error:Ae}=await U.storage.from("resource-kits").upload(`featured/${_e}`,d);if(Ae)throw Ae;const{data:Se}=U.storage.from("resource-kits").getPublicUrl(`featured/${_e}`);ge=Se.publicUrl}const Ee=o.public_enabled?o.public_slug?lZ(o.public_slug):lZ(o.name):o.public_slug?lZ(o.public_slug):null,Ne={name:o.name,description:o.description||null,featured_image_url:ge,publish_date:o.publish_date,is_published:o.is_published,public_enabled:o.public_enabled,public_slug:Ee||null,public_headline:o.public_headline||null,public_subheadline:o.public_subheadline||null,public_cta_text:o.public_cta_text||null,public_benefits:o.public_benefits.split(` `).map(Ve=>Ve.trim()).filter(Boolean),public_hero_image_url:o.public_hero_image_url||null};let Pe;const Oe=!i,ke=(i==null?void 0:i.is_published)||!1;if(i){const{error:Ve}=await U.from("resource_kits").update(Ne).eq("id",i.id);if(Ve)throw Ve;Pe=i.id;const _e=(P==null?void 0:P.filter(Ze=>Ze.kit_id===i.id).map(Ze=>Ze.id))||[],Ae=p.filter(Ze=>Ze.id).map(Ze=>Ze.id),Se=_e.filter(Ze=>!Ae.includes(Ze));Se.length>0&&await U.from("resource_kit_files").delete().in("id",Se);const We=(M==null?void 0:M.filter(Ze=>Ze.kit_id===i.id).map(Ze=>Ze.id))||[],qe=g.filter(Ze=>Ze.id).map(Ze=>Ze.id),Be=We.filter(Ze=>!qe.includes(Ze));Be.length>0&&await U.from("resource_kit_links").delete().in("id",Be)}else{const{data:Ve,error:_e}=await U.from("resource_kits").insert(Ne).select().single();if(_e)throw _e;Pe=Ve.id}for(let Ve=0;Ve0){const{error:Ve}=await U.from("resource_kit_templates").insert(y.map(_e=>({kit_id:Pe,template_id:_e})));if(Ve)throw Ve}return{kitId:Pe,kitName:o.name,isNewKit:Oe,wasPublished:ke,isPublished:o.is_published}},onSuccess:ge=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ne.success(i?"Resource kit updated":"Resource kit created"),ge.isPublished&&(ge.isNewKit||!ge.wasPublished)&&Xon(ge.kitName,ge.kitId),a(!1),D()},onError:ge=>{ne.error("Failed to save resource kit: "+ge.message)}}),J=mt({mutationFn:async ge=>{const{error:Ee}=await U.from("resource_kits").delete().eq("id",ge);if(Ee)throw Ee},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ne.success("Resource kit deleted")},onError:ge=>{ne.error("Failed to delete: "+ge.message)}}),te=ge=>{if(ge.preventDefault(),!o.name){ne.error("Please enter a name");return}ae.mutate()},ce=ge=>(P==null?void 0:P.filter(Ee=>Ee.kit_id===ge).length)||0;return e.jsx($s,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(C==null?void 0:C.length)||0})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(C==null?void 0:C.filter(ge=>ge.is_published).length)||0})})]})]}),e.jsxs(z,{onClick:()=>{D(),a(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Files"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:E?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(C==null?void 0:C.length)===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):C==null?void 0:C.map(ge=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ge.featured_image_url?e.jsx("img",{src:ge.featured_image_url,alt:ge.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(Sh,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ge.name}),ge.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ge.description})]})]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),ce(ge.id)]})}),e.jsx(yt,{children:Ys(new Date(ge.publish_date),"MMM d, yyyy")}),e.jsx(yt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ge.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ge.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[ge.public_enabled&&ge.public_slug&&e.jsx(z,{variant:"ghost",size:"icon",title:"Copy public landing page link",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/resources/${ge.public_slug}`),ne.success("Public link copied")},children:e.jsx(Wo,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{const Ee=(P==null?void 0:P.filter(Pe=>Pe.kit_id===ge.id))||[],Ne=(M==null?void 0:M.filter(Pe=>Pe.kit_id===ge.id))||[];S({...ge,files:Ee,links:Ne})},children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>F(ge),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi("Delete this resource kit?")&&J.mutate(ge.id)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},ge.id))})]})})}),e.jsxs(be,{className:"mt-6",children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Public Resource Leads",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",(I==null?void 0:I.length)||0,")"]})]})}),e.jsx(Le,{children:!I||I.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads yet. Turn on a public landing page for a kit and share the link."}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Captured"})]})}),e.jsx(Qa,{children:I.map(ge=>{var Ee;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:ge.full_name}),e.jsx(yt,{children:ge.email}),e.jsx(yt,{children:ge.brokerage||"—"}),e.jsx(yt,{children:((Ee=C==null?void 0:C.find(Ne=>Ne.id===ge.kit_id))==null?void 0:Ee.name)||"—"}),e.jsx(yt,{children:Ys(new Date(ge.created_at),"MMM d, yyyy")})]},ge.id)})})]})})]}),e.jsx(Is,{open:r,onOpenChange:a,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:te,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(Sh,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(pe,{type:"file",accept:"image/*",onChange:q})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:o.name,onChange:ge=>c({...o,name:ge.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:o.description,onChange:ge=>c({...o,description:ge}),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(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:ge=>c({...o,publish_date:ge.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(mn,{checked:o.is_published,onCheckedChange:ge=>c({...o,is_published:ge})}),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 rounded-xl border p-4 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-base",children:"Public Landing Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share this resource publicly and capture agent name, email and brokerage as leads."})]}),e.jsx(mn,{checked:o.public_enabled,onCheckedChange:ge=>c({...o,public_enabled:ge,public_slug:o.public_slug||lZ(o.name)})})]}),o.public_enabled&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Public link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex items-center rounded-md border bg-background px-2 text-sm text-muted-foreground",children:"/resources/"}),e.jsx(pe,{value:o.public_slug,onChange:ge=>c({...o,public_slug:ge.target.value}),placeholder:"listing-checklist"}),e.jsxs(z,{type:"button",variant:"outline",onClick:()=>{const ge=lZ(o.public_slug||o.name);navigator.clipboard.writeText(`${window.location.origin}/resources/${ge}`),ne.success("Public link copied")},children:[e.jsx(Kc,{className:"h-4 w-4 mr-1"})," Copy"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:o.public_headline,onChange:ge=>c({...o,public_headline:ge.target.value}),placeholder:o.name||"The Ultimate Listing Checklist"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subheadline"}),e.jsx(pe,{value:o.public_subheadline,onChange:ge=>c({...o,public_subheadline:ge.target.value}),placeholder:"Everything top agents do before a listing goes live."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Button text"}),e.jsx(pe,{value:o.public_cta_text,onChange:ge=>c({...o,public_cta_text:ge.target.value}),placeholder:"Get Instant Access"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Hero image URL (optional)"}),e.jsx(pe,{value:o.public_hero_image_url,onChange:ge=>c({...o,public_hero_image_url:ge.target.value}),placeholder:"Defaults to featured image"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Benefit bullets (one per line)"}),e.jsx("textarea",{value:o.public_benefits,onChange:ge=>c({...o,public_benefits:ge.target.value}),rows:4,placeholder:`Save hours on every listing Proven scripts included Printable + editable`,className:"w-full rounded-md border bg-background px-3 py-2 text-sm"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Resource Files"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:G,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),p.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:p.map((ge,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(z,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>V(Ee),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"File name (e.g., Getting Started Guide)",value:ge.name,onChange:Ne=>H(Ee,"name",Ne.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",onChange:Ne=>re(Ee,Ne),className:"flex-1"}),ge.file_url&&!ge.file&&e.jsx("a",{href:ge.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),ge.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(ee,{children:"Canva Links"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:K,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),g.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:g.map((ge,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(z,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Z(Ee),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"Link title (e.g., Social Media Post Template)",value:ge.title,onChange:Ne=>oe(Ee,"title",Ne.target.value)}),e.jsx(pe,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:ge.canva_share_link,onChange:Ne=>oe(Ee,"canva_share_link",Ne.target.value)})]},Ee))})]}),e.jsx(xHt,{selectedTemplateIds:y,onChange:b}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:ae.isPending,children:ae.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(Is,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{children:w==null?void 0:w.name})}),e.jsxs("div",{className:"space-y-4",children:[(w==null?void 0:w.featured_image_url)&&e.jsx("img",{src:w.featured_image_url,alt:w.name,className:"w-full h-48 object-cover rounded-lg"}),(w==null?void 0:w.description)&&e.jsx("p",{className:"text-muted-foreground",children:w.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((ve=w==null?void 0:w.files)==null?void 0:ve.length)||0,")"]}),((me=w==null?void 0:w.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:(he=w==null?void 0:w.files)==null?void 0:he.map(ge=>e.jsxs("a",{href:ge.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($r,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ge.name})]},ge.id))})]}),(w==null?void 0:w.links)&&w.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.links.map(ge=>e.jsxs("a",{href:ge.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(Kc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ge.title})]},ge.id))})]})]})]})})]})})}const dln=()=>{const{user:s}=hs(),{toast:t}=_i(),n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=_.useState(null),[h,m]=_.useState(""),{data:p=[],isLoading:f}=rt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:I}=await U.from("social_swag").select("*").order("publish_date",{ascending:!1});if(I)throw I;const{data:D,error:F}=await U.from("social_swag_links").select("*").order("sort_order");if(F)throw F;return M.map(G=>({...G,links:(D==null?void 0:D.filter(V=>V.swag_id===G.id))||[]}))}}),g=mt({mutationFn:async M=>{let I=M.existingImageUrl;if(M.image){const H=M.image.name.split(".").pop(),K=`${Date.now()}-${Math.random().toString(36).substring(7)}.${H}`,{error:Z}=await U.storage.from("template-previews").upload(K,M.image);if(Z)throw Z;const{data:oe}=U.storage.from("template-previews").getPublicUrl(K);I=oe.publicUrl}const D={title:M.item.title,description:M.item.description||null,preview_image_url:I,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 F=M.itemId;const q=!F,G=(i==null?void 0:i.is_published)||!1;if(F){const{error:H}=await U.from("social_swag").update(D).eq("id",F);if(H)throw H;await U.from("social_swag_links").delete().eq("swag_id",F)}else{const{data:H,error:K}=await U.from("social_swag").insert(D).select().single();if(K)throw K;F=H.id}const V=M.item.links.filter(H=>H.title.trim()&&H.canva_share_link.trim());if(V.length>0){const H=V.map((Z,oe)=>({swag_id:F,title:Z.title.trim(),canva_share_link:Z.canva_share_link.trim(),sort_order:oe})),{error:K}=await U.from("social_swag_links").insert(H);if(K)throw K}return{itemId:F,itemTitle:M.item.title,isNewItem:q,wasPublished:G,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)&&XHe(M.itemTitle,M.itemId),a(!1),y()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),v=mt({mutationFn:async M=>{const{error:I}=await U.from("social_swag").delete().eq("id",M);if(I)throw I},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"})}}),y=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),m(""),l(null)},b=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(I=>({id:I.id,title:I.title,canva_share_link:I.canva_share_link,sort_order:I.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(M.preview_image_url||""),a(!0)},w=M=>{var D;const I=(D=M.target.files)==null?void 0:D[0];I&&(u(I),m(URL.createObjectURL(I)))},S=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},C=M=>{if(o.links.length<=1)return;const I=o.links.filter((D,F)=>F!==M);c({...o,links:I})},E=(M,I,D)=>{const F=[...o.links];F[M]={...F[M],[I]:D},c({...o,links:F})},P=M=>{if(M.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}g.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx($s,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(M=>M.is_published).length})})]})]}),e.jsxs(Is,{open:r,onOpenChange:M=>{a(M),M||y()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:P,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{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(ee,{children:"Description"}),e.jsx(GN,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{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(mn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(z,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(nc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(pe,{type:"file",accept:"image/*",onChange:w,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Canva Links"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:S,children:[e.jsx(sn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,I)=>e.jsx(be,{children:e.jsxs(Le,{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 ",I+1]}),o.links.length>1&&e.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>C(I),children:e.jsx(er,{className:"h-3 w-3"})})]}),e.jsx(pe,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:D=>E(I,"title",D.target.value)}),e.jsx(pe,{placeholder:"Canva share link",value:M.canva_share_link,onChange:D=>E(I,"canva_share_link",D.target.value)})]})},I))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:g.isPending,children:g.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:f?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:p.map(M=>{var I;return e.jsxs(fn,{children:[e.jsx(yt,{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(nc,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(yt,{className:"font-medium",children:M.title}),e.jsxs(yt,{children:[((I=M.links)==null?void 0:I.length)||0," links"]}),e.jsx(yt,{children:new Date(M.publish_date).toLocaleDateString()}),e.jsx(yt,{children:e.jsx(ze,{variant:M.is_published?"default":"secondary",children:M.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${M.id}`,"_blank"),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>b(M),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi("Are you sure you want to delete this item?")&&v.mutate(M.id)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function uln({item:s,onEdit:t,onDelete:n,onDateChange:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=gLe({id:s.id}),u={transform:YP.Transform.toString(o),transition:c,opacity:d?.5:1,zIndex:d?10:void 0};return e.jsx("div",{ref:l,style:u,children:e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{...a,...i,className:"flex items-center justify-center gap-1 py-1.5 bg-muted hover:bg-muted/80 cursor-grab active:cursor-grabbing border-b select-none",title:"Drag to reorder",children:[e.jsx(Zf,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:"Drag to reorder"})]}),e.jsxs("div",{className:"relative aspect-[4/5]",children:[e.jsx("img",{src:s.image_url,alt:"Social swag",className:"w-full h-full object-cover",loading:"lazy",decoding:"async"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[e.jsx(z,{variant:"secondary",size:"icon",className:"h-7 w-7 bg-black/50 hover:bg-black/70 border-0 text-white",onClick:()=>t(s),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(Cn,{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(ya,{className:"h-2.5 w-2.5"}),Ys(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Le,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:Ct("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(ya,{className:"h-3 w-3"}),s.post_date?Ys(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(nd,{className:"w-auto p-0",align:"start",children:[e.jsx(Oj,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Ys(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(z,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const hln=()=>{const s=$t(),[t,n]=_.useState("all"),[r,a]=_.useState(!1),[i,l]=_.useState(Ys(new Date,"yyyy-MM")),[o,c]=_.useState([]),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(null),[g,v]=_.useState(""),[y,b]=_.useState(null),[w,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(Ys(new Date,"yyyy-MM")),[I,D]=_.useState(null),[F,q]=_.useState(""),[G,V]=_.useState(""),[H,K]=_.useState(""),[Z,oe]=_.useState(!1),re=lLe($H(kW,{activationConstraint:{distance:5}}),$H(uLe,{coordinateGetter:Ozt})),{data:ae=[],isLoading:J}=rt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:nt,error:Ge}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ge)throw Ge;return nt}}),{data:te=[]}=rt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:nt,error:Ge}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ge)throw Ge;return nt}}),{data:ce=[]}=rt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:nt,error:Ge}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ge)throw Ge;return nt}}),ve=[...new Set(ae.map(nt=>nt.month))].sort((nt,Ge)=>Ge.localeCompare(nt)),me=t==="all"?ae:ae.filter(nt=>nt.month===t),he=nt=>{const Ge=_Je(nt,"yyyy-MM",new Date);return Ys(Ge,"MMMM yyyy")},ge=nt=>{f(nt),v(nt.caption),b(nt.post_date)},Ee=async()=>{if(p){S(!0);try{const{error:nt}=await U.from("social_swag_2").update({caption:g,post_date:y}).eq("id",p.id);if(nt)throw nt;ne.success("Image updated"),f(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ne.error("Failed to update image")}finally{S(!1)}}},Ne=async nt=>{const{active:Ge,over:Je}=nt;if(!Je||Ge.id===Je.id)return;const ut=me,lt=ut.findIndex(Zt=>Zt.id===Ge.id),qt=ut.findIndex(Zt=>Zt.id===Je.id);if(lt===-1||qt===-1)return;const zt=fLe(ut,lt,qt);s.setQueryData(["admin-social-swag-2"],Zt=>{if(!Zt)return Zt;const ms={};return zt.forEach((Dt,It)=>{ms[Dt.id]=It}),Zt.map(Dt=>ms[Dt.id]!==void 0?{...Dt,sort_order:ms[Dt.id]}:Dt).sort((Dt,It)=>Dt.month!==It.month?It.month.localeCompare(Dt.month):Dt.sort_order-It.sort_order)});try{await Promise.all(zt.map((Zt,ms)=>U.from("social_swag_2").update({sort_order:ms}).eq("id",Zt.id)))}catch{ne.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Pe=nt=>{const Je=Array.from(nt.target.files||[]).sort((ut,lt)=>ut.name.localeCompare(lt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(ut=>({file:ut,preview:URL.createObjectURL(ut),caption:""}));c(ut=>[...ut,...Je].slice(0,16))},Oe=nt=>{c(Ge=>{const Je=[...Ge];return URL.revokeObjectURL(Je[nt].preview),Je.splice(nt,1),Je})},ke=(nt,Ge)=>{c(Je=>{const ut=[...Je];return ut[nt]={...ut[nt],caption:Ge},ut})},Ve=async()=>{var Ge;if(o.length===0){ne.error("Please add at least one image");return}if(o.filter(Je=>!Je.caption.trim()).length>0){ne.error("Please add captions to all images");return}u(!0);try{const{data:Je}=await U.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),ut=(((Ge=Je==null?void 0:Je[0])==null?void 0:Ge.sort_order)??-1)+1;for(let lt=0;lt{const Ge=nt.image_url.split("/social-swag-2/");Ge[1]&&await U.storage.from("social-swag-2").remove([Ge[1]]);const{error:Je}=await U.from("social_swag_2").delete().eq("id",nt.id);if(Je)throw Je},onSuccess:()=>{ne.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ne.error("Failed to delete image")}),Ae=mt({mutationFn:async({id:nt,postDate:Ge})=>{const{error:Je}=await U.from("social_swag_2").update({post_date:Ge}).eq("id",nt);if(Je)throw Je},onSuccess:()=>{ne.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ne.error("Failed to update post date")}),Se=mt({mutationFn:async({month:nt,link:Ge})=>{const{error:Je}=await U.from("social_swag_2_months").upsert({month:nt,canva_link:Ge||null},{onConflict:"month"});if(Je)throw Je},onSuccess:()=>{ne.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ne.error("Failed to update Canva link")}),We=nt=>{var Ge;return((Ge=te.find(Je=>Je.month===nt))==null?void 0:Ge.canva_link)||""},qe=nt=>ce.find(Ge=>Ge.month===nt)||null,Be=nt=>{var Je;const Ge=(Je=nt.target.files)==null?void 0:Je[0];Ge&&(D(Ge),q(URL.createObjectURL(Ge)))},Ze=()=>{F&&URL.revokeObjectURL(F),D(null),q(""),V(""),K("")},$e=async()=>{if(!I){ne.error("Please select an image");return}oe(!0);try{const nt=I.name.split(".").pop(),Ge=`reels/${P}-${Date.now()}.${nt}`,{error:Je}=await U.storage.from("social-swag-2").upload(Ge,I);if(Je)throw Je;const{data:{publicUrl:ut}}=U.storage.from("social-swag-2").getPublicUrl(Ge),{error:lt}=await U.from("social_swag_2_reels").upsert({month:P,image_url:ut,canva_link:H||null,caption:G||null},{onConflict:"month"});if(lt)throw lt;ne.success("Reel uploaded successfully!"),XHe(`${he(P)} Reel`,"social-swag-2"),Ze(),E(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(nt){console.error("Reel upload error:",nt),ne.error("Failed to upload reel")}finally{oe(!1)}},Xe=mt({mutationFn:async nt=>{const Ge=nt.image_url.split("/social-swag-2/");Ge[1]&&await U.storage.from("social-swag-2").remove([Ge[1]]);const{error:Je}=await U.from("social_swag_2_reels").delete().eq("id",nt.id);if(Je)throw Je},onSuccess:()=>{ne.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ne.error("Failed to delete reel")});return e.jsxs($s,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{open:r,onOpenChange:a,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Ls,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Month"}),e.jsx(pe,{type:"month",value:i,onChange:nt=>l(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{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:Pe,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(Ra,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((nt,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:nt.preview,alt:`Upload ${Ge+1}`,className:"w-full h-full object-cover"}),e.jsx(z,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Oe(Ge),children:e.jsx(er,{className:"h-3 w-3"})})]}),e.jsx(Ps,{placeholder:"Caption...",value:nt.caption,onChange:Je=>ke(Ge,Je.target.value),className:"text-xs h-20"})]},Ge))}),e.jsx(z,{onClick:Ve,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(Is,{open:C,onOpenChange:nt=>{E(nt),nt||Ze()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"gap-2",children:[e.jsx(Yh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Ls,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Month"}),e.jsx(pe,{type:"month",value:P,onChange:nt=>M(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Reel Preview Image"}),F?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:F,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(z,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(F),D(null),q("")},children:e.jsx(er,{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:Be,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(Yh,{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(ee,{children:"Canva Download Link"}),e.jsx(pe,{value:H,onChange:nt=>K(nt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Ps,{value:G,onChange:nt=>V(nt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(z,{onClick:$e,disabled:Z||!I,className:"w-full gap-2",children:Z?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ae.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ve.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Qr,{value:t,onValueChange:n,children:e.jsxs(Jr,{children:[e.jsx(Wt,{value:"all",children:"All"}),ve.map(nt=>e.jsx(Wt,{value:nt,children:he(nt)},nt))]})}),t!=="all"&&e.jsx(be,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Kc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ee,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",he(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(pe,{value:h.link,onChange:nt=>m({...h,link:nt.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(z,{size:"sm",onClick:()=>Se.mutate(h),children:"Save"}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>m(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:We(t)||"No link set"}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:We(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(be,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Yh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ee,{className:"text-sm text-muted-foreground",children:["Reel for ",he(t)]}),(()=>{const nt=qe(t);return nt?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:nt.image_url,alt:"Reel preview",className:"w-16 h-28 object-cover rounded"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("p",{className:"line-clamp-2",children:nt.caption||"No caption"}),nt.canva_link&&e.jsx("a",{href:nt.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(z,{variant:"destructive",size:"sm",onClick:()=>Xe.mutate(nt),children:e.jsx(Cn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),J?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):me.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nc,{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(pLe,{sensors:re,collisionDetection:cLe,onDragEnd:Ne,children:e.jsx(xLe,{items:me.map(nt=>nt.id),strategy:pae,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:me.map(nt=>e.jsx(uln,{item:nt,onEdit:ge,onDelete:Ge=>_e.mutate(Ge),onDateChange:(Ge,Je)=>Ae.mutate({id:Ge,postDate:Je})},nt.id))})})})]}),e.jsx(Is,{open:!!p,onOpenChange:nt=>{nt||f(null)},children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Edit Image"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:p.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Ps,{value:g,onChange:nt=>v(nt.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("flex-1 justify-start gap-2 font-normal",!y&&"text-muted-foreground"),children:[e.jsx(ya,{className:"h-4 w-4"}),y?Ys(new Date(y+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{mode:"single",selected:y?new Date(y+"T00:00:00"):void 0,onSelect:nt=>b(nt?Ys(nt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),y&&e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(er,{className:"h-4 w-4"})})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>f(null),children:"Cancel"}),e.jsx(z,{onClick:Ee,disabled:w,className:"gap-2",children:w?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},mln=()=>{const{toast:s}=_i(),t=$t(),[n,r]=_.useState("categories"),[a,i]=_.useState(!1),[l,o]=_.useState(null),[c,d]=_.useState({name:"",description:"",icon:""}),[u,h]=_.useState(!1),[m,p]=_.useState(null),[f,g]=_.useState({name:"",description:"",icon:""}),[v,y]=_.useState(!1),[b,w]=_.useState(null),[S,C]=_.useState(""),{data:E=[],isLoading:P}=rt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Ne,error:Pe}=await U.from("community_categories").select("*").order("sort_order");if(Pe)throw Pe;return Ne}}),{data:M=[],isLoading:I}=rt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Ne,error:Pe}=await U.from("community_private_groups").select("*").order("sort_order");if(Pe)throw Pe;return Ne}}),{data:D=[]}=rt({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Ne,error:Pe}=await U.from("community_private_group_members").select("*").eq("group_id",b.id);if(Pe)throw Pe;return Ne},enabled:!!b}),{data:F=[]}=rt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Pe=[],Oe=0,ke=!0;for(;ke;){const{data:Ve,error:_e}=await U.from("profiles").select("id, name, email, brokerage_id").order("name").range(Oe,Oe+1e3-1);if(_e)throw _e;Ve&&Ve.length>0?(Pe=[...Pe,...Ve],Oe+=1e3,ke=Ve.length===1e3):ke=!1}return Pe}}),{data:q=[]}=rt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Ne,error:Pe}=await U.from("brokerages").select("*").order("name");if(Pe)throw Pe;return Ne}}),G=mt({mutationFn:async Ne=>{if(Ne.id){const{error:Pe}=await U.from("community_categories").update({name:Ne.name,description:Ne.description||null,icon:Ne.icon||null}).eq("id",Ne.id);if(Pe)throw Pe}else{const Pe=Math.max(...E.map(ke=>ke.sort_order),0),{error:Oe}=await U.from("community_categories").insert({name:Ne.name,description:Ne.description||null,icon:Ne.icon||null,sort_order:Pe+1});if(Oe)throw Oe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Ne=>{s({title:"Error",description:Ne.message,variant:"destructive"})}}),V=mt({mutationFn:async Ne=>{const{error:Pe}=await U.from("community_categories").delete().eq("id",Ne);if(Pe)throw Pe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),H=mt({mutationFn:async({id:Ne,direction:Pe})=>{const Oe=E.findIndex(ke=>ke.id===Ne);if(Pe==="up"&&Oe>0){const ke=E[Oe-1],Ve=E[Oe];await U.from("community_categories").update({sort_order:Ve.sort_order}).eq("id",ke.id),await U.from("community_categories").update({sort_order:ke.sort_order}).eq("id",Ve.id)}else if(Pe==="down"&&Oet.invalidateQueries({queryKey:["admin-community-categories"]})}),K=mt({mutationFn:async Ne=>{if(Ne.id){const{error:Pe}=await U.from("community_private_groups").update({name:Ne.name,description:Ne.description||null,icon:Ne.icon||null}).eq("id",Ne.id);if(Pe)throw Pe}else{const Pe=Math.max(...M.map(ke=>ke.sort_order),0),{error:Oe}=await U.from("community_private_groups").insert({name:Ne.name,description:Ne.description||null,icon:Ne.icon||null,sort_order:Pe+1});if(Oe)throw Oe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),p(null),g({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Ne=>{s({title:"Error",description:Ne.message,variant:"destructive"})}}),Z=mt({mutationFn:async Ne=>{const{error:Pe}=await U.from("community_private_groups").delete().eq("id",Ne);if(Pe)throw Pe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),oe=mt({mutationFn:async({id:Ne,direction:Pe})=>{const Oe=M.findIndex(ke=>ke.id===Ne);if(Pe==="up"&&Oe>0){const ke=M[Oe-1],Ve=M[Oe];await U.from("community_private_groups").update({sort_order:Ve.sort_order}).eq("id",ke.id),await U.from("community_private_groups").update({sort_order:ke.sort_order}).eq("id",Ve.id)}else if(Pe==="down"&&Oet.invalidateQueries({queryKey:["admin-private-groups"]})}),re=mt({mutationFn:async({groupId:Ne,userId:Pe,isMember:Oe})=>{if(Oe){const{error:ke}=await U.from("community_private_group_members").delete().eq("group_id",Ne).eq("user_id",Pe);if(ke)throw ke}else{const{error:ke}=await U.from("community_private_group_members").insert({group_id:Ne,user_id:Pe});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ae=mt({mutationFn:async({groupId:Ne,brokerageId:Pe,isMember:Oe})=>{if(Oe){const{error:ke}=await U.from("community_private_group_members").delete().eq("group_id",Ne).eq("brokerage_id",Pe);if(ke)throw ke}else{const{error:ke}=await U.from("community_private_group_members").insert({group_id:Ne,brokerage_id:Pe});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),J=Ne=>{o(Ne),d({name:Ne.name,description:Ne.description||"",icon:Ne.icon||""}),i(!0)},te=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ce=Ne=>{p(Ne),g({name:Ne.name,description:Ne.description||"",icon:Ne.icon||""}),h(!0)},ve=()=>{p(null),g({name:"",description:"",icon:""}),h(!0)},me=Ne=>{w(Ne),C(""),y(!0)},he=Ne=>D.some(Pe=>Pe.user_id===Ne),ge=Ne=>D.some(Pe=>Pe.brokerage_id===Ne),Ee=F.filter(Ne=>Ne.name.toLowerCase().includes(S.toLowerCase())||Ne.email.toLowerCase().includes(S.toLowerCase()));return e.jsx($s,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(Qr,{value:n,onValueChange:r,children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"categories",children:"Public Categories"}),e.jsxs(Wt,{value:"private-groups",children:[e.jsx(Hl,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Kt,{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(z,{onClick:te,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Qa,{children:P?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):E.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):E.map((Ne,Pe)=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===0,onClick:()=>H.mutate({id:Ne.id,direction:"up"}),children:"↑"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===E.length-1,onClick:()=>H.mutate({id:Ne.id,direction:"down"}),children:"↓"})]})}),e.jsx(yt,{className:"text-2xl",children:Ne.icon||"📁"}),e.jsx(yt,{className:"font-medium",children:Ne.name}),e.jsx(yt,{className:"text-muted-foreground",children:Ne.description||"—"}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>J(Ne),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Qi("Delete this category? Posts will be uncategorized.")&&V.mutate(Ne.id)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},Ne.id))})]})})})]}),e.jsxs(Kt,{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(oi,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(z,{onClick:ve,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[120px]",children:"Members"}),e.jsx(Tt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(Qa,{children:I?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):M.map((Ne,Pe)=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===0,onClick:()=>oe.mutate({id:Ne.id,direction:"up"}),children:"↑"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Pe===M.length-1,onClick:()=>oe.mutate({id:Ne.id,direction:"down"}),children:"↓"})]})}),e.jsx(yt,{className:"text-2xl",children:Ne.icon||"🔒"}),e.jsx(yt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ne.name,Ne.brokerage_id?e.jsxs(ze,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(oi,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(Hl,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(yt,{className:"text-muted-foreground",children:Ne.description||"—"}),e.jsx(yt,{children:e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>me(Ne),children:[e.jsx(On,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Ne.brokerage_id&&e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>ce(Ne),children:e.jsx(Wa,{className:"h-4 w-4"})}),!Ne.brokerage_id&&e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Qi("Delete this private group? All posts in this group will be deleted.")&&Z.mutate(Ne.id)},children:e.jsx(Cn,{className:"h-4 w-4"})}),Ne.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Ne.id))})]})})})]})]}),e.jsx(Is,{open:a,onOpenChange:i,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{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(pe,{value:c.icon,onChange:Ne=>d(Pe=>({...Pe,icon:Ne.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(pe,{value:c.name,onChange:Ne=>d(Pe=>({...Pe,name:Ne.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ps,{value:c.description,onChange:Ne=>d(Pe=>({...Pe,description:Ne.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(z,{onClick:()=>G.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(Is,{open:u,onOpenChange:h,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:m?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(pe,{value:f.icon,onChange:Ne=>g(Pe=>({...Pe,icon:Ne.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(pe,{value:f.name,onChange:Ne=>g(Pe=>({...Pe,name:Ne.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(Ps,{value:f.description,onChange:Ne=>g(Pe=>({...Pe,description:Ne.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(z,{onClick:()=>K.mutate({...f,id:m==null?void 0:m.id}),disabled:!f.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(Is,{open:v,onOpenChange:y,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Qr,{defaultValue:"brokerages",children:[e.jsxs(Jr,{className:"w-full",children:[e.jsx(Wt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Wt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Kt,{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(Ki,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[q.map(Ne=>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(za,{checked:ge(Ne.id),onCheckedChange:()=>{b&&ae.mutate({groupId:b.id,brokerageId:Ne.id,isMember:ge(Ne.id)})}}),e.jsx("span",{className:"font-medium",children:Ne.name})]}),e.jsxs(ze,{variant:"secondary",children:[F.filter(Pe=>Pe.brokerage_id===Ne.id).length," agents"]})]},Ne.id)),q.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Kt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search users...",value:S,onChange:Ne=>C(Ne.target.value),className:"pl-9"})]}),e.jsx(Ki,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ee.map(Ne=>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(za,{checked:he(Ne.id),onCheckedChange:()=>{b&&re.mutate({groupId:b.id,userId:Ne.id,isMember:he(Ne.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ne.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ne.email})]})]})},Ne.id)),Ee.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(z,{onClick:()=>y(!1),children:"Done"})})]})]})})]})})},g1t=s=>{switch(s){case"academy_video":return e.jsx(su,{className:"h-3 w-3"});case"template":return e.jsx($r,{className:"h-3 w-3"});case"toolbox":return e.jsx(Sh,{className:"h-3 w-3"});case"newsletter":return e.jsx(vN,{className:"h-3 w-3"});case"social_swag":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(mr,{className:"h-3 w-3"})}},pln=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}},fln=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}},xln=()=>{const{toast:s}=_i(),[t,n]=_.useState([]),[r,a]=_.useState([]),[i,l]=_.useState([]),[o,c]=_.useState(!0),[d,u]=_.useState(""),[h,m]=_.useState(null),[p,f]=_.useState([]),[g,v]=_.useState([]);_.useEffect(()=>{y()},[]);const y=async()=>{try{c(!0);const{data:D,error:F}=await U.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(F)throw F;const{data:q,error:G}=await U.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(G)throw G;const V=[...new Set((q==null?void 0:q.map(J=>J.user_id))||[])],{data:H}=await U.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",V),K=new Map((H==null?void 0:H.map(J=>[J.id,J]))||[]),Z=(D==null?void 0:D.map(J=>{var te,ce,ve,me;return{id:J.id,user_id:J.user_id,app_name:J.app_name,launched_at:J.launched_at,user_name:((te=J.profiles)==null?void 0:te.name)||"Unknown",user_email:((ce=J.profiles)==null?void 0:ce.email)||"Unknown",brokerage_name:((me=(ve=J.profiles)==null?void 0:ve.brokerages)==null?void 0:me.name)||null}}))||[],oe=(q==null?void 0:q.map(J=>{var ce;const te=K.get(J.user_id);return{id:J.id,user_id:J.user_id,resource_type:J.resource_type,resource_id:J.resource_id,resource_title:J.resource_title,action_type:J.action_type,created_at:J.created_at,user_name:(te==null?void 0:te.name)||"Unknown",user_email:(te==null?void 0:te.email)||"Unknown",brokerage_name:((ce=te==null?void 0:te.brokerages)==null?void 0:ce.name)||null}}))||[];n(Z),a(oe);const re=new Map;Z.forEach(J=>{if(!re.has(J.user_id))re.set(J.user_id,{user_id:J.user_id,user_name:J.user_name,user_email:J.user_email,brokerage_name:J.brokerage_name,last_activity_type:"app",last_activity_name:J.app_name,last_activity_at:J.launched_at,total_app_launches:1,total_content_views:0});else{const te=re.get(J.user_id);te.total_app_launches++,new Date(J.launched_at)>new Date(te.last_activity_at)&&(te.last_activity_type="app",te.last_activity_name=J.app_name,te.last_activity_at=J.launched_at)}}),oe.forEach(J=>{if(!re.has(J.user_id))re.set(J.user_id,{user_id:J.user_id,user_name:J.user_name,user_email:J.user_email,brokerage_name:J.brokerage_name,last_activity_type:J.resource_type,last_activity_name:J.resource_title,last_activity_at:J.created_at,total_app_launches:0,total_content_views:1});else{const te=re.get(J.user_id);te.total_content_views++,new Date(J.created_at)>new Date(te.last_activity_at)&&(te.last_activity_type=J.resource_type,te.last_activity_name=J.resource_title,te.last_activity_at=J.created_at)}});const ae=Array.from(re.values()).sort((J,te)=>new Date(te.last_activity_at).getTime()-new Date(J.last_activity_at).getTime());l(ae)}catch(D){console.error("Error loading activity:",D),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=D=>{m({id:D.user_id,name:D.user_name,email:D.user_email});const F=t.filter(G=>G.user_id===D.user_id),q=r.filter(G=>G.user_id===D.user_id);f(F),v(q)},w=()=>{m(null),f([]),v([])},{sortKey:S,sortDirection:C,handleSort:E,sortData:P}=Mae("last_activity_at","desc"),M=i.filter(D=>{var q;if(!d)return!0;const F=d.toLowerCase();return D.user_name.toLowerCase().includes(F)||D.user_email.toLowerCase().includes(F)||((q=D.brokerage_name)==null?void 0:q.toLowerCase().includes(F))}),I=P(M,{user:D=>{var F;return((F=D.user_name)==null?void 0:F.toLowerCase())||""},brokerage:D=>{var F;return((F=D.brokerage_name)==null?void 0:F.toLowerCase())||""},last_activity_at:D=>new Date(D.last_activity_at).getTime(),apps:D=>D.total_app_launches,content:D=>D.total_content_views});return o?e.jsx(be,{children:e.jsx(Le,{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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"User Activity"}),e.jsx(En,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:D=>u(D.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Hh,{sortKey:"user",currentSortKey:S,currentDirection:C,onSort:E,children:"User"}),e.jsx(Hh,{sortKey:"brokerage",currentSortKey:S,currentDirection:C,onSort:E,children:"Brokerage"}),e.jsx(Tt,{children:"Last Activity"}),e.jsx(Hh,{sortKey:"last_activity_at",currentSortKey:S,currentDirection:C,onSort:E,children:"Last Active"}),e.jsx(Hh,{sortKey:"apps",currentSortKey:S,currentDirection:C,onSort:E,className:"text-right",children:"Apps"}),e.jsx(Hh,{sortKey:"content",currentSortKey:S,currentDirection:C,onSort:E,className:"text-right",children:"Content"})]})}),e.jsx(Qa,{children:I.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):I.map(D=>e.jsxs(fn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(D),children:[e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:D.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:D.user_email})]})}),e.jsx(yt,{children:D.brokerage_name?e.jsx(ze,{variant:"outline",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(yt,{children:e.jsx("div",{className:"flex items-center gap-2",children:D.last_activity_type==="app"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(mr,{className:"h-3 w-3 mr-1"}),D.last_activity_name]}):e.jsxs(ze,{variant:"outline",className:"flex items-center gap-1",children:[g1t(D.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:D.last_activity_name})]})})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Md(new Date(D.last_activity_at),{addSuffix:!0})}),e.jsx(yt,{className:"text-right",children:e.jsx(ze,{variant:"outline",children:D.total_app_launches})}),e.jsx(yt,{className:"text-right",children:e.jsx(ze,{variant:"outline",children:D.total_content_views})})]},D.user_id))})]})})]})]}),e.jsx(Is,{open:!!h,onOpenChange:D=>!D&&w(),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(_r,{children:h==null?void 0:h.email})]}),e.jsxs(Qr,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Wt,{value:"content",children:["Content (",g.length,")"]}),e.jsxs(Wt,{value:"apps",children:["App Launches (",p.length,")"]})]}),e.jsx(Kt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Qa,{children:g.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):g.map(D=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs(ze,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[g1t(D.resource_type),pln(D.resource_type)]})}),e.jsx(yt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:D.resource_title})}),e.jsx(yt,{children:e.jsx(ze,{variant:"secondary",children:fln(D.action_type)})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Md(new Date(D.created_at),{addSuffix:!0})})]},D.id))})]})})}),e.jsx(Kt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Qa,{children:p.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):p.map(D=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx(ze,{variant:"secondary",children:D.app_name})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Md(new Date(D.launched_at),{addSuffix:!0})})]},D.id))})]})})})]})]})})]})},gln=()=>{const{toast:s}=_i(),[t,n]=_.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=_.useState(!0);_.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await U.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await U.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await U.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await U.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),p=new Date;p.setMonth(p.getMonth()-1);const{count:f}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",p.toISOString()),{data:g}=await U.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),v=new Set(g==null?void 0:g.map(y=>y.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:f||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(be,{children:e.jsx(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(On,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Xl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},y1t={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},v1t={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 gHt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=_.useState([]),[a,i]=_.useState(!0),[l,o]=_.useState(""),[c,d]=_.useState("all");_.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let E=[];if(s&&t){const{data:V}=await U.from("profiles").select("id").eq("brokerage_id",t);if(E=(V==null?void 0:V.map(H=>H.id))||[],E.length===0){r([]),i(!1);return}}let P=U.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&E.length>0&&(P=P.or(`sender_id.in.(${E.join(",")}),recipient_id.in.(${E.join(",")})`));const{data:M,error:I}=await P;if(I)throw I;const D=new Set;M==null||M.forEach(V=>{D.add(V.sender_id),D.add(V.recipient_id)});const{data:F}=await U.from("profiles").select("id, name, email").in("id",Array.from(D)),q=new Map((F==null?void 0:F.map(V=>[V.id,V]))||[]),G=(M==null?void 0:M.map(V=>({...V,sender:q.get(V.sender_id),recipient:q.get(V.recipient_id)})))||[];r(G)}catch(E){console.error("Error loading shares:",E)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:p,sortData:f}=Mae("created_at","desc"),g=n.filter(E=>{var I,D;const P=l===""||E.resource_title.toLowerCase().includes(l.toLowerCase())||((I=E.sender)==null?void 0:I.name.toLowerCase().includes(l.toLowerCase()))||((D=E.recipient)==null?void 0:D.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||E.resource_type===c;return P&&M}),v=f(g,{resource:E=>{var P;return((P=E.resource_title)==null?void 0:P.toLowerCase())||""},type:E=>E.resource_type,sender:E=>{var P,M;return((M=(P=E.sender)==null?void 0:P.name)==null?void 0:M.toLowerCase())||""},recipient:E=>{var P,M;return((M=(P=E.recipient)==null?void 0:P.name)==null?void 0:M.toLowerCase())||""},status:E=>E.is_read?1:0,created_at:E=>new Date(E.created_at).getTime()}),y=n.length,b=new Set(n.map(E=>E.sender_id)).size,w=new Set(n.map(E=>E.recipient_id)).size,S=n.length>0?Math.round(n.filter(E=>E.is_read).length/n.length*100):0,C=n.reduce((E,P)=>(E[P.resource_type]=(E[P.resource_type]||0)+1,E),{});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((E,P)=>e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(ln,{className:"h-4 w-20"})}),e.jsx(Le,{children:e.jsx(ln,{className:"h-8 w-16"})})]},P))}),e.jsx(be,{children:e.jsx(Le,{className:"p-6",children:e.jsx(ln,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(sd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:y})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(On,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:w})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx($r,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[S,"%"]})})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Le,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(C).map(([E,P])=>e.jsxs(ze,{variant:"secondary",className:v1t[E],children:[y1t[E],": ",P]},E)),Object.keys(C).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Share History"}),e.jsxs(En,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:E=>o(E.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:c,onValueChange:d,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"Resource type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"event",children:"Events"}),e.jsx(He,{value:"template",children:"Templates"}),e.jsx(He,{value:"academy_video",children:"Academy Videos"}),e.jsx(He,{value:"resource_kit",children:"Resource Kits"}),e.jsx(He,{value:"newsletter",children:"Newsletters"}),e.jsx(He,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Ki,{className:"h-[400px]",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Hh,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:p,children:"Resource"}),e.jsx(Hh,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:p,children:"Type"}),e.jsx(Hh,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:p,children:"Sender"}),e.jsx(Hh,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:p,children:"Recipient"}),e.jsx(Hh,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:p,children:"Status"}),e.jsx(Hh,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:p,children:"Date"})]})}),e.jsx(Qa,{children:v.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):v.map(E=>{var P,M;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium max-w-[200px] truncate",children:E.resource_title}),e.jsx(yt,{children:e.jsx(ze,{variant:"secondary",className:v1t[E.resource_type],children:y1t[E.resource_type]})}),e.jsx(yt,{children:((P=E.sender)==null?void 0:P.name)||"Unknown"}),e.jsx(yt,{children:((M=E.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(yt,{children:e.jsx(ze,{variant:E.is_read?"default":"outline",children:E.is_read?"Read":"Unread"})}),e.jsx(yt,{className:"text-muted-foreground",children:Ys(new Date(E.created_at),"MMM d, yyyy")})]},E.id)})})]})})]})]})]})}const T9e={academy_video:{label:"Academy Videos",icon:Xr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:xa},template:{label:"Templates",icon:tA,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:wy},toolbox:{label:"Toolkit",icon:eC,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:Ga},newsletter:{label:"Newsletters",icon:on,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:wy},social_swag:{label:"Social Swag",icon:yc,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:wy},event:{label:"Events",icon:ya,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:wy}};function b1t(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function yln(s,t){return s==="toolbox"?t.downloads:t.clicks}function vln(){var E;const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(null),l=_.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=Mae("total_views","desc");_.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:P,error:M}=await U.rpc("get_admin_content_engagement");if(M)throw M;t(P||[])}catch(P){console.error("Error loading content engagement:",P)}finally{r(!1)}},m=P=>{i(M=>{const I=M===P?null:P;return requestAnimationFrame(()=>{var D;(D=l.current)==null||D.scrollIntoView({behavior:"smooth",block:"start"})}),I})};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((P,M)=>e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(ln,{className:"h-4 w-20"})}),e.jsx(Le,{children:e.jsx(ln,{className:"h-8 w-16"})})]},M))}),e.jsx(be,{children:e.jsx(Le,{className:"py-8",children:e.jsx(ln,{className:"h-64 w-full"})})})]});const p=s.reduce((P,M)=>P+M.total_views,0),f=s.reduce((P,M)=>P+M.total_clicks,0),g=s.reduce((P,M)=>P+M.total_downloads,0),v=s.length,y=s.reduce((P,M)=>(P[M.resource_type]||(P[M.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),P[M.resource_type].views+=M.total_views,P[M.resource_type].clicks+=M.total_clicks,P[M.resource_type].downloads+=M.total_downloads,P[M.resource_type].assets+=1,P[M.resource_type].uniqueUsers+=M.unique_users,P),{}),b=a?s.filter(P=>P.resource_type===a):s,w=u(b,{asset:P=>{var M;return((M=P.resource_title)==null?void 0:M.toLowerCase())||""},type:P=>P.resource_type,views:P=>P.total_views,actions:P=>b1t(P),unique_users:P=>P.unique_users,last_activity:P=>P.last_engaged_at?new Date(P.last_engaged_at).getTime():0}),S=a?T9e[a]||{label:a,icon:xa,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:wy}:null,C=S==null?void 0:S.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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:p.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(wy,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(wy,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[p>0?Math.round((f+g)/p*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(En,{children:"Click a category to see individual asset performance"})]}),e.jsx(Le,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(y).map(([P,M])=>{const I=T9e[P]||{label:P,icon:xa,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:wy},D=I.icon,F=a===P;return e.jsxs("button",{type:"button",onClick:()=>m(P),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${F?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${I.color}`,children:e.jsx(D,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:I.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(xa,{className:"h-3 w-3"})," ",M.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(I.actionIcon,{className:"h-3 w-3"})," ",yln(P,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(On,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},P)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-sm font-medium flex items-center gap-2",children:S&&C?e.jsxs(e.Fragment,{children:[e.jsx(C,{className:"h-4 w-4"}),S.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(En,{children:a?`${b.length} ${((E=S==null?void 0:S.label)==null?void 0:E.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Le,{children:b.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(Ki,{className:"h-[400px]",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[40px]",children:"#"}),e.jsx(Hh,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Hh,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Hh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Hh,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:S?S.actionLabel:"Actions"}),e.jsx(Hh,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Hh,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(Qa,{children:w.map((P,M)=>{const I=T9e[P.resource_type]||{label:P.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:wy};return e.jsxs(fn,{children:[e.jsx(yt,{className:"text-muted-foreground text-xs",children:M+1}),e.jsx(yt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:P.resource_title})}),!a&&e.jsx(yt,{children:e.jsx(ze,{className:`text-[10px] ${I.color}`,children:I.label})}),e.jsx(yt,{className:"text-right font-medium",children:P.total_views}),e.jsx(yt,{className:"text-right font-medium",children:b1t(P)}),e.jsx(yt,{className:"text-right",children:P.unique_users}),e.jsx(yt,{className:"text-xs text-muted-foreground",children:P.last_engaged_at?Md(new Date(P.last_engaged_at),{addSuffix:!0}):"—"})]},`${P.resource_type}-${P.resource_id}`)})})]})})})]})})]})}var bln=Array.isArray,J_=bln,_ln=typeof Pp=="object"&&Pp&&Pp.Object===Object&&Pp,yHt=_ln,wln=yHt,jln=typeof self=="object"&&self&&self.Object===Object&&self,Nln=wln||jln||Function("return this")(),LC=Nln,kln=LC,Sln=kln.Symbol,Lae=Sln,_1t=Lae,vHt=Object.prototype,Cln=vHt.hasOwnProperty,Aln=vHt.toString,cZ=_1t?_1t.toStringTag:void 0;function Eln(s){var t=Cln.call(s,cZ),n=s[cZ];try{s[cZ]=void 0;var r=!0}catch{}var a=Aln.call(s);return r&&(t?s[cZ]=n:delete s[cZ]),a}var Tln=Eln,Mln=Object.prototype,Pln=Mln.toString;function Lln(s){return Pln.call(s)}var Iln=Lln,w1t=Lae,Dln=Tln,Rln=Iln,Fln="[object Null]",Oln="[object Undefined]",j1t=w1t?w1t.toStringTag:void 0;function zln(s){return s==null?s===void 0?Oln:Fln:j1t&&j1t in Object(s)?Dln(s):Rln(s)}var GE=zln;function Bln(s){return s!=null&&typeof s=="object"}var WE=Bln,$ln=GE,Uln=WE,qln="[object Symbol]";function Vln(s){return typeof s=="symbol"||Uln(s)&&$ln(s)==qln}var IW=Vln,Hln=J_,Gln=IW,Wln=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Kln=/^\w*$/;function Yln(s,t){if(Hln(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Gln(s)?!0:Kln.test(s)||!Wln.test(s)||t!=null&&s in Object(t)}var bst=Yln;function Zln(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var OL=Zln;const DW=kd(OL);var Xln=GE,Qln=OL,Jln="[object AsyncFunction]",ecn="[object Function]",tcn="[object GeneratorFunction]",scn="[object Proxy]";function ncn(s){if(!Qln(s))return!1;var t=Xln(s);return t==ecn||t==tcn||t==Jln||t==scn}var _st=ncn;const Fl=kd(_st);var rcn=LC,acn=rcn["__core-js_shared__"],icn=acn,M9e=icn,N1t=function(){var s=/[^.]+$/.exec(M9e&&M9e.keys&&M9e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function ocn(s){return!!N1t&&N1t in s}var lcn=ocn,ccn=Function.prototype,dcn=ccn.toString;function ucn(s){if(s!=null){try{return dcn.call(s)}catch{}try{return s+""}catch{}}return""}var bHt=ucn,hcn=_st,mcn=lcn,pcn=OL,fcn=bHt,xcn=/[\\^$.*+?()[\]{}|]/g,gcn=/^\[object .+?Constructor\]$/,ycn=Function.prototype,vcn=Object.prototype,bcn=ycn.toString,_cn=vcn.hasOwnProperty,wcn=RegExp("^"+bcn.call(_cn).replace(xcn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jcn(s){if(!pcn(s)||mcn(s))return!1;var t=hcn(s)?wcn:gcn;return t.test(fcn(s))}var Ncn=jcn;function kcn(s,t){return s==null?void 0:s[t]}var Scn=kcn,Ccn=Ncn,Acn=Scn;function Ecn(s,t){var n=Acn(s,t);return Ccn(n)?n:void 0}var oz=Ecn,Tcn=oz,Mcn=Tcn(Object,"create"),hIe=Mcn,k1t=hIe;function Pcn(){this.__data__=k1t?k1t(null):{},this.size=0}var Lcn=Pcn;function Icn(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Dcn=Icn,Rcn=hIe,Fcn="__lodash_hash_undefined__",Ocn=Object.prototype,zcn=Ocn.hasOwnProperty;function Bcn(s){var t=this.__data__;if(Rcn){var n=t[s];return n===Fcn?void 0:n}return zcn.call(t,s)?t[s]:void 0}var $cn=Bcn,Ucn=hIe,qcn=Object.prototype,Vcn=qcn.hasOwnProperty;function Hcn(s){var t=this.__data__;return Ucn?t[s]!==void 0:Vcn.call(t,s)}var Gcn=Hcn,Wcn=hIe,Kcn="__lodash_hash_undefined__";function Ycn(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=Wcn&&t===void 0?Kcn:t,this}var Zcn=Ycn,Xcn=Lcn,Qcn=Dcn,Jcn=$cn,edn=Gcn,tdn=Zcn;function RW(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var ydn=gdn,vdn=mIe;function bdn(s,t){var n=this.__data__,r=vdn(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var _dn=bdn,wdn=rdn,jdn=hdn,Ndn=fdn,kdn=ydn,Sdn=_dn;function FW(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},TF=function(t){return g9(t)&&t.indexOf("%")===t.length-1},ni=function(t){return Kun(t)&&!zW(t)},Qun=function(t){return xc(t)},Sy=function(t){return ni(t)||g9(t)},Jun=0,lz=function(t){var n=++Jun;return"".concat(t||"").concat(n)},gb=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(!ni(t)&&!g9(t))return r;var i;if(TF(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return zW(i)&&(i=r),a&&i>n&&(i=n),i},O6=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},ehn=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 ohn(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 JHe(s){"@babel/helpers - typeof";return JHe=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},JHe(s)}var P1t={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"},iE=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},L1t=null,L9e=null,Mst=function s(t){if(t===L1t&&Array.isArray(L9e))return L9e;var n=[];return _.Children.forEach(t,function(r){xc(r)||(qun.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),L9e=n,L1t=t,n};function Cj(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return iE(a)}):r=[iE(t)],Mst(s).forEach(function(a){var i=Sj(a,"type.displayName")||Sj(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function Kw(s,t){var n=Cj(s,t);return n&&n[0]}var I1t=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!ni(r)||r<=0||!ni(a)||a<=0)},lhn=["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"],chn=function(t){return t&&t.type&&g9(t.type)&&lhn.indexOf(t.type)>=0},THt=function(t){return t&&JHe(t)==="object"&&"clipDot"in t},dhn=function(t,n,r,a){var i,l=(i=P9e==null?void 0:P9e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!Fl(t)&&(a&&l.includes(n)||nhn.includes(n))||r&&Tst.includes(n)},Go=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(_.isValidElement(t)&&(a=t.props),!DW(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;dhn((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},eGe=function s(t,n){if(t===n)return!0;var r=_.Children.count(t);if(r!==_.Children.count(n))return!1;if(r===0)return!0;if(r===1)return D1t(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 fhn(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 sGe(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=phn(s,mhn),u=a||{width:n,height:r,x:0,y:0},h=Sc("recharts-surface",i);return Ft.createElement("svg",tGe({},Go(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Ft.createElement("title",null,o),Ft.createElement("desc",null,c),t)}var xhn=["children","className"];function nGe(){return nGe=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 yhn(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 $d=Ft.forwardRef(function(s,t){var n=s.children,r=s.className,a=ghn(s,xhn),i=Sc("recharts-layer",r);return Ft.createElement("g",nGe({className:i},Go(a,!0),{ref:t}),n)}),NS=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:_hn(s,t,n)}var jhn=whn,Nhn="\\ud800-\\udfff",khn="\\u0300-\\u036f",Shn="\\ufe20-\\ufe2f",Chn="\\u20d0-\\u20ff",Ahn=khn+Shn+Chn,Ehn="\\ufe0e\\ufe0f",Thn="\\u200d",Mhn=RegExp("["+Thn+Nhn+Ahn+Ehn+"]");function Phn(s){return Mhn.test(s)}var MHt=Phn;function Lhn(s){return s.split("")}var Ihn=Lhn,PHt="\\ud800-\\udfff",Dhn="\\u0300-\\u036f",Rhn="\\ufe20-\\ufe2f",Fhn="\\u20d0-\\u20ff",Ohn=Dhn+Rhn+Fhn,zhn="\\ufe0e\\ufe0f",Bhn="["+PHt+"]",rGe="["+Ohn+"]",aGe="\\ud83c[\\udffb-\\udfff]",$hn="(?:"+rGe+"|"+aGe+")",LHt="[^"+PHt+"]",IHt="(?:\\ud83c[\\udde6-\\uddff]){2}",DHt="[\\ud800-\\udbff][\\udc00-\\udfff]",Uhn="\\u200d",RHt=$hn+"?",FHt="["+zhn+"]?",qhn="(?:"+Uhn+"(?:"+[LHt,IHt,DHt].join("|")+")"+FHt+RHt+")*",Vhn=FHt+RHt+qhn,Hhn="(?:"+[LHt+rGe+"?",rGe,IHt,DHt,Bhn].join("|")+")",Ghn=RegExp(aGe+"(?="+aGe+")|"+Hhn+Vhn,"g");function Whn(s){return s.match(Ghn)||[]}var Khn=Whn,Yhn=Ihn,Zhn=MHt,Xhn=Khn;function Qhn(s){return Zhn(s)?Xhn(s):Yhn(s)}var Jhn=Qhn,emn=jhn,tmn=MHt,smn=Jhn,nmn=NHt;function rmn(s){return function(t){t=nmn(t);var n=tmn(t)?smn(t):void 0,r=n?n[0]:t.charAt(0),a=n?emn(n,1).join(""):t.slice(1);return r[s]()+a}}var amn=rmn,imn=amn,omn=imn("toUpperCase"),lmn=omn;const CIe=kd(lmn);function Jm(s){return function(){return s}}const OHt=Math.cos,GEe=Math.sin,qS=Math.sqrt,WEe=Math.PI,AIe=2*WEe,iGe=Math.PI,oGe=2*iGe,YR=1e-6,cmn=oGe-YR;function zHt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return zHt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aYR)if(!(Math.abs(h*c-d*u)>YR)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-l,f=a-o,g=c*c+d*d,v=p*p+f*f,y=Math.sqrt(g),b=Math.sqrt(m),w=i*Math.tan((iGe-Math.acos((g+m-v)/(2*y*b)))/2),S=w/b,C=w/y;Math.abs(S-1)>YR&&this._append`L${t+S*u},${n+S*h}`,this._append`A${i},${i},0,0,${+(h*p>u*f)},${this._x1=t+C*c},${this._y1=n+C*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,m=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>YR||Math.abs(this._y1-u)>YR)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%oGe+oGe),m>cmn?this._append`A${r},${r},0,1,${h},${t-o},${n-c}A${r},${r},0,1,${h},${this._x1=d},${this._y1=u}`:m>YR&&this._append`A${r},${r},0,${+(m>=iGe)},${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 Pst(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 umn(t)}function Lst(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function BHt(s){this._context=s}BHt.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 EIe(s){return new BHt(s)}function $Ht(s){return s[0]}function UHt(s){return s[1]}function qHt(s,t){var n=Jm(!0),r=null,a=EIe,i=null,l=Pst(o);s=typeof s=="function"?s:s===void 0?$Ht:Jm(s),t=typeof t=="function"?t:t===void 0?UHt:Jm(t);function o(c){var d,u=(c=Lst(c)).length,h,m=!1,p;for(r==null&&(i=a(p=l())),d=0;d<=u;++d)!(d=p;--f)o.point(w[f],S[f]);o.lineEnd(),o.areaEnd()}y&&(w[m]=+s(v,m,h),S[m]=+t(v,m,h),o.point(r?+r(v,m,h):w[m],n?+n(v,m,h):S[m]))}if(b)return o=null,b+""||null}function u(){return qHt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Jm(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Jm(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Jm(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Jm(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Jm(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Jm(+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:Jm(!!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 VHt{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 hmn(s){return new VHt(s,!0)}function mmn(s){return new VHt(s,!1)}const Ist={draw(s,t){const n=qS(t/WEe);s.moveTo(n,0),s.arc(0,0,n,0,AIe)}},pmn={draw(s,t){const n=qS(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()}},HHt=qS(1/3),fmn=HHt*2,xmn={draw(s,t){const n=qS(t/fmn),r=n*HHt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},gmn={draw(s,t){const n=qS(t),r=-n/2;s.rect(r,r,n,n)}},ymn=.8908130915292852,GHt=GEe(WEe/10)/GEe(7*WEe/10),vmn=GEe(AIe/10)*GHt,bmn=-OHt(AIe/10)*GHt,_mn={draw(s,t){const n=qS(t*ymn),r=vmn*n,a=bmn*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=AIe*i/5,o=OHt(l),c=GEe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},I9e=qS(3),wmn={draw(s,t){const n=-qS(t/(I9e*3));s.moveTo(0,n*2),s.lineTo(-I9e*n,-n),s.lineTo(I9e*n,-n),s.closePath()}},w2=-.5,j2=qS(3)/2,lGe=1/qS(12),jmn=(lGe/2+1)*3,Nmn={draw(s,t){const n=qS(t/jmn),r=n/2,a=n*lGe,i=r,l=n*lGe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(w2*r-j2*a,j2*r+w2*a),s.lineTo(w2*i-j2*l,j2*i+w2*l),s.lineTo(w2*o-j2*c,j2*o+w2*c),s.lineTo(w2*r+j2*a,w2*a-j2*r),s.lineTo(w2*i+j2*l,w2*l-j2*i),s.lineTo(w2*o+j2*c,w2*c-j2*o),s.closePath()}};function kmn(s,t){let n=null,r=Pst(a);s=typeof s=="function"?s:Jm(s||Ist),t=typeof t=="function"?t:Jm(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:Jm(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Jm(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function KEe(){}function YEe(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 WHt(s){this._context=s}WHt.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:YEe(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:YEe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Smn(s){return new WHt(s)}function KHt(s){this._context=s}KHt.prototype={areaStart:KEe,areaEnd:KEe,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:YEe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Cmn(s){return new KHt(s)}function YHt(s){this._context=s}YHt.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:YEe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Amn(s){return new YHt(s)}function ZHt(s){this._context=s}ZHt.prototype={areaStart:KEe,areaEnd:KEe,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 Emn(s){return new ZHt(s)}function F1t(s){return s<0?-1:1}function O1t(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(F1t(i)+F1t(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function z1t(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function D9e(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 ZEe(s){this._context=s}ZEe.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:D9e(this,this._t0,z1t(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,D9e(this,z1t(this,n=O1t(this,s,t)),n);break;default:D9e(this,this._t0,n=O1t(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function XHt(s){this._context=new QHt(s)}(XHt.prototype=Object.create(ZEe.prototype)).point=function(s,t){ZEe.prototype.point.call(this,t,s)};function QHt(s){this._context=s}QHt.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 Tmn(s){return new ZEe(s)}function Mmn(s){return new XHt(s)}function JHt(s){this._context=s}JHt.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=B1t(s),a=B1t(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 Lmn(s){return new TIe(s,.5)}function Imn(s){return new TIe(s,0)}function Dmn(s){return new TIe(s,1)}function QH(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 Rmn(s,t){return s[t]}function Fmn(s){const t=[];return t.key=s,t}function Omn(){var s=Jm([]),t=cGe,n=QH,r=Rmn;function a(i){var l=Array.from(s.apply(this,arguments),Fmn),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 Wmn(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 eGt={symbolCircle:Ist,symbolCross:pmn,symbolDiamond:xmn,symbolSquare:gmn,symbolStar:_mn,symbolTriangle:wmn,symbolWye:Nmn},Kmn=Math.PI/180,Ymn=function(t){var n="symbol".concat(CIe(t));return eGt[n]||Ist},Zmn=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*Kmn;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}},Xmn=function(t,n){eGt["symbol".concat(CIe(t))]=n},Dst=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=Gmn(t,Umn),d=U1t(U1t({},c),{},{type:r,size:i,sizeType:o}),u=function(){var v=Ymn(r),y=kmn().type(v).size(Zmn(i,o,r));return y()},h=d.className,m=d.cx,p=d.cy,f=Go(d,!0);return m===+m&&p===+p&&i===+i?Ft.createElement("path",dGe({},f,{className:Sc("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:u()})):null};Dst.registerSymbol=Xmn;function JH(s){"@babel/helpers - typeof";return JH=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},JH(s)}function uGe(){return uGe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=p.inactive?d:p.color;return Ft.createElement("li",uGe({className:v,style:h,key:"legend-item-".concat(f)},y9(r.props,p,f)),Ft.createElement(sGe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(p)),Ft.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},g?g(y,p,f):y))})}},{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 Ft.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(_.PureComponent);Ute(Rst,"displayName","Legend");Ute(Rst,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var opn=pIe;function lpn(){this.__data__=new opn,this.size=0}var cpn=lpn;function dpn(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var upn=dpn;function hpn(s){return this.__data__.get(s)}var mpn=hpn;function ppn(s){return this.__data__.has(s)}var fpn=ppn,xpn=pIe,gpn=jst,ypn=Nst,vpn=200;function bpn(s,t){var n=this.__data__;if(n instanceof xpn){var r=n.__data__;if(!gpn||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,m=!0,p=n&Upn?new Opn:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=Gfn}var Bst=Wfn,Kfn=GE,Yfn=Bst,Zfn=WE,Xfn="[object Arguments]",Qfn="[object Array]",Jfn="[object Boolean]",exn="[object Date]",txn="[object Error]",sxn="[object Function]",nxn="[object Map]",rxn="[object Number]",axn="[object Object]",ixn="[object RegExp]",oxn="[object Set]",lxn="[object String]",cxn="[object WeakMap]",dxn="[object ArrayBuffer]",uxn="[object DataView]",hxn="[object Float32Array]",mxn="[object Float64Array]",pxn="[object Int8Array]",fxn="[object Int16Array]",xxn="[object Int32Array]",gxn="[object Uint8Array]",yxn="[object Uint8ClampedArray]",vxn="[object Uint16Array]",bxn="[object Uint32Array]",kp={};kp[hxn]=kp[mxn]=kp[pxn]=kp[fxn]=kp[xxn]=kp[gxn]=kp[yxn]=kp[vxn]=kp[bxn]=!0;kp[Xfn]=kp[Qfn]=kp[dxn]=kp[Jfn]=kp[uxn]=kp[exn]=kp[txn]=kp[sxn]=kp[nxn]=kp[rxn]=kp[axn]=kp[ixn]=kp[oxn]=kp[lxn]=kp[cxn]=!1;function _xn(s){return Zfn(s)&&Yfn(s.length)&&!!kp[Kfn(s)]}var wxn=_xn;function jxn(s){return function(t){return s(t)}}var uGt=jxn,eTe={exports:{}};eTe.exports;(function(s,t){var n=yHt,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})(eTe,eTe.exports);var Nxn=eTe.exports,kxn=wxn,Sxn=uGt,Y1t=Nxn,Z1t=Y1t&&Y1t.isTypedArray,Cxn=Z1t?Sxn(Z1t):kxn,hGt=Cxn,Axn=Mfn,Exn=Ost,Txn=J_,Mxn=dGt,Pxn=zst,Lxn=hGt,Ixn=Object.prototype,Dxn=Ixn.hasOwnProperty;function Rxn(s,t){var n=Txn(s),r=!n&&Exn(s),a=!n&&!r&&Mxn(s),i=!n&&!r&&!a&&Lxn(s),l=n||r||a||i,o=l?Axn(s.length,String):[],c=o.length;for(var d in s)(t||Dxn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Pxn(d,c)))&&o.push(d);return o}var Fxn=Rxn,Oxn=Object.prototype;function zxn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||Oxn;return s===n}var Bxn=zxn;function $xn(s,t){return function(n){return s(t(n))}}var mGt=$xn,Uxn=mGt,qxn=Uxn(Object.keys,Object),Vxn=qxn,Hxn=Bxn,Gxn=Vxn,Wxn=Object.prototype,Kxn=Wxn.hasOwnProperty;function Yxn(s){if(!Hxn(s))return Gxn(s);var t=[];for(var n in Object(s))Kxn.call(s,n)&&n!="constructor"&&t.push(n);return t}var Zxn=Yxn,Xxn=_st,Qxn=Bst;function Jxn(s){return s!=null&&Qxn(s.length)&&!Xxn(s)}var Iae=Jxn,egn=Fxn,tgn=Zxn,sgn=Iae;function ngn(s){return sgn(s)?egn(s):tgn(s)}var MIe=ngn,rgn=vfn,agn=Efn,ign=MIe;function ogn(s){return rgn(s,ign,agn)}var lgn=ogn,X1t=lgn,cgn=1,dgn=Object.prototype,ugn=dgn.hasOwnProperty;function hgn(s,t,n,r,a,i){var l=n&cgn,o=X1t(s),c=o.length,d=X1t(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:ugn.call(t,m)))return!1}var p=i.get(s),f=i.get(t);if(p&&f)return p==t&&f==s;var g=!0;i.set(s,t),i.set(t,s);for(var v=l;++h-1}var d0n=c0n;function u0n(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=S0n){var d=t?null:N0n(s);if(d)return k0n(d);l=!1,a=j0n,c=new b0n}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function U0n(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 q0n(s){return s.value}function V0n(s,t){if(Ft.isValidElement(s))return Ft.cloneElement(s,t);if(typeof s=="function")return Ft.createElement(s,t);t.ref;var n=$0n(t,L0n);return Ft.createElement(Rst,n)}var mbt=1,Bq=function(s){function t(){var n;I0n(this,t);for(var r=arguments.length,a=new Array(r),i=0;imbt||Math.abs(a.height-this.lastBoundingBox.height)>mbt)&&(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?j3({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,m;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var p=this.getBBoxSnapshot();h={left:((d||0)-p.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var f=this.getBBoxSnapshot();m={top:((u||0)-f.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return j3(j3({},h),m)}},{key:"render",value:function(){var r=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,u=a.payload,h=j3(j3({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Ft.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(p){r.wrapperNode=p}},V0n(i,j3(j3({},this.props),{},{payload:bGt(u,d,q0n)})))}}],[{key:"getWithHeight",value:function(r,a){var i=j3(j3({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&ni(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(_.PureComponent);PIe(Bq,"displayName","Legend");PIe(Bq,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var pbt=Lae,H0n=Ost,G0n=J_,fbt=pbt?pbt.isConcatSpreadable:void 0;function W0n(s){return G0n(s)||H0n(s)||!!(fbt&&s&&s[fbt])}var K0n=W0n,Y0n=lGt,Z0n=K0n;function jGt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=Z0n),a||(a=[]);++i0&&n(o)?t>1?jGt(o,t-1,n,r,a):Y0n(a,o):r||(a[a.length]=o)}return a}var NGt=jGt;function X0n(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 Q0n=X0n,J0n=Q0n,evn=J0n(),tvn=evn,svn=tvn,nvn=MIe;function rvn(s,t){return s&&svn(s,t,nvn)}var kGt=rvn,avn=Iae;function ivn(s,t){return function(n,r){if(n==null)return n;if(!avn(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 bvn=vvn,z9e=Sst,_vn=Cst,wvn=IC,jvn=SGt,Nvn=fvn,kvn=uGt,Svn=bvn,Cvn=UW,Avn=J_;function Evn(s,t,n){t.length?t=z9e(t,function(i){return Avn(i)?function(l){return _vn(l,i.length===1?i[0]:i)}:i}):t=[Cvn];var r=-1;t=z9e(t,kvn(wvn));var a=jvn(s,function(i,l,o){var c=z9e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return Nvn(a,function(i,l){return Svn(i,l,n)})}var Tvn=Evn;function Mvn(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 Pvn=Mvn,Lvn=Pvn,gbt=Math.max;function Ivn(s,t,n){return t=gbt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=gbt(r.length-t,0),l=Array(i);++a0){if(++t>=Vvn)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Kvn=Wvn,Yvn=qvn,Zvn=Kvn,Xvn=Zvn(Yvn),Qvn=Xvn,Jvn=UW,e1n=Dvn,t1n=Qvn;function s1n(s,t){return t1n(e1n(s,t,Jvn),s+"")}var n1n=s1n,r1n=wst,a1n=Iae,i1n=zst,o1n=OL;function l1n(s,t,n){if(!o1n(n))return!1;var r=typeof t;return(r=="number"?a1n(n)&&i1n(t,n.length):r=="string"&&t in n)?r1n(n[t],s):!1}var LIe=l1n,c1n=NGt,d1n=Tvn,u1n=n1n,vbt=LIe,h1n=u1n(function(s,t){if(s==null)return[];var n=t.length;return n>1&&vbt(s,t[0],t[1])?t=[]:n>2&&vbt(t[0],t[1],t[2])&&(t=[t[0]]),d1n(s,c1n(t,1),[])}),m1n=h1n;const qst=kd(m1n);function qte(s){"@babel/helpers - typeof";return qte=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},qte(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=t.x),"".concat(dZ,"-left"),ni(n)&&t&&ni(t.x)&&n=t.y),"".concat(dZ,"-top"),ni(r)&&t&&ni(t.y)&&rg?Math.max(u,c[r]):Math.max(h,c[r])}function A1n(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 E1n(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=wbt({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=wbt({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=A1n({translateX:u,translateY:h,useTranslate3d:o})):d=S1n,{cssProperties:d,cssClasses:C1n({translateX:u,translateY:h,coordinate:n})}}function tG(s){"@babel/helpers - typeof";return tG=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},tG(s)}function jbt(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 Nbt(s){for(var t=1;tkbt||Math.abs(r.height-this.state.lastBoundingBox.height)>kbt)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,p=a.offset,f=a.position,g=a.reverseDirection,v=a.useTranslate3d,y=a.viewBox,b=a.wrapperStyle,w=E1n({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:p,position:f,reverseDirection:g,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:y}),S=w.cssClasses,C=w.cssProperties,E=Nbt(Nbt({transition:m&&i?"transform ".concat(o,"ms ").concat(c):void 0},C),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},b);return Ft.createElement("div",{tabIndex:-1,className:S,style:E,ref:function(M){r.wrapperNode=M}},d)}}])}(_.PureComponent),z1n=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},kS={isSsr:z1n(),get:function(t){return kS[t]},set:function(t,n){if(typeof t=="string")kS[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){kS[a]=t[a]})}}};function sG(s){"@babel/helpers - typeof";return sG=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},sG(s)}function Sbt(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 Cbt(s){for(var t=1;t0;return Ft.createElement(O1n,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:E,offset:p,position:v,reverseDirection:y,useTranslate3d:b,viewBox:w,wrapperStyle:S},Y1n(d,Cbt(Cbt({},this.props),{},{payload:C})))}}])}(_.PureComponent);Vst(Rf,"displayName","Tooltip");Vst(Rf,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!kS.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 Z1n=LC,X1n=function(){return Z1n.Date.now()},Q1n=X1n,J1n=/\s/;function ebn(s){for(var t=s.length;t--&&J1n.test(s.charAt(t)););return t}var tbn=ebn,sbn=tbn,nbn=/^\s+/;function rbn(s){return s&&s.slice(0,sbn(s)+1).replace(nbn,"")}var abn=rbn,ibn=abn,Abt=OL,obn=IW,Ebt=NaN,lbn=/^[-+]0x[0-9a-f]+$/i,cbn=/^0b[01]+$/i,dbn=/^0o[0-7]+$/i,ubn=parseInt;function hbn(s){if(typeof s=="number")return s;if(obn(s))return Ebt;if(Abt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Abt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=ibn(s);var n=cbn.test(s);return n||dbn.test(s)?ubn(s.slice(2),n?2:8):lbn.test(s)?Ebt:+s}var PGt=hbn,mbn=OL,$9e=Q1n,Tbt=PGt,pbn="Expected a function",fbn=Math.max,xbn=Math.min;function gbn(s,t,n){var r,a,i,l,o,c,d=0,u=!1,h=!1,m=!0;if(typeof s!="function")throw new TypeError(pbn);t=Tbt(t)||0,mbn(n)&&(u=!!n.leading,h="maxWait"in n,i=h?fbn(Tbt(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function p(E){var P=r,M=a;return r=a=void 0,d=E,l=s.apply(M,P),l}function f(E){return d=E,o=setTimeout(y,t),u?p(E):l}function g(E){var P=E-c,M=E-d,I=t-P;return h?xbn(I,i-M):I}function v(E){var P=E-c,M=E-d;return c===void 0||P>=t||P<0||h&&M>=i}function y(){var E=$9e();if(v(E))return b(E);o=setTimeout(y,g(E))}function b(E){return o=void 0,m&&r?p(E):(r=a=void 0,l)}function w(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function S(){return o===void 0?l:b($9e())}function C(){var E=$9e(),P=v(E);if(r=arguments,a=this,c=E,P){if(o===void 0)return f(c);if(h)return clearTimeout(o),o=setTimeout(y,t),p(c)}return o===void 0&&(o=setTimeout(y,t)),l}return C.cancel=w,C.flush=S,C}var ybn=gbn,vbn=ybn,bbn=OL,_bn="Expected a function";function wbn(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(_bn);return bbn(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),vbn(s,t,{leading:r,maxWait:t,trailing:a})}var jbn=wbn;const LGt=kd(jbn);function Hte(s){"@babel/helpers - typeof";return Hte=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},Hte(s)}function Mbt(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 Tce(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(G=LGt(G,g,{trailing:!0,leading:!1}));var V=new ResizeObserver(G),H=C.current.getBoundingClientRect(),K=H.width,Z=H.height;return F(K,Z),V.observe(C.current),function(){V.disconnect()}},[F,g]);var q=_.useMemo(function(){var G=I.containerWidth,V=I.containerHeight;if(G<0||V<0)return null;NS(TF(l)||TF(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),NS(!n||n>0,"The aspect(%s) must be greater than zero.",n);var H=TF(l)?G:l,K=TF(c)?V:c;n&&n>0&&(H?K=H/n:K&&(H=K*n),m&&K>m&&(K=m)),NS(H>0||K>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.`,H,K,l,c,u,h,n);var Z=!Array.isArray(p)&&iE(p.type).endsWith("Chart");return Ft.Children.map(p,function(oe){return Ft.isValidElement(oe)?_.cloneElement(oe,Tce({width:H,height:K},Z?{style:Tce({height:"100%",width:"100%",maxHeight:K,maxWidth:H},oe.props.style)}:{})):oe})},[n,p,c,m,h,u,I,l]);return Ft.createElement("div",{id:v?"".concat(v):void 0,className:Sc("recharts-responsive-container",y),style:Tce(Tce({},S),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:C},q)}),cz=function(t){return null};cz.displayName="Cell";function Gte(s){"@babel/helpers - typeof";return Gte=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},Gte(s)}function Lbt(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;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||kS.isSsr)return{width:0,height:0};var r=Fbn(n),a=JSON.stringify({text:t,copyStyle:r});if(qB.widthCache[a])return qB.widthCache[a];try{var i=document.getElementById(Ibt);i||(i=document.createElement("span"),i.setAttribute("id",Ibt),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=jGe(jGe({},Rbn),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return qB.widthCache[a]=c,++qB.cacheCount>Dbn&&(qB.cacheCount=0,qB.widthCache={}),c}catch{return{width:0,height:0}}},Obn=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function Wte(s){"@babel/helpers - typeof";return Wte=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},Wte(s)}function rTe(s,t){return Ubn(s)||$bn(s,t)||Bbn(s,t)||zbn()}function zbn(){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 Bbn(s,t){if(s){if(typeof s=="string")return Dbt(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 Dbt(s,t)}}function Dbt(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 s_n(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 $bt(s,t){return i_n(s)||a_n(s,t)||r_n(s,t)||n_n()}function n_n(){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 r_n(s,t){if(s){if(typeof s=="string")return Ubt(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 Ubt(s,t)}}function Ubt(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 H.reduce(function(K,Z){var oe=Z.word,re=Z.width,ae=K[K.length-1];if(ae&&(a==null||i||ae.width+re+rZ.width?K:Z})};if(!u)return p;for(var g="…",v=function(H){var K=h.slice(0,H),Z=FGt({breakAll:d,style:c,children:K+g}).wordsWithComputedWidth,oe=m(Z),re=oe.length>l||f(oe).width>Number(a);return[re,oe]},y=0,b=h.length-1,w=0,S;y<=b&&w<=h.length-1;){var C=Math.floor((y+b)/2),E=C-1,P=v(E),M=$bt(P,2),I=M[0],D=M[1],F=v(C),q=$bt(F,1),G=q[0];if(!I&&!G&&(y=C+1),I&&G&&(b=C-1),!I&&G){S=D;break}w++}return S||p},qbt=function(t){var n=xc(t)?[]:t.toString().split(RGt);return[{words:n}]},l_n=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!kS.isSsr){var c,d,u=FGt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return qbt(a);return o_n({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return qbt(a)},Vbt="#808080",v9=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,p=m===void 0?"start":m,f=t.verticalAnchor,g=f===void 0?"end":f,v=t.fill,y=v===void 0?Vbt:v,b=Bbt(t,e_n),w=_.useMemo(function(){return l_n({breakAll:b.breakAll,children:b.children,maxLines:b.maxLines,scaleToFit:h,style:b.style,width:b.width})},[b.breakAll,b.children,b.maxLines,h,b.style,b.width]),S=b.dx,C=b.dy,E=b.angle,P=b.className,M=b.breakAll,I=Bbt(b,t_n);if(!Sy(r)||!Sy(i))return null;var D=r+(ni(S)?S:0),F=i+(ni(C)?C:0),q;switch(g){case"start":q=U9e("calc(".concat(d,")"));break;case"middle":q=U9e("calc(".concat((w.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:q=U9e("calc(".concat(w.length-1," * -").concat(o,")"));break}var G=[];if(h){var V=w[0].width,H=b.width;G.push("scale(".concat((ni(H)?H/V:1)/V,")"))}return E&&G.push("rotate(".concat(E,", ").concat(D,", ").concat(F,")")),G.length&&(I.transform=G.join(" ")),Ft.createElement("text",NGe({},Go(I,!0),{x:D,y:F,className:Sc("recharts-text",P),textAnchor:p,fill:y.includes("url")?Vbt:y}),w.map(function(K,Z){var oe=K.words.join(M?"":" ");return Ft.createElement("tspan",{x:D,dy:Z===0?q:o,key:"".concat(oe,"-").concat(Z)},oe)}))};function CP(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function c_n(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function Hst(s){let t,n,r;s.length!==2?(t=CP,n=(o,c)=>CP(s(o),c),r=(o,c)=>s(o)-c):(t=s===CP||s===c_n?s:d_n,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 d_n(){return 0}function OGt(s){return s===null?NaN:+s}function*u_n(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const h_n=Hst(CP),Dae=h_n.right;Hst(OGt).center;class Hbt extends Map{constructor(t,n=f_n){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(Gbt(this,t))}has(t){return super.has(Gbt(this,t))}set(t,n){return super.set(m_n(this,t),n)}delete(t){return super.delete(p_n(this,t))}}function Gbt({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function m_n({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function p_n({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function f_n(s){return s!==null&&typeof s=="object"?s.valueOf():s}function x_n(s=CP){if(s===CP)return zGt;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 zGt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const g_n=Math.sqrt(50),y_n=Math.sqrt(10),v_n=Math.sqrt(2);function aTe(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>=g_n?10:i>=y_n?5:i>=v_n?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 Kbt(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function BGt(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?zGt:x_n(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),m=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),p=Math.max(n,Math.floor(t-d*h/c+m)),f=Math.min(r,Math.floor(t+(c-d)*h/c+m));BGt(s,t,p,f,a)}const i=s[t];let l=n,o=r;for(uZ(s,n,t),a(s[r],i)>0&&uZ(s,n,r);l0;)--o}a(s[n],i)===0?uZ(s,n,o):(++o,uZ(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function uZ(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function b_n(s,t,n){if(s=Float64Array.from(u_n(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return Kbt(s);if(t>=1)return Wbt(s);var r,a=(r-1)*t,i=Math.floor(a),l=Wbt(BGt(s,i).subarray(0,i+1)),o=Kbt(s.subarray(i+1));return l+(o-l)*(a-i)}}function __n(s,t,n=OGt){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 w_n(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?Pce(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Pce(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=N_n.exec(s))?new A_(t[1],t[2],t[3],1):(t=k_n.exec(s))?new A_(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=S_n.exec(s))?Pce(t[1],t[2],t[3],t[4]):(t=C_n.exec(s))?Pce(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=A_n.exec(s))?t_t(t[1],t[2]/100,t[3]/100,1):(t=E_n.exec(s))?t_t(t[1],t[2]/100,t[3]/100,t[4]):Ybt.hasOwnProperty(s)?Qbt(Ybt[s]):s==="transparent"?new A_(NaN,NaN,NaN,0):null}function Qbt(s){return new A_(s>>16&255,s>>8&255,s&255,1)}function Pce(s,t,n,r){return r<=0&&(s=t=n=NaN),new A_(s,t,n,r)}function P_n(s){return s instanceof Rae||(s=Xte(s)),s?(s=s.rgb(),new A_(s.r,s.g,s.b,s.opacity)):new A_}function EGe(s,t,n,r){return arguments.length===1?P_n(s):new A_(s,t,n,r??1)}function A_(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}Wst(A_,EGe,UGt(Rae,{brighter(s){return s=s==null?iTe:Math.pow(iTe,s),new A_(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?Yte:Math.pow(Yte,s),new A_(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new A_(I7(this.r),I7(this.g),I7(this.b),oTe(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:Jbt,formatHex:Jbt,formatHex8:L_n,formatRgb:e_t,toString:e_t}));function Jbt(){return`#${MF(this.r)}${MF(this.g)}${MF(this.b)}`}function L_n(){return`#${MF(this.r)}${MF(this.g)}${MF(this.b)}${MF((isNaN(this.opacity)?1:this.opacity)*255)}`}function e_t(){const s=oTe(this.opacity);return`${s===1?"rgb(":"rgba("}${I7(this.r)}, ${I7(this.g)}, ${I7(this.b)}${s===1?")":`, ${s})`}`}function oTe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function I7(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function MF(s){return s=I7(s),(s<16?"0":"")+s.toString(16)}function t_t(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new lS(s,t,n,r)}function qGt(s){if(s instanceof lS)return new lS(s.h,s.s,s.l,s.opacity);if(s instanceof Rae||(s=Xte(s)),!s)return new lS;if(s instanceof lS)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 lS(l,o,c,s.opacity)}function I_n(s,t,n,r){return arguments.length===1?qGt(s):new lS(s,t,n,r??1)}function lS(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}Wst(lS,I_n,UGt(Rae,{brighter(s){return s=s==null?iTe:Math.pow(iTe,s),new lS(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Yte:Math.pow(Yte,s),new lS(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 A_(q9e(s>=240?s-240:s+120,a,r),q9e(s,a,r),q9e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new lS(s_t(this.h),Lce(this.s),Lce(this.l),oTe(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=oTe(this.opacity);return`${s===1?"hsl(":"hsla("}${s_t(this.h)}, ${Lce(this.s)*100}%, ${Lce(this.l)*100}%${s===1?")":`, ${s})`}`}}));function s_t(s){return s=(s||0)%360,s<0?s+360:s}function Lce(s){return Math.max(0,Math.min(1,s||0))}function q9e(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 Kst=s=>()=>s;function D_n(s,t){return function(n){return s+n*t}}function R_n(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 F_n(s){return(s=+s)==1?VGt:function(t,n){return n-t?R_n(t,n,s):Kst(isNaN(t)?n:t)}}function VGt(s,t){var n=t-s;return n?D_n(s,n):Kst(isNaN(s)?t:s)}const n_t=function s(t){var n=F_n(t);function r(a,i){var l=n((a=EGe(a)).r,(i=EGe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=VGt(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 O_n(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:lTe(r,a)})),n=V9e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function Y_n(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?Z_n:Y_n,c=d=null,h}function h(m){return m==null||isNaN(m=+m)?i:(c||(c=o(s.map(r),t,n)))(r(l(m)))}return h.invert=function(m){return l(a((d||(d=o(t,s.map(r),lTe)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,cTe),u()):s.slice()},h.range=function(m){return arguments.length?(t=Array.from(m),u()):t.slice()},h.rangeRound=function(m){return t=Array.from(m),n=Yst,u()},h.clamp=function(m){return arguments.length?(l=m?!0:yb,u()):l!==yb},h.interpolate=function(m){return arguments.length?(n=m,u()):n},h.unknown=function(m){return arguments.length?(i=m,h):i},function(m,p){return r=m,a=p,u()}}function Zst(){return IIe()(yb,yb)}function X_n(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function dTe(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 nG(s){return s=dTe(Math.abs(s)),s?s[1]:NaN}function Q_n(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 J_n(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var ewn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Qte(s){if(!(t=ewn.exec(s)))throw new Error("invalid format: "+s);var t;return new Xst({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]})}Qte.prototype=Xst.prototype;function Xst(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+""}Xst.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 twn(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 HGt;function swn(s,t){var n=dTe(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(HGt=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")+dTe(s,Math.max(0,t+i-1))[0]}function a_t(s,t){var n=dTe(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 i_t={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:X_n,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)=>a_t(s*100,t),r:a_t,s:swn,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function o_t(s){return s}var l_t=Array.prototype.map,c_t=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function nwn(s){var t=s.grouping===void 0||s.thousands===void 0?o_t:Q_n(l_t.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?o_t:J_n(l_t.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=Qte(h);var m=h.fill,p=h.align,f=h.sign,g=h.symbol,v=h.zero,y=h.width,b=h.comma,w=h.precision,S=h.trim,C=h.type;C==="n"?(b=!0,C="g"):i_t[C]||(w===void 0&&(w=12),S=!0,C="g"),(v||m==="0"&&p==="=")&&(v=!0,m="0",p="=");var E=g==="$"?n:g==="#"&&/[boxX]/.test(C)?"0"+C.toLowerCase():"",P=g==="$"?r:/[%p]/.test(C)?l:"",M=i_t[C],I=/[defgprs%]/.test(C);w=w===void 0?6:/[gprs]/.test(C)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w));function D(F){var q=E,G=P,V,H,K;if(C==="c")G=M(F)+G,F="";else{F=+F;var Z=F<0||1/F<0;if(F=isNaN(F)?c:M(Math.abs(F),w),S&&(F=twn(F)),Z&&+F==0&&f!=="+"&&(Z=!1),q=(Z?f==="("?f:o:f==="-"||f==="("?"":f)+q,G=(C==="s"?c_t[8+HGt/3]:"")+G+(Z&&f==="("?")":""),I){for(V=-1,H=F.length;++VK||K>57){G=(K===46?a+F.slice(V+1):F.slice(V))+G,F=F.slice(0,V);break}}}b&&!v&&(F=t(F,1/0));var oe=q.length+F.length+G.length,re=oe>1)+q+F+G+re.slice(oe);break;default:F=re+q+F+G;break}return i(F)}return D.toString=function(){return h+""},D}function u(h,m){var p=d((h=Qte(h),h.type="f",h)),f=Math.max(-8,Math.min(8,Math.floor(nG(m)/3)))*3,g=Math.pow(10,-f),v=c_t[8+f/3];return function(y){return p(g*y)+v}}return{format:d,formatPrefix:u}}var Ice,Qst,GGt;rwn({thousands:",",grouping:[3],currency:["$",""]});function rwn(s){return Ice=nwn(s),Qst=Ice.format,GGt=Ice.formatPrefix,Ice}function awn(s){return Math.max(0,-nG(Math.abs(s)))}function iwn(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(nG(t)/3)))*3-nG(Math.abs(s)))}function own(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,nG(t)-nG(s))+1}function WGt(s,t,n,r){var a=CGe(s,t,n),i;switch(r=Qte(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=iwn(a,l))&&(r.precision=i),GGt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=own(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=awn(a))&&(r.precision=i-(r.type==="%")*2);break}}return Qst(r)}function zL(s){var t=s.domain;return s.ticks=function(n){var r=t();return kGe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return WGt(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=SGe(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 uTe(){var s=Zst();return s.copy=function(){return Fae(s,uTe())},KN.apply(s,arguments),zL(s)}function KGt(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,cTe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return KGt(s).unknown(t)},s=arguments.length?Array.from(s,cTe):[0,1],zL(n)}function YGt(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 hwn(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 h_t(s){return(t,n)=>-s(-t,n)}function Jst(s){const t=s(d_t,u_t),n=t.domain;let r=10,a,i;function l(){return a=hwn(r),i=uwn(r),n()[0]<0?(a=h_t(a),i=h_t(i),s(lwn,cwn)):s(d_t,u_t),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=p;++m)for(f=1;fu)break;y.push(g)}}else for(;m<=p;++m)for(f=r-1;f>=1;--f)if(g=m>0?f/i(-m):f*i(m),!(gu)break;y.push(g)}y.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=Qte(c)).precision==null&&(c.trim=!0),c=Qst(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(YGt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function ZGt(){const s=Jst(IIe()).domain([1,10]);return s.copy=()=>Fae(s,ZGt()).base(s.base()),KN.apply(s,arguments),s}function m_t(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function p_t(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function ent(s){var t=1,n=s(m_t(t),p_t(t));return n.constant=function(r){return arguments.length?s(m_t(t=+r),p_t(t)):t},zL(n)}function XGt(){var s=ent(IIe());return s.copy=function(){return Fae(s,XGt()).constant(s.constant())},KN.apply(s,arguments)}function f_t(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function mwn(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function pwn(s){return s<0?-s*s:s*s}function tnt(s){var t=s(yb,yb),n=1;function r(){return n===1?s(yb,yb):n===.5?s(mwn,pwn):s(f_t(n),f_t(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},zL(t)}function snt(){var s=tnt(IIe());return s.copy=function(){return Fae(s,snt()).exponent(s.exponent())},KN.apply(s,arguments),s}function fwn(){return snt.apply(null,arguments).exponent(.5)}function x_t(s){return Math.sign(s)*s*s}function xwn(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function QGt(){var s=Zst(),t=[0,1],n=!1,r;function a(i){var l=xwn(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(x_t(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,cTe)).map(x_t)),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 QGt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},KN.apply(a,arguments),zL(a)}function JGt(){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 eWt().domain([s,t]).range(a).unknown(i)},KN.apply(zL(l),arguments)}function tWt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Dae(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 tWt().domain(s).range(t).unknown(n)},KN.apply(a,arguments)}const H9e=new Date,G9e=new Date;function Uy(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(dUy(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)=>(H9e.setTime(+i),G9e.setTime(+l),s(H9e),s(G9e),Math.floor(n(H9e,G9e))),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 hTe=Uy(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);hTe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Uy(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):hTe);hTe.range;const $A=1e3,dN=$A*60,UA=dN*60,CE=UA*24,nnt=CE*7,g_t=CE*30,W9e=CE*365,PF=Uy(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*$A)},(s,t)=>(t-s)/$A,s=>s.getUTCSeconds());PF.range;const rnt=Uy(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*$A)},(s,t)=>{s.setTime(+s+t*dN)},(s,t)=>(t-s)/dN,s=>s.getMinutes());rnt.range;const ant=Uy(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*dN)},(s,t)=>(t-s)/dN,s=>s.getUTCMinutes());ant.range;const int=Uy(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*$A-s.getMinutes()*dN)},(s,t)=>{s.setTime(+s+t*UA)},(s,t)=>(t-s)/UA,s=>s.getHours());int.range;const ont=Uy(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*UA)},(s,t)=>(t-s)/UA,s=>s.getUTCHours());ont.range;const Oae=Uy(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*dN)/CE,s=>s.getDate()-1);Oae.range;const DIe=Uy(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/CE,s=>s.getUTCDate()-1);DIe.range;const sWt=Uy(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/CE,s=>Math.floor(s/CE));sWt.range;function dz(s){return Uy(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())*dN)/nnt)}const RIe=dz(0),mTe=dz(1),gwn=dz(2),ywn=dz(3),rG=dz(4),vwn=dz(5),bwn=dz(6);RIe.range;mTe.range;gwn.range;ywn.range;rG.range;vwn.range;bwn.range;function uz(s){return Uy(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)/nnt)}const FIe=uz(0),pTe=uz(1),_wn=uz(2),wwn=uz(3),aG=uz(4),jwn=uz(5),Nwn=uz(6);FIe.range;pTe.range;_wn.range;wwn.range;aG.range;jwn.range;Nwn.range;const lnt=Uy(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());lnt.range;const cnt=Uy(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());cnt.range;const AE=Uy(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());AE.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Uy(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)});AE.range;const EE=Uy(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());EE.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Uy(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)});EE.range;function nWt(s,t,n,r,a,i){const l=[[PF,1,$A],[PF,5,5*$A],[PF,15,15*$A],[PF,30,30*$A],[i,1,dN],[i,5,5*dN],[i,15,15*dN],[i,30,30*dN],[a,1,UA],[a,3,3*UA],[a,6,6*UA],[a,12,12*UA],[r,1,CE],[r,2,2*CE],[n,1,nnt],[t,1,g_t],[t,3,3*g_t],[s,1,W9e]];function o(d,u,h){const m=uv).right(l,m);if(p===l.length)return s.every(CGe(d/W9e,u/W9e,h));if(p===0)return hTe.every(Math.max(CGe(d,u,h),1));const[f,g]=l[m/l[p-1][2]53)return null;"w"in ke||(ke.w=1),"Z"in ke?(_e=Y9e(hZ(ke.y,0,1)),Ae=_e.getUTCDay(),_e=Ae>4||Ae===0?pTe.ceil(_e):pTe(_e),_e=DIe.offset(_e,(ke.V-1)*7),ke.y=_e.getUTCFullYear(),ke.m=_e.getUTCMonth(),ke.d=_e.getUTCDate()+(ke.w+6)%7):(_e=K9e(hZ(ke.y,0,1)),Ae=_e.getDay(),_e=Ae>4||Ae===0?mTe.ceil(_e):mTe(_e),_e=Oae.offset(_e,(ke.V-1)*7),ke.y=_e.getFullYear(),ke.m=_e.getMonth(),ke.d=_e.getDate()+(ke.w+6)%7)}else("W"in ke||"U"in ke)&&("w"in ke||(ke.w="u"in ke?ke.u%7:"W"in ke?1:0),Ae="Z"in ke?Y9e(hZ(ke.y,0,1)).getUTCDay():K9e(hZ(ke.y,0,1)).getDay(),ke.m=0,ke.d="W"in ke?(ke.w+6)%7+ke.W*7-(Ae+5)%7:ke.w+ke.U*7-(Ae+6)%7);return"Z"in ke?(ke.H+=ke.Z/100|0,ke.M+=ke.Z%100,Y9e(ke)):K9e(ke)}}function M(Ne,Pe,Oe,ke){for(var Ve=0,_e=Pe.length,Ae=Oe.length,Se,We;Ve<_e;){if(ke>=Ae)return-1;if(Se=Pe.charCodeAt(Ve++),Se===37){if(Se=Pe.charAt(Ve++),We=C[Se in y_t?Pe.charAt(Ve++):Se],!We||(ke=We(Ne,Oe,ke))<0)return-1}else if(Se!=Oe.charCodeAt(ke++))return-1}return ke}function I(Ne,Pe,Oe){var ke=d.exec(Pe.slice(Oe));return ke?(Ne.p=u.get(ke[0].toLowerCase()),Oe+ke[0].length):-1}function D(Ne,Pe,Oe){var ke=p.exec(Pe.slice(Oe));return ke?(Ne.w=f.get(ke[0].toLowerCase()),Oe+ke[0].length):-1}function F(Ne,Pe,Oe){var ke=h.exec(Pe.slice(Oe));return ke?(Ne.w=m.get(ke[0].toLowerCase()),Oe+ke[0].length):-1}function q(Ne,Pe,Oe){var ke=y.exec(Pe.slice(Oe));return ke?(Ne.m=b.get(ke[0].toLowerCase()),Oe+ke[0].length):-1}function G(Ne,Pe,Oe){var ke=g.exec(Pe.slice(Oe));return ke?(Ne.m=v.get(ke[0].toLowerCase()),Oe+ke[0].length):-1}function V(Ne,Pe,Oe){return M(Ne,t,Pe,Oe)}function H(Ne,Pe,Oe){return M(Ne,n,Pe,Oe)}function K(Ne,Pe,Oe){return M(Ne,r,Pe,Oe)}function Z(Ne){return l[Ne.getDay()]}function oe(Ne){return i[Ne.getDay()]}function re(Ne){return c[Ne.getMonth()]}function ae(Ne){return o[Ne.getMonth()]}function J(Ne){return a[+(Ne.getHours()>=12)]}function te(Ne){return 1+~~(Ne.getMonth()/3)}function ce(Ne){return l[Ne.getUTCDay()]}function ve(Ne){return i[Ne.getUTCDay()]}function me(Ne){return c[Ne.getUTCMonth()]}function he(Ne){return o[Ne.getUTCMonth()]}function ge(Ne){return a[+(Ne.getUTCHours()>=12)]}function Ee(Ne){return 1+~~(Ne.getUTCMonth()/3)}return{format:function(Ne){var Pe=E(Ne+="",w);return Pe.toString=function(){return Ne},Pe},parse:function(Ne){var Pe=P(Ne+="",!1);return Pe.toString=function(){return Ne},Pe},utcFormat:function(Ne){var Pe=E(Ne+="",S);return Pe.toString=function(){return Ne},Pe},utcParse:function(Ne){var Pe=P(Ne+="",!0);return Pe.toString=function(){return Ne},Pe}}}var y_t={"-":"",_:" ",0:"0"},L0=/^\s*\d+/,Twn=/^%/,Mwn=/[\\^$*+?|[\]().{}]/g;function Wu(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function Lwn(s,t,n){var r=L0.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function Iwn(s,t,n){var r=L0.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function Dwn(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function Rwn(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function Fwn(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function v_t(s,t,n){var r=L0.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function b_t(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Own(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 zwn(s,t,n){var r=L0.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function Bwn(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function __t(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function $wn(s,t,n){var r=L0.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function w_t(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function Uwn(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function qwn(s,t,n){var r=L0.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function Vwn(s,t,n){var r=L0.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function Hwn(s,t,n){var r=L0.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Gwn(s,t,n){var r=Twn.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function Wwn(s,t,n){var r=L0.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function Kwn(s,t,n){var r=L0.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function j_t(s,t){return Wu(s.getDate(),t,2)}function Ywn(s,t){return Wu(s.getHours(),t,2)}function Zwn(s,t){return Wu(s.getHours()%12||12,t,2)}function Xwn(s,t){return Wu(1+Oae.count(AE(s),s),t,3)}function rWt(s,t){return Wu(s.getMilliseconds(),t,3)}function Qwn(s,t){return rWt(s,t)+"000"}function Jwn(s,t){return Wu(s.getMonth()+1,t,2)}function ejn(s,t){return Wu(s.getMinutes(),t,2)}function tjn(s,t){return Wu(s.getSeconds(),t,2)}function sjn(s){var t=s.getDay();return t===0?7:t}function njn(s,t){return Wu(RIe.count(AE(s)-1,s),t,2)}function aWt(s){var t=s.getDay();return t>=4||t===0?rG(s):rG.ceil(s)}function rjn(s,t){return s=aWt(s),Wu(rG.count(AE(s),s)+(AE(s).getDay()===4),t,2)}function ajn(s){return s.getDay()}function ijn(s,t){return Wu(mTe.count(AE(s)-1,s),t,2)}function ojn(s,t){return Wu(s.getFullYear()%100,t,2)}function ljn(s,t){return s=aWt(s),Wu(s.getFullYear()%100,t,2)}function cjn(s,t){return Wu(s.getFullYear()%1e4,t,4)}function djn(s,t){var n=s.getDay();return s=n>=4||n===0?rG(s):rG.ceil(s),Wu(s.getFullYear()%1e4,t,4)}function ujn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Wu(t/60|0,"0",2)+Wu(t%60,"0",2)}function N_t(s,t){return Wu(s.getUTCDate(),t,2)}function hjn(s,t){return Wu(s.getUTCHours(),t,2)}function mjn(s,t){return Wu(s.getUTCHours()%12||12,t,2)}function pjn(s,t){return Wu(1+DIe.count(EE(s),s),t,3)}function iWt(s,t){return Wu(s.getUTCMilliseconds(),t,3)}function fjn(s,t){return iWt(s,t)+"000"}function xjn(s,t){return Wu(s.getUTCMonth()+1,t,2)}function gjn(s,t){return Wu(s.getUTCMinutes(),t,2)}function yjn(s,t){return Wu(s.getUTCSeconds(),t,2)}function vjn(s){var t=s.getUTCDay();return t===0?7:t}function bjn(s,t){return Wu(FIe.count(EE(s)-1,s),t,2)}function oWt(s){var t=s.getUTCDay();return t>=4||t===0?aG(s):aG.ceil(s)}function _jn(s,t){return s=oWt(s),Wu(aG.count(EE(s),s)+(EE(s).getUTCDay()===4),t,2)}function wjn(s){return s.getUTCDay()}function jjn(s,t){return Wu(pTe.count(EE(s)-1,s),t,2)}function Njn(s,t){return Wu(s.getUTCFullYear()%100,t,2)}function kjn(s,t){return s=oWt(s),Wu(s.getUTCFullYear()%100,t,2)}function Sjn(s,t){return Wu(s.getUTCFullYear()%1e4,t,4)}function Cjn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?aG(s):aG.ceil(s),Wu(s.getUTCFullYear()%1e4,t,4)}function Ajn(){return"+0000"}function k_t(){return"%"}function S_t(s){return+s}function C_t(s){return Math.floor(+s/1e3)}var VB,lWt,cWt;Ejn({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 Ejn(s){return VB=Ewn(s),lWt=VB.format,VB.parse,cWt=VB.utcFormat,VB.utcParse,VB}function Tjn(s){return new Date(s)}function Mjn(s){return s instanceof Date?+s:+new Date(+s)}function dnt(s,t,n,r,a,i,l,o,c,d){var u=Zst(),h=u.invert,m=u.domain,p=d(".%L"),f=d(":%S"),g=d("%I:%M"),v=d("%I %p"),y=d("%a %d"),b=d("%b %d"),w=d("%B"),S=d("%Y");function C(E){return(c(E)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>b_n(s,i/r))},n.copy=function(){return mWt(t).domain(s)},KE.apply(n,arguments)}function zIe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=yb,u,h=!1,m;function p(g){return isNaN(g=+g)?m:(g=.5+((g=+u(g))-i)*(r*gt}var gWt=Ojn,zjn=BIe,Bjn=gWt,$jn=UW;function Ujn(s){return s&&s.length?zjn(s,$jn,Bjn):void 0}var qjn=Ujn;const DM=kd(qjn);function Vjn(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};yo.decimalPlaces=yo.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*Ap;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};yo.dividedBy=yo.div=function(s){return oE(this,new this.constructor(s))};yo.dividedToIntegerBy=yo.idiv=function(s){var t=this,n=t.constructor;return Dm(oE(t,new n(s),0,1),n.precision)};yo.equals=yo.eq=function(s){return!this.cmp(s)};yo.exponent=function(){return Vg(this)};yo.greaterThan=yo.gt=function(s){return this.cmp(s)>0};yo.greaterThanOrEqualTo=yo.gte=function(s){return this.cmp(s)>=0};yo.isInteger=yo.isint=function(){return this.e>this.d.length-2};yo.isNegative=yo.isneg=function(){return this.s<0};yo.isPositive=yo.ispos=function(){return this.s>0};yo.isZero=function(){return this.s===0};yo.lessThan=yo.lt=function(s){return this.cmp(s)<0};yo.lessThanOrEqualTo=yo.lte=function(s){return this.cmp(s)<1};yo.logarithm=yo.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(nj))throw Error(IN+"NaN");if(n.s<1)throw Error(IN+(n.s?"NaN":"-Infinity"));return n.eq(nj)?new r(0):(af=!1,t=oE(Jte(n,i),Jte(s,i),i),af=!0,Dm(t,a))};yo.minus=yo.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?wWt(t,s):bWt(t,(s.s=-s.s,s))};yo.modulo=yo.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(IN+"NaN");return n.s?(af=!1,t=oE(n,s,0,1).times(s),af=!0,n.minus(t)):Dm(new r(n),a)};yo.naturalExponential=yo.exp=function(){return _Wt(this)};yo.naturalLogarithm=yo.ln=function(){return Jte(this)};yo.negated=yo.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};yo.plus=yo.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?bWt(t,s):wWt(t,(s.s=-s.s,s))};yo.precision=yo.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(D7+s);if(t=Vg(a)+1,r=a.d.length-1,n=r*Ap+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};yo.squareRoot=yo.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(IN+"NaN")}for(s=Vg(o),af=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=F4(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=HW((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(oE(o,i,l+2)).times(.5),F4(i.d).slice(0,l)===(t=F4(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Dm(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return af=!0,Dm(r,n)};yo.times=yo.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,m=u.d,p=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=m.length,d=p.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+p[r]*m[a-r-1]+t,i[a--]=o%u0|0,t=o/u0|0;i[a]=(i[a]+t)%u0|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,af?Dm(s,h.precision):s};yo.toDecimalPlaces=yo.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(yC(s,0,VW),t===void 0?t=r.rounding:yC(t,0,8),Dm(n,s+Vg(n)+1,t))};yo.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=_9(r,!0):(yC(s,0,VW),t===void 0?t=a.rounding:yC(t,0,8),r=Dm(new a(r),s+1,t),n=_9(r,!0,s+1)),n};yo.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?_9(a):(yC(s,0,VW),t===void 0?t=i.rounding:yC(t,0,8),r=Dm(new i(a),s+Vg(a)+1,t),n=_9(r.abs(),!1,s+Vg(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};yo.toInteger=yo.toint=function(){var s=this,t=s.constructor;return Dm(new t(s),Vg(s)+1,t.rounding)};yo.toNumber=function(){return+this};yo.toPower=yo.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(nj);if(o=new c(o),!o.s){if(s.s<1)throw Error(IN+"Infinity");return o}if(o.eq(nj))return o;if(r=c.precision,s.eq(nj))return Dm(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=vWt){for(a=new c(nj),t=Math.ceil(r/Ap+4),af=!1;n%2&&(a=a.times(o),T_t(a.d,t)),n=HW(n/2),n!==0;)o=o.times(o),T_t(o.d,t);return af=!0,s.s<0?new c(nj).div(a):Dm(a,r)}}else if(i<0)throw Error(IN+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,af=!1,a=s.times(Jte(o,r+d)),af=!0,a=_Wt(a),a.s=i,a};yo.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Vg(a),r=_9(a,n<=i.toExpNeg||n>=i.toExpPos)):(yC(s,1,VW),t===void 0?t=i.rounding:yC(t,0,8),a=Dm(new i(a),s,t),n=Vg(a),r=_9(a,s<=n||n<=i.toExpNeg,s)),r};yo.toSignificantDigits=yo.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(yC(s,1,VW),t===void 0?t=r.rounding:yC(t,0,8)),Dm(new r(n),s,t)};yo.toString=yo.valueOf=yo.val=yo.toJSON=yo[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Vg(s),n=s.constructor;return _9(s,t<=n.toExpNeg||t>=n.toExpPos)};function bWt(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)),af?Dm(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/Ap),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)/u0|0,c[i]%=u0;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,af?Dm(t,h):t}function yC(s,t,n){if(s!==~~s||sn)throw Error(D7+s)}function F4(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,p,f,g,v,y,b,w,S,C,E,P,M,I=r.constructor,D=r.s==a.s?1:-1,F=r.d,q=a.d;if(!r.s)return new I(r);if(!a.s)throw Error(IN+"Division by zero");for(c=r.e-a.e,P=q.length,C=F.length,p=new I(D),f=p.d=[],d=0;q[d]==(F[d]||0);)++d;if(q[d]>(F[d]||0)&&--c,i==null?b=i=I.precision:l?b=i+(Vg(r)-Vg(a))+1:b=i,b<0)return new I(0);if(b=b/Ap+2|0,d=0,P==1)for(u=0,q=q[0],b++;(d1&&(q=s(q,u),F=s(F,u),P=q.length,C=F.length),S=P,g=F.slice(0,P),v=g.length;v=u0/2&&++E;do u=0,o=t(q,g,P,v),o<0?(y=g[0],P!=v&&(y=y*u0+(g[1]||0)),u=y/E|0,u>1?(u>=u0&&(u=u0-1),h=s(q,u),m=h.length,v=g.length,o=t(h,g,m,v),o==1&&(u--,n(h,P16)throw Error(mnt+Vg(s));if(!s.s)return new u(nj);for(t==null?(af=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(XR(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(nj),u.precision=o;;){if(a=Dm(a.times(s),o),n=n.times(++c),l=i.plus(oE(a,n,o)),F4(l.d).slice(0,o)===F4(i.d).slice(0,o)){for(;d--;)i=Dm(i.times(i),o);return u.precision=h,t==null?(af=!0,Dm(i,h)):i}i=l}}function Vg(s){for(var t=s.e*Ap,n=s.d[0];n>=10;n/=10)t++;return t}function Z9e(s,t,n){if(t>s.LN10.sd())throw af=!0,n&&(s.precision=n),Error(IN+"LN10 precision limit exceeded");return Dm(new s(s.LN10),t)}function k6(s){for(var t="";s--;)t+="0";return t}function Jte(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,p=s,f=p.d,g=p.constructor,v=g.precision;if(p.s<1)throw Error(IN+(p.s?"NaN":"-Infinity"));if(p.eq(nj))return new g(0);if(t==null?(af=!1,d=v):d=t,p.eq(10))return t==null&&(af=!0),Z9e(g,d);if(d+=m,g.precision=d,n=F4(f),r=n.charAt(0),i=Vg(p),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(s),n=F4(p.d),r=n.charAt(0),h++;i=Vg(p),r>1?(p=new g("0."+n),i++):p=new g(r+"."+n.slice(1))}else return c=Z9e(g,d+2,v).times(i+""),p=Jte(new g(r+"."+n.slice(1)),d-m).plus(c),g.precision=v,t==null?(af=!0,Dm(p,v)):p;for(o=l=p=oE(p.minus(nj),p.plus(nj),d),u=Dm(p.times(p),d),a=3;;){if(l=Dm(l.times(u),d),c=o.plus(oE(l,new g(a),d)),F4(c.d).slice(0,d)===F4(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(Z9e(g,d+2,v).times(i+""))),o=oE(o,new g(h),d),g.precision=v,t==null?(af=!0,Dm(o,v)):o;o=c,a+=2}}function E_t(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=HW(n/Ap),s.d=[],r=(n+1)%Ap,n<0&&(r+=Ap),rfTe||s.e<-fTe))throw Error(mnt+n)}else s.s=0,s.e=0,s.d=[0];return s}function Dm(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+=Ap,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/Ap),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=Ap,a=r-Ap+l}if(n!==void 0&&(i=XR(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/XR(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Vg(s),h.length=1,t=t-i-1,h[0]=XR(10,(Ap-t%Ap)%Ap),s.e=HW(-t/Ap)||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=XR(10,Ap-r),h[u]=a>0?(d/XR(10,l-a)%XR(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==u0&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=u0)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(af&&(s.e>fTe||s.e<-fTe))throw Error(mnt+Vg(s));return s}function wWt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,p=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),af?Dm(t,p):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(p/Ap),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)+k6(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+k6(-a-1)+i,n&&(r=n-l)>0&&(i+=k6(r))):a>=l?(i+=k6(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+k6(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=k6(r))),s.s<0?"-"+i:i}function T_t(s,t){if(s.length>t)return s.length=t,!0}function jWt(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(D7+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 E_t(l,i.toString())}else if(typeof i!="string")throw Error(D7+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,u2n.test(i))E_t(l,i);else throw Error(D7+i)}if(a.prototype=yo,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=jWt,a.config=a.set=h2n,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(D7+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(D7+n+": "+r);return this}var pnt=jWt(d2n);nj=new pnt(1);const im=pnt;function m2n(s){return g2n(s)||x2n(s)||f2n(s)||p2n()}function p2n(){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 f2n(s,t){if(s){if(typeof s=="string")return PGe(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 PGe(s,t)}}function x2n(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function g2n(s){if(Array.isArray(s))return PGe(s)}function PGe(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,M_t(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 P2n(s){if(Array.isArray(s))return s}function AWt(s){var t=ese(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function EWt(s,t,n){if(s.lte(0))return new im(0);var r=qIe.getDigitCount(s.toNumber()),a=new im(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new im(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new im(Math.ceil(c))}function L2n(s,t,n){var r=1,a=new im(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new im(10).pow(qIe.getDigitCount(s)-1),a=new im(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new im(Math.floor(s)))}else s===0?a=new im(Math.floor((t-1)/2)):n||(a=new im(Math.floor(s)));var l=Math.floor((t-1)/2),o=_2n(b2n(function(c){return a.add(new im(c-l).mul(r)).toNumber()}),LGe);return o(0,t)}function TWt(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 im(0),tickMin:new im(0),tickMax:new im(0)};var i=EWt(new im(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new im(0):(l=new im(s).add(t).div(2),l=l.sub(new im(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new im(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?TWt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new im(o).mul(i)),tickMax:l.add(new im(c).mul(i))})}function I2n(s){var t=ese(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=AWt([n,r]),c=ese(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(DGe(LGe(0,a-1).map(function(){return 1/0}))):[].concat(DGe(LGe(0,a-1).map(function(){return-1/0})),[u]);return n>r?IGe(h):h}if(d===u)return L2n(d,a,i);var m=TWt(d,u,l,i),p=m.step,f=m.tickMin,g=m.tickMax,v=qIe.rangeStep(f,g.add(new im(.1).mul(p)),p);return n>r?IGe(v):v}function D2n(s,t){var n=ese(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=AWt([r,a]),o=ese(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=EWt(new im(d).sub(c).div(u-1),i,0),m=[].concat(DGe(qIe.rangeStep(new im(c),new im(d).sub(new im(.99).mul(h)),h)),[d]);return r>a?IGe(m):m}var R2n=SWt(I2n),F2n=SWt(D2n),O2n="Invariant failed";function w9(s,t){throw new Error(O2n)}var z2n=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function iG(s){"@babel/helpers - typeof";return iG=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},iG(s)}function xTe(){return xTe=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 G2n(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 W2n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function K2n(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(n=r==null?void 0:r.length)!==null&&n!==void 0?n:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,h=a[d].coordinate,m=d>=o-1?a[0].coordinate:a[d+1].coordinate,p=void 0;if(xb(h-u)!==xb(m-h)){var f=[];if(xb(m-h)===xb(c[1]-c[0])){p=m;var g=h+c[1]-c[0];f[0]=Math.min(g,(g+u)/2),f[1]=Math.max(g,(g+u)/2)}else{p=u;var v=m+c[1]-c[0];f[0]=Math.min(h,(v+h)/2),f[1]=Math.max(h,(v+h)/2)}var y=[Math.min(h,(p+h)/2),Math.max(h,(p+h)/2)];if(t>y[0]&&t<=y[1]||t>=f[0]&&t<=f[1]){l=a[d].index;break}}else{var b=Math.min(u,m),w=Math.max(u,m);if(t>(b+h)/2&&t<=(w+h)/2){l=a[d].index;break}}}else for(var S=0;S0&&S(r[S].coordinate+r[S-1].coordinate)/2&&t<=(r[S].coordinate+r[S+1].coordinate)/2||S===o-1&&t>(r[S].coordinate+r[S-1].coordinate)/2){l=r[S].index;break}return l},fnt=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?wx(wx({},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},uNn=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(y&&y.length){var b=y[0].type.defaultProps,w=b!==void 0?wx(wx({},b),y[0].props):y[0].props,S=w.barSize,C=w[v];l[C]||(l[C]=[]);var E=xc(S)?n:S;l[C].push({item:y[0],stackList:y.slice(1),barSize:xc(E)?void 0:gb(E,r,0)})}}return l},hNn=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=gb(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,p=a/c,f=l.reduce(function(S,C){return S+C.barSize||0},0);f+=(c-1)*d,f>=a&&(f-=(c-1)*d,d=0),f>=a&&p>0&&(m=!0,p*=.9,f=c*p);var g=(a-f)/2>>0,v={offset:g-d,size:0};u=l.reduce(function(S,C){var E={item:C.item,position:{offset:v.offset+v.size+d,size:m?p:C.barSize}},P=[].concat(I_t(S),[E]);return v=P[P.length-1].position,C.stackList&&C.stackList.length&&C.stackList.forEach(function(M){P.push({item:M,position:v})}),P},h)}else{var y=gb(r,a,0,!0);a-2*y-(c-1)*d<=0&&(d=0);var b=(a-2*y-(c-1)*d)/c;b>1&&(b>>=0);var w=o===+o?Math.min(b,o):b;u=l.reduce(function(S,C,E){var P=[].concat(I_t(S),[{item:C.item,position:{offset:y+(b+d)*E+(b-w)/2,size:w}}]);return C.stackList&&C.stackList.length&&C.stackList.forEach(function(M){P.push({item:M,position:P[P.length-1].position})}),P},h)}return u},mNn=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=IWt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,p=d.align,f=d.verticalAlign,g=d.layout;if((g==="vertical"||g==="horizontal"&&f==="middle")&&p!=="center"&&ni(t[p]))return wx(wx({},t),{},Uq({},p,t[p]+(h||0)));if((g==="horizontal"||g==="vertical"&&p==="center")&&f!=="middle"&&ni(t[f]))return wx(wx({},t),{},Uq({},f,t[f]+(m||0)))}return t},pNn=function(t,n,r){return xc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},DWt=function(t,n,r,a,i){var l=n.props.children,o=Cj(l,zae).filter(function(d){return pNn(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=dg(u,r);if(xc(h))return d;var m=Array.isArray(h)?[$Ie(h),DM(h)]:[h,h],p=c.reduce(function(f,g){var v=dg(u,g,0),y=m[0]-Math.abs(Array.isArray(v)?v[0]:v),b=m[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(y,f[0]),Math.max(b,f[1])]},[1/0,-1/0]);return[Math.min(p[0],d[0]),Math.max(p[1],d[1])]},[1/0,-1/0])}return null},fNn=function(t,n,r,a,i){var l=n.map(function(o){return DWt(t,o,r,i,a)}).filter(function(o){return!xc(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},RWt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&DWt(t,c,d,a)||nee(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?xb(o[0]-o[1])*2*d:d,n&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(h){var m=i?i.indexOf(h):h;return{coordinate:a(m)+d,value:h,offset:d}});return u.filter(function(h){return!zW(h.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(h,m){return{coordinate:a(h)+d,value:h,index:m,offset:d}}):a.ticks&&!r?a.ticks(t.tickCount).map(function(h){return{coordinate:a(h)+d,value:h,offset:d}}):a.domain().map(function(h,m){return{coordinate:a(h)+d,value:i?i[h]:h,index:m,offset:d}})},X9e=new WeakMap,Dce=function(t,n){if(typeof n!="function")return t;X9e.has(t)||X9e.set(t,new WeakMap);var r=X9e.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},zWt=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:Kte(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:uTe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:see(),realScaleType:"point"}:i==="category"?{scale:Kte(),realScaleType:"band"}:{scale:uTe(),realScaleType:"linear"};if(g9(a)){var c="scale".concat(CIe(a));return{scale:(A_t[c]||see)(),realScaleType:A_t[c]?c:"point"}}return Fl(a)?{scale:a}:{scale:see(),realScaleType:"point"}},R_t=1e-4,BWt=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])-R_t,l=Math.max(a[0],a[1])+R_t,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},xNn=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])}},vNn=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)}},bNn={sign:yNn,expand:zmn,none:QH,silhouette:Bmn,wiggle:$mn,positive:vNn},_Nn=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=bNn[r],l=Omn().keys(a).value(function(o,c){return+dg(o,c,0)}).order(cGe).offset(i);return l(t)},wNn=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var p,f=(p=m.type)!==null&&p!==void 0&&p.defaultProps?wx(wx({},m.type.defaultProps),m.props):m.props,g=f.stackId,v=f.hide;if(v)return h;var y=f[r],b=h[y]||{hasStack:!1,stackGroups:{}};if(Sy(g)){var w=b.stackGroups[g]||{numericAxisId:r,cateAxisId:a,items:[]};w.items.push(m),b.hasStack=!0,b.stackGroups[g]=w}else b.stackGroups[lz("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return wx(wx({},h),{},Uq({},y,b))},c),u={};return Object.keys(d).reduce(function(h,m){var p=d[m];if(p.hasStack){var f={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(g,v){var y=p.stackGroups[v];return wx(wx({},g),{},Uq({},v,{numericAxisId:r,cateAxisId:a,items:y.items,stackedData:_Nn(t,y.items,i)}))},f)}return wx(wx({},h),{},Uq({},m,p))},u)},$Wt=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=R2n(d,i,o);return t.domain([$Ie(u),DM(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=F2n(h,i,o);return{niceTicks:m}}return null};function yTe(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&&!xc(a[t.dataKey])){var o=VEe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=dg(a,xc(l)?t.dataKey:l);return xc(c)?null:t.scale(c)}var F_t=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=dg(l,n.dataKey,n.domain[o]);return xc(c)?null:n.scale(c)-i/2+a},jNn=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]},NNn=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?wx(wx({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(Sy(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},kNn=function(t){return t.reduce(function(n,r){return[$Ie(r.concat([n[0]]).filter(ni)),DM(r.concat([n[1]]).filter(ni))]},[1/0,-1/0])},UWt=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=kNn(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})},O_t=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,z_t=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,zGe=function(t,n,r){if(Fl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(ni(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(O_t.test(t[0])){var i=+O_t.exec(t[0])[1];a[0]=n[0]-i}else Fl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(ni(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(z_t.test(t[1])){var l=+z_t.exec(t[1])[1];a[1]=n[1]+l}else Fl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},vTe=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=qst(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},INn=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=gb(t.cx,l,l/2),h=gb(t.cy,o,o/2),m=HWt(l,o,r),p=gb(t.innerRadius,m,0),f=gb(t.outerRadius,m,m*.8),g=Object.keys(n);return g.reduce(function(v,y){var b=n[y],w=b.domain,S=b.reversed,C;if(xc(b.range))a==="angleAxis"?C=[c,d]:a==="radiusAxis"&&(C=[p,f]),S&&(C=[C[1],C[0]]);else{C=b.range;var E=C,P=ANn(E,2);c=P[0],d=P[1]}var M=zWt(b,i),I=M.realScaleType,D=M.scale;D.domain(w).range(C),BWt(D);var F=$Wt(D,W3(W3({},b),{},{realScaleType:I})),q=W3(W3(W3({},b),F),{},{range:C,radius:f,realScaleType:I,scale:D,cx:u,cy:h,innerRadius:p,outerRadius:f,startAngle:c,endAngle:d});return W3(W3({},v),{},VWt({},y,q))},{})},DNn=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))},RNn=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=DNn({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:LNn(d),angleInRadian:d}},FNn=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}},ONn=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},q_t=function(t,n){var r=t.x,a=t.y,i=RNn({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=FNn(n),h=u.startAngle,m=u.endAngle,p=o,f;if(h<=m){for(;p>m;)p-=360;for(;p=h&&p<=m}else{for(;p>h;)p-=360;for(;p=m&&p<=h}return f?W3(W3({},n),{},{radius:l,angle:ONn(p,n)}):null},GWt=function(t){return!_.isValidElement(t)&&!Fl(t)&&typeof t!="boolean"?t.className:""};function rse(s){"@babel/helpers - typeof";return rse=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},rse(s)}var zNn=["offset"];function BNn(s){return VNn(s)||qNn(s)||UNn(s)||$Nn()}function $Nn(){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 UNn(s,t){if(s){if(typeof s=="string")return BGe(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 BGe(s,t)}}function qNn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function VNn(s){if(Array.isArray(s))return BGe(s)}function BGe(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 GNn(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 V_t(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 ry(s){for(var t=1;t=0?1:-1,w,S;a==="insideStart"?(w=p+b*l,S=g):a==="insideEnd"?(w=f-b*l,S=!g):a==="end"&&(w=f+b*l,S=g),S=y<=0?S:!S;var C=rp(d,u,v,w),E=rp(d,u,v,w+(S?1:-1)*359),P="M".concat(C.x,",").concat(C.y,` A`).concat(v,",").concat(v,",0,1,").concat(S?0:1,`, `).concat(E.x,",").concat(E.y),M=xc(t.id)?lz("recharts-radial-line-"):t.id;return Ft.createElement("text",ase({},r,{dominantBaseline:"central",className:Sc("recharts-radial-bar-label",o)}),Ft.createElement("defs",null,Ft.createElement("path",{id:M,d:P})),Ft.createElement("textPath",{xlinkHref:"#".concat(M)},n))},JNn=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,m=(u+h)/2;if(a==="outside"){var p=rp(l,o,d+r,m),f=p.x,g=p.y;return{x:f,y:g,textAnchor:f>=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,y=rp(l,o,v,m),b=y.x,w=y.y;return{x:b,y:w,textAnchor:"middle",verticalAnchor:"middle"}},ekn=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,p=h>0?"end":"start",f=h>0?"start":"end",g=d>=0?1:-1,v=g*a,y=g>0?"end":"start",b=g>0?"start":"end";if(i==="top"){var w={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:p};return ry(ry({},w),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var S={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:f};return ry(ry({},S),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var C={x:o-v,y:c+u/2,textAnchor:y,verticalAnchor:"middle"};return ry(ry({},C),r?{width:Math.max(C.x-r.x,0),height:u}:{})}if(i==="right"){var E={x:o+d+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return ry(ry({},E),r?{width:Math.max(r.x+r.width-E.x,0),height:u}:{})}var P=r?{width:d,height:u}:{};return i==="insideLeft"?ry({x:o+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},P):i==="insideRight"?ry({x:o+d-v,y:c+u/2,textAnchor:y,verticalAnchor:"middle"},P):i==="insideTop"?ry({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:f},P):i==="insideBottom"?ry({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:p},P):i==="insideTopLeft"?ry({x:o+v,y:c+m,textAnchor:b,verticalAnchor:f},P):i==="insideTopRight"?ry({x:o+d-v,y:c+m,textAnchor:y,verticalAnchor:f},P):i==="insideBottomLeft"?ry({x:o+v,y:c+u-m,textAnchor:b,verticalAnchor:p},P):i==="insideBottomRight"?ry({x:o+d-v,y:c+u-m,textAnchor:y,verticalAnchor:p},P):DW(i)&&(ni(i.x)||TF(i.x))&&(ni(i.y)||TF(i.y))?ry({x:o+gb(i.x,d),y:c+gb(i.y,u),textAnchor:"end",verticalAnchor:"end"},P):ry({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},P)},tkn=function(t){return"cx"in t&&ni(t.cx)};function g0(s){var t=s.offset,n=t===void 0?5:t,r=HNn(s,zNn),a=ry({offset:n},r),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,u=a.className,h=u===void 0?"":u,m=a.textBreakAll;if(!i||xc(o)&&xc(c)&&!_.isValidElement(d)&&!Fl(d))return null;if(_.isValidElement(d))return _.cloneElement(d,a);var p;if(Fl(d)){if(p=_.createElement(d,a),_.isValidElement(p))return p}else p=ZNn(a);var f=tkn(i),g=Go(a,!0);if(f&&(l==="insideStart"||l==="insideEnd"||l==="end"))return QNn(a,p,g);var v=f?JNn(a):ekn(a);return Ft.createElement(v9,ase({className:Sc("recharts-label",h)},g,v,{breakAll:m}),p)}g0.displayName="Label";var WWt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,p=t.top,f=t.left,g=t.width,v=t.height,y=t.clockWise,b=t.labelViewBox;if(b)return b;if(ni(g)&&ni(v)){if(ni(h)&&ni(m))return{x:h,y:m,width:g,height:v};if(ni(p)&&ni(f))return{x:p,y:f,width:g,height:v}}return ni(h)&&ni(m)?{x:h,y:m,width:0,height:0}:ni(n)&&ni(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:y}:t.viewBox?t.viewBox:{}},skn=function(t,n){return t?t===!0?Ft.createElement(g0,{key:"label-implicit",viewBox:n}):Sy(t)?Ft.createElement(g0,{key:"label-implicit",viewBox:n,value:t}):_.isValidElement(t)?t.type===g0?_.cloneElement(t,{key:"label-implicit",viewBox:n}):Ft.createElement(g0,{key:"label-implicit",content:t,viewBox:n}):Fl(t)?Ft.createElement(g0,{key:"label-implicit",content:t,viewBox:n}):DW(t)?Ft.createElement(g0,ase({viewBox:n},t,{key:"label-implicit"})):null:null},nkn=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=WWt(t),l=Cj(a,g0).map(function(c,d){return _.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=skn(t.label,n||i);return[o].concat(BNn(l))};g0.parseViewBox=WWt;g0.renderCallByParent=nkn;function rkn(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var akn=rkn;const ikn=kd(akn);function ise(s){"@babel/helpers - typeof";return ise=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},ise(s)}var okn=["valueAccessor"],lkn=["data","dataKey","clockWise","id","textBreakAll"];function ckn(s){return mkn(s)||hkn(s)||ukn(s)||dkn()}function dkn(){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 ukn(s,t){if(s){if(typeof s=="string")return $Ge(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 $Ge(s,t)}}function hkn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function mkn(s){if(Array.isArray(s))return $Ge(s)}function $Ge(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 gkn(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 ykn=function(t){return Array.isArray(t.value)?ikn(t.value):t.value};function iC(s){var t=s.valueAccessor,n=t===void 0?ykn:t,r=W_t(s,okn),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=W_t(r,lkn);return!a||!a.length?null:Ft.createElement($d,{className:"recharts-label-list"},a.map(function(u,h){var m=xc(i)?n(u,h):dg(u&&u.payload,i),p=xc(o)?{}:{id:"".concat(o,"-").concat(h)};return Ft.createElement(g0,_Te({},Go(u,!0),d,p,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:g0.parseViewBox(xc(l)?u:G_t(G_t({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}iC.displayName="LabelList";function vkn(s,t){return s?s===!0?Ft.createElement(iC,{key:"labelList-implicit",data:t}):Ft.isValidElement(s)||Fl(s)?Ft.createElement(iC,{key:"labelList-implicit",data:t,content:s}):DW(s)?Ft.createElement(iC,_Te({data:t},s,{key:"labelList-implicit"})):null:null}function bkn(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=Cj(r,iC).map(function(l,o){return _.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=vkn(s.label,t);return[i].concat(ckn(a))}iC.renderCallByParent=bkn;function ose(s){"@babel/helpers - typeof";return ose=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},ose(s)}function UGe(){return UGe=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var p=rp(n,r,a,l),f=rp(n,r,a,d);m+="L ".concat(f.x,",").concat(f.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(p.x,",").concat(p.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},kkn=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=xb(u-d),m=Rce({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),p=m.circleTangency,f=m.lineTangency,g=m.theta,v=Rce({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),y=v.circleTangency,b=v.lineTangency,w=v.theta,S=c?Math.abs(d-u):Math.abs(d-u)-g-w;if(S<0)return o?"M ".concat(f.x,",").concat(f.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 `):KWt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var C="M ".concat(f.x,",").concat(f.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(p.x,",").concat(p.y,` A`).concat(i,",").concat(i,",0,").concat(+(S>180),",").concat(+(h<0),",").concat(y.x,",").concat(y.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var E=Rce({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),P=E.circleTangency,M=E.lineTangency,I=E.theta,D=Rce({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),F=D.circleTangency,q=D.lineTangency,G=D.theta,V=c?Math.abs(d-u):Math.abs(d-u)-I-G;if(V<0&&l===0)return"".concat(C,"L").concat(n,",").concat(r,"Z");C+="L".concat(q.x,",").concat(q.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(F.x,",").concat(F.y,` A`).concat(a,",").concat(a,",0,").concat(+(V>180),",").concat(+(h>0),",").concat(P.x,",").concat(P.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(M.x,",").concat(M.y,"Z")}else C+="L".concat(n,",").concat(r,"Z");return C},Skn={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},YWt=function(t){var n=Y_t(Y_t({},Skn),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,m=n.className;if(l0&&Math.abs(u-h)<360?v=kkn({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(g,f/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):v=KWt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Ft.createElement("path",UGe({},Go(n,!0),{className:p,d:v,role:"img"}))};function lse(s){"@babel/helpers - typeof";return lse=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},lse(s)}function qGe(){return qGe=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 $kn(s,t){return GW(s.getTime(),t.getTime())}function nwt(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,m=h[0],p=h[1],f=o.value,g=f[0],v=f[1];!d&&!r[u]&&(d=n.equals(m,g,i,u,s,t,n)&&n.equals(p,v,m,g,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function Ukn(s,t,n){var r=swt(s),a=r.length;if(swt(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===eKt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!JWt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function gZ(s,t,n){var r=ewt(s),a=r.length;if(ewt(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===eKt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!JWt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=twt(s,i),o=twt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function qkn(s,t){return GW(s.valueOf(),t.valueOf())}function Vkn(s,t){return s.source===t.source&&s.flags===t.flags}function rwt(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 Hkn(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 Gkn="[object Arguments]",Wkn="[object Boolean]",Kkn="[object Date]",Ykn="[object Map]",Zkn="[object Number]",Xkn="[object Object]",Qkn="[object RegExp]",Jkn="[object Set]",eSn="[object String]",tSn=Array.isArray,awt=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,iwt=Object.assign,sSn=Object.prototype.toString.call.bind(Object.prototype.toString);function nSn(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,m){if(u===h)return!0;if(u==null||h==null||typeof u!="object"||typeof h!="object")return u!==u&&h!==h;var p=u.constructor;if(p!==h.constructor)return!1;if(p===Object)return a(u,h,m);if(tSn(u))return t(u,h,m);if(awt!=null&&awt(u))return c(u,h,m);if(p===Date)return n(u,h,m);if(p===RegExp)return l(u,h,m);if(p===Map)return r(u,h,m);if(p===Set)return o(u,h,m);var f=sSn(u);return f===Kkn?n(u,h,m):f===Qkn?l(u,h,m):f===Ykn?r(u,h,m):f===Jkn?o(u,h,m):f===Xkn?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,m):f===Gkn?a(u,h,m):f===Wkn||f===Zkn||f===eSn?i(u,h,m):!1}}function rSn(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?gZ:Bkn,areDatesEqual:$kn,areMapsEqual:r?J_t(nwt,gZ):nwt,areObjectsEqual:r?gZ:Ukn,arePrimitiveWrappersEqual:qkn,areRegExpsEqual:Vkn,areSetsEqual:r?J_t(rwt,gZ):rwt,areTypedArraysEqual:r?gZ:Hkn};if(n&&(a=iwt({},a,n(a))),t){var i=Oce(a.areArraysEqual),l=Oce(a.areMapsEqual),o=Oce(a.areObjectsEqual),c=Oce(a.areSetsEqual);a=iwt({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function aSn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function iSn(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,m=h===void 0?t?new WeakMap:void 0:h,p=u.meta;return n(c,d,{cache:m,equals:a,meta:p,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 oSn=$L();$L({strict:!0});$L({circular:!0});$L({circular:!0,strict:!0});$L({createInternalComparator:function(){return GW}});$L({strict:!0,createInternalComparator:function(){return GW}});$L({circular:!0,createInternalComparator:function(){return GW}});$L({circular:!0,createInternalComparator:function(){return GW},strict:!0});function $L(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=rSn(s),c=nSn(o),d=r?r(c):aSn(c);return iSn({circular:n,comparator:c,createState:a,equals:d,strict:l})}function lSn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function owt(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):lSn(a)};requestAnimationFrame(r)}function VGe(s){"@babel/helpers - typeof";return VGe=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},VGe(s)}function cSn(s){return mSn(s)||hSn(s)||uSn(s)||dSn()}function dSn(){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 uSn(s,t){if(s){if(typeof s=="string")return lwt(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 lwt(s,t)}}function lwt(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:y<0?0:y},g=function(y){for(var b=y>1?1:y,w=b,S=0;S<8;++S){var C=h(w)-b,E=p(w);if(Math.abs(C-b)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var p=-(u-h)*r,f=m*i,g=m+(p-f)*o/1e3,v=m*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 VSn(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 Q9e(s){return KSn(s)||WSn(s)||GSn(s)||HSn()}function HSn(){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 GSn(s,t){if(s){if(typeof s=="string")return YGe(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 YGe(s,t)}}function WSn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function KSn(s){if(Array.isArray(s))return YGe(s)}function YGe(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 NTe(s){return NTe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},NTe(s)}var DS=function(s){JSn(n,s);var t=e5n(n);function n(r,a){var i;YSn(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,m=l.children,p=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(QGe(i)),i.changeStyle=i.changeStyle.bind(QGe(i)),!o||p<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),XGe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},XGe(i);i.state={style:c?RX({},c,d):d}}else i.state={style:{}};return i}return XSn(n,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,h=i.from,m=this.state.style;if(o){if(!l){var p={style:c?RX({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(p);return}if(!(oSn(a.to,u)&&a.canBegin&&a.isActive)){var f=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var g=f||d?h:a.to;if(this.state&&m){var v={style:c?RX({},c,g):g};(c&&m[c]!==g||!c&&m!==g)&&this.setState(v)}this.runAnimation(wk(wk({},this.props),{},{from:g,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,u=a.begin,h=a.onAnimationEnd,m=a.onAnimationStart,p=$Sn(l,o,TSn(d),c,this.changeStyle),f=function(){i.stopJSAnimation=p()};this.manager.start([m,u,f,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,p=function(g,v,y){if(y===0)return g;var b=v.duration,w=v.easing,S=w===void 0?"ease":w,C=v.style,E=v.properties,P=v.onAnimationEnd,M=y>0?l[y-1]:v,I=E||Object.keys(C);if(typeof S=="function"||S==="spring")return[].concat(Q9e(g),[i.runJSAnimation.bind(i,{from:M.style,to:C,duration:b,easing:S}),b]);var D=uwt(I,b,S),F=wk(wk(wk({},M.style),C),{},{transition:D});return[].concat(Q9e(g),[F,b,P]).filter(ySn)};return this.manager.start([c].concat(Q9e(l.reduce(p,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=pSn());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,m=a.steps,p=a.children,f=this.manager;if(this.unSubscribe=f.subscribe(this.handleStyleChange),typeof d=="function"||typeof p=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var g=o?RX({},o,c):c,v=uwt(Object.keys(g),l,d);f.start([u,i,wk(wk({},g),{},{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=qSn(a,USn),d=_.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(p){var f=p.props,g=f.style,v=g===void 0?{}:g,y=f.className,b=_.cloneElement(p,wk(wk({},c),{},{style:wk(wk({},v),u),className:y}));return b};return d===1?h(_.Children.only(i)):Ft.createElement("div",null,_.Children.map(i,function(m){return h(m)}))}}]),n}(_.PureComponent);DS.displayName="Animate";DS.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};DS.propTypes={from:wh.oneOfType([wh.object,wh.string]),to:wh.oneOfType([wh.object,wh.string]),attributeName:wh.string,duration:wh.number,begin:wh.number,easing:wh.oneOfType([wh.string,wh.func]),steps:wh.arrayOf(wh.shape({duration:wh.number.isRequired,style:wh.object.isRequired,easing:wh.oneOfType([wh.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),wh.func]),properties:wh.arrayOf("string"),onAnimationEnd:wh.func})),children:wh.oneOfType([wh.node,wh.func]),isActive:wh.bool,canBegin:wh.bool,onAnimationEnd:wh.func,shouldReAnimate:wh.bool,onAnimationStart:wh.func,onAnimationReStart:wh.func};function use(s){"@babel/helpers - typeof";return use=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},use(s)}function kTe(){return kTe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],m=0,p=4;ml?l:i[m];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var f=Math.min(l,i);u="M ".concat(t,",").concat(n+o*f,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+c*f,",").concat(n,` L `).concat(t+r-c*f,",").concat(n,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*f,` L `).concat(t+r,",").concat(n+a-o*f,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t+r-c*f,",").concat(n+a,` L `).concat(t+c*f,",").concat(n+a,` A `).concat(f,",").concat(f,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*f," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},d5n=function(t,n){if(!t||!n)return!1;var r=t.x,a=t.y,i=n.x,l=n.y,o=n.width,c=n.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),u=Math.max(i,i+o),h=Math.min(l,l+c),m=Math.max(l,l+c);return r>=d&&r<=u&&a>=h&&a<=m}return!1},u5n={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},xnt=function(t){var n=vwt(vwt({},u5n),t),r=_.useRef(),a=_.useState(-1),i=s5n(a,2),l=i[0],o=i[1];_.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var S=r.current.getTotalLength();S&&o(S)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,p=n.className,f=n.animationEasing,g=n.animationDuration,v=n.animationBegin,y=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var w=Sc("recharts-rectangle",p);return b?Ft.createElement(DS,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:g,animationEasing:f,isActive:b},function(S){var C=S.width,E=S.height,P=S.x,M=S.y;return Ft.createElement(DS,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:g,isActive:y,easing:f},Ft.createElement("path",kTe({},Go(n,!0),{className:w,d:bwt(P,M,C,E,m),ref:r})))}):Ft.createElement("path",kTe({},Go(n,!0),{className:w,d:bwt(c,d,u,h,m)}))},h5n=["points","className","baseLinePoints","connectNulls"];function pU(){return pU=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 p5n(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 _wt(s){return y5n(s)||g5n(s)||x5n(s)||f5n()}function f5n(){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 x5n(s,t){if(s){if(typeof s=="string")return JGe(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 JGe(s,t)}}function g5n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function y5n(s){if(Array.isArray(s))return JGe(s)}function JGe(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){wwt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),wwt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},aee=function(t,n){var r=v5n(t);n&&(r=[r.reduce(function(i,l){return[].concat(_wt(i),_wt(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},b5n=function(t,n,r){var a=aee(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(aee(n.reverse(),r).slice(1))},_5n=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=m5n(t,h5n);if(!n||!n.length)return null;var o=Sc("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=b5n(n,a,i);return Ft.createElement("g",{className:o},Ft.createElement("path",pU({},Go(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Ft.createElement("path",pU({},Go(l,!0),{fill:"none",d:aee(n,i)})):null,c?Ft.createElement("path",pU({},Go(l,!0),{fill:"none",d:aee(a,i)})):null)}var u=aee(n,i);return Ft.createElement("path",pU({},Go(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function eWe(){return eWe=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 A5n(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 E5n=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},T5n=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,m=t.height,p=m===void 0?0:m,f=t.className,g=C5n(t,w5n),v=j5n({x:r,y:i,top:o,left:d,width:h,height:p},g);return!ni(r)||!ni(i)||!ni(h)||!ni(p)||!ni(o)||!ni(d)?null:Ft.createElement("path",tWe({},Go(v,!0),{className:Sc("recharts-cross",f),d:E5n(r,i,h,p,o,d)}))},M5n=BIe,P5n=gWt,L5n=IC;function I5n(s,t){return s&&s.length?M5n(s,L5n(t),P5n):void 0}var D5n=I5n;const R5n=kd(D5n);var F5n=BIe,O5n=IC,z5n=yWt;function B5n(s,t){return s&&s.length?F5n(s,O5n(t),z5n):void 0}var $5n=B5n;const U5n=kd($5n);var q5n=["cx","cy","angle","ticks","axisLine"],V5n=["ticks","tick","angle","tickFormatter","stroke"];function lG(s){"@babel/helpers - typeof";return lG=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},lG(s)}function iee(){return iee=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 H5n(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 G5n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Swt(s,t){for(var n=0;nEwt?l=a==="outer"?"start":"end":i<-Ewt?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=DI(DI({},Go(this.props,!1)),{},{fill:"none"},Go(o,!1));if(c==="circle")return Ft.createElement(Bae,dF({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return rp(a,i,l,m.coordinate)});return Ft.createElement(_5n,dF({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=Go(this.props,!1),h=Go(l,!1),m=DI(DI({},u),{},{fill:"none"},Go(o,!1)),p=i.map(function(f,g){var v=r.getTickLineCoord(f),y=r.getTickTextAnchor(f),b=DI(DI(DI({textAnchor:y},u),{},{stroke:"none",fill:d},h),{},{index:g,payload:f,x:v.x2,y:v.y2});return Ft.createElement($d,dF({className:Sc("recharts-polar-angle-axis-tick",GWt(l)),key:"tick-".concat(f.coordinate)},y9(r.props,f,g)),o&&Ft.createElement("line",dF({className:"recharts-polar-angle-axis-tick-line"},m,v)),l&&t.renderTickItem(l,b,c?c(f.value,g):f.value))});return Ft.createElement($d,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Ft.createElement($d,{className:Sc("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Ft.isValidElement(r)?l=Ft.cloneElement(r,a):Fl(r)?l=r(a):l=Ft.createElement(v9,dF({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(_.PureComponent);GIe(WIe,"displayName","PolarAngleAxis");GIe(WIe,"axisType","angleAxis");GIe(WIe,"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 o4n=mGt,l4n=o4n(Object.getPrototypeOf,Object),c4n=l4n,d4n=GE,u4n=c4n,h4n=WE,m4n="[object Object]",p4n=Function.prototype,f4n=Object.prototype,uKt=p4n.toString,x4n=f4n.hasOwnProperty,g4n=uKt.call(Object);function y4n(s){if(!h4n(s)||d4n(s)!=m4n)return!1;var t=u4n(s);if(t===null)return!0;var n=x4n.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&uKt.call(n)==g4n}var v4n=y4n;const b4n=kd(v4n);var _4n=GE,w4n=WE,j4n="[object Boolean]";function N4n(s){return s===!0||s===!1||w4n(s)&&_4n(s)==j4n}var k4n=N4n;const S4n=kd(k4n);function mse(s){"@babel/helpers - typeof";return mse=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},mse(s)}function ATe(){return ATe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0,from:{upperWidth:0,lowerWidth:0,height:m,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:m,x:c,y:d},duration:g,animationEasing:f,isActive:y},function(w){var S=w.upperWidth,C=w.lowerWidth,E=w.height,P=w.x,M=w.y;return Ft.createElement(DS,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:g,easing:f},Ft.createElement("path",ATe({},Go(n,!0),{className:b,d:Lwt(P,M,S,C,E),ref:r})))}):Ft.createElement("g",null,Ft.createElement("path",ATe({},Go(n,!0),{className:b,d:Lwt(c,d,u,h,m)})))},F4n=["option","shapeType","propTransformer","activeClassName","isActive"];function pse(s){"@babel/helpers - typeof";return pse=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},pse(s)}function O4n(s,t){if(s==null)return{};var n=z4n(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 z4n(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 Iwt(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 ETe(s){for(var t=1;t0?Sj(w,"paddingAngle",0):0;if(C){var P=_y(C.endAngle-C.startAngle,w.endAngle-w.startAngle),M=Qm(Qm({},w),{},{startAngle:b+E,endAngle:b+P(g)+E});v.push(M),b=M.endAngle}else{var I=w.endAngle,D=w.startAngle,F=_y(0,I-D),q=F(g),G=Qm(Qm({},w),{},{startAngle:b+E,endAngle:b+q+E});v.push(G),b=G.endAngle}}),Ft.createElement($d,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||!b9(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,p=a.isAnimationActive,f=this.state.isAnimationFinished;if(i||!l||!l.length||!ni(d)||!ni(u)||!ni(h)||!ni(m))return null;var g=Sc("recharts-pie",o);return Ft.createElement($d,{tabIndex:this.props.rootTabIndex,className:g,ref:function(y){r.pieRef=y}},this.renderSectors(),c&&this.renderLabels(l),g0.renderCallByParent(this.props,null,!1),(!p||f)&&iC.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?b:b-1)*c,S=v-b*p-w,C=a.reduce(function(M,I){var D=dg(I,y,0);return M+(ni(D)?D:0)},0),E;if(C>0){var P;E=a.map(function(M,I){var D=dg(M,y,0),F=dg(M,u,I),q=(ni(D)?D:0)/C,G;I?G=P.endAngle+xb(g)*c*(D!==0?1:0):G=l;var V=G+xb(g)*((D!==0?p:0)+q*S),H=(G+V)/2,K=(f.innerRadius+f.outerRadius)/2,Z=[{name:F,value:D,payload:M,dataKey:y,type:m}],oe=rp(f.cx,f.cy,K,H);return P=Qm(Qm(Qm({percent:q,cornerRadius:i,name:F,tooltipPayload:Z,midAngle:H,middleRadius:K,tooltipPosition:oe},M),f),{},{value:dg(M,y),startAngle:G,endAngle:V,payload:M,paddingAngle:xb(g)*c}),P})}return Qm(Qm({},f),{},{sectors:E,data:a})});var iCn=Math.ceil,oCn=Math.max;function lCn(s,t,n,r){for(var a=-1,i=oCn(iCn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var cCn=lCn,dCn=PGt,Owt=1/0,uCn=17976931348623157e292;function hCn(s){if(!s)return s===0?s:0;if(s=dCn(s),s===Owt||s===-Owt){var t=s<0?-1:1;return t*uCn}return s===s?s:0}var fKt=hCn,mCn=cCn,pCn=LIe,J9e=fKt;function fCn(s){return function(t,n,r){return r&&typeof r!="number"&&pCn(t,n,r)&&(n=r=void 0),t=J9e(t),n===void 0?(n=t,t=0):n=J9e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),Lw(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()}),Lw(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),Lw(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),Lw(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),Lw(r,"handleSlideDragStart",function(a){var i=qwt(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 ECn(t,s),kCn(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),m=Math.max(a,i),p=t.getIndexInRange(l,h),f=t.getIndexInRange(l,m);return{startIndex:p-p%c,endIndex:f===u?u:f-f%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=dg(i[r],o,r);return Fl(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,m=c.startIndex,p=c.endIndex,f=c.onChange,g=r.pageX-i;g>0?g=Math.min(g,d+u-h-o,d+u-h-l):g<0&&(g=Math.max(g,d-l,d-o));var v=this.getIndex({startX:l+g,endX:o+g});(v.startIndex!==m||v.endIndex!==p)&&f&&f(v),this.setState({startX:l+g,endX:o+g,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=qwt(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,p=u.travellerWidth,f=u.onChange,g=u.gap,v=u.data,y={startX:this.state.startX,endX:this.state.endX},b=r.pageX-i;b>0?b=Math.min(b,h+m-p-d):b<0&&(b=Math.max(b,h-d)),y[l]=d+b;var w=this.getIndex(y),S=w.startIndex,C=w.endIndex,E=function(){var M=v.length-1;return l==="startX"&&(o>c?S%g===0:C%g===0)||oc?C%g===0:S%g===0)||o>c&&C===M};this.setState(Lw(Lw({},l,d+b),"brushMoveStartX",r.pageX),function(){f&&E()&&f(w)})}},{key:"handleTravellerMoveKeyboard",value:function(r,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],h=o.indexOf(u);if(h!==-1){var m=h+r;if(!(m===-1||m>=o.length)){var p=o[m];a==="startX"&&p>=d||a==="endX"&&p<=c||this.setState(Lw({},a,p),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Ft.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=_.Children.only(d);return h?Ft.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,p=c.ariaLabel,f=c.data,g=c.startIndex,v=c.endIndex,y=Math.max(r,this.props.x),b=eze(eze({},Go(this.props,!1)),{},{x:y,y:d,width:u,height:h}),w=p||"Min value: ".concat((i=f[g])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=f[v])===null||l===void 0?void 0:l.name);return Ft.createElement($d,{tabIndex:0,role:"slider","aria-label":w,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(C){["ArrowLeft","ArrowRight"].includes(C.key)&&(C.preventDefault(),C.stopPropagation(),o.handleTravellerMoveKeyboard(C.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(m,b))}},{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 Ft.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,p=5,f={pointerEvents:"none",fill:d};return Ft.createElement($d,{className:"recharts-brush-texts"},Ft.createElement(v9,PTe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-p,y:l+o/2},f),this.getTextOfTick(a)),Ft.createElement(v9,PTe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+p,y:l+o/2},f),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,p=m.startX,f=m.endX,g=m.isTextActive,v=m.isSlideMoving,y=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!ni(o)||!ni(c)||!ni(d)||!ni(u)||d<=0||u<=0)return null;var w=Sc("recharts-brush",i),S=Ft.Children.count(l)===1,C=jCn("userSelect","none");return Ft.createElement($d,{className:w,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:C},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(p,f),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(f,"endX"),(g||v||y||b||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 Ft.createElement(Ft.Fragment,null,Ft.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Ft.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Ft.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 Ft.isValidElement(r)?i=Ft.cloneElement(r,a):Fl(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 eze({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?MCn({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var m=a.scale.domain().map(function(p){return a.scale(p)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:m}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(_.PureComponent);Lw(hG,"displayName","Brush");Lw(hG,"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 PCn=Ust;function LCn(s,t){var n;return PCn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var ICn=LCn,DCn=aGt,RCn=IC,FCn=ICn,OCn=J_,zCn=LIe;function BCn(s,t,n){var r=OCn(s)?DCn:FCn;return n&&zCn(s,t,n)&&(t=void 0),r(s,RCn(t))}var $Cn=BCn;const UCn=kd($Cn);var oC=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},Vwt=CGt;function qCn(s,t,n){t=="__proto__"&&Vwt?Vwt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var VCn=qCn,HCn=VCn,GCn=kGt,WCn=IC;function KCn(s,t){var n={};return t=WCn(t),GCn(s,function(r,a,i){HCn(n,a,t(r,a,i))}),n}var YCn=KCn;const ZCn=kd(YCn);function XCn(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 p3n(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 f3n(s,t){var n=s.x,r=s.y,a=m3n(s,c3n),i="".concat(n),l=parseInt(i,10),o="".concat(r),c=parseInt(o,10),d="".concat(t.height||a.height),u=parseInt(d,10),h="".concat(t.width||a.width),m=parseInt(h,10);return yZ(yZ(yZ(yZ(yZ({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function Gwt(s){return Ft.createElement(hKt,iWe({shapeType:"rectangle",propTransformer:f3n,activeClassName:"recharts-active-bar"},s))}var x3n=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=ni(r)||Qun(r);return i?t(r,a):(i||w9(),n)}},g3n=["value","background"],bKt;function mG(s){"@babel/helpers - typeof";return mG=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},mG(s)}function y3n(s,t){if(s==null)return{};var n=v3n(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 v3n(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 ITe(){return ITe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(H)0&&Math.abs(V)0&&(G=Math.min((ve||0)-(V[me-1]||0),G))}),Number.isFinite(G)){var H=G/q,K=g.layout==="vertical"?r.height:r.width;if(g.padding==="gap"&&(P=H*K/2),g.padding==="no-gap"){var Z=gb(t.barCategoryGap,H*K),oe=H*K/2;P=oe-Z-(oe-Z)/K*Z}}}a==="xAxis"?M=[r.left+(w.left||0)+(P||0),r.left+r.width-(w.right||0)-(P||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(w.bottom||0),r.top+(w.top||0)]:[r.top+(w.top||0)+(P||0),r.top+r.height-(w.bottom||0)-(P||0)]:M=g.range,C&&(M=[M[1],M[0]]);var re=zWt(g,i,m),ae=re.scale,J=re.realScaleType;ae.domain(y).range(M),BWt(ae);var te=$Wt(ae,Jk(Jk({},g),{},{realScaleType:J}));a==="xAxis"?(F=v==="top"&&!S||v==="bottom"&&S,I=r.left,D=h[E]-F*g.height):a==="yAxis"&&(F=v==="left"&&!S||v==="right"&&S,I=h[E]-F*g.width,D=r.top);var ce=Jk(Jk(Jk({},g),te),{},{realScaleType:J,x:I,y:D,scale:ae,width:a==="xAxis"?r.width:g.width,height:a==="yAxis"?r.height:g.height});return ce.bandSize=vTe(ce,te),!g.hide&&a==="xAxis"?h[E]+=(F?-1:1)*ce.height:g.hide||(h[E]+=(F?-1:1)*ce.width),Jk(Jk({},p),{},ZIe({},f,ce))},{})},NKt=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)}},T3n=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return NKt({x:n,y:r},{x:a,y:i})},kKt=function(){function s(t){C3n(this,s),this.scale=t}return A3n(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)}}])}();ZIe(kKt,"EPS",1e-4);var ynt=function(t){var n=Object.keys(t).reduce(function(r,a){return Jk(Jk({},r),{},ZIe({},a,kKt.create(t[a])))},{});return Jk(Jk({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return ZCn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return vKt(a,function(i,l){return n[l].isInRange(i)})}})};function M3n(s){return(s%180+180)%180}var P3n=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=M3n(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var F3n=R3n,O3n=fKt;function z3n(s){var t=O3n(s),n=t%1;return t===t?n?t-n:t:0}var B3n=z3n,$3n=vGt,U3n=IC,q3n=B3n,V3n=Math.max;function H3n(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:q3n(n);return a<0&&(a=V3n(r+a,0)),$3n(s,U3n(t),a)}var G3n=H3n,W3n=F3n,K3n=G3n,Y3n=W3n(K3n),Z3n=Y3n;const X3n=kd(Z3n);var Q3n=sun(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("")}),vnt=_.createContext(void 0),bnt=_.createContext(void 0),SKt=_.createContext(void 0),CKt=_.createContext({}),AKt=_.createContext(void 0),EKt=_.createContext(0),TKt=_.createContext(0),Xwt=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=Q3n(i);return Ft.createElement(vnt.Provider,{value:r},Ft.createElement(bnt.Provider,{value:a},Ft.createElement(CKt.Provider,{value:i},Ft.createElement(SKt.Provider,{value:u},Ft.createElement(AKt.Provider,{value:l},Ft.createElement(EKt.Provider,{value:d},Ft.createElement(TKt.Provider,{value:c},o)))))))},J3n=function(){return _.useContext(AKt)},MKt=function(t){var n=_.useContext(vnt);n==null&&w9();var r=n[t];return r==null&&w9(),r},eAn=function(){var t=_.useContext(vnt);return O6(t)},tAn=function(){var t=_.useContext(bnt),n=X3n(t,function(r){return vKt(r.domain,Number.isFinite)});return n||O6(t)},PKt=function(t){var n=_.useContext(bnt);n==null&&w9();var r=n[t];return r==null&&w9(),r},sAn=function(){var t=_.useContext(SKt);return t},nAn=function(){return _.useContext(CKt)},_nt=function(){return _.useContext(TKt)},wnt=function(){return _.useContext(EKt)};function pG(s){"@babel/helpers - typeof";return pG=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},pG(s)}function rAn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function aAn(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 BAn(s,t){return zKt(s,t+1)}function $An(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 f=r==null?void 0:r[c];if(f===void 0)return{v:zKt(r,d)};var g=c,v,y=function(){return v===void 0&&(v=n(f,g)),v},b=f.coordinate,w=c===0||zTe(s,b,y,u,o);w||(c=0,u=l,d+=1),w&&(u=b+s*(y()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function vse(s){"@babel/helpers - typeof";return vse=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},vse(s)}function ajt(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 a1(s){for(var t=1;t0?p.coordinate-v*s:p.coordinate})}else i[m]=p=a1(a1({},p),{},{tickCoord:p.coordinate});var y=zTe(s,p.tickCoord,g,o,c);y&&(c=p.tickCoord-s*(g()/2+a),i[m]=a1(a1({},p),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function GAn(s,t,n,r,a,i){var l=(r||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var u=r[o-1],h=n(u,o-1),m=s*(u.coordinate+s*h/2-d);l[o-1]=u=a1(a1({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var p=zTe(s,u.tickCoord,function(){return h},c,d);p&&(d=u.tickCoord-s*(h/2+a),l[o-1]=a1(a1({},u),{},{isShow:!0}))}for(var f=i?o-1:o,g=function(b){var w=l[b],S,C=function(){return S===void 0&&(S=n(w,b)),S};if(b===0){var E=s*(w.coordinate-s*C()/2-c);l[b]=w=a1(a1({},w),{},{tickCoord:E<0?w.coordinate-E*s:w.coordinate})}else l[b]=w=a1(a1({},w),{},{tickCoord:w.coordinate});var P=zTe(s,w.tickCoord,C,c,d);P&&(c=w.tickCoord+s*(C()/2+a),l[b]=a1(a1({},w),{},{isShow:!0}))},v=0;v=2?xb(a[1].coordinate-a[0].coordinate):1,y=zAn(i,v,p);return c==="equidistantPreserveStart"?$An(v,y,g,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=GAn(v,y,g,a,l,c==="preserveStartEnd"):m=HAn(v,y,g,a,l),m.filter(function(b){return b.isShow}))}var WAn=["viewBox"],KAn=["viewBox"],YAn=["ticks"];function gG(s){"@babel/helpers - typeof";return gG=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},gG(s)}function xU(){return xU=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 ZAn(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 XAn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function ojt(s,t){for(var n=0;n0?c(this.props):c(p)),l<=0||o<=0||!f||!f.length?null:Ft.createElement($d,{className:Sc("recharts-cartesian-axis",d),ref:function(v){r.layerReference=v}},i&&this.renderAxisLine(),this.renderTicks(f,this.state.fontSize,this.state.letterSpacing),g0.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=Sc(a.className,"recharts-cartesian-axis-tick-value");return Ft.isValidElement(r)?l=Ft.cloneElement(r,sy(sy({},a),{},{className:o})):Fl(r)?l=r(sy(sy({},a),{},{className:o})):l=Ft.createElement(v9,xU({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(_.Component);Snt(WW,"displayName","CartesianAxis");Snt(WW,"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 rEn=["x1","y1","x2","y2","key"],aEn=["offset"];function j9(s){"@babel/helpers - typeof";return j9=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},j9(s)}function ljt(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 l1(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function cEn(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 dEn=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 Ft.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function UKt(s,t){var n;if(Ft.isValidElement(s))n=Ft.cloneElement(s,t);else if(Fl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=cjt(t,rEn),d=Go(c,!1);d.offset;var u=cjt(d,aEn);n=Ft.createElement("line",LF({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function uEn(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=l1(l1({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return UKt(a,d)});return Ft.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function hEn(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=l1(l1({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return UKt(a,d)});return Ft.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function mEn(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,p){return m-p});a!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var f=!u[p+1],g=f?a+l-m:u[p+1]-m;if(g<=0)return null;var v=p%t.length;return Ft.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:g,width:i,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Ft.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function pEn(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,p){return m-p});i!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var f=!u[p+1],g=f?i+o-m:u[p+1]-m;if(g<=0)return null;var v=p%r.length;return Ft.createElement("rect",{key:"react-".concat(p),x:m,y:l,width:g,height:c,stroke:"none",fill:r[v],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Ft.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var fEn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return OWt(knt(l1(l1(l1({},WW.defaultProps),r),{},{ticks:qA(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},xEn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return OWt(knt(l1(l1(l1({},WW.defaultProps),r),{},{ticks:qA(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},HB={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function TE(s){var t,n,r,a,i,l,o=_nt(),c=wnt(),d=nAn(),u=l1(l1({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:HB.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:HB.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:HB.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:HB.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:HB.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:HB.verticalFill,x:ni(s.x)?s.x:d.left,y:ni(s.y)?s.y:d.top,width:ni(s.width)?s.width:d.width,height:ni(s.height)?s.height:d.height}),h=u.x,m=u.y,p=u.width,f=u.height,g=u.syncWithTicks,v=u.horizontalValues,y=u.verticalValues,b=eAn(),w=tAn();if(!ni(p)||p<=0||!ni(f)||f<=0||!ni(h)||h!==+h||!ni(m)||m!==+m)return null;var S=u.verticalCoordinatesGenerator||fEn,C=u.horizontalCoordinatesGenerator||xEn,E=u.horizontalPoints,P=u.verticalPoints;if((!E||!E.length)&&Fl(C)){var M=v&&v.length,I=C({yAxis:w?l1(l1({},w),{},{ticks:M?v:w.ticks}):void 0,width:o,height:c,offset:d},M?!0:g);NS(Array.isArray(I),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(j9(I),"]")),Array.isArray(I)&&(E=I)}if((!P||!P.length)&&Fl(S)){var D=y&&y.length,F=S({xAxis:b?l1(l1({},b),{},{ticks:D?y:b.ticks}):void 0,width:o,height:c,offset:d},D?!0:g);NS(Array.isArray(F),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(j9(F),"]")),Array.isArray(F)&&(P=F)}return Ft.createElement("g",{className:"recharts-cartesian-grid"},Ft.createElement(dEn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Ft.createElement(uEn,LF({},u,{offset:d,horizontalPoints:E,xAxis:b,yAxis:w})),Ft.createElement(hEn,LF({},u,{offset:d,verticalPoints:P,xAxis:b,yAxis:w})),Ft.createElement(mEn,LF({},u,{horizontalPoints:E})),Ft.createElement(pEn,LF({},u,{verticalPoints:P})))}TE.displayName="CartesianGrid";var gEn=["type","layout","connectNulls","ref"],yEn=["key"];function yG(s){"@babel/helpers - typeof";return yG=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},yG(s)}function djt(s,t){if(s==null)return{};var n=vEn(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 vEn(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 oee(){return oee=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){p=[].concat(GB(c.slice(0,f)),[h-g]);break}var v=p.length%2===0?[0,m]:[m];return[].concat(GB(t.repeat(c,u)),GB(p),v).map(function(y){return"".concat(y,"px")}).join(", ")}),eS(n,"id",lz("recharts-line-")),eS(n,"pathRef",function(l){n.mainCurve=l}),eS(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),eS(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return EEn(t,s),kEn(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=Cj(u,zae);if(!h)return null;var m=function(g,v){return{x:g.x,y:g.y,value:g.value,errorVal:dg(g.payload,v)}},p={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Ft.createElement($d,p,h.map(function(f){return Ft.cloneElement(f,{key:"bar-".concat(f.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=Go(this.props,!1),m=Go(c,!0),p=d.map(function(g,v){var y=Aw(Aw(Aw({key:"dot-".concat(v),r:3},h),m),{},{index:v,cx:g.x,cy:g.y,value:g.value,dataKey:u,payload:g.payload,points:d});return t.renderDotItem(c,y)}),f={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Ft.createElement($d,oee({className:"recharts-line-dots",key:"dots"},f),p)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=djt(o,gEn),m=Aw(Aw(Aw({},Go(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 Ft.createElement(R7,oee({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,p=l.animationId,f=l.animateNewValues,g=l.width,v=l.height,y=this.state,b=y.prevPoints,w=y.totalLength;return Ft.createElement(DS,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(S){var C=S.t;if(b){var E=b.length/o.length,P=o.map(function(q,G){var V=Math.floor(G*E);if(b[V]){var H=b[V],K=_y(H.x,q.x),Z=_y(H.y,q.y);return Aw(Aw({},q),{},{x:K(C),y:Z(C)})}if(f){var oe=_y(g*2,q.x),re=_y(v/2,q.y);return Aw(Aw({},q),{},{x:oe(C),y:re(C)})}return Aw(Aw({},q),{},{x:q.x,y:q.y})});return i.renderCurveStatically(P,r,a)}var M=_y(0,w),I=M(C),D;if(c){var F="".concat(c).split(/[,\s]+/gim).map(function(q){return parseFloat(q)});D=i.getStrokeDasharray(I,w,F)}else D=i.generateSimpleStrokeDasharray(w,I);return i.renderCurveStatically(o,r,a,{strokeDasharray:D})})}},{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||!b9(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,p=a.width,f=a.height,g=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var y=this.state.isAnimationFinished,b=o.length===1,w=Sc("recharts-line",c),S=d&&d.allowDataOverflow,C=u&&u.allowDataOverflow,E=S||C,P=xc(v)?this.id:v,M=(r=Go(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,D=I===void 0?3:I,F=M.strokeWidth,q=F===void 0?2:F,G=THt(l)?l:{},V=G.clipDot,H=V===void 0?!0:V,K=D*2+q;return Ft.createElement($d,{className:w},S||C?Ft.createElement("defs",null,Ft.createElement("clipPath",{id:"clipPath-".concat(P)},Ft.createElement("rect",{x:S?m:m-p/2,y:C?h:h-f/2,width:S?p:p*2,height:C?f:f*2})),!H&&Ft.createElement("clipPath",{id:"clipPath-dots-".concat(P)},Ft.createElement("rect",{x:m-K/2,y:h-K/2,width:p+K,height:f+K}))):null,!b&&this.renderCurve(E,P),this.renderErrorBar(E,P),(b||l)&&this.renderDots(E,H,P),(!g||y)&&iC.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(GB(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function LEn(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 IF(){return IF=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!b9(u,l)||!b9(h,o))?this.renderAreaWithAnimation(r,a):this.renderAreaStatically(l,o,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.top,u=a.left,h=a.xAxis,m=a.yAxis,p=a.width,f=a.height,g=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var y=this.state.isAnimationFinished,b=o.length===1,w=Sc("recharts-area",c),S=h&&h.allowDataOverflow,C=m&&m.allowDataOverflow,E=S||C,P=xc(v)?this.id:v,M=(r=Go(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,D=I===void 0?3:I,F=M.strokeWidth,q=F===void 0?2:F,G=THt(l)?l:{},V=G.clipDot,H=V===void 0?!0:V,K=D*2+q;return Ft.createElement($d,{className:w},S||C?Ft.createElement("defs",null,Ft.createElement("clipPath",{id:"clipPath-".concat(P)},Ft.createElement("rect",{x:S?u:u-p/2,y:C?d:d-f/2,width:S?p:p*2,height:C?f:f*2})),!H&&Ft.createElement("clipPath",{id:"clipPath-dots-".concat(P)},Ft.createElement("rect",{x:u-K/2,y:d-K/2,width:p+K,height:f+K}))):null,b?null:this.renderArea(E,P),(l||b)&&this.renderDots(E,H,P),(!g||y)&&iC.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,curBaseLine:r.baseLine,prevPoints:a.curPoints,prevBaseLine:a.curBaseLine}:r.points!==a.curPoints||r.baseLine!==a.curBaseLine?{curPoints:r.points,curBaseLine:r.baseLine}:null}}])}(_.PureComponent);HKt=q_;O4(q_,"displayName","Area");O4(q_,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!kS.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});O4(q_,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(ni(o)&&typeof o=="number")return o;var c=a==="horizontal"?r:n,d=c.scale.domain();if(c.type==="number"){var u=Math.max(d[0],d[1]),h=Math.min(d[0],d[1]);return o==="dataMin"?h:o==="dataMax"||u<0?u:Math.max(Math.min(d[0],d[1]),0)}return o==="dataMin"?d[0]:o==="dataMax"?d[1]:d[0]});O4(q_,"getComposedData",function(s){var t=s.props,n=s.item,r=s.xAxis,a=s.yAxis,i=s.xAxisTicks,l=s.yAxisTicks,o=s.bandSize,c=s.dataKey,d=s.stackedData,u=s.dataStartIndex,h=s.displayedData,m=s.offset,p=t.layout,f=d&&d.length,g=HKt.getBaseValue(t,n,r,a),v=p==="horizontal",y=!1,b=h.map(function(S,C){var E;f?E=d[u+C]:(E=dg(S,c),Array.isArray(E)?y=!0:E=[g,E]);var P=E[1]==null||f&&dg(S,c)==null;return v?{x:yTe({axis:r,ticks:i,bandSize:o,entry:S,index:C}),y:P?null:a.scale(E[1]),value:E,payload:S}:{x:P?null:r.scale(E[1]),y:yTe({axis:a,ticks:l,bandSize:o,entry:S,index:C}),value:E,payload:S}}),w;return f||y?w=b.map(function(S){var C=Array.isArray(S.value)?S.value[0]:null;return v?{x:S.x,y:C!=null&&S.y!=null?a.scale(C):null}:{x:C!=null?r.scale(C):null,y:S.y}}):w=v?a.scale(g):r.scale(g),a6({points:b,baseLine:w,layout:p,isRange:y},m)});O4(q_,"renderDotItem",function(s,t){var n;if(Ft.isValidElement(s))n=Ft.cloneElement(s,t);else if(Fl(s))n=s(t);else{var r=Sc("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=GKt(t,PEn);n=Ft.createElement(Bae,IF({},i,{key:a,className:r}))}return n});function bG(s){"@babel/helpers - typeof";return bG=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},bG(s)}function $En(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function UEn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function ATn(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 ETn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function TTn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&ni(a)&&ni(i)?t.slice(a,i+1):[]};function lYt(s){return s==="number"?[0,"auto"]:void 0}var SWe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=t8e(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var m;if(l.dataKey&&!l.allowDuplicatedCategory){var p=h===void 0?o:h;m=VEe(p,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(jG(c),[qWt(d,m)]):c},[])},bjt=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=UTn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=dNn(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=SWe(t,n,u,h),p=qTn(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:p}}return null},VTn=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=t.stackOffset,p=FWt(u,i);return r.reduce(function(f,g){var v,y=g.type.defaultProps!==void 0?ia(ia({},g.type.defaultProps),g.props):g.props,b=y.type,w=y.dataKey,S=y.allowDataOverflow,C=y.allowDuplicatedCategory,E=y.scale,P=y.ticks,M=y.includeHidden,I=y[l];if(f[I])return f;var D=t8e(t.data,{graphicalItems:a.filter(function(te){var ce,ve=l in te.props?te.props[l]:(ce=te.type.defaultProps)===null||ce===void 0?void 0:ce[l];return ve===I}),dataStartIndex:c,dataEndIndex:d}),F=D.length,q,G,V;xTn(y.domain,S,b)&&(q=zGe(y.domain,null,S),p&&(b==="number"||E!=="auto")&&(V=nee(D,w,"category")));var H=lYt(b);if(!q||q.length===0){var K,Z=(K=y.domain)!==null&&K!==void 0?K:H;if(w){if(q=nee(D,w,b),b==="category"&&p){var oe=ehn(q);C&&oe?(G=q,q=MTe(0,F)):C||(q=B_t(Z,q,g).reduce(function(te,ce){return te.indexOf(ce)>=0?te:[].concat(jG(te),[ce])},[]))}else if(b==="category")C?q=q.filter(function(te){return te!==""&&!xc(te)}):q=B_t(Z,q,g).reduce(function(te,ce){return te.indexOf(ce)>=0||ce===""||xc(ce)?te:[].concat(jG(te),[ce])},[]);else if(b==="number"){var re=fNn(D,a.filter(function(te){var ce,ve,me=l in te.props?te.props[l]:(ce=te.type.defaultProps)===null||ce===void 0?void 0:ce[l],he="hide"in te.props?te.props.hide:(ve=te.type.defaultProps)===null||ve===void 0?void 0:ve.hide;return me===I&&(M||!he)}),w,i,u);re&&(q=re)}p&&(b==="number"||E!=="auto")&&(V=nee(D,w,"category"))}else p?q=MTe(0,F):o&&o[I]&&o[I].hasStack&&b==="number"?q=m==="expand"?[0,1]:UWt(o[I].stackGroups,c,d):q=RWt(D,a.filter(function(te){var ce=l in te.props?te.props[l]:te.type.defaultProps[l],ve="hide"in te.props?te.props.hide:te.type.defaultProps.hide;return ce===I&&(M||!ve)}),b,u,!0);if(b==="number")q=jWe(h,q,I,i,P),Z&&(q=zGe(Z,q,S));else if(b==="category"&&Z){var ae=Z,J=q.every(function(te){return ae.indexOf(te)>=0});J&&(q=ae)}}return ia(ia({},f),{},Rl({},I,ia(ia({},y),{},{axisType:i,domain:q,categoricalDomain:V,duplicateDomain:G,originalDomain:(v=y.domain)!==null&&v!==void 0?v:H,isCategorical:p,layout:u})))},{})},HTn=function(t,n){var r=n.graphicalItems,a=n.Axis,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=t8e(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),p=m.length,f=FWt(u,i),g=-1;return r.reduce(function(v,y){var b=y.type.defaultProps!==void 0?ia(ia({},y.type.defaultProps),y.props):y.props,w=b[l],S=lYt("number");if(!v[w]){g++;var C;return f?C=MTe(0,p):o&&o[w]&&o[w].hasStack?(C=UWt(o[w].stackGroups,c,d),C=jWe(h,C,w,i)):(C=zGe(S,RWt(m,r.filter(function(E){var P,M,I=l in E.props?E.props[l]:(P=E.type.defaultProps)===null||P===void 0?void 0:P[l],D="hide"in E.props?E.props.hide:(M=E.type.defaultProps)===null||M===void 0?void 0:M.hide;return I===w&&!D}),"number",u),a.defaultProps.allowDataOverflow),C=jWe(h,C,w,i)),ia(ia({},v),{},Rl({},w,ia(ia({axisType:i},a.defaultProps),{},{hide:!0,orientation:Sj(BTn,"".concat(i,".").concat(g%2),null),domain:C,originalDomain:S,isCategorical:f,layout:u})))}return v},{})},GTn=function(t,n){var r=n.axisType,a=r===void 0?"xAxis":r,i=n.AxisComp,l=n.graphicalItems,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.children,h="".concat(a,"Id"),m=Cj(u,i),p={};return m&&m.length?p=VTn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(p=HTn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),p},WTn=function(t){var n=O6(t),r=qA(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:qst(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:vTe(n,r)}},_jt=function(t){var n=t.children,r=t.defaultShowTooltip,a=Kw(n,hG),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}},KTn=function(t){return!t||!t.length?!1:t.some(function(n){var r=iE(n&&n.type);return r&&r.indexOf("Bar")>=0})},wjt=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"}},YTn=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,m=r.margin||{},p=Kw(h,hG),f=Kw(h,Bq),g=Object.keys(c).reduce(function(C,E){var P=c[E],M=P.orientation;return!P.mirror&&!P.hide?ia(ia({},C),{},Rl({},M,C[M]+P.width)):C},{left:m.left||0,right:m.right||0}),v=Object.keys(l).reduce(function(C,E){var P=l[E],M=P.orientation;return!P.mirror&&!P.hide?ia(ia({},C),{},Rl({},M,Sj(C,"".concat(M))+P.height)):C},{top:m.top||0,bottom:m.bottom||0}),y=ia(ia({},v),g),b=y.bottom;p&&(y.bottom+=p.props.height||hG.defaultProps.height),f&&n&&(y=mNn(y,a,r,n));var w=d-y.left-y.right,S=u-y.top-y.bottom;return ia(ia({brushBottom:b},y),{},{width:Math.max(w,0),height:Math.max(S,0)})},ZTn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},s8e=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,m=function(y,b){var w=b.graphicalItems,S=b.stackGroups,C=b.offset,E=b.updateId,P=b.dataStartIndex,M=b.dataEndIndex,I=y.barSize,D=y.layout,F=y.barGap,q=y.barCategoryGap,G=y.maxBarSize,V=wjt(D),H=V.numericAxisName,K=V.cateAxisName,Z=KTn(w),oe=[];return w.forEach(function(re,ae){var J=t8e(y.data,{graphicalItems:[re],dataStartIndex:P,dataEndIndex:M}),te=re.type.defaultProps!==void 0?ia(ia({},re.type.defaultProps),re.props):re.props,ce=te.dataKey,ve=te.maxBarSize,me=te["".concat(H,"Id")],he=te["".concat(K,"Id")],ge={},Ee=c.reduce(function($e,Xe){var nt=b["".concat(Xe.axisType,"Map")],Ge=te["".concat(Xe.axisType,"Id")];nt&&nt[Ge]||Xe.axisType==="zAxis"||w9();var Je=nt[Ge];return ia(ia({},$e),{},Rl(Rl({},Xe.axisType,Je),"".concat(Xe.axisType,"Ticks"),qA(Je)))},ge),Ne=Ee[K],Pe=Ee["".concat(K,"Ticks")],Oe=S&&S[me]&&S[me].hasStack&&NNn(re,S[me].stackGroups),ke=iE(re.type).indexOf("Bar")>=0,Ve=vTe(Ne,Pe),_e=[],Ae=Z&&uNn({barSize:I,stackGroups:S,totalSize:ZTn(Ee,K)});if(ke){var Se,We,qe=xc(ve)?G:ve,Be=(Se=(We=vTe(Ne,Pe,!0))!==null&&We!==void 0?We:qe)!==null&&Se!==void 0?Se:0;_e=hNn({barGap:F,barCategoryGap:q,bandSize:Be!==Ve?Be:Ve,sizeList:Ae[he],maxBarSize:qe}),Be!==Ve&&(_e=_e.map(function($e){return ia(ia({},$e),{},{position:ia(ia({},$e.position),{},{offset:$e.position.offset-Be/2})})}))}var Ze=re&&re.type&&re.type.getComposedData;Ze&&oe.push({props:ia(ia({},Ze(ia(ia({},Ee),{},{displayedData:J,props:y,dataKey:ce,item:re,bandSize:Ve,barPosition:_e,offset:C,stackedData:Oe,layout:D,dataStartIndex:P,dataEndIndex:M}))),{},Rl(Rl(Rl({key:re.key||"item-".concat(ae)},H,Ee[H]),K,Ee[K]),"animationId",E)),childIndex:hhn(re,y.children),item:re})}),oe},p=function(y,b){var w=y.props,S=y.dataStartIndex,C=y.dataEndIndex,E=y.updateId;if(!I1t({props:w}))return null;var P=w.children,M=w.layout,I=w.stackOffset,D=w.data,F=w.reverseStackOrder,q=wjt(M),G=q.numericAxisName,V=q.cateAxisName,H=Cj(P,r),K=wNn(D,H,"".concat(G,"Id"),"".concat(V,"Id"),I,F),Z=c.reduce(function(te,ce){var ve="".concat(ce.axisType,"Map");return ia(ia({},te),{},Rl({},ve,GTn(w,ia(ia({},ce),{},{graphicalItems:H,stackGroups:ce.axisType===G&&K,dataStartIndex:S,dataEndIndex:C}))))},{}),oe=YTn(ia(ia({},Z),{},{props:w,graphicalItems:H}),b==null?void 0:b.legendBBox);Object.keys(Z).forEach(function(te){Z[te]=u(w,Z[te],oe,te.replace("Map",""),n)});var re=Z["".concat(V,"Map")],ae=WTn(re),J=m(w,ia(ia({},Z),{},{dataStartIndex:S,dataEndIndex:C,updateId:E,graphicalItems:H,stackGroups:K,offset:oe}));return ia(ia({formattedGraphicalItems:J,graphicalItems:H,offset:oe,stackGroups:K},ae),Z)},f=function(v){function y(b){var w,S,C;return ETn(this,y),C=PTn(this,y,[b]),Rl(C,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Rl(C,"accessibilityManager",new fTn),Rl(C,"handleLegendBBoxUpdate",function(E){if(E){var P=C.state,M=P.dataStartIndex,I=P.dataEndIndex,D=P.updateId;C.setState(ia({legendBBox:E},p({props:C.props,dataStartIndex:M,dataEndIndex:I,updateId:D},ia(ia({},C.state),{},{legendBBox:E}))))}}),Rl(C,"handleReceiveSyncEvent",function(E,P,M){if(C.props.syncId===E){if(M===C.eventEmitterSymbol&&typeof C.props.syncMethod!="function")return;C.applySyncEvent(P)}}),Rl(C,"handleBrushChange",function(E){var P=E.startIndex,M=E.endIndex;if(P!==C.state.dataStartIndex||M!==C.state.dataEndIndex){var I=C.state.updateId;C.setState(function(){return ia({dataStartIndex:P,dataEndIndex:M},p({props:C.props,dataStartIndex:P,dataEndIndex:M,updateId:I},C.state))}),C.triggerSyncEvent({dataStartIndex:P,dataEndIndex:M})}}),Rl(C,"handleMouseEnter",function(E){var P=C.getMouseInfo(E);if(P){var M=ia(ia({},P),{},{isTooltipActive:!0});C.setState(M),C.triggerSyncEvent(M);var I=C.props.onMouseEnter;Fl(I)&&I(M,E)}}),Rl(C,"triggeredAfterMouseMove",function(E){var P=C.getMouseInfo(E),M=P?ia(ia({},P),{},{isTooltipActive:!0}):{isTooltipActive:!1};C.setState(M),C.triggerSyncEvent(M);var I=C.props.onMouseMove;Fl(I)&&I(M,E)}),Rl(C,"handleItemMouseEnter",function(E){C.setState(function(){return{isTooltipActive:!0,activeItem:E,activePayload:E.tooltipPayload,activeCoordinate:E.tooltipPosition||{x:E.cx,y:E.cy}}})}),Rl(C,"handleItemMouseLeave",function(){C.setState(function(){return{isTooltipActive:!1}})}),Rl(C,"handleMouseMove",function(E){E.persist(),C.throttleTriggeredAfterMouseMove(E)}),Rl(C,"handleMouseLeave",function(E){C.throttleTriggeredAfterMouseMove.cancel();var P={isTooltipActive:!1};C.setState(P),C.triggerSyncEvent(P);var M=C.props.onMouseLeave;Fl(M)&&M(P,E)}),Rl(C,"handleOuterEvent",function(E){var P=uhn(E),M=Sj(C.props,"".concat(P));if(P&&Fl(M)){var I,D;/.*touch.*/i.test(P)?D=C.getMouseInfo(E.changedTouches[0]):D=C.getMouseInfo(E),M((I=D)!==null&&I!==void 0?I:{},E)}}),Rl(C,"handleClick",function(E){var P=C.getMouseInfo(E);if(P){var M=ia(ia({},P),{},{isTooltipActive:!0});C.setState(M),C.triggerSyncEvent(M);var I=C.props.onClick;Fl(I)&&I(M,E)}}),Rl(C,"handleMouseDown",function(E){var P=C.props.onMouseDown;if(Fl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Rl(C,"handleMouseUp",function(E){var P=C.props.onMouseUp;if(Fl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Rl(C,"handleTouchMove",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.throttleTriggeredAfterMouseMove(E.changedTouches[0])}),Rl(C,"handleTouchStart",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.handleMouseDown(E.changedTouches[0])}),Rl(C,"handleTouchEnd",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.handleMouseUp(E.changedTouches[0])}),Rl(C,"handleDoubleClick",function(E){var P=C.props.onDoubleClick;if(Fl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Rl(C,"handleContextMenu",function(E){var P=C.props.onContextMenu;if(Fl(P)){var M=C.getMouseInfo(E);P(M,E)}}),Rl(C,"triggerSyncEvent",function(E){C.props.syncId!==void 0&&sze.emit(nze,C.props.syncId,E,C.eventEmitterSymbol)}),Rl(C,"applySyncEvent",function(E){var P=C.props,M=P.layout,I=P.syncMethod,D=C.state.updateId,F=E.dataStartIndex,q=E.dataEndIndex;if(E.dataStartIndex!==void 0||E.dataEndIndex!==void 0)C.setState(ia({dataStartIndex:F,dataEndIndex:q},p({props:C.props,dataStartIndex:F,dataEndIndex:q,updateId:D},C.state)));else if(E.activeTooltipIndex!==void 0){var G=E.chartX,V=E.chartY,H=E.activeTooltipIndex,K=C.state,Z=K.offset,oe=K.tooltipTicks;if(!Z)return;if(typeof I=="function")H=I(oe,E);else if(I==="value"){H=-1;for(var re=0;re=0){var Oe,ke;if(G.dataKey&&!G.allowDuplicatedCategory){var Ve=typeof G.dataKey=="function"?Pe:"payload.".concat(G.dataKey.toString());Oe=VEe(re,Ve,H),ke=ae&&J&&VEe(J,Ve,H)}else Oe=re==null?void 0:re[V],ke=ae&&J&&J[V];if(he||me){var _e=E.props.activeIndex!==void 0?E.props.activeIndex:V;return[_.cloneElement(E,ia(ia(ia({},I.props),Ee),{},{activeIndex:_e})),null,null]}if(!xc(Oe))return[Ne].concat(jG(C.renderActivePoints({item:I,activePoint:Oe,basePoint:ke,childIndex:V,isRange:ae})))}else{var Ae,Se=(Ae=C.getItemByXY(C.state.activeCoordinate))!==null&&Ae!==void 0?Ae:{graphicalItem:Ne},We=Se.graphicalItem,qe=We.item,Be=qe===void 0?E:qe,Ze=We.childIndex,$e=ia(ia(ia({},I.props),Ee),{},{activeIndex:Ze});return[_.cloneElement(Be,$e),null,null]}return ae?[Ne,null,null]:[Ne,null]}),Rl(C,"renderCustomized",function(E,P,M){return _.cloneElement(E,ia(ia({key:"recharts-customized-".concat(M)},C.props),C.state))}),Rl(C,"renderMap",{CartesianGrid:{handler:Bce,once:!0},ReferenceArea:{handler:C.renderReferenceElement},ReferenceLine:{handler:Bce},ReferenceDot:{handler:C.renderReferenceElement},XAxis:{handler:Bce},YAxis:{handler:Bce},Brush:{handler:C.renderBrush,once:!0},Bar:{handler:C.renderGraphicChild},Line:{handler:C.renderGraphicChild},Area:{handler:C.renderGraphicChild},Radar:{handler:C.renderGraphicChild},RadialBar:{handler:C.renderGraphicChild},Scatter:{handler:C.renderGraphicChild},Pie:{handler:C.renderGraphicChild},Funnel:{handler:C.renderGraphicChild},Tooltip:{handler:C.renderCursor,once:!0},PolarGrid:{handler:C.renderPolarGrid,once:!0},PolarAngleAxis:{handler:C.renderPolarAxis},PolarRadiusAxis:{handler:C.renderPolarAxis},Customized:{handler:C.renderCustomized}}),C.clipPathId="".concat((w=b.id)!==null&&w!==void 0?w:lz("recharts"),"-clip"),C.throttleTriggeredAfterMouseMove=LGt(C.triggeredAfterMouseMove,(S=b.throttleDelay)!==null&&S!==void 0?S:1e3/60),C.state={},C}return DTn(y,v),MTn(y,[{key:"componentDidMount",value:function(){var w,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(w=this.props.margin.left)!==null&&w!==void 0?w:0,top:(S=this.props.margin.top)!==null&&S!==void 0?S:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var w=this.props,S=w.children,C=w.data,E=w.height,P=w.layout,M=Kw(S,Rf);if(M){var I=M.props.defaultIndex;if(!(typeof I!="number"||I<0||I>this.state.tooltipTicks.length-1)){var D=this.state.tooltipTicks[I]&&this.state.tooltipTicks[I].value,F=SWe(this.state,C,I,D),q=this.state.tooltipTicks[I].coordinate,G=(this.state.offset.top+E)/2,V=P==="horizontal",H=V?{x:q,y:G}:{y:q,x:G},K=this.state.formattedGraphicalItems.find(function(oe){var re=oe.item;return re.type.name==="Scatter"});K&&(H=ia(ia({},H),K.props.points[I].tooltipPosition),F=K.props.points[I].tooltipPayload);var Z={activeTooltipIndex:I,isTooltipActive:!0,activeLabel:D,activePayload:F,activeCoordinate:H};this.setState(Z),this.renderCursor(M),this.accessibilityManager.setIndex(I)}}}},{key:"getSnapshotBeforeUpdate",value:function(w,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==w.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==w.margin){var C,E;this.accessibilityManager.setDetails({offset:{left:(C=this.props.margin.left)!==null&&C!==void 0?C:0,top:(E=this.props.margin.top)!==null&&E!==void 0?E:0}})}return null}},{key:"componentDidUpdate",value:function(w){eGe([Kw(w.children,Rf)],[Kw(this.props.children,Rf)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var w=Kw(this.props.children,Rf);if(w&&typeof w.props.shared=="boolean"){var S=w.props.shared?"axis":"item";return o.indexOf(S)>=0?S:i}return i}},{key:"getMouseInfo",value:function(w){if(!this.container)return null;var S=this.container,C=S.getBoundingClientRect(),E=Obn(C),P={chartX:Math.round(w.pageX-E.left),chartY:Math.round(w.pageY-E.top)},M=C.width/S.offsetWidth||1,I=this.inRange(P.chartX,P.chartY,M);if(!I)return null;var D=this.state,F=D.xAxisMap,q=D.yAxisMap,G=this.getTooltipEventType(),V=bjt(this.state,this.props.data,this.props.layout,I);if(G!=="axis"&&F&&q){var H=O6(F).scale,K=O6(q).scale,Z=H&&H.invert?H.invert(P.chartX):null,oe=K&&K.invert?K.invert(P.chartY):null;return ia(ia({},P),{},{xValue:Z,yValue:oe},V)}return V?ia(ia({},P),V):null}},{key:"inRange",value:function(w,S){var C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,E=this.props.layout,P=w/C,M=S/C;if(E==="horizontal"||E==="vertical"){var I=this.state.offset,D=P>=I.left&&P<=I.left+I.width&&M>=I.top&&M<=I.top+I.height;return D?{x:P,y:M}:null}var F=this.state,q=F.angleAxisMap,G=F.radiusAxisMap;if(q&&G){var V=O6(q);return q_t({x:P,y:M},V)}return null}},{key:"parseEventsOfWrapper",value:function(){var w=this.props.children,S=this.getTooltipEventType(),C=Kw(w,Rf),E={};C&&S==="axis"&&(C.props.trigger==="click"?E={onClick:this.handleClick}:E={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 P=HEe(this.props,this.handleOuterEvent);return ia(ia({},P),E)}},{key:"addListener",value:function(){sze.on(nze,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){sze.removeListener(nze,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(w,S,C){for(var E=this.state.formattedGraphicalItems,P=0,M=E.length;P{const{data:b,error:w}=await U.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(w)throw w;return b}}),{data:r}=rt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:b,error:w}=await U.from("profiles").select("id, name, email");if(w)throw w;return b}});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(b=>[b.id,b])),l=a.reduce((b,w)=>b+(w.sent_count||0),0),o=a.reduce((b,w)=>b+(w.open_count||0),0),c=a.reduce((b,w)=>b+(w.click_count||0),0),d=a.reduce((b,w)=>b+(w.bounce_count||0),0),u=a.reduce((b,w)=>b+(w.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",m=l>0?(c/l*100).toFixed(1):"0.0",p=[{label:"Campaigns Sent",value:a.length,icon:Fr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:On,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:xa,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:wy,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:nl,color:"text-orange-600"},{label:"Complaints",value:u,icon:kl,color:"text-destructive"}],f=new Map;a.forEach(b=>{var C,E;const w=b.user_id,S=f.get(w)||{name:((C=i.get(w))==null?void 0:C.name)||((E=i.get(w))==null?void 0:E.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};S.campaigns++,S.sent+=b.sent_count||0,S.opens+=b.open_count||0,S.clicks+=b.click_count||0,f.set(w,S)});const g=[...f.entries()].map(([b,w])=>({id:b,...w,openRate:w.sent>0?+(w.opens/w.sent*100).toFixed(1):0})).sort((b,w)=>w.sent-b.sent),v=g.slice(0,6).map(b=>({name:b.name,value:b.sent})),y=a.map(b=>{var w;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((w=i.get(b.user_id))==null?void 0:w.name)||"Unknown",openRate:b.sent_count>0?+(b.open_count/b.sent_count*100).toFixed(1):0,clickRate:b.sent_count>0?+(b.click_count/b.sent_count*100).toFixed(1):0,sent:b.sent_count,date:b.sent_at?Ys(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:p.map(b=>e.jsx(be,{children:e.jsxs(Le,{className:"p-4 text-center",children:[e.jsx(b.icon,{className:`h-5 w-5 mx-auto mb-1 ${b.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:b.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.label})]})},b.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Le,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Nb,{width:"100%",height:"100%",children:e.jsxs(KW,{data:y,children:[e.jsx(Mv,{dataKey:"date",fontSize:11}),e.jsx(Pv,{fontSize:11,unit:"%"}),e.jsx(Rf,{formatter:b=>`${b}%`}),e.jsx(W_,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(W_,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Le,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Nb,{width:"100%",height:"100%",children:e.jsxs(cYt,{children:[e.jsx(DC,{data:v,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:w})=>`${b} (${(w*100).toFixed(0)}%)`,fontSize:11,children:v.map((b,w)=>e.jsx(cz,{fill:jjt[w%jjt.length]},w))}),e.jsx(Rf,{})]})})})})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Le,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(Nb,{width:"100%",height:"100%",children:e.jsxs(Cnt,{data:y,children:[e.jsx(Mv,{dataKey:"date",fontSize:11}),e.jsx(Pv,{fontSize:11}),e.jsx(Rf,{}),e.jsx(XP,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Agent Performance"})}),e.jsx(Le,{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:g.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:b.name}),e.jsx("td",{className:"py-2.5 text-center",children:b.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:b.sent}),e.jsx("td",{className:"py-2.5 text-center",children:b.opens}),e.jsx("td",{className:"py-2.5 text-center",children:b.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(ze,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,w)=>{const S=b.sent_count>0?b.open_count/b.sent_count:0;return(w.sent_count>0?w.open_count/w.sent_count:0)-S}).slice(0,10).map((b,w)=>{const S=b.sent_count>0?(b.open_count/b.sent_count*100).toFixed(1):"0.0",C=b.sent_count>0?(b.click_count/b.sent_count*100).toFixed(1):"0.0",E=i.get(b.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/${b.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",w+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(E==null?void 0:E.name)||"Unknown"," · ",b.sent_at?Ys(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(xa,{className:"h-3 w-3"})," ",S,"%"]}),e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(wy,{className:"h-3 w-3"})," ",C,"%"]})]})]},b.id)})})})]})]})})}const QTn=()=>{const{toast:s}=_i(),[t,n]=_.useState(!0),[r,a]=_.useState([]),[i,l]=_.useState([]),[o,c]=_.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});_.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:m}=await U.from("website_apps").select("slug, name").order("sort_order"),p=[];let f=0;for(;;){const{data:C,error:E}=await U.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(f,f+999);if(E)throw E;if(p.push(...C||[]),!C||C.length<1e3)break;f+=1e3}const g=[];for(f=0;;){const{data:C,error:E}=await U.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(f,f+999);if(E)throw E;if(g.push(...C||[]),!C||C.length<1e3||(f+=1e3,f>2e4))break}const v=new Map;for(const C of m||[])v.set(C.slug,{app_slug:C.slug,app_name:C.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const C of p){const E=v.get(C.app_slug);E&&(E.installs+=1,C.enabled&&(E.enabled+=1))}for(const C of g){const E=v.get(C.app_slug);E&&(C.event_type==="impression"?E.impressions+=1:C.event_type==="expand"?E.expands+=1:C.event_type==="cta_click"?E.cta_clicks+=1:C.event_type==="lead_capture"&&(E.lead_captures+=1))}const y=new Map;for(const C of p){if(!C.enabled)continue;const E=y.get(C.user_id)||{user_id:C.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};E.apps_enabled.includes(C.app_slug)||E.apps_enabled.push(C.app_slug),y.set(C.user_id,E)}for(const C of g){const E=y.get(C.user_id);E&&(E.events_30d+=1,C.event_type==="lead_capture"&&(E.leads_30d+=1))}const b=Array.from(y.keys());if(b.length>0){const{data:C}=await U.from("profiles").select("id, name, email").in("id",b);for(const E of C||[]){const P=y.get(E.id);P&&(P.name=E.name,P.email=E.email)}}const w=Array.from(v.values()),S=Array.from(y.values()).sort((C,E)=>E.events_30d-C.events_30d);a(w),l(S),c({installs:w.reduce((C,E)=>C+E.enabled,0),activeAgents:S.length,impressions30d:w.reduce((C,E)=>C+E.impressions,0),leads30d:w.reduce((C,E)=>C+E.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(be,{children:e.jsx(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(Wo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(On,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(on,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"App Performance (last 30 days)"})}),e.jsx(Le,{children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{className:"text-right",children:"Installs"}),e.jsx(Tt,{className:"text-right",children:"Enabled"}),e.jsx(Tt,{className:"text-right",children:"Impressions"}),e.jsx(Tt,{className:"text-right",children:"Expands"}),e.jsx(Tt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Tt,{className:"text-right",children:"Leads"}),e.jsx(Tt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(Qa,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:u.app_name}),e.jsx(yt,{className:"text-right",children:u.installs}),e.jsx(yt,{className:"text-right",children:u.enabled}),e.jsx(yt,{className:"text-right",children:u.impressions}),e.jsx(yt,{className:"text-right",children:u.expands}),e.jsx(yt,{className:"text-right",children:u.cta_clicks}),e.jsx(yt,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(yt,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(fn,{children:e.jsx(yt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Le,{children:[e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Apps Enabled"}),e.jsx(Tt,{className:"text-right",children:"Events (30d)"}),e.jsx(Tt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(Qa,{children:[i.slice(0,100).map(u=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:u.name||"—"}),e.jsx(yt,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(yt,{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(yt,{className:"text-right",children:u.events_30d}),e.jsx(yt,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(fn,{children:e.jsx(yt,{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."]})]})]})]})},JTn=()=>{const[s,t]=_.useState([]),[n,r]=_.useState([]),[a,i]=_.useState({}),[l,o]=_.useState(!0);_.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([U.rpc("get_extension_usage_summary"),U.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),p=h||[],f=m||[];t(p),r(f);const g=Array.from(new Set(f.map(v=>v.user_id)));if(g.length){const{data:v}=await U.from("profiles").select("id, name, email").in("id",g),y={};(v||[]).forEach(b=>{y[b.id]={name:b.name,email:b.email}}),i(y)}}finally{o(!1)}},d=s.reduce((h,m)=>({users:h.users+1,contacts:h.contacts+Number(m.contacts_saved||0),listings:h.listings+Number(m.listings_imported||0),activities:h.activities+Number(m.activities_logged||0),events:h.events+Number(m.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(be,{children:e.jsx(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(On,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(t7,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Pl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(qi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Users by Extension Activity"})}),e.jsx(Le,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{className:"text-right",children:"Total"}),e.jsx(Tt,{className:"text-right",children:"Contacts"}),e.jsx(Tt,{className:"text-right",children:"Listings"}),e.jsx(Tt,{className:"text-right",children:"Activities"}),e.jsx(Tt,{children:"First Used"}),e.jsx(Tt,{children:"Last Used"})]})}),e.jsx(Qa,{children:s.map(h=>e.jsxs(fn,{children:[e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(yt,{className:"text-right font-medium",children:h.total_events}),e.jsx(yt,{className:"text-right",children:h.contacts_saved}),e.jsx(yt,{className:"text-right",children:h.listings_imported}),e.jsx(yt,{className:"text-right",children:h.activities_logged}),e.jsx(yt,{className:"text-xs text-muted-foreground",children:h.first_event_at?Ys(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(yt,{className:"text-xs text-muted-foreground",children:h.last_event_at?Ys(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Recent Activity"})}),e.jsx(Le,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const m=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ze,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(m==null?void 0:m.name)||(m==null?void 0:m.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},e6n=()=>e.jsx($s,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs(Qr,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"analytics",children:"Analytics"}),e.jsx(Wt,{value:"website-apps",children:"Website Apps"}),e.jsx(Wt,{value:"extension",children:"Chrome Extension"}),e.jsx(Wt,{value:"content",children:"Content"}),e.jsx(Wt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Wt,{value:"activity",children:"Activity"}),e.jsx(Wt,{value:"shares",children:"Shares"})]}),e.jsx(Kt,{value:"analytics",className:"space-y-4",children:e.jsx(gln,{})}),e.jsx(Kt,{value:"website-apps",className:"space-y-4",children:e.jsx(QTn,{})}),e.jsx(Kt,{value:"extension",className:"space-y-4",children:e.jsx(JTn,{})}),e.jsx(Kt,{value:"content",className:"space-y-4",children:e.jsx(vln,{})}),e.jsx(Kt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(XTn,{})}),e.jsx(Kt,{value:"activity",className:"space-y-4",children:e.jsx(xln,{})}),e.jsx(Kt,{value:"shares",className:"space-y-4",children:e.jsx(gHt,{})})]})]})});function t6n(){const s=$t(),[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState([]),[p,f]=_.useState([]),[g,v]=_.useState([]),[y,b]=_.useState(!1),[w,S]=_.useState(null),[C,E]=_.useState(""),{data:P,isLoading:M}=rt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ve)throw Ve;return ke}}),{data:I}=rt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),{data:D}=rt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),{data:F}=rt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),{data:q,isLoading:G}=rt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),V=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),f([]),v([]),a(null),E("")},H=ke=>{a(ke),l({title:ke.title,description:ke.description||"",publish_date:ke.publish_date.split("T")[0],is_published:ke.is_published,category_id:ke.category_id||""}),u(ke.preview_image_url||""),E("");const Ve=(I==null?void 0:I.filter(Se=>Se.resource_id===ke.id))||[];m(Ve.map(Se=>({id:Se.id,name:Se.name,file_url:Se.file_url,file_size:Se.file_size,sort_order:Se.sort_order})));const _e=(D==null?void 0:D.filter(Se=>Se.resource_id===ke.id))||[];f(_e.map(Se=>({id:Se.id,title:Se.title,video_url:Se.video_url,sort_order:Se.sort_order})));const Ae=(F==null?void 0:F.filter(Se=>Se.resource_id===ke.id))||[];v(Ae.map(Se=>({id:Se.id,title:Se.title,canva_share_link:Se.canva_share_link,sort_order:Se.sort_order}))),n(!0)},K=ke=>{var _e;const Ve=(_e=ke.target.files)==null?void 0:_e[0];Ve&&(c(Ve),u(URL.createObjectURL(Ve)))},Z=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},oe=ke=>{m(h.filter((Ve,_e)=>_e!==ke))},re=(ke,Ve,_e)=>{const Ae=[...h];if(Ve==="file"&&_e instanceof File){const Se=_e.name.replace(/\.[^/.]+$/,"");Ae[ke]={...Ae[ke],file:_e,file_size:_e.size,name:Ae[ke].name||Se}}else Ae[ke]={...Ae[ke],[Ve]:_e};m(Ae)},ae=()=>{f([...p,{title:"",video_url:"",sort_order:p.length}])},J=ke=>{f(p.filter((Ve,_e)=>_e!==ke))},te=(ke,Ve,_e)=>{const Ae=[...p];Ve==="file"&&_e instanceof File?Ae[ke]={...Ae[ke],file:_e}:Ae[ke]={...Ae[ke],[Ve]:_e},f(Ae)},ce=()=>{v([...g,{title:"",canva_share_link:"",sort_order:g.length}])},ve=ke=>{v(g.filter((Ve,_e)=>_e!==ke))},me=(ke,Ve,_e)=>{const Ae=[...g];Ae[ke]={...Ae[ke],[Ve]:_e},v(Ae)},he=async(ke,Ve)=>{try{const _e=await U.functions.invoke("bunny-upload",{body:{action:"create",title:ke.name}});if(_e.error)throw _e.error;const{videoId:Ae,uploadUrl:Se,libraryId:We}=_e.data,qe=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ae,libraryId:We}});if(qe.error)throw qe.error;const{uploadUrl:Be,apiKey:Ze}=qe.data,$e=new XMLHttpRequest;return $e.open("PUT",Be,!0),$e.setRequestHeader("AccessKey",Ze),$e.upload.onprogress=Xe=>{if(Xe.lengthComputable){const nt=Math.round(Xe.loaded/Xe.total*100),Ge=[...p];Ge[Ve]={...Ge[Ve],uploadProgress:nt},f(Ge)}},await new Promise((Xe,nt)=>{$e.onload=()=>$e.status>=200&&$e.status<300?Xe():nt(new Error("Upload failed")),$e.onerror=()=>nt(new Error("Upload failed")),$e.send(ke)}),`https://iframe.mediadelivery.net/embed/${We}/${Ae}`}catch(_e){throw console.error("Bunny upload error:",_e),_e}},ge=mt({mutationFn:async ke=>{const{data:Ve,error:_e}=await U.from("brokerage_resource_categories").insert({name:ke,sort_order:(q==null?void 0:q.length)||0}).select().single();if(_e)throw _e;return Ve},onSuccess:ke=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ke.id}),E(""),ne.success("Category created")},onError:ke=>{ne.error("Failed to create category: "+ke.message)}}),Ee=mt({mutationFn:async()=>{b(!0);let ke=(r==null?void 0:r.preview_image_url)||null;if(o){const Ae=o.name.split(".").pop(),Se=`${Date.now()}.${Ae}`,{error:We}=await U.storage.from("brokerage-resources").upload(`previews/${Se}`,o);if(We)throw We;const{data:qe}=U.storage.from("brokerage-resources").getPublicUrl(`previews/${Se}`);ke=qe.publicUrl}const Ve={title:i.title,description:i.description||null,preview_image_url:ke,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let _e;if(r){const{error:Ae}=await U.from("brokerage_resources").update(Ve).eq("id",r.id);if(Ae)throw Ae;_e=r.id;const Se=(I==null?void 0:I.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],We=h.filter(Je=>Je.id).map(Je=>Je.id),qe=Se.filter(Je=>!We.includes(Je));qe.length>0&&await U.from("brokerage_resource_pdfs").delete().in("id",qe);const Be=(D==null?void 0:D.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],Ze=p.filter(Je=>Je.id).map(Je=>Je.id),$e=Be.filter(Je=>!Ze.includes(Je));$e.length>0&&await U.from("brokerage_resource_videos").delete().in("id",$e);const Xe=(F==null?void 0:F.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],nt=g.filter(Je=>Je.id).map(Je=>Je.id),Ge=Xe.filter(Je=>!nt.includes(Je));Ge.length>0&&await U.from("brokerage_resource_links").delete().in("id",Ge)}else{const{data:Ae,error:Se}=await U.from("brokerage_resources").insert(Ve).select().single();if(Se)throw Se;_e=Ae.id}for(let Ae=0;Ae{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ne.success(r?"Resource updated":"Resource created"),n(!1),V(),b(!1)},onError:ke=>{ne.error("Failed to save resource: "+ke.message),b(!1)}}),Ne=mt({mutationFn:async ke=>{const{error:Ve}=await U.from("brokerage_resources").delete().eq("id",ke);if(Ve)throw Ve},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ne.success("Resource deleted")},onError:ke=>{ne.error("Failed to delete: "+ke.message)}}),Pe=ke=>{if(ke.preventDefault(),!i.title){ne.error("Please enter a title");return}Ee.mutate()},Oe=ke=>{const Ve=(I==null?void 0:I.filter(Se=>Se.resource_id===ke).length)||0,_e=(D==null?void 0:D.filter(Se=>Se.resource_id===ke).length)||0,Ae=(F==null?void 0:F.filter(Se=>Se.resource_id===ke).length)||0;return{pdfCount:Ve,videoCount:_e,linkCount:Ae}};return e.jsx($s,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.length)||0})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.filter(ke=>ke.is_published).length)||0})})]})]}),e.jsxs(z,{onClick:()=>{V(),n(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Content"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:M?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(P==null?void 0:P.length)===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):P==null?void 0:P.map(ke=>{const{pdfCount:Ve,videoCount:_e,linkCount:Ae}=Oe(ke.id),Se=q==null?void 0:q.find(We=>We.id===ke.category_id);return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ke.preview_image_url?e.jsx("img",{src:ke.preview_image_url,alt:ke.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(Px,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ke.title}),ke.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ke.description})]})]})}),e.jsx(yt,{children:Se?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Se.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(yt,{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($r,{className:"h-3.5 w-3.5"}),Ve]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),_e]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Kc,{className:"h-3.5 w-3.5"}),Ae]})]})}),e.jsx(yt,{children:Ys(new Date(ke.publish_date),"MMM d, yyyy")}),e.jsx(yt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ke.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ke.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{const We=(I==null?void 0:I.filter(Ze=>Ze.resource_id===ke.id))||[],qe=(D==null?void 0:D.filter(Ze=>Ze.resource_id===ke.id))||[],Be=(F==null?void 0:F.filter(Ze=>Ze.resource_id===ke.id))||[];S({...ke,pdfs:We,videos:qe,links:Be})},children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>H(ke),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi("Delete this resource?")&&Ne.mutate(ke.id)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},ke.id)})})]})})}),e.jsx(Is,{open:t,onOpenChange:n,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Pe,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(Px,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(pe,{type:"file",accept:"image/*",onChange:K})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i.title,onChange:ke=>l({...i,title:ke.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Ip,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:i.category_id,onValueChange:ke=>l({...i,category_id:ke}),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(cs,{placeholder:"Select a category"})}),e.jsx(as,{children:q==null?void 0:q.map(ke=>e.jsx(He,{value:ke.id,children:ke.name},ke.id))})]}),i.category_id&&e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Or create new category...",value:C,onChange:ke=>E(ke.target.value),className:"flex-1"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:!C.trim()||ge.isPending,onClick:()=>ge.mutate(C.trim()),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:i.description,onChange:ke=>l({...i,description:ke}),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(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:i.publish_date,onChange:ke=>l({...i,publish_date:ke.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(mn,{checked:i.is_published,onCheckedChange:ke=>l({...i,is_published:ke})}),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(ee,{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:Z,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((ke,Ve)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(pe,{placeholder:"PDF Name",value:ke.name,onChange:_e=>re(Ve,"name",_e.target.value),className:"flex-1"}),e.jsx(pe,{type:"file",accept:".pdf",onChange:_e=>{var Se;const Ae=(Se=_e.target.files)==null?void 0:Se[0];Ae&&re(Ve,"file",Ae)},className:"flex-1"}),ke.file_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>oe(Ve),children:e.jsx(er,{className:"h-4 w-4"})})]},Ve))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Videos (",p.length,")"]}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:ae,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),p.map((ke,Ve)=>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(pe,{placeholder:"Video Title",value:ke.title,onChange:_e=>te(Ve,"title",_e.target.value),className:"flex-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>J(Ve),children:e.jsx(er,{className:"h-4 w-4"})})]}),e.jsx(pe,{type:"file",accept:"video/*",onChange:_e=>{var Se;const Ae=(Se=_e.target.files)==null?void 0:Se[0];Ae&&te(Ve,"file",Ae)}}),ke.uploadProgress!==void 0&&ke.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:`${ke.uploadProgress}%`}})}),ke.video_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Ve))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Kc,{className:"h-4 w-4"}),"Canva Links (",g.length,")"]}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),g.map((ke,Ve)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(pe,{placeholder:"Link Title",value:ke.title,onChange:_e=>me(Ve,"title",_e.target.value),className:"flex-1"}),e.jsx(pe,{placeholder:"Canva Share Link",value:ke.canva_share_link,onChange:_e=>me(Ve,"canva_share_link",_e.target.value),className:"flex-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>ve(Ve),children:e.jsx(er,{className:"h-4 w-4"})})]},Ve))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:Ee.isPending||y,children:Ee.isPending||y?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(Is,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:w==null?void 0:w.title})}),w&&e.jsxs("div",{className:"space-y-4",children:[w.preview_image_url&&e.jsx("img",{src:w.preview_image_url,alt:w.title,className:"w-full h-48 object-cover rounded-lg"}),w.description&&e.jsx("p",{className:"text-muted-foreground",children:w.description}),w.pdfs&&w.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),"PDF Documents (",w.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.pdfs.map(ke=>e.jsx("a",{href:ke.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.name},ke.id))})]}),w.videos&&w.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Videos (",w.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.videos.map(ke=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ke.title})},ke.id))})]}),w.links&&w.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Kc,{className:"h-4 w-4"}),"Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.links.map(ke=>e.jsx("a",{href:ke.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.title},ke.id))})]})]})]})})]})})}const dYt=[{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 s6n(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState(""),[v,y]=_.useState(""),[b,w]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState("Learn More"),[M,I]=_.useState("top"),[D,F]=_.useState(""),[q,G]=_.useState(!0),[V,H]=_.useState(""),[K,Z]=_.useState("");_.useEffect(()=>{oe()},[]);const oe=async()=>{try{const{data:ge,error:Ee}=await U.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ee)throw Ee;t(ge||[])}catch(ge){ne.error("Failed to load banners: "+ge.message)}finally{r(!1)}},re=()=>{g(""),y(""),w(""),C(""),P("Learn More"),I("top"),F(""),G(!0),H(""),Z(""),d(null)},ae=ge=>{d(ge),g(ge.title),y(ge.description||""),w(ge.image_url),C(ge.link_url||""),P(ge.link_text||"Learn More"),I(ge.placement),F(ge.section_after||""),G(ge.is_active),H(ge.start_date?Ys(new Date(ge.start_date),"yyyy-MM-dd'T'HH:mm"):""),Z(ge.end_date?Ys(new Date(ge.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},J=async ge=>{var Ne;const Ee=(Ne=ge.target.files)==null?void 0:Ne[0];if(Ee){h(!0);try{const Pe=Ee.name.split(".").pop(),Oe=`${Date.now()}.${Pe}`,{error:ke}=await U.storage.from("banner-images").upload(Oe,Ee);if(ke)throw ke;const{data:{publicUrl:Ve}}=U.storage.from("banner-images").getPublicUrl(Oe);w(Ve),ne.success("Image uploaded successfully")}catch(Pe){ne.error("Failed to upload image: "+Pe.message)}finally{h(!1)}}},te=async()=>{if(!f.trim()||!b){ne.error("Please fill in required fields (title and image)");return}p(!0);try{const ge={title:f.trim(),description:v.trim()||null,image_url:b,link_url:S.trim()||null,link_text:E.trim()||"Learn More",placement:M,section_after:M==="between"?D:null,is_active:q,start_date:V?new Date(V).toISOString():null,end_date:K?new Date(K).toISOString():null};if(c){const{error:Ee}=await U.from("dashboard_banners").update(ge).eq("id",c.id);if(Ee)throw Ee;ne.success("Banner updated successfully")}else{const Ee=s.filter(Pe=>Pe.placement===M).length,{error:Ne}=await U.from("dashboard_banners").insert({...ge,sort_order:Ee});if(Ne)throw Ne;ne.success("Banner created successfully")}i(!1),re(),oe()}catch(ge){ne.error("Failed to save banner: "+ge.message)}finally{p(!1)}},ce=async()=>{if(c)try{const{error:ge}=await U.from("dashboard_banners").delete().eq("id",c.id);if(ge)throw ge;ne.success("Banner deleted successfully"),o(!1),d(null),oe()}catch(ge){ne.error("Failed to delete banner: "+ge.message)}},ve=async ge=>{try{const{error:Ee}=await U.from("dashboard_banners").update({is_active:!ge.is_active}).eq("id",ge.id);if(Ee)throw Ee;ne.success(ge.is_active?"Banner deactivated":"Banner activated"),oe()}catch(Ee){ne.error("Failed to update banner: "+Ee.message)}},me=s.filter(ge=>ge.placement==="top"),he=s.filter(ge=>ge.placement==="between");return n?e.jsx($s,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs($s,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(nc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(En,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(Is,{open:a&&M==="top",onOpenChange:ge=>{ge||re(),i(ge),ge&&I("top")},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{onClick:()=>{re(),I("top")},children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(_r,{children:"Configure the banner's content and display settings"})]}),e.jsx(Njt,{title:f,setTitle:g,description:v,setDescription:y,imageUrl:b,linkUrl:S,setLinkUrl:C,linkText:E,setLinkText:P,placement:M,setPlacement:I,sectionAfter:D,setSectionAfter:F,isActive:q,setIsActive:G,startDate:V,setStartDate:H,endDate:K,setEndDate:Z,handleImageUpload:J,uploading:u,showPlacementOptions:!1}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>{i(!1),re()},children:"Cancel"}),e.jsx(z,{onClick:te,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Le,{children:me.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:me.map(ge=>e.jsx(kjt,{banner:ge,onEdit:()=>ae(ge),onDelete:()=>{d(ge),o(!0)},onToggleActive:()=>ve(ge)},ge.id))})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(nc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(En,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(Is,{open:a&&M==="between",onOpenChange:ge=>{ge||re(),i(ge),ge&&I("between")},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{onClick:()=>{re(),I("between")},children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(_r,{children:"Configure where this banner appears between sections"})]}),e.jsx(Njt,{title:f,setTitle:g,description:v,setDescription:y,imageUrl:b,linkUrl:S,setLinkUrl:C,linkText:E,setLinkText:P,placement:M,setPlacement:I,sectionAfter:D,setSectionAfter:F,isActive:q,setIsActive:G,startDate:V,setStartDate:H,endDate:K,setEndDate:Z,handleImageUpload:J,uploading:u,showPlacementOptions:!0}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>{i(!1),re()},children:"Cancel"}),e.jsx(z,{onClick:te,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Le,{children:he.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:he.map(ge=>e.jsx(kjt,{banner:ge,onEdit:()=>ae(ge),onDelete:()=>{d(ge),o(!0)},onToggleActive:()=>ve(ge),showSection:!0},ge.id))})})]})]}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Delete Banner"}),e.jsxs(_r,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(z,{variant:"destructive",onClick:ce,children:"Delete"})]})]})})]})}function Njt({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:p,setIsActive:f,startDate:g,setStartDate:v,endDate:y,setEndDate:b,handleImageUpload:w,uploading:S,showPlacementOptions:C}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",placeholder:"Banner headline...",value:s,onChange:E=>t(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",placeholder:"Optional banner description...",value:n,onChange:E=>r(E.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:w,disabled:S,className:"flex-1"}),S&&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(ee,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(pe,{id:"linkUrl",placeholder:"https://...",value:i,onChange:E=>l(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"linkText",children:"Button Text"}),e.jsx(pe,{id:"linkText",placeholder:"Learn More",value:o,onChange:E=>c(E.target.value)})]})]}),C&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Placement"}),e.jsxs(ls,{value:h,onValueChange:m,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select section placement..."})}),e.jsx(as,{children:dYt.map(E=>e.jsx(He,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(pe,{id:"startDate",type:"datetime-local",value:g,onChange:E=>v(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(pe,{id:"endDate",type:"datetime-local",value:y,onChange:E=>b(E.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(mn,{id:"isActive",checked:p,onCheckedChange:f}),e.jsx(ee,{htmlFor:"isActive",children:"Active"})]})})]})}function kjt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=dYt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=_.useState(null);return _.useEffect(()=>{(async()=>{const{count:u}=await U.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Zf,{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(Gh,{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(z,{variant:"ghost",size:"icon",children:e.jsx(mr,{className:"h-4 w-4"})})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Yf,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})]})}const $ce={open:{label:"Open",icon:Zr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Bu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Xl,color:"bg-green-500"},closed:{label:"Closed",icon:Bd,color:"bg-muted-foreground"}},Sjt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function n6n(){var M,I;const{user:s}=hs(),t=$t(),[n,r]=_.useState(null),[a,i]=_.useState(""),[l,o]=_.useState([]),[c,d]=_.useState("all"),[u,h]=_.useState("all"),[m,p]=_.useState(!1),{data:f=[],isLoading:g}=rt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let D=U.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(D=D.eq("status",c)),u!=="all"&&(D=D.eq("category",u));const{data:F,error:q}=await D;if(q)throw q;return F}}),{data:v=[]}=rt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:D,error:F}=await U.from("user_roles").select("user_id").eq("role","admin");if(F)throw F;const q=D.map(oe=>oe.user_id),{data:G,error:V}=await U.from("profiles").select("id, name, email").in("id",q);if(V)throw V;const{data:H,error:K}=await U.from("support_notification_settings").select("user_id, receive_notifications");if(K)throw K;const Z=new Map((H==null?void 0:H.map(oe=>[oe.user_id,oe.receive_notifications]))||[]);return G.map(oe=>({...oe,receives_notifications:Z.get(oe.id)||!1}))}}),{data:y=[]}=rt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:D,error:F}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(F)throw F;return D},enabled:!!n}),b=mt({mutationFn:async({userId:D,enabled:F})=>{const{data:q}=await U.from("support_notification_settings").select("id").eq("user_id",D).maybeSingle();if(q){const{error:G}=await U.from("support_notification_settings").update({receive_notifications:F}).eq("user_id",D);if(G)throw G}else{const{error:G}=await U.from("support_notification_settings").insert({user_id:D,receive_notifications:F});if(G)throw G}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ne.success("Notification settings updated")},onError:()=>{ne.error("Failed to update settings")}}),w=mt({mutationFn:async({ticketId:D,status:F})=>{const{error:q}=await U.from("support_tickets").update({status:F}).eq("id",D);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ne.success("Status updated")},onError:()=>{ne.error("Failed to update status")}}),S=mt({mutationFn:async({ticketId:D,assignedTo:F})=>{const{error:q}=await U.from("support_tickets").update({assigned_to:F}).eq("id",D);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ne.success("Ticket assigned")},onError:()=>{ne.error("Failed to assign ticket")}}),C=mt({mutationFn:async({content:D,attachments:F})=>{var G,V;if(!n||!s)throw new Error("Missing data");const{error:q}=await U.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:D,is_admin_reply:!0,attachments:F});if(q)throw q;try{await U.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:D,userEmail:(G=n.profiles)==null?void 0:G.email,userName:(V=n.profiles)==null?void 0:V.name}})}catch(H){console.error("Failed to send reply notification:",H)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ne.success("Reply sent!")},onError:()=>{ne.error("Failed to send reply")}}),E=()=>{!a.trim()&&l.length===0||C.mutate({content:a,attachments:l})};_.useEffect(()=>{const D=U.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{U.removeChannel(D)}},[t]);const P=f.filter(D=>D.status==="open").length;return n?($ce[n.status].icon,e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(ka,{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:Sjt[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((M=n.profiles)==null?void 0:M.name)||"Unknown"," (",(I=n.profiles)==null?void 0:I.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm",children:"Status"})}),e.jsx(Le,{children:e.jsxs(ls,{value:n.status,onValueChange:D=>{w.mutate({ticketId:n.id,status:D}),r({...n,status:D})},children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"open",children:"Open"}),e.jsx(He,{value:"in_progress",children:"In Progress"}),e.jsx(He,{value:"resolved",children:"Resolved"}),e.jsx(He,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm",children:"Assigned To"})}),e.jsx(Le,{children:e.jsxs(ls,{value:n.assigned_to||"unassigned",onValueChange:D=>{const F=D==="unassigned"?null:D;S.mutate({ticketId:n.id,assignedTo:F}),r({...n,assigned_to:F})},children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Unassigned"})}),e.jsxs(as,{children:[e.jsx(He,{value:"unassigned",children:"Unassigned"}),v.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))]})]})})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(En,{children:["Created on ",Ys(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Le,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Le,{children:[e.jsx(Ki,{className:"h-[300px] pr-4",children:y.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:y.map(D=>{var F,q;return e.jsxs("div",{className:`p-4 rounded-lg ${D.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:D.is_admin_reply?`${((F=D.profiles)==null?void 0:F.name)||"Admin"} (Support)`:((q=D.profiles)==null?void 0:q.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(D.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:D.content}),D.attachments&&D.attachments.length>0&&e.jsx(lHt,{attachments:D.attachments})]},D.id)})})}),e.jsx(fc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ps,{placeholder:"Type your reply...",value:a,onChange:D=>i(D.target.value),className:"min-h-[80px]"}),e.jsx(z,{onClick:E,disabled:!a.trim()&&l.length===0||C.isPending,className:"self-end",children:e.jsx(Fr,{className:"h-4 w-4"})})]}),e.jsx(oHt,{value:l,onChange:o,disabled:C.isPending})]})]})]})]})})):e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",P>0&&e.jsxs(ze,{variant:"destructive",className:"ml-2",children:[P," open"]})]})]}),e.jsxs(Is,{open:m,onOpenChange:p,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",children:[e.jsx(Gc,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Email Notification Settings"}),e.jsx(_r,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:v.map(D=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[D.receives_notifications?e.jsx($g,{className:"h-4 w-4 text-primary"}):e.jsx(pS,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(mn,{checked:D.receives_notifications,onCheckedChange:F=>b.mutate({userId:D.id,enabled:F})})]})]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(Qr,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Jr,{children:[e.jsx(Wt,{value:"all",children:"All"}),e.jsx(Wt,{value:"open",children:"Open"}),e.jsx(Wt,{value:"in_progress",children:"In Progress"}),e.jsx(Wt,{value:"resolved",children:"Resolved"}),e.jsx(Wt,{value:"closed",children:"Closed"})]})}),e.jsxs(ls,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"All Categories"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Categories"}),e.jsx(He,{value:"general",children:"General Support"}),e.jsx(He,{value:"technology",children:"Technology Support"}),e.jsx(He,{value:"crm",children:"CRM Support"}),e.jsx(He,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:g?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):f.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"text-center py-12",children:[e.jsx(Bu,{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:f.map(D=>{var q,G;const F=$ce[D.status].icon;return e.jsx(be,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(D),children:e.jsx(Le,{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:D.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(ze,{variant:"outline",className:"text-xs",children:Sjt[D.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(q=D.profiles)==null?void 0:q.name," • ",Ys(new Date(D.created_at),"MMM d, yyyy")]}),D.assigned_to&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Oo,{className:"h-3 w-3"}),((G=v.find(V=>V.id===D.assigned_to))==null?void 0:G.name)||"Assigned"]})]})]}),e.jsxs(ze,{className:$ce[D.status].color,children:[e.jsx(F,{className:"h-3 w-3 mr-1"}),$ce[D.status].label]})]})})},D.id)})})})]})]})})}const uYt=Tv.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 r6n({content:s,onChange:t,variables:n}){const r=ULe({extensions:[qLe,HLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),GLe.configure({types:["heading","paragraph"]}),Mtt,uYt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});_.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(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(HA,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(KA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(My,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(bj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(QM,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(XM,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(JM,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(Kc,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(GA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(nE,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(tE,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(wq,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(qd,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(ua,{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($Le,{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 a6n(){const s=$t(),[t,n]=_.useState(null),[r,a]=_.useState(null),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(!0),[p,f]=_.useState("visual"),{data:g,isLoading:v}=rt({queryKey:["email-templates"],queryFn:async()=>{const{data:C,error:E}=await U.from("email_templates").select("*").order("name");if(E)throw E;return C.map(P=>({...P,available_variables:P.available_variables||[]}))}}),y=mt({mutationFn:async C=>{const{error:E}=await U.from("email_templates").update({subject:C.subject,body_html:C.body_html,description:C.description,is_active:C.is_active}).eq("id",C.id);if(E)throw E},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ne.success("Email template updated successfully"),n(null)},onError:C=>{ne.error("Failed to update template: "+C.message)}}),b=C=>{n(C),l(C.subject),c(C.body_html),u(C.description||""),m(C.is_active),f("visual")},w=()=>{t&&y.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},S=(C,E)=>{let P=C;return E.forEach(M=>{const I=`{{${M.key}}}`,D=`[${M.label}]`;P=P.replace(new RegExp(I.replace(/[{}]/g,"\\$&"),"g"),D)}),P};return t?e.jsxs($s,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(z,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(z,{variant:"outline",onClick:()=>a(t),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(z,{onClick:w,disabled:y.isPending,children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),y.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),t.name]}),e.jsxs(En,{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(ee,{htmlFor:"active-toggle",children:"Active"}),e.jsx(mn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",value:d,onChange:C=>u(C.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"subject",children:"Email Subject"}),e.jsx(pe,{id:"subject",value:i,onChange:C=>l(C.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(ee,{children:"Email Body"}),e.jsx(Qr,{value:p,onValueChange:C=>f(C),children:e.jsxs(Jr,{className:"h-8",children:[e.jsxs(Wt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(yN,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Wt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(GA,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),p==="visual"?e.jsx(r6n,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ps,{value:o,onChange:C=>c(C.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(Is,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Email Preview"}),e.jsxs(_r,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:S(o,t.available_variables)}})})]})})]}):e.jsx($s,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),v?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((C,E)=>e.jsx(be,{children:e.jsxs(_t,{children:[e.jsx(ln,{className:"h-5 w-48"}),e.jsx(ln,{className:"h-4 w-96"})]})},E))}):e.jsx("div",{className:"grid gap-4",children:g==null?void 0:g.map(C=>e.jsxs(be,{className:"hover:shadow-md transition-shadow",children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(on,{className:"h-5 w-5 text-muted-foreground"}),C.name,!C.is_active&&e.jsx(ze,{variant:"secondary",children:"Inactive"})]}),e.jsx(En,{children:C.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>a(C),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(z,{size:"sm",onClick:()=>b(C),children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Le,{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:C.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:C.available_variables.map(E=>e.jsx(ze,{variant:"outline",className:"font-mono text-xs",children:`{{${E.key}}}`},E.key))})]})]})})]},C.id))}),e.jsx(Is,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(_r,{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:S(r.body_html,r.available_variables)}})})]})})]})})}function i6n(){const s=$t(),[t,n]=_.useState("templates"),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[p,f]=_.useState({name:"",description:"",icon:"📧"}),{data:g=[]}=rt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:D,error:F}=await U.from("email_template_categories").select("*").order("sort_order");if(F)throw F;return D}}),{data:v=[],isLoading:y}=rt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:D,error:F}=await U.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(F)throw F;return D}}),b=mt({mutationFn:async D=>{const F={title:D.title,subject:D.subject,body:D.body,description:D.description||null,tone:D.tone||null,category_id:D.category_id||null,is_active:D.is_active};if(D.id){const{error:q}=await U.from("agent_email_templates").update(F).eq("id",D.id);if(q)throw q}else{const{error:q}=await U.from("agent_email_templates").insert(F);if(q)throw q}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ne.success(r?"Template updated":"Template created")},onError:()=>ne.error("Failed to save template")}),w=mt({mutationFn:async D=>{const{error:F}=await U.from("agent_email_templates").delete().eq("id",D);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ne.success("Template deleted")}}),S=mt({mutationFn:async D=>{const F={name:D.name,description:D.description||null,icon:D.icon};if(D.id){const{error:q}=await U.from("email_template_categories").update(F).eq("id",D.id);if(q)throw q}else{const q=g.length>0?Math.max(...g.map(V=>V.sort_order))+1:0,{error:G}=await U.from("email_template_categories").insert({...F,sort_order:q});if(G)throw G}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ne.success(i?"Category updated":"Category created")},onError:()=>ne.error("Failed to save category")}),C=mt({mutationFn:async D=>{const{error:F}=await U.from("email_template_categories").delete().eq("id",D);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ne.success("Category deleted")}}),E=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},P=D=>{a(D),m({title:D.title,subject:D.subject,body:D.body,description:D.description||"",tone:D.tone||"",category_id:D.category_id||"",is_active:D.is_active}),c(!0)},M=()=>{l(null),f({name:"",description:"",icon:"📧"}),u(!0)},I=D=>{l(D),f({name:D.name,description:D.description||"",icon:D.icon}),u(!0)};return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Xh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(Qr,{value:t,onValueChange:n,children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"templates",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Wt,{value:"categories",className:"gap-2",children:[e.jsx(wv,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Kt,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:E,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Template"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:y?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8",children:e.jsx(bt,{className:"h-6 w-6 animate-spin mx-auto"})})}):v.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):v.map(D=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:D.subject})]})}),e.jsx(yt,{className:"hidden md:table-cell",children:D.category?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[D.category.icon," ",D.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(yt,{className:"hidden md:table-cell",children:D.tone?e.jsx(ze,{variant:"secondary",children:D.tone}):"—"}),e.jsx(yt,{children:e.jsx(ze,{variant:D.is_active?"default":"secondary",children:D.is_active?"Active":"Inactive"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>P(D),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await Qi("Delete this template?")&&w.mutate(D.id)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},D.id))})]})})})]}),e.jsxs(Kt,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:M,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:g.map(D=>e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:D.icon})," ",D.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(D),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await Qi("Delete this category?")&&C.mutate(D.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Le,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[v.filter(F=>F.category_id===D.id).length," templates"]})]})]},D.id))})]})]}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Title"}),e.jsx(pe,{value:h.title,onChange:D=>m(F=>({...F,title:D.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ls,{value:h.category_id,onValueChange:D=>m(F=>({...F,category_id:D})),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select category"})}),e.jsx(as,{children:g.map(D=>e.jsxs(He,{value:D.id,children:[D.icon," ",D.name]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Subject Line"}),e.jsx(pe,{value:h.subject,onChange:D=>m(F=>({...F,subject:D.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(ee,{children:"Email Body"}),e.jsx(Ps,{value:h.body,onChange:D=>m(F=>({...F,body:D.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(ee,{children:"Description (internal)"}),e.jsx(pe,{value:h.description,onChange:D=>m(F=>({...F,description:D.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tone"}),e.jsx(pe,{value:h.tone,onChange:D=>m(F=>({...F,tone:D.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:h.is_active,onCheckedChange:D=>m(F=>({...F,is_active:D}))}),e.jsx(ee,{children:"Active"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>b.mutate({...h,id:r==null?void 0:r.id}),disabled:b.isPending||!h.title||!h.subject||!h.body,children:[b.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(Is,{open:d,onOpenChange:u,children:e.jsxs(Ls,{className:"sm:max-w-[450px]",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Icon"}),e.jsx(pe,{value:p.icon,onChange:D=>f(F=>({...F,icon:D.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:p.name,onChange:D=>f(F=>({...F,name:D.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:p.description,onChange:D=>f(F=>({...F,description:D.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>S.mutate({...p,id:i==null?void 0:i.id}),disabled:S.isPending||!p.name,children:[S.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const o6n=({brokerageId:s})=>{var Qt,ks,gs;const{toast:t}=_i(),n=zn(),[r,a]=_.useState([]),[i,l]=_.useState(!0),[o,c]=_.useState(""),[d,u]=_.useState("all"),[h,m]=_.useState(new Set),[p,f]=_.useState(!1),[g,v]=_.useState({}),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=_.useState({email:"",name:"",password:"",phone:""}),[P,M]=_.useState(null),[I,D]=_.useState([]),[F,q]=_.useState("none"),[G,V]=_.useState(!1),[H,K]=_.useState(null),[Z,oe]=_.useState(!1),[re,ae]=_.useState(!1),[J,te]=_.useState(!1),[ce,ve]=_.useState(""),[me,he]=_.useState(!1),[ge,Ee]=_.useState([]),[Ne,Pe]=_.useState(!1),[Oe,ke]=_.useState(!1),[Ve,_e]=_.useState(null),[Ae,Se]=_.useState({name:"",phone:"",email:""}),[We,qe]=_.useState(!1),[Be,Ze]=_.useState(!1),[$e,Xe]=_.useState(null),[nt,Ge]=_.useState("asc"),[Je,ut]=_.useState(!1),[lt,qt]=_.useState(null),[zt,Zt]=_.useState(!1),[ms,Dt]=_.useState(null),[It,qs]=_.useState(""),[wt,Us]=_.useState(!1),[Es,kn]=_.useState(null);_.useEffect(()=>{cr(),bn(),Sn()},[s]);const Sn=async()=>{try{const{data:Vt}=await U.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Vt||!Vt.enabled){M(null),D([]);return}const{data:Vs}=await U.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Vt.id).order("sort_order",{ascending:!0});M({id:Vt.id,name:Vt.name}),D(Vs||[]),Vs&&Vs.length>0&&q(Vs[0].id)}catch(Vt){console.error("Error loading partnership packages:",Vt)}},bn=async()=>{try{const{data:Vt,error:Vs}=await U.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Vs)throw Vs;Ee((Vt==null?void 0:Vt.map(Zs=>Zs.user_id))||[])}catch(Vt){console.error("Error loading brokerage managers:",Vt)}},cr=async()=>{try{l(!0);const{data:Vt,error:Vs}=await U.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Vs)throw Vs;const Zs=Vt.agents||[];if(a(Zs),Zs.length>0){const Zn=Zs.map(oa=>oa.id),{data:Or}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",Zn);if(Or&&Or.length>0){const oa=Or.map(Tr=>Tr.assistant_id),{data:aa}=await U.from("profiles").select("id, name, email").in("id",oa),Kr={};for(const Tr of Or){const Hr=aa==null?void 0:aa.find(Ba=>Ba.id===Tr.assistant_id);Hr&&(Kr[Tr.agent_id]={name:Hr.name||"",email:Hr.email||""})}v(Kr)}else v({})}}catch(Vt){console.error("Error loading agents:",Vt),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},Fs=async()=>{var Vt;if(!C.email||!C.name||!C.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}S(!0);try{const{data:{session:Vs}}=await U.auth.getSession(),Zs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vs==null?void 0:Vs.access_token}`},body:JSON.stringify({...C,brokerageId:s,partnershipPackageId:P&&F!=="none"?F:void 0})}),Zn=await Zs.json();if(!Zs.ok)throw new Error(Zn.error||"Failed to create agent");t({title:"Success",description:`Agent ${C.email} created successfully`}),E({email:"",name:"",password:"",phone:""}),q(((Vt=I[0])==null?void 0:Vt.id)||"none"),b(!1),cr()}catch(Vs){console.error("Error creating agent:",Vs),t({title:"Error",description:Vs.message||"Failed to create agent",variant:"destructive"})}finally{S(!1)}},cn=async Vt=>{try{const{data:{session:Vs}}=await U.auth.getSession(),Zs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vs==null?void 0:Vs.access_token}`},body:JSON.stringify({userId:Vt})}),Zn=await Zs.json();if(!Zs.ok)throw new Error(Zn.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Vs){console.error("Error resending welcome email:",Vs),t({title:"Error",description:Vs.message||"Failed to resend welcome email",variant:"destructive"})}},lr=async(Vt,Vs)=>{try{const{error:Zs}=await U.functions.invoke("send-password-reset",{body:{email:Vt,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(Zs)throw Zs;t({title:"Password Reset Sent",description:`Password reset email sent to ${Vs}`})}catch(Zs){console.error("Error sending password reset:",Zs),t({title:"Error",description:Zs.message||"Failed to send password reset email",variant:"destructive"})}},Tn=Vt=>{K(Vt),V(!0)},Yn=Vt=>{_e(Vt),Se({name:Vt.name,phone:Vt.phone||"",email:Vt.email}),ke(!0)},fs=async()=>{if(!Ve)return;if(!Ae.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Vt=Ae.email.trim().toLowerCase()!==Ve.email.toLowerCase();qe(!0);try{if(Vt){if(!Ae.email.trim())throw new Error("Email is required");Ze(!0);const{data:{session:Zs}}=await U.auth.getSession(),Zn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zs==null?void 0:Zs.access_token}`},body:JSON.stringify({agentId:Ve.id,newEmail:Ae.email.trim(),brokerageId:s})}),Or=await Zn.json();if(Ze(!1),!Zn.ok)throw new Error(Or.error||"Failed to update email")}const{error:Vs}=await U.from("profiles").update({name:Ae.name.trim(),phone:Ae.phone.trim()||null}).eq("id",Ve.id);if(Vs)throw Vs;t({title:"Success",description:"Agent profile updated successfully"}),ke(!1),_e(null),cr()}catch(Vs){console.error("Error updating agent:",Vs),t({title:"Error",description:Vs.message||"Failed to update agent",variant:"destructive"})}finally{qe(!1),Ze(!1)}},wn=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}he(!0);try{const{data:{session:Vt}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vt==null?void 0:Vt.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),Zs=await Vs.json();if(!Vs.ok)throw new Error(Zs.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),te(!1),ve(""),bn()}catch(Vt){console.error("Error adding brokerage manager:",Vt),t({title:"Error",description:Vt.message||"Failed to add brokerage manager",variant:"destructive"})}finally{he(!1)}},As=async Vt=>{try{const{data:{session:Vs}}=await U.auth.getSession(),Zs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vs==null?void 0:Vs.access_token}`},body:JSON.stringify({userId:Vt,role:"brokerage_manager",action:"remove",brokerageId:s})}),Zn=await Zs.json();if(!Zs.ok)throw new Error(Zn.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),bn()}catch(Vs){console.error("Error removing brokerage manager:",Vs),t({title:"Error",description:Vs.message||"Failed to remove brokerage manager",variant:"destructive"})}},Ss=Vt=>ge.includes(Vt),pr=Vt=>{Dt(Vt),qs(""),Zt(!0)},hn=async()=>{if(!(!ms||!It)){if(It.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Us(!0);try{const{data:{session:Vt}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vt==null?void 0:Vt.access_token}`},body:JSON.stringify({agentId:ms.id,brokerageId:s,action:"set_password",newPassword:It})}),Zs=await Vs.json();if(!Vs.ok)throw new Error(Zs.error||"Failed to set password");t({title:"Success",description:`Password set for ${ms.name}`}),Zt(!1),Dt(null),qs("")}catch(Vt){console.error("Error setting password:",Vt),t({title:"Error",description:Vt.message||"Failed to set password",variant:"destructive"})}finally{Us(!1)}}},Pn=async Vt=>{kn(Vt.id);try{const{data:{session:Vs}}=await U.auth.getSession(),Zs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vs==null?void 0:Vs.access_token}`},body:JSON.stringify({agentId:Vt.id,brokerageId:s,action:"claim_account"})}),Zn=await Zs.json();if(!Zs.ok)throw new Error(Zn.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Vt.name}`}),cr()}catch(Vs){console.error("Error claiming account:",Vs),t({title:"Error",description:Vs.message||"Failed to claim account",variant:"destructive"})}finally{kn(null)}},Gs=async()=>{if(H){oe(!0);try{const{data:{session:Vt}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vt==null?void 0:Vt.access_token}`},body:JSON.stringify({userId:H.id,brokerageId:s})}),Zs=await Vs.json();if(!Vs.ok)throw new Error(Zs.error||"Failed to remove agent");t({title:"Success",description:`${H.name} has been removed from your brokerage`}),V(!1),K(null),cr()}catch(Vt){console.error("Error removing agent:",Vt),t({title:"Error",description:Vt.message||"Failed to remove agent",variant:"destructive"})}finally{oe(!1)}}},an=Vt=>{const Vs=Vt.trim().split(" ");return Vs.length>1?Vs[Vs.length-1].toLowerCase():Vt.toLowerCase()},tr=Vt=>{$e===Vt?Ge(nt==="asc"?"desc":"asc"):(Xe(Vt),Ge("asc"))},Lr=Vt=>$e!==Vt?e.jsx(Og,{className:"ml-1 h-4 w-4"}):nt==="asc"?e.jsx(ap,{className:"ml-1 h-4 w-4"}):e.jsx(Vf,{className:"ml-1 h-4 w-4"}),Yt=r.filter(Vt=>{if(d==="active"&&!Vt.claimed||d==="pending"&&Vt.claimed)return!1;if(!o)return!0;const Vs=o.toLowerCase();return Vt.name.toLowerCase().includes(Vs)||Vt.email.toLowerCase().includes(Vs)}),it=[...Yt].sort((Vt,Vs)=>{if(!$e)return 0;let Zs=0;return $e==="name"?Zs=an(Vt.name).localeCompare(an(Vs.name)):$e==="status"&&(Zs=Vt.claimed===Vs.claimed?0:Vt.claimed?-1:1),nt==="asc"?Zs:-Zs});Yt.filter(Vt=>Vt.claimed&&!Ss(Vt.id));const gt=Vt=>{m(Vs=>{const Zs=new Set(Vs);return Zs.has(Vt)?Zs.delete(Vt):Zs.add(Vt),Zs})},ft=()=>{h.size===it.length?m(new Set):m(new Set(it.map(Vt=>Vt.id)))},Lt=()=>{m(new Set)},Mt=async()=>{const Vt=Array.from(h);if(Vt.length===0)return;f(!0);let Vs=0,Zs=0;try{const{data:{session:Zn}}=await U.auth.getSession();for(const Or of Vt)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?Vs++:Zs++}catch{Zs++}Vs>0?t({title:"Success",description:`Welcome emails sent to ${Vs} agent${Vs>1?"s":""}${Zs>0?` (${Zs} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Lt()}catch(Zn){console.error("Error bulk sending welcome emails:",Zn),t({title:"Error",description:Zn.message||"Failed to send welcome emails",variant:"destructive"})}finally{f(!1)}};return i?e.jsx(be,{children:e.jsx(Le,{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(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Agents"}),e.jsx(En,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>te(!0),children:[e.jsx(Om,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(z,{variant:"outline",onClick:()=>ae(!0),children:[e.jsx(xN,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(z,{onClick:()=>b(!0),children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:o,onChange:Vt=>c(Vt.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:d,onValueChange:Vt=>u(Vt),children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(cs,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Agents"}),e.jsx(He,{value:"active",children:"Active"}),e.jsx(He,{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(z,{size:"sm",variant:"outline",onClick:()=>{const Vs=r.filter(Zs=>h.has(Zs.id)&&Zs.email).map(Zs=>({email:Zs.email,name:Zs.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Vs)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Vs}})},disabled:p,children:[e.jsx(Nh,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:Mt,disabled:p,children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),p?"Sending...":"Resend Welcome Email"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:Lt,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(za,{checked:it.length>0&&h.size===it.length,onCheckedChange:ft,"aria-label":"Select all"})}),e.jsx(Tt,{children:e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>tr("name"),children:["Name (Last)",Lr("name")]})}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>tr("status"),children:["Status",Lr("status")]})}),e.jsx(Tt,{children:"Actions"})]})}),e.jsx(Qa,{children:it.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):it.map(Vt=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx(za,{checked:h.has(Vt.id),onCheckedChange:()=>gt(Vt.id),"aria-label":`Select ${Vt.name}`})}),e.jsx(yt,{className:"font-medium",children:Vt.name}),e.jsx(yt,{children:Vt.email}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Vt.claimed?e.jsx(ze,{variant:"default",children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Pending"}),Ss(Vt.id)&&e.jsxs(ze,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(Ch,{className:"mr-1 h-3 w-3"}),"Manager"]}),g[Vt.id]&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[e.jsx(On,{className:"mr-1 h-3 w-3"}),"Asst: ",g[Vt.id].name||g[Vt.id].email]})]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>{qt(Vt),ut(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(Ix,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>Yn(Vt),title:"Edit agent",children:e.jsx(Wa,{className:"h-4 w-4"})}),!Vt.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>cn(Vt.id),title:"Resend welcome email",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>Pn(Vt),title:"Claim account for agent",disabled:Es===Vt.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(jj,{className:"h-4 w-4"})})]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>pr(Vt),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Hl,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>lr(Vt.email,Vt.name),title:"Send password reset email",children:e.jsx(iP,{className:"h-4 w-4"})}),Ss(Vt.id)&&e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>As(Vt.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Om,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>Tn(Vt),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},Vt.id))})]})})]})]}),e.jsx(Is,{open:y,onOpenChange:b,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add New Agent"}),e.jsx(_r,{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(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:C.name,onChange:Vt=>E({...C,name:Vt.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:C.email,onChange:Vt=>E({...C,email:Vt.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(pe,{id:"phone",type:"tel",value:C.phone,onChange:Vt=>E({...C,phone:Vt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"password",children:"Temporary Password"}),e.jsx(pe,{id:"password",type:"password",value:C.password,onChange:Vt=>E({...C,password:Vt.target.value}),placeholder:"Temporary password"})]}),P&&I.length>0&&e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"package",children:[P.name," Package"]}),e.jsxs(ls,{value:F,onValueChange:q,children:[e.jsx(rs,{id:"package",children:e.jsx(cs,{placeholder:"Choose a package"})}),e.jsxs(as,{children:[I.map(Vt=>e.jsx(He,{value:Vt.id,children:Vt.name},Vt.id)),e.jsx(He,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:F==="none"?"Agent gets unrestricted LevelUp access.":((Qt=I.find(Vt=>Vt.id===F))==null?void 0:Qt.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(z,{onClick:Fs,disabled:w,children:w?"Creating...":"Create Agent"})]})]})}),e.jsx(Is,{open:G,onOpenChange:V,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Remove Agent"}),e.jsxs(_r,{children:["Are you sure you want to remove ",e.jsx("strong",{children:H==null?void 0:H.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>V(!1),children:"Cancel"}),e.jsx(z,{variant:"destructive",onClick:Gs,disabled:Z,children:Z?"Removing...":"Remove Agent"})]})]})}),e.jsx(cHt,{open:re,onOpenChange:ae,fixedBrokerageId:s,onSuccess:cr}),e.jsx(Is,{open:J,onOpenChange:te,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add Brokerage Manager"}),e.jsx(_r,{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(ee,{children:"Select Agent"}),e.jsxs(hd,{open:Ne,onOpenChange:Pe,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox","aria-expanded":Ne,className:"w-full justify-between",children:[ce?((ks=r.find(Vt=>Vt.id===ce))==null?void 0:ks.name)+" ("+((gs=r.find(Vt=>Vt.id===ce))==null?void 0:gs.email)+")":"Select an agent to promote...",e.jsx(R_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-full p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search by name or email..."}),e.jsxs(Rj,{className:"max-h-[200px]",children:[e.jsx(Fj,{children:"No eligible agents found."}),e.jsx(G_,{children:r.filter(Vt=>!Ss(Vt.id)).map(Vt=>e.jsxs(c1,{value:`${Vt.name} ${Vt.email}`,onSelect:()=>{ve(Vt.id),Pe(!1)},children:[e.jsx(Wr,{className:`mr-2 h-4 w-4 ${ce===Vt.id?"opacity-100":"opacity-0"}`}),Vt.name," (",Vt.email,")"]},Vt.id))})]})]})})]}),r.filter(Vt=>!Ss(Vt.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>te(!1),children:"Cancel"}),e.jsx(z,{onClick:wn,disabled:me||!ce,children:me?"Adding...":"Add as Manager"})]})]})}),e.jsx(Is,{open:Oe,onOpenChange:ke,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Edit Agent"}),e.jsxs(_r,{children:["Update profile information for ",Ve==null?void 0:Ve.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"edit-name",children:"Name"}),e.jsx(pe,{id:"edit-name",value:Ae.name,onChange:Vt=>Se({...Ae,name:Vt.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"edit-email",children:"Email"}),e.jsx(pe,{id:"edit-email",type:"email",value:Ae.email,onChange:Vt=>Se({...Ae,email:Vt.target.value}),placeholder:"agent@example.com"}),Ae.email.trim().toLowerCase()!==(Ve==null?void 0:Ve.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(ee,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(pe,{id:"edit-phone",type:"tel",value:Ae.phone,onChange:Vt=>Se({...Ae,phone:Vt.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>ke(!1),children:"Cancel"}),e.jsx(z,{onClick:fs,disabled:We||Be,children:Be?"Updating email...":We?"Saving...":"Save Changes"})]})]})}),lt&&e.jsx(dHt,{open:Je,onOpenChange:Vt=>{ut(Vt),Vt||qt(null)},userId:lt.id,userName:lt.name}),e.jsx(Is,{open:zt,onOpenChange:Zt,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Set Password"}),e.jsxs(_r,{children:["Set a new password for ",ms==null?void 0:ms.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(ee,{htmlFor:"new-password",children:"New Password"}),e.jsx(pe,{id:"new-password",type:"password",value:It,onChange:Vt=>qs(Vt.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(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>Zt(!1),children:"Cancel"}),e.jsx(z,{onClick:hn,disabled:wt||!It||It.length<6,children:wt?"Setting...":"Set Password"})]})]})})]})},l6n={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},c6n={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},d6n=s=>{switch(s){case"academy_video":return e.jsx(Xr,{className:"h-4 w-4"});case"template":return e.jsx($r,{className:"h-4 w-4"});case"toolbox":return e.jsx($r,{className:"h-4 w-4"});case"newsletter":return e.jsx(vN,{className:"h-4 w-4"});case"social_swag":return e.jsx(un,{className:"h-4 w-4"});case"event":return e.jsx(ya,{className:"h-4 w-4"});default:return e.jsx(mr,{className:"h-4 w-4"})}},u6n=({brokerageId:s})=>{const{toast:t}=_i(),[n,r]=_.useState([]),[a,i]=_.useState([]),[l,o]=_.useState([]),[c,d]=_.useState(!0),[u,h]=_.useState(null);_.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:g,error:v}=await U.from("profiles").select("id, name, email").eq("brokerage_id",s);if(v)throw v;const y=g.map(F=>F.id),b=new Map(g.map(F=>[F.id,F]));if(y.length===0){r([]),i([]),o([]);return}const{data:w,error:S}=await U.from("activity_logs").select("*").in("user_id",y).order("launched_at",{ascending:!1});if(S)throw S;const C=w.map(F=>{var q,G;return{id:F.id,user_id:F.user_id,app_name:F.app_name,launched_at:F.launched_at,user_name:((q=b.get(F.user_id))==null?void 0:q.name)||"Unknown",user_email:((G=b.get(F.user_id))==null?void 0:G.email)||"Unknown"}});r(C);const{data:E,error:P}=await U.from("content_engagement_logs").select("*").in("user_id",y).order("created_at",{ascending:!1});if(P)throw P;const M=(E||[]).map(F=>{var q,G;return{id:F.id,user_id:F.user_id,resource_type:F.resource_type,resource_id:F.resource_id,resource_title:F.resource_title,action_type:F.action_type,created_at:F.created_at,user_name:((q=b.get(F.user_id))==null?void 0:q.name)||"Unknown",user_email:((G=b.get(F.user_id))==null?void 0:G.email)||"Unknown"}});i(M);const I=new Map;g.forEach(F=>{I.set(F.id,{user_id:F.id,user_name:F.name,user_email:F.email,app_launches:0,content_views:0,last_activity:""})}),C.forEach(F=>{const q=I.get(F.user_id);q&&(q.app_launches++,(!q.last_activity||new Date(F.launched_at)>new Date(q.last_activity))&&(q.last_activity=F.launched_at))}),M.forEach(F=>{const q=I.get(F.user_id);q&&(q.content_views++,(!q.last_activity||new Date(F.created_at)>new Date(q.last_activity))&&(q.last_activity=F.created_at))});const D=Array.from(I.values()).filter(F=>F.app_launches>0||F.content_views>0).sort((F,q)=>new Date(q.last_activity).getTime()-new Date(F.last_activity).getTime());o(D)}catch(g){console.error("Error loading activity:",g),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},p=g=>n.filter(v=>v.user_id===g),f=g=>a.filter(v=>v.user_id===g);return c?e.jsx(be,{children:e.jsx(Le,{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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Agent Activity"}),e.jsx(En,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Le,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"App Launches"}),e.jsx(Tt,{className:"text-center",children:"Content Views"}),e.jsx(Tt,{children:"Last Active"})]})}),e.jsx(Qa,{children:l.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(g=>e.jsxs(fn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:g.user_id,name:g.user_name,email:g.user_email}),children:[e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:g.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:g.user_email})]})}),e.jsx(yt,{className:"text-center",children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(su,{className:"h-3 w-3"}),g.app_launches]})}),e.jsx(yt,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx($r,{className:"h-3 w-3"}),g.content_views]})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:g.last_activity&&Md(new Date(g.last_activity),{addSuffix:!0})})]},g.user_id))})]})})})]}),e.jsx(Is,{open:!!u,onOpenChange:g=>!g&&h(null),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(_r,{children:u==null?void 0:u.email})]}),e.jsxs(Qr,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsx(Wt,{value:"content",children:"Content Engagement"}),e.jsx(Wt,{value:"apps",children:"App Launches"})]}),e.jsx(Kt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Qa,{children:u&&f(u.id).length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&f(u.id).map(g=>e.jsxs(fn,{children:[e.jsx(yt,{className:"max-w-[200px] truncate font-medium",children:g.resource_title}),e.jsx(yt,{children:e.jsxs(ze,{variant:"outline",className:"gap-1",children:[d6n(g.resource_type),l6n[g.resource_type]||g.resource_type]})}),e.jsx(yt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:c6n[g.action_type]||g.action_type})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Md(new Date(g.created_at),{addSuffix:!0})})]},g.id))})]})})}),e.jsx(Kt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(Qa,{children:u&&p(u.id).length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&p(u.id).map(g=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx(ze,{variant:"outline",children:g.app_name})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Md(new Date(g.launched_at),{addSuffix:!0})})]},g.id))})]})})})]})]})})]})},h6n=({brokerageId:s})=>{const{toast:t}=_i(),[n,r]=_.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=_.useState(!0);_.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await U.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(C=>C.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:m}=await U.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:p}=await U.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),f=p||0,g=u-f,{count:v}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),y=new Date;y.setDate(y.getDate()-7);const{count:b}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",y.toISOString()),w=new Date;w.setMonth(w.getMonth()-1);const{count:S}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",w.toISOString());r({totalAgents:u,activeAgents:f,pendingAgents:g,totalLaunches:v||0,launchesThisWeek:b||0,launchesThisMonth:S||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(be,{children:e.jsx(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(On,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Xl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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"})]})]})]})},m6n=({brokerageId:s})=>{const[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState({description:"",maxUses:""});_.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:y,error:b}=await U.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(y||[])}catch(y){console.error("Error loading invite codes:",y),ne.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),p=async()=>{l(!0);try{const y=m(),{error:b}=await U.from("invite_codes").insert({code:y,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;ne.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(y){console.error("Error creating invite code:",y),ne.error("Failed to create invite link")}finally{l(!1)}},f=async y=>{try{const{error:b}=await U.from("invite_codes").delete().eq("id",y);if(b)throw b;ne.success("Invite link deleted"),n(t.filter(w=>w.id!==y))}catch(b){console.error("Error deleting invite code:",b),ne.error("Failed to delete invite link")}},g=async(y,b)=>{try{const{error:w}=await U.from("invite_codes").update({is_active:!b}).eq("id",y);if(w)throw w;n(t.map(S=>S.id===y?{...S,is_active:!b}:S)),ne.success(`Invite link ${b?"deactivated":"activated"}`)}catch(w){console.error("Error toggling invite code:",w),ne.error("Failed to update invite link")}},v=y=>{const b=`${window.location.origin}/join?code=${y}`;navigator.clipboard.writeText(b),ne.success("Link copied to clipboard!")};return r?e.jsx(be,{children:e.jsx(Le,{className:"flex items-center justify-center py-8",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Kc,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(En,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(Is,{open:o,onOpenChange:c,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create Invite Link"}),e.jsx(_r,{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(ee,{htmlFor:"description",children:"Description (optional)"}),e.jsx(pe,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:y=>u({...d,description:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(pe,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:y=>u({...d,maxUses:y.target.value})})]}),e.jsx(z,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Le,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Kc,{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(y=>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:y.code}),e.jsx(ze,{variant:y.is_active?"default":"secondary",children:y.is_active?"Active":"Inactive"})]}),y.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:y.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[y.uses_count," uses",y.max_uses&&` / ${y.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>v(y.code),title:"Copy link",children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>g(y.id,y.is_active),title:y.is_active?"Deactivate":"Activate",children:y.is_active?"Disable":"Enable"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>f(y.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Cn,{className:"h-4 w-4"})})]})]},y.id))})})]})},p6n=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=_.useState(""),[d,u]=_.useState([]),[h,m]=_.useState(""),[p,f]=_.useState(!1),g=S=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S),v=()=>{const S=o.trim().toLowerCase();if(S&&g(S)&&!d.includes(S)){if(d.length>=10){ne.error("Maximum 10 emails per invite");return}u([...d,S]),c("")}else S&&!g(S)?ne.error("Please enter a valid email address"):d.includes(S)&&ne.error("Email already added")},y=S=>{u(d.filter(C=>C!==S))},b=S=>{(S.key==="Enter"||S.key===",")&&(S.preventDefault(),v())},w=async()=>{if(d.length===0){ne.error("Please add at least one email address");return}f(!0);try{const{data:S,error:C}=await U.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(C)throw C;S.successCount===S.totalCount?ne.success(`${S.successCount} invite${S.successCount>1?"s":""} sent successfully!`):ne.warning(`${S.successCount} of ${S.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(S){console.error("Error sending invites:",S),ne.error("Failed to send invites. Please try again.")}finally{f(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[550px]",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(_r,{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(Ko,{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(ee,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:S=>c(S.target.value),onKeyDown:b,onBlur:v}),e.jsx(z,{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(S=>e.jsxs(ze,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[S,e.jsx("button",{type:"button",onClick:()=>y(S),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(er,{className:"h-3 w-3"})})]},S))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ps,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:S=>m(S.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(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:w,disabled:d.length===0||p,children:p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},f6n=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=_.useState([]),[a,i]=_.useState(!0);_.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await U.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;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(Xl,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(ze,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Bd,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Zr,{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(on,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),n.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",Ys(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},x6n=()=>{const{brokerageId:s,user:t}=hs(),[n,r]=_.useState(null),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState([]),[u,h]=_.useState(!0),[m,p]=_.useState(!1),[f,g]=_.useState(0);_.useEffect(()=>{s&&v()},[s]);const v=async()=>{try{const[E,P]=await Promise.all([U.from("brokerages").select("name").eq("id",s).single(),t?U.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);E.data&&i(E.data.name),P.data&&o(P.data.name||"A LevelUp Member");const{data:M}=await U.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const D=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await U.from("referral_codes").insert({brokerage_id:s,code:D}),r(D)}const{data:I}=await U.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(I||[])}catch(E){console.error("Error fetching referral data:",E)}finally{h(!1)}},y=()=>{const E=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(E),ne.success("Referral link copied to clipboard!")},b=c.filter(E=>E.status==="qualified").length,w=c.filter(E=>E.status==="pending").length,S=b*25,C=Math.max(0,Math.ceil((299-S)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(be,{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(Ko,{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:["$",S]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),S>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(Xl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),C>0&&S<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",C," 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"})]}),S>=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(Le,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(z,{onClick:()=>p(!0),className:"w-full",size:"lg",children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(z,{onClick:y,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Sa,{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(Nd,{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:["$",S]}),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(On,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:b}),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(Zr,{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:w}),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(f6n,{brokerageId:s,refreshTrigger:f}),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(E=>{var P,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:((P=E.referred_brokerage)==null?void 0:P.name)||((M=E.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs(ze,{variant:E.status==="qualified"?"default":E.status==="pending"?"secondary":"destructive",className:E.status==="qualified"?"bg-green-600":"",children:[E.status==="qualified"&&e.jsx(Xl,{className:"h-3 w-3 mr-1"}),E.status]})]},E.id)})]})]})]}),e.jsx(p6n,{open:m,onOpenChange:p,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>g(E=>E+1)})]})},g6n=({brokerageId:s})=>{const t=zn(),{teams:n,isLoading:r}=PC(s),{data:a,isLoading:i}=rt({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(E=>E.id),{data:h}=await U.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(E=>({team_id:E.id,team_name:E.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(E=>E.user_id),p=h.filter(E=>E.role==="team_leader").map(E=>E.user_id),{data:f}=await U.from("profiles").select("id, name, avatar_url").in("id",p),g=new Map((f||[]).map(E=>[E.id,E])),{data:v}=await U.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:y}=await U.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:b}=await U.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),w=new Map;(v||[]).forEach(E=>{w.set(E.owner_user_id,(w.get(E.owner_user_id)||0)+1)});const S=new Map;(y||[]).forEach(E=>{S.set(E.owner_user_id,(S.get(E.owner_user_id)||0)+1)});const C=new Map;return(b||[]).forEach(E=>{C.set(E.owner_user_id,(C.get(E.owner_user_id)||0)+1)}),n.map(E=>{const P=h.filter(V=>V.team_id===E.id),M=P.find(V=>V.role==="team_leader"),I=M?g.get(M.user_id):null,D=P.map(V=>V.user_id),F=D.reduce((V,H)=>V+(w.get(H)||0),0),q=D.reduce((V,H)=>V+(S.get(H)||0),0),G=D.reduce((V,H)=>V+(C.get(H)||0),0);return{team_id:E.id,team_name:E.name,member_count:P.length,leader_name:(I==null?void 0:I.name)||null,leader_avatar:(I==null?void 0:I.avatar_url)||null,total_contacts:F,total_deals:q,total_videos:G}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(ln,{className:"h-5 w-32"})}),e.jsx(Le,{children:e.jsx(ln,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(On,{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(z,{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(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(On,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(On,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(nP,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Px,{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(be,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Nt,{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(ja,{className:"h-6 w-6",children:[e.jsx(xi,{src:u.leader_avatar||""}),e.jsx(Na,{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(Kf,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Le,{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(z,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},y6n=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=hs(),o=zn(),{toast:c}=_i(),[d,u]=_.useState(""),[h,m]=_.useState(!0),p=i||(a.length>0?a[0].id:n);_.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),p?f():a.length===0&&!n&&m(!1)},[s,t,r,p,o,a,i]);const f=async()=>{if(!p){m(!1);return}try{const{data:g,error:v}=await U.from("brokerages").select("name").eq("id",p).single();if(v)throw v;u(g.name)}catch(g){console.error("Error loading brokerage info:",g),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{m(!1)}};return h?e.jsx($s,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):p?e.jsx($s,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ls,{value:i||"",onValueChange:l,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),e.jsx(cs,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(g=>e.jsx(He,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs(Qr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Wt,{value:"agents",children:"Agents"}),e.jsx(Wt,{value:"teams",children:"Teams"}),e.jsx(Wt,{value:"invite",children:"Invite Links"}),e.jsx(Wt,{value:"referrals",children:"Referrals"}),e.jsx(Wt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Wt,{value:"activity",children:"Activity"}),e.jsx(Wt,{value:"analytics",children:"Analytics"}),e.jsx(Wt,{value:"shares",children:"Shares"})]}),e.jsx(Kt,{value:"agents",className:"space-y-4",children:e.jsx(o6n,{brokerageId:p})}),e.jsx(Kt,{value:"teams",className:"space-y-4",children:e.jsx(g6n,{brokerageId:p})}),e.jsx(Kt,{value:"invite",className:"space-y-4",children:e.jsx(m6n,{brokerageId:p})}),e.jsx(Kt,{value:"referrals",className:"space-y-4",children:e.jsx(x6n,{})}),e.jsx(Kt,{value:"leaderboard",className:"space-y-4",children:e.jsx(OUt,{brokerageId:p,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Kt,{value:"activity",className:"space-y-4",children:e.jsx(u6n,{brokerageId:p})}),e.jsx(Kt,{value:"analytics",className:"space-y-4",children:e.jsx(h6n,{brokerageId:p})}),e.jsx(Kt,{value:"shares",className:"space-y-4",children:e.jsx(gHt,{brokerageOnly:!0,brokerageId:p})})]})]})}):e.jsx($s,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(oi,{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 v6n({brokerageId:s,canManage:t}){const{user:n}=hs(),[r,a]=_.useState([]),[i,l]=_.useState(!0),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(!1),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(!1),C=async()=>{try{const{data:D,error:F}=await U.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(F)throw F;const q=D;if(q&&q.length>0){const G=[...new Set(q.map(Z=>Z.created_by))],{data:V}=await U.from("profiles").select("id, name, avatar_url").in("id",G),H=new Map((V==null?void 0:V.map(Z=>[Z.id,Z]))||[]),K=q.map(Z=>({...Z,author:H.get(Z.created_by)||{name:"Unknown",avatar_url:null}}));a(K)}else a([])}catch(D){console.error("Error fetching announcements:",D)}finally{l(!1)}};_.useEffect(()=>{C()},[s]);const E=()=>{v(""),b(""),S(!1),u(null)},P=D=>{D?(u(D),v(D.title),b(D.content),S(D.is_pinned)):E(),c(!0)},M=async()=>{if(!g.trim()||!y.trim()){ne.error("Please fill in all fields");return}f(!0);try{if(d){const{error:D}=await U.from("brokerage_announcements").update({title:g.trim(),content:y.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null}).eq("id",d.id);if(D)throw D;ne.success("Announcement updated")}else{const{error:D}=await U.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:g.trim(),content:y.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null});if(D)throw D;ne.success("Announcement created")}c(!1),E(),C()}catch(D){console.error("Error saving announcement:",D),ne.error("Failed to save announcement")}finally{f(!1)}},I=async()=>{if(h)try{const{error:D}=await U.from("brokerage_announcements").delete().eq("id",h);if(D)throw D;ne.success("Announcement deleted"),C()}catch(D){console.error("Error deleting announcement:",D),ne.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Nh,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Nh,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(z,{size:"sm",onClick:()=>P(),className:"gap-1",children:[e.jsx(sn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Le,{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(D=>{var F,q,G,V;return e.jsx("div",{className:`p-4 rounded-lg border ${D.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:[D.is_pinned&&e.jsx(JA,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:D.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:D.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(ja,{className:"h-5 w-5",children:[e.jsx(xi,{src:((F=D.author)==null?void 0:F.avatar_url)||void 0}),e.jsx(Na,{className:"text-[10px]",children:((G=(q=D.author)==null?void 0:q.name)==null?void 0:G.charAt(0))||"?"})]}),e.jsx("span",{children:(V=D.author)==null?void 0:V.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ys(new Date(D.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>P(D),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(D.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})},D.id)})})})]}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",value:g,onChange:D=>v(D.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"content",children:"Content"}),e.jsx(Ps,{id:"content",value:y,onChange:D=>b(D.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(mn,{id:"pinned",checked:w,onCheckedChange:S}),e.jsxs(ee,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(JA,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(z,{onClick:M,disabled:p,children:p?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Ql,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Announcement"}),e.jsx(ql,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function b6n({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=iPe(),{user:a}=hs(),[i,l]=_.useState([]),[o,c]=_.useState(!0),[d,u]=_.useState(""),[h,m]=_.useState(new Set);_.useEffect(()=>{(async()=>{try{const{data:g,error:v}=await U.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(v)throw v;if(l(g||[]),g&&g.length>0){const y=g.map(w=>w.id),{data:b}=await U.from("agent_assistant_assignments").select("agent_id").in("agent_id",y);b&&m(new Set(b.map(w=>w.agent_id)))}}catch(g){console.error("Error fetching agents:",g)}finally{c(!1)}})()},[s]);const p=i.filter(f=>{var g,v;return f.name.toLowerCase().includes(d.toLowerCase())||f.email.toLowerCase().includes(d.toLowerCase())||((g=f.title)==null?void 0:g.toLowerCase().includes(d.toLowerCase()))||((v=f.areas_served)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Le,{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(f=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},f))})})]}):e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:d,onChange:f=>u(f.target.value),className:"pl-9"})]})]}),e.jsx(Le,{children:p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:p.map(f=>e.jsx(_6n,{agent:f,hasAssistant:h.has(f.id),canImpersonate:t&&f.id!==(a==null?void 0:a.id),onImpersonate:()=>n(f.id,"/my-brokerage"),impersonationLoading:r},f.id))})})]})}function _6n({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(ja,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(xi,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(Na,{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(Ha,{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(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{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(lP,{className:"h-4 w-4"})})}),e.jsxs(Tx,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(z,{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(va,{className:"h-4 w-4"})})}),e.jsx(z,{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(on,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(z,{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(fg,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(z,{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(Fm,{className:"h-4 w-4"})})})]})]})}function w6n({brokerageId:s}){const[t,n]=_.useState([]),[r,a]=_.useState(!0);if(_.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(g=>g.id),{data:h,error:m}=await U.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const p=new Map(c.map(g=>[g.id,g])),f=(h||[]).filter(g=>g.total_points>0).map(g=>{const v=p.get(g.user_id);return{user_id:g.user_id,total_points:g.total_points,name:(v==null?void 0:v.name)||"Unknown",avatar_url:(v==null?void 0:v.avatar_url)||null}});n(f)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Le,{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(YA,{className:Ct("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Le,{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:Ct("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(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:o.avatar_url||void 0}),e.jsx(Na,{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 j6n({brokerageId:s}){const t=zn(),[n,r]=_.useState([]),[a,i]=_.useState(!0);_.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(g=>g.id),h=new Map(c.map(g=>[g.id,g])),{data:m,error:p}=await U.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(p)throw p;const f=(m||[]).map(g=>({id:g.id,slug:g.slug,property_address:g.property_address,city:g.city,price:g.price,property_type:g.property_type,agent_id:g.agent_id,agent:h.get(g.agent_id)||null,photos:g.listing_photos||[]}));r(f)}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(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Le,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sa,{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(z,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(sn,{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(sa,{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(z,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(mr,{className:"h-3 w-3 ml-1"})]})]})]})}const N6n={primary_color:"",secondary_color:"",accent_color:"",logo_url:"",logo_dark_url:"",icon_mark_url:"",heading_font:"",body_font:"",legal_name:"",license_number:"",license_state:"",compliance_line:""};function k6n({brokerageId:s,canManage:t}){const{user:n}=hs(),{toast:r}=_i(),{data:a,isLoading:i}=OXs(s),l=zXs(s),[o,c]=_.useState({...N6n}),[d,u]=_.useState({show_equal_housing:!1,show_realtor_logo:!1,lock_colors:!1,lock_logo:!1}),[h,m]=_.useState(null),p={logo_url:_.useRef(null),logo_dark_url:_.useRef(null),icon_mark_url:_.useRef(null)};_.useEffect(()=>{a&&(c({primary_color:a.primary_color||"",secondary_color:a.secondary_color||"",accent_color:a.accent_color||"",logo_url:a.logo_url||"",logo_dark_url:a.logo_dark_url||"",icon_mark_url:a.icon_mark_url||"",heading_font:a.heading_font||"",body_font:a.body_font||"",legal_name:a.legal_name||"",license_number:a.license_number||"",license_state:a.license_state||"",compliance_line:a.compliance_line||""}),u({show_equal_housing:!!a.show_equal_housing,show_realtor_logo:!!a.show_realtor_logo,lock_colors:!!a.lock_colors,lock_logo:!!a.lock_logo}))},[a]);const f=(b,w)=>c(S=>({...S,[b]:w})),g=async(b,w)=>{if(n){m(b);try{const S=await RUt(n.id,w,`brokerage-${b}`);f(b,S),r({title:"Image uploaded"})}catch(S){r({title:"Upload failed",description:S.message,variant:"destructive"})}finally{m(null)}}},v=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([b,w])=>[b,w||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(b){r({title:"Could not save",description:b.message,variant:"destructive"})}},y=(b,w)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:w}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[b]&&e.jsx("img",{src:o[b],alt:w,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:p[b],type:"file",accept:"image/*",className:"hidden",onChange:S=>{var C;return((C=S.target.files)==null?void 0:C[0])&&g(b,S.target.files[0])}}),e.jsxs(z,{type:"button",variant:"outline",disabled:!t||h===b,onClick:()=>{var S;return(S=p[b].current)==null?void 0:S.click()},children:[h===b?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[b]&&t&&e.jsx(z,{type:"button",variant:"ghost",onClick:()=>f(b,""),children:"Remove"})]})]});return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(En,{children:t?"Every agent in this brokerage inherits these colors, logos and disclaimer wherever they leave their own brand blank — including AI-generated marketing through the LevelUp connector.":"These are your brokerage brand settings. Only a brokerage manager can change them."})]}),e.jsx(Le,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["primary_color","Primary color","#2a4c64"],["secondary_color","Secondary color","#1c1c1c"],["accent_color","Accent color","#B8965A"]].map(([b,w,S])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:w}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[b]||S,onChange:C=>f(b,C.target.value)}),e.jsx(pe,{disabled:!t,value:o[b],placeholder:S,onChange:C=>f(b,C.target.value)})]})]},b))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[y("logo_url","Logo (light background)"),y("logo_dark_url","Logo (dark background)"),y("icon_mark_url","Icon mark")]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Heading font"}),e.jsx(pe,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:b=>f("heading_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Body font"}),e.jsx(pe,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:b=>f("body_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Legal brokerage name"}),e.jsx(pe,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:b=>f("legal_name",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage license #"}),e.jsx(pe,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:b=>f("license_number",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:b=>f("license_state",b.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Required disclaimer / compliance line"}),e.jsx(Ps,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:b=>f("compliance_line",b.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Included in every brand kit so AI-generated marketing carries it automatically."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[["show_equal_housing","Include Equal Housing logo"],["show_realtor_logo","Include REALTOR® logo"],["lock_colors","Lock colors (agents cannot override)"],["lock_logo","Lock logo (agents cannot override)"]].map(([b,w])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(ee,{className:"text-sm font-normal",children:w}),e.jsx(mn,{disabled:!t,checked:d[b],onCheckedChange:S=>u(C=>({...C,[b]:S}))})]},b))}),t&&e.jsxs(z,{onClick:v,disabled:l.isPending,children:[l.isPending?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}const hYt="brokerage-onboarding-docs",PA=s=>s.status==="approved"||s.status==="complete";function mYt(s){return rt({queryKey:["onboarding-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_onboarding_templates").select("*").eq("brokerage_id",s).eq("is_archived",!1).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function S6n(s){return rt({queryKey:["onboarding-template-steps",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_onboarding_template_steps").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function pYt(s){return rt({queryKey:["onboarding-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("profiles").select("id, name, email, avatar_url, created_at").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;const{data:r,error:a}=await U.from("brokerage_onboarding_assignments").select("*").eq("brokerage_id",s);if(a)throw a;const i=(r||[]).map(c=>c.id);let l=[];if(i.length){const{data:c,error:d}=await U.from("brokerage_onboarding_steps").select("*").in("assignment_id",i);if(d)throw d;l=c||[]}const o=new Date().toISOString().slice(0,10);return(t||[]).map(c=>{const d=(r||[]).find(h=>h.agent_user_id===c.id)||null,u=d?l.filter(h=>h.assignment_id===d.id):[];return{agentId:c.id,name:c.name||c.email,email:c.email,avatarUrl:c.avatar_url||null,joinedAt:c.created_at||null,assignment:d,total:u.length,done:u.filter(PA).length,overdue:u.filter(h=>!PA(h)&&h.due_date&&h.due_dateh.status==="submitted").length}})}})}function fYt(s){return rt({queryKey:["onboarding-detail",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_onboarding_steps").select("*").eq("assignment_id",s).order("sort_order",{ascending:!0});if(n)throw n;const r=(t||[]).map(i=>i.id);let a=[];if(r.length){const{data:i,error:l}=await U.from("brokerage_onboarding_documents").select("*").in("step_id",r).order("version",{ascending:!1});if(l)throw l;a=i||[]}return{steps:t||[],documents:a}}})}function C6n(s){return rt({queryKey:["my-onboarding",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_onboarding_assignments").select("*").eq("agent_user_id",s).maybeSingle();if(n)throw n;return t||null}})}function A6n(s,t){return rt({queryKey:["agent-record",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("brokerage_agent_records").select("*").eq("brokerage_id",s).eq("agent_user_id",t).maybeSingle();if(r)throw r;return n||null}})}function E6n(s,t){return rt({queryKey:["agent-notes",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("brokerage_agent_notes").select("*").eq("brokerage_id",s).eq("agent_user_id",t).order("created_at",{ascending:!1});if(r)throw r;return n||[]}})}function xYt(s,t){return rt({queryKey:["agent-activity",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("brokerage_onboarding_activity").select("*").eq("brokerage_id",s).eq("agent_user_id",t).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n||[]}})}async function Uce(s){const{data:t}=await U.auth.getUser();t.user&&await U.from("brokerage_onboarding_activity").insert({brokerage_id:s.brokerageId,agent_user_id:s.agentUserId,actor_id:t.user.id,event_type:s.eventType,description:s.description})}function n8e(s){const t=$t(),n=(h,m)=>{t.invalidateQueries({queryKey:["onboarding-roster",s]}),m&&t.invalidateQueries({queryKey:["onboarding-detail",m]}),h&&(t.invalidateQueries({queryKey:["agent-activity",s,h]}),t.invalidateQueries({queryKey:["my-onboarding",h]}))},r=mt({mutationFn:async({agentUserId:h,templateId:m})=>{var S;const{data:p}=await U.auth.getUser(),{data:f,error:g}=await U.from("brokerage_onboarding_templates").select("id, name").eq("id",m).single();if(g)throw g;const{data:v,error:y}=await U.from("brokerage_onboarding_template_steps").select("*").eq("template_id",m).order("sort_order",{ascending:!0});if(y)throw y;const{data:b,error:w}=await U.from("brokerage_onboarding_assignments").insert({brokerage_id:s,agent_user_id:h,template_id:m,template_name:f.name,status:"in_progress",created_by:((S=p.user)==null?void 0:S.id)??null}).select().single();if(w)throw w;if(v!=null&&v.length){const C=new Date,E=v.map(M=>{let I=null;if(M.due_days!=null){const D=new Date(C);D.setDate(D.getDate()+M.due_days),I=D.toISOString().slice(0,10)}return{assignment_id:b.id,title:M.title,description:M.description,step_type:M.step_type,assignee:M.assignee,form_template_id:M.form_template_id,external_url:M.external_url,due_date:I,sort_order:M.sort_order}}),{error:P}=await U.from("brokerage_onboarding_steps").insert(E);if(P)throw P}return await Uce({brokerageId:s,agentUserId:h,eventType:"onboarding_started",description:`Onboarding started using "${f.name}"`}),b},onSuccess:h=>n(h.agent_user_id,h.id)}),a=mt({mutationFn:async h=>{const{error:m}=await U.from("brokerage_onboarding_assignments").delete().eq("id",h.id);if(m)throw m;return h},onSuccess:h=>n(h.agent_user_id,h.id)}),i=mt({mutationFn:async({step:h,status:m,note:p,agentUserId:f})=>{var b;const{data:g}=await U.auth.getUser(),v=m==="approved"||m==="complete",{error:y}=await U.from("brokerage_onboarding_steps").update({status:m,review_note:p??null,completed_at:v?new Date().toISOString():null,completed_by:v?((b=g.user)==null?void 0:b.id)??null:null}).eq("id",h.id);if(y)throw y;return s&&await Uce({brokerageId:s,agentUserId:f,eventType:`step_${m}`,description:`"${h.title}" marked ${m.replace("_"," ")}`}),{step:h,agentUserId:f}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),l=mt({mutationFn:async({step:h,file:m,agentUserId:p,existingVersions:f})=>{var S;const{data:g}=await U.auth.getUser(),v=m.name.replace(/[^a-zA-Z0-9._-]/g,"_"),y=`${s}/${p}/${h.id}/${Date.now()}-${v}`,{error:b}=await U.storage.from(hYt).upload(y,m,{upsert:!1,contentType:m.type||void 0});if(b)throw b;const{error:w}=await U.from("brokerage_onboarding_documents").insert({step_id:h.id,storage_path:y,file_name:m.name,file_size:m.size,file_type:m.type,version:f+1,uploaded_by:((S=g.user)==null?void 0:S.id)??null,review_status:"submitted"});if(w)throw w;return await U.from("brokerage_onboarding_steps").update({status:"submitted",review_note:null}).eq("id",h.id),s&&await Uce({brokerageId:s,agentUserId:p,eventType:"document_uploaded",description:`Document uploaded for "${h.title}"`}),{step:h,agentUserId:p}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),o=mt({mutationFn:async({doc:h,step:m,status:p,note:f,agentUserId:g})=>{var w;const{data:v}=await U.auth.getUser(),{error:y}=await U.from("brokerage_onboarding_documents").update({review_status:p,review_note:f??null,reviewed_by:((w=v.user)==null?void 0:w.id)??null,reviewed_at:new Date().toISOString()}).eq("id",h.id);if(y)throw y;const b=p==="approved"?"approved":p==="changes_requested"?"changes_requested":"submitted";return await U.from("brokerage_onboarding_steps").update({status:b,review_note:f??null,completed_at:p==="approved"?new Date().toISOString():null}).eq("id",m.id),s&&await Uce({brokerageId:s,agentUserId:g,eventType:`document_${p}`,description:`${h.file_name} ${p==="approved"?"approved":p==="changes_requested"?"needs changes":"approval revoked"}`}),{step:m,agentUserId:g}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),c=mt({mutationFn:async h=>{const{error:m}=await U.from("brokerage_agent_records").upsert(h,{onConflict:"brokerage_id,agent_user_id"});if(m)throw m;return h},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-record",h.brokerage_id,h.agent_user_id]})}}),d=mt({mutationFn:async({agentUserId:h,body:m})=>{const{data:p}=await U.auth.getUser(),{error:f}=await U.from("brokerage_agent_notes").insert({brokerage_id:s,agent_user_id:h,body:m,author_id:p.user.id});if(f)throw f;return h},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-notes",s,h]})}}),u=mt({mutationFn:async({id:h,agentUserId:m})=>{const{error:p}=await U.from("brokerage_agent_notes").delete().eq("id",h);if(p)throw p;return m},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-notes",s,h]})}});return{assignTemplate:r,removeAssignment:a,setStepStatus:i,uploadDocument:l,reviewDocument:o,saveRecord:c,addNote:d,deleteNote:u}}function T6n(s){const t=$t(),n=d=>{t.invalidateQueries({queryKey:["onboarding-templates",s]}),d&&t.invalidateQueries({queryKey:["onboarding-template-steps",d]})},r=mt({mutationFn:async({name:d,description:u})=>{var f;const{data:h}=await U.auth.getUser(),{data:m,error:p}=await U.from("brokerage_onboarding_templates").insert({brokerage_id:s,name:d,description:u||null,created_by:((f=h.user)==null?void 0:f.id)??null}).select().single();if(p)throw p;return m},onSuccess:()=>n()}),a=mt({mutationFn:async({id:d,...u})=>{const{error:h}=await U.from("brokerage_onboarding_templates").update(u).eq("id",d);if(h)throw h;return d},onSuccess:()=>n()}),i=mt({mutationFn:async d=>{const{error:u}=await U.from("brokerage_onboarding_templates").delete().eq("id",d);if(u)throw u;return d},onSuccess:()=>n()}),l=mt({mutationFn:async d=>{if(d.id){const{error:u}=await U.from("brokerage_onboarding_template_steps").update(d).eq("id",d.id);if(u)throw u}else{const{error:u}=await U.from("brokerage_onboarding_template_steps").insert(d);if(u)throw u}return d.template_id},onSuccess:d=>n(d)}),o=mt({mutationFn:async({id:d,templateId:u})=>{const{error:h}=await U.from("brokerage_onboarding_template_steps").delete().eq("id",d);if(h)throw h;return u},onSuccess:d=>n(d)}),c=mt({mutationFn:async({steps:d,templateId:u})=>{for(let h=0;hn(d)});return{createTemplate:r,updateTemplate:a,deleteTemplate:i,upsertStep:l,deleteStep:o,reorderSteps:c}}async function M6n(s){const{data:t,error:n}=await U.storage.from(hYt).createSignedUrl(s,300);if(n)throw n;return t.signedUrl}const P6n=s=>s==="document"?$r:s==="form"?cb:Zw,L6n=s=>{switch(s.status){case"approved":return{label:"Approved",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"};case"complete":return{label:"Complete",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"};case"submitted":return{label:"In review",className:"bg-amber-500/15 text-amber-600 border-amber-500/30"};case"changes_requested":return{label:"Needs changes",className:"bg-destructive/10 text-destructive border-destructive/30"};default:return{label:"Pending",className:"bg-muted text-muted-foreground border-border"}}},CWe=({brokerageId:s,agentUserId:t,steps:n,documents:r,mode:a,displayMode:i="all"})=>{const{toast:l}=_i(),{setStepStatus:o,uploadDocument:c,reviewDocument:d}=n8e(s),u=_.useRef({}),[h,m]=_.useState(null),[p,f]=_.useState(""),g=new Date().toISOString().slice(0,10),v=w=>r.filter(S=>S.step_id===w).sort((S,C)=>C.version-S.version),y=async(w,S)=>{try{await c.mutateAsync({step:w,file:S,agentUserId:t,existingVersions:v(w.id).length}),l({title:"Uploaded",description:`${S.name} is ready for review.`})}catch(C){l({title:"Upload failed",description:C.message,variant:"destructive"})}},b=async w=>{try{const S=await M6n(w);window.open(S,"_blank","noopener,noreferrer")}catch(S){l({title:"Could not open file",description:S.message,variant:"destructive"})}};return e.jsxs("div",{className:"space-y-3",children:[n.filter(w=>i==="all"||w.step_type!=="task").length===0&&e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No steps in this checklist yet."}),n.filter(w=>i==="all"||w.step_type!=="task").map(w=>{const S=P6n(w.step_type),C=L6n(w),E=v(w.id),P=E[0],M=!PA(w)&&w.due_date&&w.due_date0&&e.jsx("div",{className:"mt-3 space-y-1",children:E.map(D=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.file_name}),e.jsxs(ze,{variant:"outline",className:"capitalize",children:["v",D.version," · ",D.review_status.replace("_"," ")]}),e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>b(D.storage_path),children:[e.jsx(Ga,{className:"mr-1 h-4 w-4"})," Open"]})]},D.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w.step_type!=="task"&&I&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"file",className:"hidden",accept:".pdf,.png,.jpg,.jpeg,.heic,.doc,.docx",ref:D=>u.current[w.id]=D,onChange:D=>{var q;const F=(q=D.target.files)==null?void 0:q[0];F&&y(w,F),D.target.value=""}}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{var D;return(D=u.current[w.id])==null?void 0:D.click()},children:[e.jsx(Ra,{className:"mr-1 h-4 w-4"})," Upload"]})]}),w.step_type==="task"&&I&&!PA(w)&&e.jsxs(z,{size:"sm",onClick:()=>o.mutate({step:w,status:"complete",agentUserId:t}),children:[e.jsx(Zw,{className:"mr-1 h-4 w-4"})," Complete"]}),a==="manager"&&P&&P.review_status!=="approved"&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{size:"sm",onClick:()=>d.mutate({doc:P,step:w,status:"approved",agentUserId:t}),children:[e.jsx(Mr,{className:"mr-1 h-4 w-4"})," Approve"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{m({step:w,doc:P}),f("")},children:[e.jsx(Bd,{className:"mr-1 h-4 w-4"})," Needs changes"]})]}),a==="manager"&&PA(w)&&e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>P?d.mutate({doc:P,step:w,status:"submitted",agentUserId:t}):o.mutate({step:w,status:"pending",agentUserId:t}),children:[e.jsx(Dx,{className:"mr-1 h-4 w-4"})," Revoke"]})]})]})},w.id)}),e.jsx(Is,{open:!!h,onOpenChange:w=>!w&&m(null),children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Request changes"})}),e.jsx(Ps,{rows:4,value:p,onChange:w=>f(w.target.value),placeholder:"Tell the agent what needs to be fixed…"}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(z,{onClick:async()=>{h&&(await d.mutateAsync({doc:h.doc,step:h.step,status:"changes_requested",note:p,agentUserId:t}),m(null))},children:"Send back"})]})]})})]})},I6n=()=>{const{user:s}=hs(),{data:t}=C6n(s==null?void 0:s.id),{data:n}=fYt(t==null?void 0:t.id);if(!t)return null;const r=(n==null?void 0:n.steps)||[],a=r.filter(PA).length,i=r.length?Math.round(a/r.length*100):0;return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fN,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(Nt,{children:"Your onboarding"}),e.jsx(En,{children:t.template_name||"Onboarding checklist"})]})]}),e.jsxs("div",{className:"w-full max-w-[220px]",children:[e.jsx(Di,{value:i}),e.jsxs("p",{className:"mt-1 text-right text-xs text-muted-foreground",children:[a," of ",r.length," complete"]})]})]})}),e.jsx(Le,{children:e.jsx(CWe,{brokerageId:t.brokerage_id,agentUserId:t.agent_user_id,steps:r,documents:(n==null?void 0:n.documents)||[],mode:"agent"})})]})};function D6n(){const{user:s,isAdmin:t,isBrokerageManager:n}=hs(),r=zn(),[a,i]=_.useState(!0),[l,o]=_.useState(null),[c,d]=_.useState(""),[u,h]=_.useState(0),[m,p]=_.useState(!1),[f,g]=_.useState(!1);return _.useEffect(()=>{(async()=>{if(s)try{const{data:y}=await U.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(y!=null&&y.brokerage_id)){i(!1);return}o(y.brokerage_id);const{data:b}=await U.from("brokerages").select("name").eq("id",y.brokerage_id).maybeSingle();b&&d(b.name);const{count:w}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",y.brokerage_id);if(h(w||0),t)p(!0),g(!0);else if(n){const{data:S}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",y.brokerage_id).maybeSingle();p(!!S),g(!!S)}}catch(y){console.error("Error fetching brokerage info:",y)}finally{i(!1)}})()},[s,t,n]),a?e.jsx($s,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx($s,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(On,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),f&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(ip,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(z,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(sa,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(I6n,{}),e.jsx(k6n,{brokerageId:l,canManage:m}),e.jsx(v6n,{brokerageId:l,canManage:m}),e.jsx(b6n,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(w6n,{brokerageId:l}),e.jsx(j6n,{brokerageId:l})]})]})}):e.jsx($s,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(oi,{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 R6n(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 F6n(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 Cjt={video:{icon:su,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:$r,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Oc,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ya,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:yc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function O6n({item:s,canManage:t}){const[n,r]=_.useState(!1),[a,i]=_.useState(null),l=AUs(),o=zn(),c=Cjt[s.content_type]||Cjt.link,d=c.icon,u=_.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?R6n(s.url):null,[s]);_.useEffect(()=>{u||!s.url||s.content_type!=="video"||!F6n(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(f=>f.ok?f.json():null).then(f=>{f!=null&&f.thumbnail_url&&i(f.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},p=async()=>{try{await l.mutateAsync(s.id),ne.success("Content deleted")}catch{ne.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:m,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(Le,{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:["📅 ",Ys(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Ys(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,onClick:f=>f.stopPropagation(),children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsx(qd,{align:"end",children:e.jsxs(ua,{onClick:f=>{f.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Ql,{open:n,onOpenChange:r,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Content"}),e.jsxs(ql,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:p,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function z6n(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 Ajt=[{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 B6n({brokerageId:s,categories:t}){var te;const{user:n}=hs(),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(""),[d,u]=_.useState("📁"),[h,m]=_.useState(!1);_.useRef(null);const[p,f]=_.useState("video"),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(""),[F,q]=_.useState(""),G=CUs(),V=EUs(s),H=TUs(),K=MUs(s),Z=()=>{f("video"),v(""),b(""),S(""),E(""),M(""),D(""),q("")},oe=async(ce,ve)=>{var he;const me=(he=ce.target.files)==null?void 0:he[0];if(me){m(!0);try{const ge=me.name.split(".").pop(),Ee=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ge}`,{error:Ne}=await U.storage.from("brokerage-content").upload(Ee,me);if(Ne)throw Ne;const{data:{publicUrl:Pe}}=U.storage.from("brokerage-content").getPublicUrl(Ee);ve==="file"?(E(Pe),p==="graphic"&&!P&&M(Pe)):M(Pe),ne.success("File uploaded")}catch(ge){ne.error(ge.message||"Upload failed")}finally{m(!1)}}},re=async()=>{if(!g.trim()){ne.error("Title is required");return}if(n)try{await G.mutateAsync({brokerage_id:s,category_id:F||null,content_type:p,title:g.trim(),description:y.trim()||null,url:w.trim()||null,file_url:C.trim()||null,thumbnail_url:P.trim()||null,event_date:I?new Date(I).toISOString():null,created_by:n.id}),ne.success("Content added!"),Z(),a(!1)}catch(ce){ne.error(ce.message||"Failed to add content")}},ae=async()=>{if(o.trim())try{await V.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ne.success("Category created")}catch(ce){ne.error(ce.message||"Failed to create category")}},J=async()=>{try{await K.mutateAsync(),ne.success("Default categories created")}catch{ne.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Is,{open:r,onOpenChange:a,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Content Type"}),e.jsxs(ls,{value:p,onValueChange:f,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Ajt.map(ce=>e.jsx(He,{value:ce.value,children:ce.label},ce.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(te=Ajt.find(ce=>ce.value===p))==null?void 0:te.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ls,{value:F,onValueChange:q,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select category (optional)"})}),e.jsx(as,{children:t.map(ce=>e.jsxs(He,{value:ce.id,children:[ce.icon," ",ce.name]},ce.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:g,onChange:ce=>v(ce.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:y,onChange:ce=>b(ce.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:p==="video"?"Video URL":p==="graphic"?"Canva / Image URL":p==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(pe,{value:w,onChange:ce=>{const ve=ce.target.value;if(S(ve),p==="video"&&!P){const me=z6n(ve);me&&M(me)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:p==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",accept:p==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ce=>oe(ce,"file"),disabled:h}),h&&e.jsx(bt,{className:"h-4 w-4 animate-spin"})]}),C&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Thumbnail Image (optional)"}),e.jsx(pe,{type:"file",accept:"image/*",onChange:ce=>oe(ce,"thumbnail"),disabled:h}),P&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:P,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(er,{className:"h-3 w-3"})})]})]}),p==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Event Date & Time"}),e.jsx(pe,{type:"datetime-local",value:I,onChange:ce=>D(ce.target.value)})]}),e.jsxs(z,{onClick:re,disabled:G.isPending||!g.trim(),className:"w-full",children:[G.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(Is,{open:i,onOpenChange:l,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",children:[e.jsx(Gc,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{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(z,{variant:"outline",size:"sm",onClick:J,disabled:K.isPending,children:[K.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(ce=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[ce.icon," ",ce.name]}),!ce.is_default&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await H.mutateAsync(ce.id),ne.success("Category deleted")},children:e.jsx(er,{className:"h-4 w-4"})})]},ce.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(pe,{value:d,onChange:ce=>u(ce.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(pe,{value:o,onChange:ce=>c(ce.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ce=>ce.key==="Enter"&&ae()}),e.jsx(z,{size:"sm",onClick:ae,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function $6n(){const{user:s,isAdmin:t,isBrokerageManager:n}=hs(),[r,a]=_.useState(!0),[i,l]=_.useState(null),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState("");_.useEffect(()=>{(async()=>{if(s)try{const{data:S}=await U.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(S!=null&&S.brokerage_id)){a(!1);return}l(S.brokerage_id);const{data:C}=await U.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle();if(C&&c(C.name),t)u(!0);else if(n){const{data:E}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",S.brokerage_id).maybeSingle();u(!!E)}}catch(S){console.error("Error fetching brokerage info:",S)}finally{a(!1)}})()},[s,t,n]);const{data:g=[]}=NUs(i),{data:v=[],isLoading:y}=kUs(i,h),b=_.useMemo(()=>{if(!p.trim())return v;const w=p.toLowerCase();return v.filter(S=>{var C;return S.title.toLowerCase().includes(w)||((C=S.description)==null?void 0:C.toLowerCase().includes(w))||S.content_type.toLowerCase().includes(w)})},[v,p]);return r?e.jsx($s,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx($s,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(B6n,{brokerageId:i,categories:g}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search content...",value:p,onChange:w=>f(w.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),g.map(w=>e.jsxs(z,{variant:h===w.id?"default":"outline",size:"sm",onClick:()=>m(w.id),children:[e.jsx("span",{className:"mr-1",children:w.icon}),w.name]},w.id))]})]}),y?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.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(wv,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:p.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:p.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(w=>e.jsx(O6n,{item:w,canManage:d},w.id))})]})}):e.jsx($s,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(oi,{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 Ejt={video:{icon:su,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:$r,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Oc,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ya,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:yc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function U6n(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 q6n(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function V6n(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function H6n(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function G6n(){const{contentId:s}=Mi(),{data:t,isLoading:n}=rt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await U.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx($s,{title:"Brokerage Content",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!t)return e.jsx($s,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(oi,{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(z,{asChild:!0,className:"mt-4",children:e.jsx(or,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=Ejt[t.content_type]||Ejt.link,a=r.icon,i=t.url||t.file_url,l=i&&q6n(i)?U6n(i):null,o=i&&V6n(i)?H6n(i):null,c=l||o;return e.jsx($s,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(or,{to:"/brokerage-content",children:[e.jsx(ka,{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 ",Ys(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(be,{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(be,{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(be,{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(be,{children:e.jsx(Le,{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(be,{children:e.jsxs(Le,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ya,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Ys(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx(z,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(z,{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(mr,{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 GTe={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 W6n(s="open"){const{user:t}=hs();return rt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=U.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")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 U.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function K6n(s){return rt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Y6n(s){return rt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Z6n(){const s=$t(),{user:t,brokerageId:n}=hs();return mt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await U.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await U.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function X6n(){const s=$t(),{user:t}=hs();return mt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await U.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 Q6n(){const s=$t();return mt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await U.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await U.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await U.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,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 J6n(){const s=$t();return mt({mutationFn:async({claim_id:t})=>{const{error:n}=await U.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 eMn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.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 tMn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.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 sMn(){const{user:s,brokerageId:t}=hs(),n=$t(),r=rt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await U.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=mt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await U.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function nMn(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 rMn(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 aMn({req:s,onClick:t}){var i;const n=GTe[s.request_type],r=nMn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(be,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Le,{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(yi,{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(Zr,{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(Ha,{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(Nd,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:rMn(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 iMn(){var c;const s=zn(),{brokerageId:t}=hs(),[n,r]=_.useState("open"),{data:a=[],isLoading:i}=W6n(n),l=sMn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx($s,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(Qr,{value:n,onValueChange:d=>r(d),children:e.jsxs(Jr,{children:[e.jsx(Wt,{value:"open",children:"Open"}),e.jsx(Wt,{value:"mine",children:"My Posts"}),e.jsx(Wt,{value:"my_claims",children:"My Claims"}),e.jsx(Wt,{value:"filled",children:"Filled"})]})}),e.jsxs(z,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsxs(Le,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx($g,{className:"h-4 w-4 text-primary"}):e.jsx(pS,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(ee,{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(mn,{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(be,{className:"bg-muted/30 border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(_4,{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(aMn,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx($s,{title:"Help Board",description:"Brokerage Help Board",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(_4,{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 oMn(){const s=zn(),{toast:t}=_i(),n=Z6n(),[r,a]=_.useState("open_house"),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState("goodwill"),[F,q]=_.useState(""),[G,V]=_.useState(""),H=r==="open_house"||r==="showing_coverage",K=r!=="general",Z=(re,ae)=>!re||!ae?null:`${re}T${ae}:00`,oe=async re=>{if(re.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const ae=Z(d,h),J=Z(d,p);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:ae,event_end_at:J,address:H&&g.trim()||null,city:H&&y.trim()||null,state:H&&w.trim()||null,zip:H&&C.trim()||null,mls_number:P.trim()||null,compensation_type:I,compensation_amount:F?Number(F):null,compensation_notes:G.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(ae){t({title:"Could not post",description:(ae==null?void 0:ae.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx($s,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:oe,children:e.jsx(be,{children:e.jsxs(Le,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(GTe).map(re=>{const ae=GTe[re],J=re===r;return e.jsxs("button",{type:"button",onClick:()=>a(re),className:`text-left p-3 rounded-lg border-2 transition ${J?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:ae.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ae.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ae.description})]},re)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i,onChange:re=>l(re.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(ee,{htmlFor:"description",children:"Details"}),e.jsx(Ps,{id:"description",value:o,onChange:re=>c(re.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),K&&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(ee,{htmlFor:"date",children:"Date"}),e.jsx(pe,{id:"date",type:"date",value:d,onChange:re=>u(re.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"start",children:"Start"}),e.jsx(pe,{id:"start",type:"time",value:h,onChange:re=>m(re.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"end",children:"End"}),e.jsx(pe,{id:"end",type:"time",value:p,onChange:re=>f(re.target.value)})]})]}),H&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"address",children:"Address"}),e.jsx(pe,{id:"address",value:g,onChange:re=>v(re.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(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:y,onChange:re=>b(re.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:w,onChange:re=>S(re.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(ee,{htmlFor:"zip",children:"Zip"}),e.jsx(pe,{id:"zip",value:C,onChange:re=>E(re.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(pe,{id:"mls",value:P,onChange:re=>M(re.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(ee,{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(re=>{const ae=I===re.val;return e.jsxs("button",{type:"button",onClick:()=>D(re.val),className:`text-left p-3 rounded-lg border-2 transition ${ae?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:re.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:re.sub})]},re.val)})}),I!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"amount",children:I==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(pe,{id:"amount",type:"number",min:"0",step:I==="referral_percent"?"1":"5",value:F,onChange:re=>q(re.target.value),placeholder:I==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(pe,{id:"comp-notes",value:G,onChange:re=>V(re.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(z,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function lMn(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 aze(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function cMn(){var P,M,I,D,F,q,G,V;const{id:s}=Mi(),t=zn(),{user:n}=hs(),{toast:r}=_i(),{data:a,isLoading:i}=K6n(s),{data:l=[]}=Y6n(s),o=X6n(),c=Q6n(),d=J6n(),u=eMn(),h=tMn(),[m,p]=_.useState("");if(i)return e.jsx($s,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs($s,{title:"Not Found",description:"",children:[e.jsxs(z,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(ka,{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 f=GTe[a.request_type],g=lMn(a.event_start_at,a.event_end_at),v=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),y=(n==null?void 0:n.id)===a.requester_user_id,b=l.find(H=>H.claimant_user_id===(n==null?void 0:n.id)),w=l.find(H=>H.status==="accepted"),S=a.status==="open",C=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)",E=async()=>{if(!m.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:m.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),p("")}catch(H){r({title:"Could not submit",description:H==null?void 0:H.message,variant:"destructive"})}};return e.jsx($s,{title:a.title,description:`${f.emoji} ${f.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx(be,{children:e.jsxs(Le,{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:[f.emoji," ",f.label]}),e.jsx(ze,{variant:S?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(xi,{src:((P=a.requester)==null?void 0:P.avatar_url)||void 0}),e.jsx(Na,{children:aze((M=a.requester)==null?void 0:M.name)})]}),e.jsx("span",{children:((I=a.requester)==null?void 0:I.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:[g&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Zr,{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:g})]})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ha,{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(Nd,{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:C})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(aP,{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]})]})}),!y&&S&&!b&&e.jsx(be,{children:e.jsxs(Le,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ps,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:H=>p(H.target.value),rows:3,maxLength:400}),e.jsxs(z,{onClick:E,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(bt,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!y&&b&&e.jsx(be,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(Wr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",b.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.status==="pending"&&"Waiting for the requester to pick.",b.status==="accepted"&&"You're confirmed — see contact info below.",b.status==="declined"&&"They went with someone else this time."]})]})]})}),w&&(y||w.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(be,{className:"border-primary/30",children:e.jsxs(Le,{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(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:((D=w.claimant)==null?void 0:D.avatar_url)||void 0}),e.jsx(Na,{children:aze((F=w.claimant)==null?void 0:F.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(q=w.claimant)==null?void 0:q.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((G=w.claimant)==null?void 0:G.email)&&e.jsxs("a",{href:`mailto:${w.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(on,{className:"h-4 w-4"})," ",w.claimant.email]}),((V=w.claimant)==null?void 0:V.phone)&&e.jsxs("a",{href:`tel:${w.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(va,{className:"h-4 w-4"})," ",w.claimant.phone]})]})]})}),y&&e.jsx(be,{children:e.jsxs(Le,{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(H=>{var K,Z,oe,re,ae;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:((K=H.claimant)==null?void 0:K.avatar_url)||void 0}),e.jsx(Na,{children:aze((Z=H.claimant)==null?void 0:Z.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium",children:((oe=H.claimant)==null?void 0:oe.name)||"Teammate"}),e.jsx(ze,{variant:"outline",className:"capitalize text-xs",children:H.status})]}),H.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',H.note,'"']}),H.status==="pending"&&S&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(z,{size:"sm",onClick:()=>c.mutate({claim_id:H.id,request_id:a.id,claimant_user_id:H.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Pick ",((ae=(re=H.claimant)==null?void 0:re.name)==null?void 0:ae.split(" ")[0])||"them"]}),e.jsxs(z,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:H.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(er,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},H.id)}),y&&S&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),y&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(z,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function gYt({onSelect:s,maxHeight:t="460px"}){const[n,r]=_.useState(""),[a,i]=_.useState("all"),{data:l=[],isLoading:o}=rt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await U.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=_.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=_.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(m=>m.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{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(Ki,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{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(nc,{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(Ia,{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 dMn=[{key:"search",label:"Search for Properties",icon:Rr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:va,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:on,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:ya,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:sa,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Nd,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:Ha,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:sd,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:Gh,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function Tjt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function uMn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Ent({html:s,onChange:t}){const{user:n}=hs(),r=_.useRef(null),a=_.useRef(""),i=_.useRef(t);i.current=t;const[l,o]=_.useState("desktop"),c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),g=_.useRef(null),v=()=>{var wt;const It=(wt=r.current)==null?void 0:wt.contentDocument,qs=It==null?void 0:It.getSelection();qs&&qs.rangeCount>0&&(It!=null&&It.body.contains(qs.anchorNode))&&(g.current=qs.getRangeAt(0).cloneRange())},y=()=>{var kn;const It=c.current,qs=(kn=r.current)==null?void 0:kn.contentDocument;if(!It||!qs)return;let wt=h.trim();wt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(wt)&&(wt="https://"+wt),It.setAttribute("href",wt),It.setAttribute("target","_blank");const Us=p.trim();Us&&Us!==(It.textContent||"").trim()&&(It.textContent=Us);const Es=` `+qs.documentElement.outerHTML;a.current=Es,i.current(Es),u(!1)};_.useEffect(()=>{var wt,Us;const It=r.current;if(!It||a.current===s)return;const qs=()=>{const Es=It.contentDocument;if(!Es)return;Es.open(),Es.write(s||""),Es.close(),a.current=s;const kn=Es.body;if(!kn)return;kn.setAttribute("contenteditable","true"),kn.style.outline="none",kn.style.minHeight="400px",kn.style.cursor="text";const Sn=()=>{const cr=` `+Es.documentElement.outerHTML;a.current=cr,i.current(cr)};kn.addEventListener("input",Sn),kn.addEventListener("blur",Sn),kn.addEventListener("mouseup",v),kn.addEventListener("keyup",v),Es.addEventListener("selectionchange",v);const bn=cr=>{var fs;const Fs=cr.target,cn=Fs==null?void 0:Fs.closest("a");if(cn){if(cr.metaKey||cr.ctrlKey||cr.shiftKey)return;cr.preventDefault(),cr.stopPropagation(),c.current=cn,m(cn.getAttribute("href")||""),f((cn.textContent||"").trim()),u(!0);return}const lr=Es.getSelection();if(!lr)return;const Tn=(fs=Es.caretRangeFromPoint)==null?void 0:fs.call(Es,cr.clientX,cr.clientY),Yn=Tn==null?void 0:Tn.startContainer;if(Yn&&Yn.nodeType===Node.TEXT_NODE){const wn=Yn.textContent||"",As=Tn.startOffset,Ss=wn.lastIndexOf("[",As),pr=wn.indexOf("]",As);if(Ss!==-1&&pr!==-1&&pr>Ss){const hn=Es.createRange();hn.setStart(Yn,Ss),hn.setEnd(Yn,pr+1),lr.removeAllRanges(),lr.addRange(hn),g.current=hn.cloneRange()}}};kn.addEventListener("click",bn,!0)};((wt=It.contentDocument)==null?void 0:wt.readyState)==="complete"||(Us=It.contentDocument)!=null&&Us.body?qs():It.addEventListener("load",qs,{once:!0})},[s]);const b=(It,qs)=>{var Es;const wt=(Es=r.current)==null?void 0:Es.contentDocument;if(!wt)return;wt.body.focus(),wt.execCommand(It,!1,qs);const Us=` `+wt.documentElement.outerHTML;a.current=Us,i.current(Us)},w=()=>{const It=window.prompt("Enter URL (https://...)");It&&b("createLink",It)},S=(It,qs)=>{var Es;const wt=(Es=r.current)==null?void 0:Es.contentDocument;if(!wt)return;if(wt.body.focus(),qs==="cursor"&&g.current&&wt.body.contains(g.current.startContainer)){const kn=wt.getSelection();if(kn){kn.removeAllRanges(),kn.addRange(g.current),wt.execCommand("insertHTML",!1,It);const Sn=` `+wt.documentElement.outerHTML;a.current=Sn,i.current(Sn);return}}qs==="top"?wt.body.insertAdjacentHTML("afterbegin",It):wt.body.insertAdjacentHTML("beforeend",It);const Us=` `+wt.documentElement.outerHTML;a.current=Us,i.current(Us)},[C,E]=_.useState(!1),[P,M]=_.useState(null),[I,D]=_.useState(""),[F,q]=_.useState(""),[G,V]=_.useState("#406E71"),[H,K]=_.useState("cursor"),Z=It=>{M(It),D(It.defaultText),q(""),E(!0)},oe=()=>{if(!P)return;const It=F.trim();if(!P.isForward&&!It)return;let qs=It;if(P.isForward){const kn=It||"",Sn=encodeURIComponent("You should see this newsletter"),bn=encodeURIComponent(kn?`I thought you'd like this — take a look: ${kn} `:`I thought you'd like this newsletter — take a look! `);qs=`mailto:?subject=${Sn}&body=${bn}`}else P.hrefPrefix==="tel:"?qs="tel:"+It.replace(/[^0-9+]/g,""):P.hrefPrefix==="mailto:"?qs="mailto:"+It:/^https?:\/\//i.test(It)||(qs="https://"+It);const wt=(I||P.defaultText).replace(/[<>]/g,""),Us=G||"#406E71",Es=`
${wt}

 

`;S(Es,H),E(!1)},[re,ae]=_.useState(!1),[J,te]=_.useState(""),[ce,ve]=_.useState(""),[me,he]=_.useState(""),[ge,Ee]=_.useState("cursor"),Ne=(()=>{if(ce.trim())return ce.trim();const It=Tjt(J);return It?`https://i.ytimg.com/vi/${It}/hqdefault.jpg`:""})(),Pe=()=>{te(""),ve(""),he(""),ae(!0)},Oe=()=>{const It=J.trim();if(!It)return;let qs=It;/^https?:\/\//i.test(qs)||(qs="https://"+qs);const wt=Tjt(qs),Us=wt?null:uMn(qs);let Es=ce.trim();!Es&&wt&&(Es=`https://i.ytimg.com/vi/${wt}/hqdefault.jpg`),!Es&&Us&&(Es=`https://vumbnail.com/${Us}.jpg`),Es||(Es="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const kn=(me||"Watch the video").replace(/[<>]/g,""),Sn=`
${kn}
▶
▶ ${kn}

 

`.trim();S(Sn,ge),ae(!1)},[ke,Ve]=_.useState(!1),[_e,Ae]=_.useState(""),[Se,We]=_.useState(""),[qe,Be]=_.useState("full"),[Ze,$e]=_.useState("cursor"),[Xe,nt]=_.useState(!1),Ge=_.useRef(null),Je=()=>{Ae(""),We(""),Be("full"),Ve(!0)},ut=async It=>{var qs;if(!n){ne.error("You must be signed in to upload images");return}if(It.size>10*1024*1024){ne.error("Image must be under 10MB");return}nt(!0);try{const wt=((qs=It.name.split(".").pop())==null?void 0:qs.toLowerCase())||"png",Us=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${wt}`,{error:Es}=await U.storage.from("email-assets").upload(Us,It,{cacheControl:"3600",upsert:!1,contentType:It.type});if(Es)throw Es;const{data:kn}=U.storage.from("email-assets").getPublicUrl(Us);Ae(kn.publicUrl),ne.success("Image uploaded")}catch(wt){ne.error(wt.message||"Upload failed")}finally{nt(!1)}},lt=()=>{if(!_e.trim())return;const It=(Se||"").replace(/[<>"]/g,""),qs=qe==="half"?280:560,wt=`
${It}

 

`.trim();S(wt,Ze),Ve(!1)},{data:qt,isLoading:zt}=rt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&re,queryFn:async()=>{const{data:It,error:qs}=await U.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(qs)throw qs;return It||[]}}),Zt=It=>{It.share_token&&(te(`https://video.relevelup.com/share/video/${It.share_token}`),ve(`https://video.relevelup.com/thumb/${It.share_token}`),he(It.title||"Watch the video"))},ms=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(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("bold"),title:"Bold",children:e.jsx(HA,{className:"h-3.5 w-3.5"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("italic"),title:"Italic",children:e.jsx(KA,{className:"h-3.5 w-3.5"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("underline"),title:"Underline",children:e.jsx(b7,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertUnorderedList"),title:"Bullet list",children:e.jsx(My,{className:"h-3.5 w-3.5"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertOrderedList"),title:"Numbered list",children:e.jsx(bj,{className:"h-3.5 w-3.5"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:w,title:"Insert link",children:e.jsx(Kc,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("undo"),title:"Undo",children:e.jsx(nE,{className:"h-3.5 w-3.5"})}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("redo"),title:"Redo",children:e.jsx(tE,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(Gh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(qd,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(qP,{children:"Insert a call-to-action"}),e.jsx(Iy,{}),dMn.map(It=>{const qs=It.icon;return e.jsxs(ua,{onClick:()=>Z(It),children:[e.jsx(qs,{className:"h-4 w-4 mr-2"}),It.label]},It.key)})]})]}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:Je,children:[e.jsx(nc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Pe,children:[e.jsx(Xr,{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(Oq,{type:"single",value:l,onValueChange:It=>It&&o(It),size:"sm",className:"h-7",children:[e.jsx(L7,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(yN,{className:"h-3.5 w-3.5"})}),e.jsx(L7,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(p1,{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(Gh,{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:ms,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(Is,{open:d,onOpenChange:u,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(pe,{id:"link-edit-text",value:p,onChange:It=>f(It.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(pe,{id:"link-edit-href",value:h,onChange:It=>m(It.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(hr,{children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(z,{type:"button",onClick:y,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(Is,{open:C,onOpenChange:E,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Insert ",(P==null?void 0:P.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-text",children:"Button text"}),e.jsx(pe,{id:"cta-text",value:I,onChange:It=>D(It.target.value),placeholder:P==null?void 0:P.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-value",children:P==null?void 0:P.helper}),e.jsx(pe,{id:"cta-value",value:F,onChange:It=>q(It.target.value),placeholder:P==null?void 0:P.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{id:"cta-color",type:"color",value:G,onChange:It=>V(It.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(pe,{value:G,onChange:It=>V(It.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Position"}),e.jsxs(C_,{value:H,onValueChange:It=>K(It),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"cursor",id:"cta-cursor"}),e.jsxs(ee,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Gh,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"top",id:"cta-top"}),e.jsxs(ee,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ap,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"bottom",id:"cta-bottom"}),e.jsxs(ee,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Vf,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:G,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:I||(P==null?void 0:P.defaultText)})})]}),e.jsxs(hr,{children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(z,{type:"button",onClick:oe,disabled:!(P!=null&&P.isForward)&&!F.trim(),children:"Insert Button"})]})]})}),e.jsx(Is,{open:re,onOpenChange:ae,children:e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Insert Video Block"})}),e.jsxs(Qr,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsx(Wt,{value:"library",children:"My Library"}),e.jsx(Wt,{value:"url",children:"From URL"}),e.jsx(Wt,{value:"record",children:"Record New"})]}),e.jsxs(Kt,{value:"library",className:"space-y-3 mt-2",children:[zt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(bt,{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(Xr,{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(It=>{const qs=J.includes(It.share_token||"___"),wt=It.share_token?`https://video.relevelup.com/thumb/${It.share_token}`:It.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Zt(It),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${qs?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[wt?e.jsx("img",{src:wt,alt:It.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(Xr,{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(su,{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:It.title||"Untitled"})})]},It.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(pe,{id:"vid-title-lib",value:me,onChange:It=>he(It.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Kt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(pe,{id:"vid-url",value:J,onChange:It=>te(It.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(ee,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(pe,{id:"vid-title",value:me,onChange:It=>he(It.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(pe,{id:"vid-thumb",value:ce,onChange:It=>ve(It.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Kt,{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(Xr,{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(z,{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(ee,{children:"Position"}),e.jsxs(C_,{value:ge,onValueChange:It=>Ee(It),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"cursor",id:"vid-cursor"}),e.jsxs(ee,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Gh,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"top",id:"vid-top"}),e.jsxs(ee,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ap,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"bottom",id:"vid-bottom"}),e.jsxs(ee,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Vf,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Ne&&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:Ne,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:It=>{It.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(hr,{children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsx(z,{type:"button",onClick:Oe,disabled:!J.trim(),children:"Insert Video"})]})]})}),e.jsx(Is,{open:ke,onOpenChange:Ve,children:e.jsxs(Ls,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Insert Image"})}),e.jsxs(Qr,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsx(Wt,{value:"library",children:"Library"}),e.jsx(Wt,{value:"upload",children:"Upload"}),e.jsx(Wt,{value:"url",children:"From URL"})]}),e.jsx(Kt,{value:"library",className:"mt-2",children:e.jsx(gYt,{maxHeight:"380px",onSelect:It=>{Ae(It.image_url),Se||We(It.title)}})}),e.jsxs(Kt,{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:It=>{var wt;const qs=(wt=It.target.files)==null?void 0:wt[0];qs&&ut(qs),It.target.value=""}}),_e?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:_e,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(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ae(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var It;return(It=Ge.current)==null?void 0:It.click()},disabled:Xe,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:Xe?e.jsxs(e.Fragment,{children:[e.jsx(bt,{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(Ra,{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(Kt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"img-url",children:"Image URL"}),e.jsx(pe,{id:"img-url",value:_e,onChange:It=>Ae(It.target.value),placeholder:"https://..."})]}),_e&&/^https?:\/\//i.test(_e)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:_e,alt:"Preview",className:"w-full max-h-48 object-contain",onError:It=>{It.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(ee,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(pe,{id:"img-alt",value:Se,onChange:It=>We(It.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Size"}),e.jsxs(C_,{value:qe,onValueChange:It=>Be(It),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"full",id:"img-full"}),e.jsx(ee,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"half",id:"img-half"}),e.jsx(ee,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Position"}),e.jsxs(C_,{value:Ze,onValueChange:It=>$e(It),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"cursor",id:"img-cursor"}),e.jsxs(ee,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Gh,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"top",id:"img-top"}),e.jsxs(ee,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ap,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(am,{value:"bottom",id:"img-bottom"}),e.jsxs(ee,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Vf,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>Ve(!1),children:"Cancel"}),e.jsx(z,{type:"button",onClick:lt,disabled:!_e.trim()||Xe,children:"Insert Image"})]})]})})]})}const Mjt="newsletter-content",hMn="inline-images";function mMn(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await U.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),C=(S==null?void 0:S.role)==="team_leader",E=(S==null?void 0:S.team_id)??null;_.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),p((n==null?void 0:n.html_content)??xMn()),g((n==null?void 0:n.is_template)??!1),y((n==null?void 0:n.share_scope)??"private"))},[s,n]);const P=async()=>{if(a){if(!c.trim()){ne.error("Please enter a title");return}if(!m.trim()){ne.error("Newsletter content is empty");return}w(!0);try{const M=await pMn(m);M!==m&&p(M);const I={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:f,share_scope:v,shared_team_id:v==="team"?E:null,shared_brokerage_id:v==="brokerage"?o:null};if(v==="team"&&!E){ne.error("You must be a team leader to share with a team"),w(!1);return}if(v==="brokerage"&&!l){ne.error("Only brokerage managers can share to a brokerage"),w(!1);return}if(v==="global"&&!i){ne.error("Only admins can publish global starter templates"),w(!1);return}let D;if(n!=null&&n.id?{error:D}=await U.from("agent_custom_newsletters").update(I).eq("id",n.id):{error:D}=await U.from("agent_custom_newsletters").insert(I),D)throw D;ne.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){ne.error(M.message||"Failed to save")}finally{w(!1)}}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Os,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(Rs,{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(ee,{htmlFor:"acn-title",children:"Title *"}),e.jsx(pe,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(pe,{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(mn,{id:"acn-template",checked:f,onCheckedChange:g}),e.jsx(ee,{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"})]}),(C||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(C_,{value:v,onValueChange:M=>y(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(am,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(ee,{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"})]})]}),C&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(am,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(ee,{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(am,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(ee,{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(am,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(ee,{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(ee,{className:"mb-2 block",children:"Content"}),e.jsx(Ent,{html:m,onChange:p})]})]}),e.jsxs(hr,{className:"px-6 py-3 border-t",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(z,{onClick:P,disabled:b,children:[b?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function xMn(){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 Tnt=/\[[^\]\[<>]{2,80}\]/g,gMn=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function Mnt(s){return!gMn.test(s)}function yMn(s){return(s.match(Tnt)||[]).filter(Mnt)}function Pjt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function vMn(s){const t=[],n=new RegExp(Tnt.source,"g");let r;for(;(r=n.exec(s))!==null;)Mnt(r[0])&&t.push({token:r[0],start:r.index});const a=t.reduce((l,o)=>(l[o.token]=(l[o.token]||0)+1,l),{}),i={};return t.map((l,o)=>{const c=l.token.slice(1,-1),d=/^#+$/.test(c);i[l.token]=(i[l.token]||0)+1;const u=t[o+1],h=u?u.token.slice(1,-1):"";let m;return d?m=u&&!/^#+$/.test(h)?`Date · ${Pjt(h)}`:`Date ${i[l.token]}`:(m=Pjt(c),a[l.token]>1&&(m+=` (${i[l.token]} of ${a[l.token]})`)),{index:o,token:l.token,label:m,hint:d?"Day of the month, e.g. 14":l.token}})}function bMn({html:s,onChange:t,originalHtml:n}){const r=_.useMemo(()=>vMn(s),[s]),[a,i]=_.useState({}),[l,o]=_.useState([]),c=_.useRef(null);c.current===null&&s&&(c.current=n??s);const d=_.useRef(!1);_.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const y=new RegExp(Tnt.source,"g");let b=0;const w=s.replace(y,S=>{if(!Mnt(S))return S;const C=(a[b]||"").trim();return b+=1,C||S});w!==s&&(o(S=>[...S,{html:s,values:a}]),d.current=!0,i({}),t(w))},h=()=>{const y=l[l.length-1];y&&(o(b=>b.slice(0,-1)),d.current=!0,i(y.values),t(y.html))},m=()=>{const y=c.current;!y||y===s||(o([]),d.current=!0,i({}),t(y))},p=l.length>0,f=!!c.current&&c.current!==s,g=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(z,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!p,children:[e.jsx(_J,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs(z,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!f,children:[e.jsx(Dx,{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(Mr,{className:"h-4 w-4 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"All template fields are filled in. Your name, phone, website and brokerage fill in automatically."})]}),(p||f)&&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?"}),g]})]});const v=r.filter(y=>(a[y.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(nl,{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(y=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:y.label}),e.jsx(pe,{value:a[y.index]||"",placeholder:y.hint,className:"h-10 text-sm",onChange:b=>i(w=>({...w,[y.index]:b.target.value})),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),u())}})]},y.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(z,{type:"button",size:"sm",onClick:u,children:[e.jsx(nq,{className:"h-3.5 w-3.5 mr-1"}),"Apply to email"]}),g]}),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 hz(){const s=ha();return rt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function _Mn(s){return rt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function Pnt(){const s=$t(),t=ha();return mt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await U.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 wMn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.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 jMn(){const s=$t();return mt({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 U.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function yYt(){const s=$t();return mt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await U.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 NMn(){const s=$t();return mt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await U.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 $ae(){const s=ha();return rt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags!inner(id, name, color, owner_user_id)").eq("tag.owner_user_id",s);if(n)throw n;return t},staleTime:5*60*1e3,enabled:!!s})}function Lnt(){const{user:s}=hs();return rt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function vYt(){const s=$t(),{user:t}=hs();return mt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await U.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"]}),la({title:"Smart filter saved"})},onError:n=>{la({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function bYt(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),la({title:"Smart filter deleted"})}})}const Ljt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function Ijt(s,t,n,r){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c=(n==null?void 0:n.name)||"",d=c.split(/\s+/).filter(Boolean).map(p=>p[0]).join("").slice(0,2).toUpperCase(),u=((n==null?void 0:n.website_url)||"").trim(),h=[n==null?void 0:n.return_address_line1,[n==null?void 0:n.return_address_city,n==null?void 0:n.return_address_state].filter(Boolean).join(", "),n==null?void 0:n.return_address_zip].filter(Boolean).join(" · "),m={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:c,agent_first_name:c.split(" ")[0]||"",agent_initials:d,agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",agent_website:u.replace(/^https?:\/\//i,"").replace(/\/$/,""),agent_website_url:u?/^https?:\/\//i.test(u)?u:`https://${u}`:"#",market_city:(n==null?void 0:n.market_city)||t.city||"",brokerage:r||(n==null?void 0:n.brokerage_name)||"",brokerage_address:h,current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(p,f)=>m[f]??`{{${f}}}`)}function kMn(s,t,n,r){const a=t.trim()?`
${Ljt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${Ljt(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function SMn(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 CMn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function AMn(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=CMn.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 Int({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=hs();bg();const{isReady:l,settings:o}=NL(),{data:c}=xae(),[d,u]=_.useState(!1),h=ha(),{data:m}=rt({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:an}=await U.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 an}}),[p,f]=_.useState("visual"),[g,v]=_.useState("all"),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(!0),[F,q]=_.useState([]),[G,V]=_.useState(null),[H,K]=_.useState(new Set),[Z,oe]=_.useState(""),[re,ae]=_.useState(!1),[J,te]=_.useState(!1),[ce,ve]=_.useState(!1),[me,he]=_.useState({sent:0,failed:0,total:0,currentName:""}),[ge,Ee]=_.useState(!0),[Ne,Pe]=_.useState(!1),[Oe,ke]=_.useState([]),[Ve,_e]=_.useState(!1),[Ae,Se]=_.useState(new Set),[We,qe]=_.useState("now"),[Be,Ze]=_.useState(""),{data:$e=[]}=hz(),{data:Xe=[]}=$ae(),{data:nt=[]}=Lnt(),{data:Ge=[],isLoading:Je}=rt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const an=[];let tr=0;const Lr=1e3;for(;;){const{data:Yt,error:it}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name").range(tr,tr+Lr-1);if(it)throw it;if(!Yt||Yt.length===0||(an.push(...Yt),Yt.length{const{data:an}=await U.from("ses_suppressed_emails").select("email");return(an||[]).map(tr=>tr.email.toLowerCase())}}),{data:lt}=rt({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:an}=await U.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(an!=null&&an.brokerage_id))return null;const{data:tr}=await U.from("brokerages").select("name, city, state").eq("id",an.brokerage_id).maybeSingle();return tr}}),{data:qt}=rt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:an}=await U.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 an}}),zt=!!(qt!=null&&qt.mls_provider_id),Zt=(qt==null?void 0:qt.mls_agent_id)||(qt==null?void 0:qt.mls_agent_key)||null,{data:ms=[],isLoading:Dt}=rt({queryKey:["newsletter-agent-listings",h,Zt],enabled:!!h&&!!Zt&&Ve,staleTime:60*1e3,queryFn:async()=>{if(!Zt)return[];const{data:an}=await U.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",Zt).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return an||[]}}),{data:It=[],isLoading:qs}=rt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ve,staleTime:60*1e3,queryFn:async()=>{const{data:an}=await U.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),tr=an||[];if(tr.length===0)return[];const Lr=tr.map(ft=>ft.id),{data:Yt}=await U.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Lr),it=new Map,gt=new Map;for(const ft of Yt||[])ft.is_primary&&!it.has(ft.listing_id)&&it.set(ft.listing_id,ft.photo_url),gt.has(ft.listing_id)||gt.set(ft.listing_id,ft.photo_url);return tr.map(ft=>({...ft,_photo:it.get(ft.id)||gt.get(ft.id)||""}))}}),{data:wt=!1}=rt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:an}=await U.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(an||0)>0}}),Us=_.useMemo(()=>{const an=new Set(ut);return Ge.filter(tr=>tr.email&&tr.email.includes("@")&&!an.has(tr.email.toLowerCase()))},[Ge,ut]),Es=_.useMemo(()=>{if(F.length===0)return null;const an=new Set;for(const tr of Xe)F.includes(tr.tag_id)&&an.add(tr.contact_id);return an},[Xe,F]),kn=_.useMemo(()=>nt.find(an=>an.id===G)||null,[nt,G]),Sn=_.useMemo(()=>{var an;if(g==="all")return Us;if(g==="tags")return Es?Us.filter(tr=>Es.has(tr.id)):[];if(g==="smartlists"){if(!kn)return[];const tr=(((an=kn.filters)==null?void 0:an.search)||"").toLowerCase().trim();return tr?Us.filter(Lr=>`${Lr.first_name||""} ${Lr.last_name||""}`.toLowerCase().includes(tr)||(Lr.email||"").toLowerCase().includes(tr)):Us}return Us.filter(tr=>H.has(tr.id))},[g,Us,Es,kn,H]),bn=_.useMemo(()=>{if(!Z.trim())return Us;const an=Z.toLowerCase();return Us.filter(tr=>`${tr.first_name||""} ${tr.last_name||""}`.toLowerCase().includes(an))},[Us,Z]);_.useEffect(()=>{s&&(b(""),S(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),E(`As always, reach out anytime if I can help. Talk soon!`),M(a||""),f("light"),v("all"),q([]),V(null),K(new Set),oe(""),ae(!1),D(!0),Ee(!0),ke([]),qe("now"),Ze(""),he({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const cr=l,Fs=_.useMemo(()=>yMn(P||a||""),[P,a]),cn=!!(y.trim()&&cr&&Sn.length>0&&!J&&Fs.length===0),lr=an=>{const tr=P||a,Lr=I&&(m!=null&&m.email_signature)?m.email_signature:null;let Yt;return p==="light"?Yt=kMn(tr,w,C,Lr):Yt=Lr?`${tr}
${Lr}
`:tr,ge&&(Yt+=SMn(m??null,lt??null,an.email)),Ijt(Yt,an,m??null,(lt==null?void 0:lt.name)??null)},Tn=_.useMemo(()=>lr({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[p,w,C,P,a,I,m,ge,lt]),Yn=_.useMemo(()=>AMn(y,p==="advanced"||p==="visual"?P:a),[y,p,P,a]),fs=async()=>{Pe(!0),ke([]);try{const an=p==="advanced"||p==="visual"?P:a,{data:tr,error:Lr}=await U.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:an,currentSubject:y}});if(Lr)throw Lr;const Yt=tr==null?void 0:tr.subjects;if(!Array.isArray(Yt)||Yt.length===0)throw new Error("No subjects returned");ke(Yt)}catch(an){const tr=(an==null?void 0:an.message)||"Failed to generate subjects";tr.includes("credits exhausted")||tr.includes("402")?ne.error("AI credits exhausted. Please add credits to your workspace."):tr.includes("Rate limit")||tr.includes("429")?ne.error("Rate limit hit — try again in a moment."):ne.error(tr)}finally{Pe(!1)}},wn=an=>an?"$"+Number(an).toLocaleString("en-US"):"",As=()=>{var gt,ft;if(Ae.size===0){ne.error("Pick at least one listing first.");return}const an=(qt==null?void 0:qt.subdomain_slug)||"",tr=an?`https://${an}.relevelup.com`:"https://relevelup.com",Lr=[];for(const Lt of ms){const Mt=`mls:${Lt.listing_key}`;if(!Ae.has(Mt))continue;const Qt=Array.isArray(Lt.photos)&&Lt.photos.length>0?typeof Lt.photos[0]=="string"?Lt.photos[0]:((gt=Lt.photos[0])==null?void 0:gt.MediaURL)||((ft=Lt.photos[0])==null?void 0:ft.url)||"":"",ks=Lt.bedrooms?`${Lt.bedrooms} bd`:"",gs=Lt.bathrooms_total?`${Lt.bathrooms_total} ba`:"",Vt=Lt.living_area?`${Number(Lt.living_area).toLocaleString()} sqft`:"";Lr.push({url:`${tr}/listings/${Lt.listing_key}`,photo:Qt,price:wn(Lt.list_price),addr:`${Lt.address||""}${Lt.city?", "+Lt.city:""}`,stats:[ks,gs,Vt].filter(Boolean).join(" • ")})}for(const Lt of It){const Mt=`ex:${Lt.id}`;if(!Ae.has(Mt))continue;const Qt=Lt.bedrooms?`${Lt.bedrooms} bd`:"",ks=Lt.bathrooms?`${Lt.bathrooms} ba`:"",gs=Lt.square_footage?`${Number(Lt.square_footage).toLocaleString()} sqft`:"";Lr.push({url:`https://listings.relevelup.com/${Lt.slug||Lt.id}`,photo:Lt._photo||"",price:wn(Lt.price),addr:`${Lt.property_address||""}${Lt.city?", "+Lt.city:""}`,stats:[Qt,ks,gs].filter(Boolean).join(" • ")})}const it=`

Featured Listings

${Lr.map(Lt=>`
${Lt.photo?`${Lt.addr}`:""}
${Lt.price}
${Lt.addr}
${Lt.stats}
`.trim()).join(` `)}
`.trim();M(Lt=>(Lt||a||"")+` `+it),f("visual"),Se(new Set),_e(!1),ne.success(`Added ${Lr.length} listing${Lr.length===1?"":"s"} to your newsletter.`)},Ss=()=>lr({first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"}).replace(/__FN__/g,"{{first_name}}").replace(/__LN__/g,"{{last_name}}").replace(/__EM__/g,"{{email}}").replace(/__NAME__/g,"{{name}}").replace(/__PHONE__/g,"{{phone}}").replace(/__ADDR__/g,"{{address}}").replace(/__CITY__/g,"{{city}}").replace(/__STATE__/g,"{{state}}").replace(/__ZIP__/g,"{{zip}}"),pr=()=>Ijt(y,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(lt==null?void 0:lt.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}}"),hn=()=>{if(Fs.length>0){ne.error(`Fill in ${Fs.length} template field${Fs.length===1?"":"s"} before sending.`);return}if(cn){if(We==="later"){if(!Be){ne.error("Pick a date and time to schedule.");return}const an=new Date(Be).getTime();if(Number.isNaN(an)||an{if(!(!cn||!i)){ve(!1),te(!0),he({sent:0,failed:0,total:Sn.length,currentName:"Preparing campaign…"});try{const tr=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Lr=Ss(),Yt=pr(),it=We==="later",{data:gt,error:ft}=await U.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:Yt,body_html:Lr,from_email:tr,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Sn.length,status:it?"scheduled":"draft",scheduled_at:it?new Date(Be).toISOString():null}).select("id").single();if(ft)throw ft;he(Mt=>({...Mt,currentName:"Adding recipients…"}));const Lt=Sn.map(Mt=>({campaign_id:gt.id,contact_id:Mt.id,email:Mt.email,name:[Mt.first_name,Mt.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Mt=0;Mt({...gs,sent:Math.min(Mt+Qt.length,Lt.length)}))}if(it){const{error:Mt}=await U.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:gt.id}});if(Mt)throw Mt;ne.success(`Newsletter scheduled for ${new Date(Be).toLocaleString()}.`)}else{const{error:Mt}=await U.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:gt.id}});if(Mt)throw Mt;ne.success(`Sending to ${Sn.length} contact${Sn.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(an){console.error("Newsletter send failed:",an),ne.error(`Failed to send: ${an.message||"Unknown error"}`)}finally{te(!1)}}},Gs=an=>{K(tr=>{const Lr=new Set(tr);return Lr.has(an)?Lr.delete(an):Lr.add(an),Lr})};return e.jsxs(Is,{open:s,onOpenChange:an=>!J&&t(an),children:[e.jsxs(Ls,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5"})," Send Newsletter"]})}),!cr&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border-2 border-destructive/40 bg-destructive/10 p-4 text-sm",children:[e.jsx(Ho,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx(z,{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(ee,{children:"Subject"}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:fs,disabled:Ne,title:"Generate subject lines with AI",children:[Ne?e.jsx(bt,{className:"h-3 w-3 animate-spin"}):e.jsx(un,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(pe,{value:y,onChange:an=>b(an.target.value),placeholder:"Newsletter subject"}),Oe.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:"}),Oe.map((an,tr)=>e.jsxs("button",{type:"button",onClick:()=>{b(an),ke([])},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"}),an]},tr))]}),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}}"})]})]}),Yn.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(uq,{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:Yn.map((an,tr)=>e.jsx("li",{children:an},tr))})]}),(zt||wt)&&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(sa,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:zt&&wt?"Pick from your live MLS listings or your Listing Exchange listings.":zt?"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(z,{type:"button",size:"sm",variant:"outline",onClick:()=>_e(!0),children:"Choose listings"})]}),e.jsx(bMn,{html:P||a||"",originalHtml:a||"",onChange:M}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Editing"}),e.jsxs(Qr,{value:p,onValueChange:an=>f(an),children:[e.jsxs(Jr,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Wt,{value:"visual",children:[e.jsx(rg,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Wt,{value:"light",children:[e.jsx($r,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Wt,{value:"advanced",children:[e.jsx(b4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Kt,{value:"visual",className:"mt-3",children:e.jsx(Ent,{html:P,onChange:M})}),e.jsxs(Kt,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ps,{value:w,onChange:an=>S(an.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ps,{value:C,onChange:an=>E(an.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Kt,{value:"advanced",className:"mt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ps,{value:P,onChange:an=>M(an.target.value),rows:14,className:"font-mono text-xs"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Append my email signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:m!=null&&m.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(mn,{checked:I&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:D})]}),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(mn,{checked:ge,onCheckedChange:Ee})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Recipients"}),e.jsxs(Qr,{value:g,onValueChange:an=>v(an),children:[e.jsxs(Jr,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Wt,{value:"all",children:[e.jsx(On,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Wt,{value:"tags",children:[e.jsx(Ip,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Wt,{value:"smartlists",children:[e.jsx(KQ,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Wt,{value:"individual",children:[e.jsx(Oo,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Kt,{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:Us.length})," contact",Us.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Kt,{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(Ki,{className:"h-40 rounded-lg border p-2",children:$e.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."}):$e.map(an=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(za,{checked:F.includes(an.id),onCheckedChange:tr=>q(Lr=>tr?[...Lr,an.id]:Lr.filter(Yt=>Yt!==an.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:an.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:an.name})]},an.id))})]}),e.jsxs(Kt,{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(Ki,{className:"h-40 rounded-lg border p-2",children:nt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):nt.map(an=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx("input",{type:"radio",name:"smartlist",checked:G===an.id,onChange:()=>V(an.id)}),e.jsx("span",{className:"text-sm",children:an.name})]},an.id))})]}),e.jsxs(Kt,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(pe,{placeholder:"Search contacts...",value:Z,onChange:an=>oe(an.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[H.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>K(new Set),children:"Clear"})]}),e.jsxs(Ki,{className:"h-48 rounded-lg border p-2",children:[Je&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!Je&&bn.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),bn.slice(0,200).map(an=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(za,{checked:H.has(an.id),onCheckedChange:()=>Gs(an.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[an.first_name," ",an.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:an.email})]})]},an.id)),bn.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(Mr,{className:"h-3 w-3"})," ",Sn.length," recipient",Sn.length===1?"":"s"]}),cr&&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(ee,{children:"Preview"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>ae(an=>!an),children:re?e.jsxs(e.Fragment,{children:[e.jsx(Yf,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(xa,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),re?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:Tn,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)."]})]})]}),J&&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(bt,{className:"h-4 w-4 animate-spin"}),"Sending to ",me.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[me.sent+me.failed," / ",me.total]})]}),e.jsx(Di,{value:me.total?(me.sent+me.failed)/me.total*100:0}),me.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[me.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Zr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(C_,{value:We,onValueChange:an=>qe(an),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(am,{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(am,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Ud,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),We==="later"&&e.jsx(pe,{type:"datetime-local",value:Be,onChange:an=>Ze(an.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:Fs.length>0?`${Fs.length} template field${Fs.length===1?"":"s"} still need${Fs.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(z,{variant:"outline",onClick:()=>t(!1),disabled:J,children:"Cancel"}),e.jsx(z,{onClick:hn,disabled:!cn,children:J?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):We==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Ud,{className:"h-4 w-4 mr-1"}),"Schedule for ",Sn.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send to ",Sn.length]})})]})]})]})]}),e.jsx(Ql,{open:ce,onOpenChange:ve,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:We==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(ql,{children:[We==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',y,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Sn.length," contact",Sn.length===1?"":"s"]}),We==="later"&&Be?` for ${new Date(Be).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:Pn,children:We==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Ud,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send to ",Sn.length]})})]})]})}),e.jsx(Is,{open:Ve,onOpenChange:_e,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(sa,{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||qs)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Dt&&!qs&&ms.length===0&&It.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."}),ms.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:ms.map(an=>{var it,gt;const tr=`mls:${an.listing_key}`,Lr=Ae.has(tr),Yt=Array.isArray(an.photos)&&an.photos.length>0?typeof an.photos[0]=="string"?an.photos[0]:((it=an.photos[0])==null?void 0:it.MediaURL)||((gt=an.photos[0])==null?void 0:gt.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Se(ft=>{const Lt=new Set(ft);return Lt.has(tr)?Lt.delete(tr):Lt.size<6?Lt.add(tr):ne.error("Max 6 listings per newsletter"),Lt})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Lr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Yt&&e.jsx("img",{src:Yt,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:an.list_price?`$${Number(an.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:an.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[an.city,an.state?`, ${an.state}`:""]})]}),Lr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Mr,{className:"h-4 w-4"})})]},tr)})})]}),It.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:It.map(an=>{const tr=`ex:${an.id}`,Lr=Ae.has(tr);return e.jsxs("button",{type:"button",onClick:()=>{Se(Yt=>{const it=new Set(Yt);return it.has(tr)?it.delete(tr):it.size<6?it.add(tr):ne.error("Max 6 listings per newsletter"),it})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Lr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[an._photo&&e.jsx("img",{src:an._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:an.price?`$${Number(an.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:an.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[an.city,an.state?`, ${an.state}`:""]})]}),Lr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Mr,{className:"h-4 w-4"})})]},tr)})})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>_e(!1),children:"Cancel"}),e.jsxs(z,{onClick:As,disabled:Ae.size===0,children:["Insert ",Ae.size>0?Ae.size:""," listing",Ae.size===1?"":"s"]})]})]})}),e.jsx(wLe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function EMn(){const{user:s}=hs(),t=$t(),[n,r]=_.useState("starters"),[a,i]=_.useState(!1),[l,o]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),{data:m,isLoading:p}=rt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:P,error:M}=await U.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return P||[]}}),f=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),g=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&!P.is_template))??[],v=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&P.is_template))??[],y=(m==null?void 0:m.filter(P=>P.user_id!==(s==null?void 0:s.id)&&P.is_template&&(P.share_scope==="team"||P.share_scope==="brokerage"||P.share_scope==="global")))??[],b=(m==null?void 0:m.filter(P=>P.share_scope==="global"&&P.is_template))??[],w=n==="starters"?b:n==="mine"?g:n==="templates"?v:y.filter(P=>P.share_scope!=="global"),S=async P=>{if(!s)return;const{error:M}=await U.from("agent_custom_newsletters").insert({user_id:s.id,title:`${P.title} (Copy)`,description:P.description,html_content:P.html_content,is_template:!1,share_scope:"private"});if(M){ne.error(M.message);return}ne.success('Duplicated to "My Newsletters"'),f(),r("mine")},C=async P=>{const{error:M}=await U.from("agent_custom_newsletters").delete().eq("id",P);if(M){ne.error(M.message);return}ne.success("Deleted"),h(null),f()},E=P=>P.share_scope==="global"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Starter"]}):P.share_scope==="brokerage"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),"Brokerage"]}):P.share_scope==="team"?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(On,{className:"h-3 w-3"}),"Team"]}):e.jsxs(ze,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Hl,{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(z,{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 (",b.length,")"]}),e.jsxs(z,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",g.length,")"]}),e.jsxs(z,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",v.length,")"]}),e.jsxs(z,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",y.filter(P=>P.share_scope!=="global").length,")"]})]}),e.jsxs(z,{onClick:()=>{o(null),i(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((P,M)=>e.jsx(ln,{className:"h-48 w-full"},M))}),n==="starters"&&!p&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(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.']})]}),!p&&w.length===0&&e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx($r,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!p&&w.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:w.map(P=>{const M=P.user_id===(s==null?void 0:s.id);return e.jsxs(be,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",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 p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${P.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[P.is_template&&e.jsx(ze,{className:"bg-primary/90",children:"Template"}),E(P)]})]}),e.jsxs(Le,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:P.title}),P.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:P.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Ys(new Date(P.updated_at||P.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(z,{size:"sm",onClick:()=>d(P),className:"flex-1 min-w-[80px]",children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),M?e.jsxs(e.Fragment,{children:[e.jsx(z,{size:"sm",variant:"outline",onClick:()=>{o(P),i(!0)},children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>S(P),children:e.jsx(Sa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>h(P.id),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]}):e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>S(P),children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},P.id)})}),e.jsx(fMn,{open:a,onOpenChange:i,initial:l,onSaved:f}),c&&e.jsx(Int,{open:!!c,onOpenChange:P=>!P&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Ql,{open:!!u,onOpenChange:P=>!P&&h(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete this newsletter?"}),e.jsx(ql,{children:"This cannot be undone."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>u&&C(u),children:"Delete"})]})]})})]})}function TMn(){const s=zn(),[t,n]=_.useState(""),[r,a]=_.useState("grid"),[i,l]=_.useState(null),{data:o,isLoading:c}=rt({queryKey:["newsletters"],queryFn:async()=>{const{data:C,error:E}=await U.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(E)throw E;return C}}),{data:d}=rt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:C}=await U.from("newsletter_likes").select("newsletter_id");return C||[]}}),{data:u}=rt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:C}=await U.from("newsletter_comments").select("newsletter_id");return C||[]}}),{data:h}=rt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[C,E,P,M]=await Promise.all([U.from("newsletter_canva_links").select("newsletter_id"),U.from("newsletter_pdfs").select("newsletter_id"),U.from("newsletter_videos").select("newsletter_id"),U.from("newsletter_drive_links").select("newsletter_id")]);return{canva:C.data||[],pdfs:E.data||[],videos:P.data||[],drives:M.data||[]}}}),m=C=>(d==null?void 0:d.filter(E=>E.newsletter_id===C).length)||0,p=C=>(u==null?void 0:u.filter(E=>E.newsletter_id===C).length)||0,f=C=>{var E;return((E=h==null?void 0:h.canva)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},g=C=>{var E;return((E=h==null?void 0:h.pdfs)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},v=C=>{var E;return((E=h==null?void 0:h.videos)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},y=C=>{var E;return((E=h==null?void 0:h.drives)==null?void 0:E.filter(P=>P.newsletter_id===C).length)||0},b=C=>f(C)+g(C)+v(C)+y(C),w=o==null?void 0:o.filter(C=>{var E;return C.title.toLowerCase().includes(t.toLowerCase())||((E=C.description)==null?void 0:E.toLowerCase().includes(t.toLowerCase()))}),S=C=>{s(`/newsletters/${C}`)};return e.jsx($s,{title:"Newsletter Content",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Newsletter Content"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly templates, plus newsletters you build yourself"})]}),e.jsxs(Qr,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"custom",children:"Build & Send"}),e.jsx(Wt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Kt,{value:"custom",className:"mt-2",children:e.jsx(EMn,{})}),e.jsxs(Kt,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search newsletters...",value:t,onChange:C=>n(C.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(z,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(op,{className:"h-4 w-4"})}),e.jsx(z,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(My,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(w==null?void 0:w.length)||0," item",(w==null?void 0:w.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((C,E)=>e.jsx(be,{children:e.jsxs(Le,{className:"p-0",children:[e.jsx(ln,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(ln,{className:"h-5 w-3/4"}),e.jsx(ln,{className:"h-4 w-full"})]})]})},E))}),!c&&(w==null?void 0:w.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx($r,{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(z,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&w&&w.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:w.map(C=>{const E=b(C.id),P=f(C.id),M=g(C.id),I=v(C.id);return r==="grid"?e.jsxs(be,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(C.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.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($r,{className:"h-16 w-16"})})}),e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:C.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(ya,{className:"h-3 w-3"}),Ys(new Date(C.publish_date),"MMM d, yyyy")]})]}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:C.description.replace(/<[^>]*>/g,"")}),E>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[P>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(yc,{className:"h-3 w-3"})," ",P," Template",P>1?"s":""]}),M>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Ga,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),I>0&&e.jsxs(ze,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(su,{className:"h-3 w-3"})," ",I," Video",I>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(Ug,{className:"h-3 w-3"})," ",m(C.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3 w-3"})," ",p(C.id)]})]}),C.html_code&&e.jsxs(z,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(C)},children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},C.id):e.jsx(be,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(C.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:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.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($r,{className:"h-10 w-10"})})}),e.jsxs(Le,{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:C.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(ya,{className:"h-3 w-3"}),Ys(new Date(C.publish_date),"MMM d, yyyy")]})]}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:C.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[E>0&&e.jsxs("span",{children:[E," resource",E>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ug,{className:"h-3 w-3"})," ",m(C.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3 w-3"})," ",p(C.id)]})]})]}),C.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(z,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(C)},children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},C.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(Int,{open:!!i,onOpenChange:C=>!C&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function MMn({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(be,{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(Le,{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 PMn(){const{id:s}=Mi(),t=zn(),{user:n}=hs(),{toast:r}=_i(),a=$t(),{trackEngagement:i}=CW(),[l,o]=_.useState(""),[c,d]=_.useState(!1),{data:u,isLoading:h}=rt({queryKey:["newsletter",s],queryFn:async()=>{const{data:P,error:M}=await U.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return P},enabled:!!s});_.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=rt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:p}=rt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:f}=rt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:g}=rt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:v}=rt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_likes").select("*").eq("newsletter_id",s);return P||[]},enabled:!!s}),{data:y}=rt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return P||[]},enabled:!!s}),b=v==null?void 0:v.some(P=>P.user_id===(n==null?void 0:n.id)),w=mt({mutationFn:async()=>{b?await U.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await U.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),S=mt({mutationFn:async P=>{const{error:M}=await U.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:P});if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),C=mt({mutationFn:async P=>{const{error:M}=await U.from("newsletter_comments").delete().eq("id",P);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),E=P=>{if(P.includes("player.mediadelivery.net")||P.includes("iframe.mediadelivery.net")){const M=P.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(P.includes("youtube.com")||P.includes("youtu.be")){const M=P.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:P,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(su,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx($s,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-8 w-32"}),e.jsx(ln,{className:"h-64 w-full"}),e.jsx(ln,{className:"h-32 w-full"})]})}):u?e.jsx($s,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(z,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),u.preview_image_url&&e.jsx("img",{src:u.preview_image_url,alt:u.title,className:"w-full h-64 md:h-80 object-cover rounded-lg"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:u.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:Ys(new Date(u.publish_date),"MMMM d, yyyy")})]}),u.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:u.description}}),e.jsx(MMn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(TW,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(z,{variant:b?"default":"outline",size:"sm",onClick:()=>w.mutate(),children:[e.jsx(Fo,{className:`h-4 w-4 mr-1 ${b?"fill-current":""}`}),(v==null?void 0:v.length)||0," ",(v==null?void 0:v.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs(z,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(Int,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),g&&g.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Le,{className:"space-y-2",children:g.map(P=>e.jsxs("a",{href:P.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(yc,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:P.title}),e.jsx(mr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},P.id))})]}),m&&m.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Le,{className:"space-y-2",children:m.map(P=>e.jsxs("a",{href:P.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(mr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:P.title})]},P.id))})]}),p&&p.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Le,{className:"space-y-2",children:p.map(P=>e.jsxs("a",{href:P.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($r,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:P.name}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground"})]},P.id))})]}),f&&f.length>0&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Videos"})}),e.jsx(Le,{className:"space-y-6",children:f.map(P=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:P.title}),E(P.video_url)]},P.id))})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-lg",children:["Comments (",(y==null?void 0:y.length)||0,")"]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ps,{placeholder:"Write a comment...",value:l,onChange:P=>o(P.target.value),className:"flex-1"}),e.jsx(z,{onClick:()=>l.trim()&&S.mutate(l),disabled:!l.trim()||S.isPending,children:e.jsx(Fr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:y==null?void 0:y.map(P=>{var M,I,D;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{children:((I=(M=P.profiles)==null?void 0:M.name)==null?void 0:I[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:((D=P.profiles)==null?void 0:D.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(P.created_at),"MMM d, yyyy")}),P.user_id===(n==null?void 0:n.id)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>C.mutate(P.id),children:e.jsx(Cn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:P.content})]})]},P.id)})})]})]})]})}):e.jsx($s,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(z,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function LMn({rows:s,onChange:t}){const[n,r]=_.useState(null),[a,i]=_.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,p)=>p!==h))},c=(h,m,p,f)=>{const g=[...s];g[h]={...g[h],columns:g[h].columns.map((v,y)=>y===m?{...v,[p]:f}:v)},t(g)},d=async(h,m,p)=>{var v;const f=(v=p.target.files)==null?void 0:v[0];if(!f)return;const g=`${h}-${m}`;r(g);try{const y=`content-blocks/${Date.now()}-${f.name}`,{error:b}=await U.storage.from("newsletter-content").upload(y,f);if(!b){const{data:w}=U.storage.from("newsletter-content").getPublicUrl(y);c(h,m,"image_url",w.publicUrl)}}finally{r(null)}},u=(h,m)=>{c(h,m,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((h,m)=>e.jsxs(be,{className:"relative",children:[e.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(m),children:e.jsx(er,{className:"h-4 w-4"})}),e.jsxs(Le,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Zf,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((p,f)=>{const g=`${m}-${f}`;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 ",f+1]}),p.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:p.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(z,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(m,f),children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(pe,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${g}`,onChange:v=>d(m,f,v)}),e.jsx(z,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===g,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${g}`,className:"cursor-pointer",children:n===g?"...":e.jsxs(e.Fragment,{children:[e.jsx(nc,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:m,col:f}),children:[e.jsx(vj,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(pe,{placeholder:"Title",value:p.title,onChange:v=>c(m,f,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(Ps,{placeholder:"Description",value:p.description,onChange:v=>c(m,f,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},f)})})]})]},m)),e.jsx(Is,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Ls,{className:"sm:max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Choose a Graphic"})}),e.jsx(gYt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function IMn(){const{toast:s}=_i(),t=$t(),[n,r]=_.useState(!1),[a,i]=_.useState(null),[l,o]=_.useState({title:"",description:"",publish_date:Ys(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=_.useState(null),[u,h]=_.useState(null),[m,p]=_.useState([]),[f,g]=_.useState([]),[v,y]=_.useState([]),[b,w]=_.useState([]),[S,C]=_.useState([]),[E,P]=_.useState(""),[M,I]=_.useState([]),[D,F]=_.useState(!1),{data:q,isLoading:G}=rt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:ge,error:Ee}=await U.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return ge}}),V=mt({mutationFn:async ge=>{const{data:Ee,error:Ne}=await U.from("newsletter_content").insert({title:ge.title,description:ge.description||null,preview_image_url:ge.preview_image_url,publish_date:ge.publish_date,is_published:ge.is_published,content_blocks:ge.content_blocks,html_code:ge.html_code}).select().single();if(Ne)throw Ne;return Ee},onSuccess:async ge=>{await Z(ge.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),ge.is_published&&Qon(ge.title,ge.id),ae()},onError:ge=>{s({title:"Error creating newsletter",description:ge.message,variant:"destructive"})}}),H=mt({mutationFn:async ge=>{const{error:Ee}=await U.from("newsletter_content").update({title:ge.title,description:ge.description||null,preview_image_url:ge.preview_image_url,publish_date:ge.publish_date,is_published:ge.is_published,content_blocks:ge.content_blocks,html_code:ge.html_code}).eq("id",ge.id);if(Ee)throw Ee;return ge.id},onSuccess:async ge=>{await Z(ge),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ae()},onError:ge=>{s({title:"Error updating newsletter",description:ge.message,variant:"destructive"})}}),K=mt({mutationFn:async ge=>{const{error:Ee}=await U.from("newsletter_content").delete().eq("id",ge);if(Ee)throw Ee},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:ge=>{s({title:"Error deleting newsletter",description:ge.message,variant:"destructive"})}}),Z=async ge=>{await U.from("newsletter_drive_links").delete().eq("newsletter_id",ge),await U.from("newsletter_pdfs").delete().eq("newsletter_id",ge),await U.from("newsletter_videos").delete().eq("newsletter_id",ge),await U.from("newsletter_canva_links").delete().eq("newsletter_id",ge);for(const Ee of M){const Ne=`${ge}/${Date.now()}-${Ee.file.name}`,{error:Pe}=await U.storage.from("newsletter-content").upload(Ne,Ee.file);if(!Pe){const{data:Oe}=U.storage.from("newsletter-content").getPublicUrl(Ne);f.push({name:Ee.name,file_url:Oe.publicUrl,file_size:Ee.file.size,sort_order:f.length})}}m.length>0&&await U.from("newsletter_drive_links").insert(m.map((Ee,Ne)=>({newsletter_id:ge,title:Ee.title,drive_url:Ee.drive_url,sort_order:Ne}))),f.length>0&&await U.from("newsletter_pdfs").insert(f.map((Ee,Ne)=>({newsletter_id:ge,name:Ee.name,file_url:Ee.file_url,file_size:Ee.file_size||null,sort_order:Ne}))),v.length>0&&await U.from("newsletter_videos").insert(v.map((Ee,Ne)=>({newsletter_id:ge,title:Ee.title,video_url:Ee.video_url,sort_order:Ne}))),b.length>0&&await U.from("newsletter_canva_links").insert(b.map((Ee,Ne)=>({newsletter_id:ge,title:Ee.title,canva_share_link:Ee.canva_share_link,sort_order:Ne})))},oe=async ge=>{i(ge),o({title:ge.title,description:ge.description||"",publish_date:Ys(new Date(ge.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:ge.is_published}),h(ge.preview_image_url),C(ge.content_blocks||[]),P(ge.html_code||"");const[Ee,Ne,Pe,Oe]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",ge.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",ge.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",ge.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",ge.id).order("sort_order")]);p(Ee.data||[]),g(Ne.data||[]),y(Pe.data||[]),w(Oe.data||[]),I([]),r(!0)},re=async ge=>{const[Ee,Ne,Pe,Oe]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",ge.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",ge.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",ge.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",ge.id).order("sort_order")]);i(null),o({title:`${ge.title} (Copy)`,description:ge.description||"",publish_date:Ys(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(ge.preview_image_url),C(ge.content_blocks||[]),P(ge.html_code||""),p((Ee.data||[]).map(({id:ke,...Ve})=>Ve)),g((Ne.data||[]).map(({id:ke,...Ve})=>Ve)),y((Pe.data||[]).map(({id:ke,...Ve})=>Ve)),w((Oe.data||[]).map(({id:ke,...Ve})=>Ve)),I([]),r(!0)},ae=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Ys(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),p([]),g([]),y([]),w([]),C([]),P(""),I([])},J=async ge=>{var Ne;const Ee=(Ne=ge.target.files)==null?void 0:Ne[0];Ee&&(d(Ee),h(URL.createObjectURL(Ee)))},te=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}F(!0);let ge=u;if(c){const Ee=`previews/${Date.now()}-${c.name}`,{error:Ne}=await U.storage.from("newsletter-content").upload(Ee,c);if(!Ne){const{data:Pe}=U.storage.from("newsletter-content").getPublicUrl(Ee);ge=Pe.publicUrl}}a?H.mutate({id:a.id,...l,preview_image_url:ge,content_blocks:S,html_code:E||null}):V.mutate({...l,preview_image_url:ge,content_blocks:S,html_code:E||null}),F(!1)},ce=()=>p([...m,{title:"",drive_url:"",sort_order:m.length}]),ve=()=>y([...v,{title:"",video_url:"",sort_order:v.length}]),me=()=>w([...b,{title:"",canva_share_link:"",sort_order:b.length}]),he=ge=>{const Ee=ge.target.files;if(!Ee)return;const Ne=Array.from(Ee).map(Pe=>({file:Pe,name:Pe.name.replace(/\.[^/.]+$/,"")}));I([...M,...Ne])};return e.jsx($s,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(q==null?void 0:q.length)||0})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(q==null?void 0:q.filter(ge=>ge.is_published).length)||0})})]})]}),e.jsxs(Is,{open:n,onOpenChange:ge=>!ge&&ae(),children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{onClick:()=>r(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Ls,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Title *"}),e.jsx(pe,{value:l.title,onChange:ge=>o({...l,title:ge.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Publish Date"}),e.jsx(pe,{type:"datetime-local",value:l.publish_date,onChange:ge=>o({...l,publish_date:ge.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:l.description,onChange:ge=>o({...l,description:ge}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(z,{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(er,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:J,className:"hidden",id:"preview-upload"}),e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:l.is_published,onCheckedChange:ge=>o({...l,is_published:ge})}),e.jsx(ee,{children:"Published"})]}),e.jsx(LMn,{rows:S,onChange:C}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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:E,onChange:ge=>P(ge.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(ee,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:me,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((ge,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:ge.title,onChange:Ne=>{const Pe=[...b];Pe[Ee].title=Ne.target.value,w(Pe)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Canva share link",value:ge.canva_share_link,onChange:Ne=>{const Pe=[...b];Pe[Ee].canva_share_link=Ne.target.value,w(Pe)},className:"flex-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>w(b.filter((Ne,Pe)=>Pe!==Ee)),children:e.jsx(er,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((ge,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:ge.title,onChange:Ne=>{const Pe=[...m];Pe[Ee].title=Ne.target.value,p(Pe)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Google Drive URL",value:ge.drive_url,onChange:Ne=>{const Pe=[...m];Pe[Ee].drive_url=Ne.target.value,p(Pe)},className:"flex-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>p(m.filter((Ne,Pe)=>Pe!==Ee)),children:e.jsx(er,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(pe,{type:"file",accept:".pdf",multiple:!0,onChange:he,className:"hidden",id:"pdf-upload"}),e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(Ra,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),f.map((ge,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:ge.name}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>g(f.filter((Ne,Pe)=>Pe!==Ee)),children:e.jsx(er,{className:"h-4 w-4"})})]},`existing-${Ee}`)),M.map((ge,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:ge.name,onChange:Ne=>{const Pe=[...M];Pe[Ee].name=Ne.target.value,I(Pe)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>I(M.filter((Ne,Pe)=>Pe!==Ee)),children:e.jsx(er,{className:"h-4 w-4"})})]},`pending-${Ee}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:ve,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),v.map((ge,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Video title",value:ge.title,onChange:Ne=>{const Pe=[...v];Pe[Ee].title=Ne.target.value,y(Pe)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Video URL",value:ge.video_url,onChange:Ne=>{const Pe=[...v];Pe[Ee].video_url=Ne.target.value,y(Pe)},className:"flex-1"}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(v.filter((Ne,Pe)=>Pe!==Ee)),children:e.jsx(er,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(z,{variant:"outline",onClick:ae,children:"Cancel"}),e.jsx(z,{onClick:te,disabled:D||V.isPending||H.isPending,children:D?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:G?e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(q==null?void 0:q.length)===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):q==null?void 0:q.map(ge=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ge.preview_image_url?e.jsx("img",{src:ge.preview_image_url,alt:ge.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($r,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ge.title}),ge.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ge.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(yt,{children:Ys(new Date(ge.publish_date),"MMM d, yyyy")}),e.jsx(yt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ge.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:ge.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>oe(ge),title:"Edit",children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>re(ge),title:"Duplicate",children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await Qi("Are you sure you want to delete this newsletter?")&&K.mutate(ge.id)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},ge.id))})]})})})]})})}const DMn={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function RMn({brokerages:s}){var C;const{toast:t}=_i(),[n,r]=_.useState(DMn),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(null),[m,p]=_.useState(!1),[f,g]=_.useState(!1),[v,y]=_.useState(null),b=(E,P)=>r(M=>({...M,[E]:P}));_.useEffect(()=>{const E=setTimeout(async()=>{p(!0);try{const{data:P,error:M}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(M)throw M;h(P)}catch{h(null)}finally{p(!1)}},450);return()=>clearTimeout(E)},[n,a]);const w=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}g(!0);const{data:E,error:P}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(g(!1),P||E!=null&&E.error){t({title:"Test failed",description:(E==null?void 0:E.error)||(P==null?void 0:P.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},S=async()=>{const E=(u==null?void 0:u.count)||0;if(!(!a.trim()||E===0||!await Qi({title:"Send text broadcast?",description:`This will text ${E} member${E===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){g(!0),y({total:E,sent:0,failed:0});try{const{data:M,error:I}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(I||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||(I==null?void 0:I.message));let D=0,F=0,q=M.total,G=0;for(;q>0&&G++<400;){const{data:V,error:H}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:M.broadcast_id,limit:40}});if(H||V!=null&&V.error)throw new Error((V==null?void 0:V.error)||(H==null?void 0:H.message));if(V.deferred){t({title:"Paused for quiet hours",description:V.reason});break}D+=V.sent||0,F+=V.failed||0,q=V.remaining||0,y({total:E,sent:D,failed:F})}t({title:"Broadcast complete",description:`${D} sent${F?`, ${F} failed`:""}.`})}catch(M){t({title:"Broadcast failed",description:M.message,variant:"destructive"})}finally{g(!1)}}};return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ch,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(En,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Account status"}),e.jsxs(ls,{value:n.status,onValueChange:E=>b("status",E),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All members"}),e.jsx(He,{value:"active",children:"Signed in before"}),e.jsx(He,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Billing"}),e.jsxs(ls,{value:n.billing,onValueChange:E=>b("billing",E),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All"}),e.jsx(He,{value:"trial",children:"On trial"}),e.jsx(He,{value:"paid",children:"Paid"}),e.jsx(He,{value:"grandfathered",children:"Grandfathered"}),e.jsx(He,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Role"}),e.jsxs(ls,{value:n.role,onValueChange:E=>b("role",E),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All roles"}),e.jsx(He,{value:"user",children:"Agents"}),e.jsx(He,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(He,{value:"coach",children:"Coaches"}),e.jsx(He,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Brokerage"}),e.jsxs(ls,{value:n.brokerage,onValueChange:E=>b("brokerage",E),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All brokerages"}),e.jsx(He,{value:"none",children:"No brokerage"}),s.map(E=>e.jsx(He,{value:E.id,children:E.name},E.id))]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"SMS-eligible members"}),e.jsx("span",{className:"text-lg font-semibold",children:m?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):(u==null?void 0:u.count)??0})]}),(C=u==null?void 0:u.sample)!=null&&C.length?e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["e.g. ",u.sample.slice(0,3).map(E=>E.name||E.phone).join(", ")]}):null]}),u&&!u.quiet_hours_ok&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs",children:[e.jsx(Zr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"Outside the 9:00 AM – 8:00 PM ET sending window. Queued texts will be held and resumed instead of sent now."})]})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(qi,{className:"h-4 w-4"})," Text message"]}),e.jsxs(En,{children:["Merge tags: ",e.jsx("code",{children:"{{first_name}}"})," ",e.jsx("code",{children:"{{name}}"}),'. The LevelUp prefix and "Reply STOP to opt out" are added automatically.']})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(pe,{id:"sms-broadcast-name",value:l,onChange:E=>o(E.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Ps,{id:"sms-broadcast-body",value:a,onChange:E=>i(E.target.value),rows:5,maxLength:480,placeholder:"Hi {{first_name}} — join us Thursday at 11am ET for the LevelUp Live session on listing videos."}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(u==null?void 0:u.length)??a.length," characters"]}),e.jsxs(ze,{variant:((u==null?void 0:u.segments)??1)>2?"destructive":"secondary",children:[(u==null?void 0:u.segments)??1," segment",((u==null?void 0:u.segments)??1)===1?"":"s"]})]})]}),(u==null?void 0:u.composed)&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Preview as delivered"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.composed})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",style:{minWidth:200},children:[e.jsx(ee,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(pe,{id:"sms-test-phone",value:c,onChange:E=>d(E.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs(z,{variant:"outline",onClick:w,disabled:f,children:[f&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Di,{value:v.total?(v.sent+v.failed)/v.total*100:0}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Mr,{className:"h-3 w-3"})," ",v.sent," sent"]}),v.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(Ho,{className:"h-3 w-3"})," ",v.failed," failed"]}),e.jsxs("span",{children:["of ",v.total]})]})]}),e.jsxs(z,{onClick:S,disabled:f||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[f?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"mr-2 h-4 w-4"}),"Send to ",(u==null?void 0:u.count)??0," member",((u==null?void 0:u.count)??0)===1?"":"s"]})]})]})})]})}const ize={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},FMn=["{{first_name}}","{{name}}","{{email}}"];function OMn(s){return`${s||'

Your email preview will appear here…

'}`}function zMn(){var Ge;const{toast:s}=_i(),{user:t}=hs(),n=$t(),[r,a]=_.useState("filters"),[i,l]=_.useState([]),[o,c]=_.useState(""),[d,u]=_.useState([]),[h,m]=_.useState(!1),[p,f]=_.useState(""),[g,v]=_.useState(!1),[y,b]=_.useState(ize),[w,S]=_.useState(null),[C,E]=_.useState(!1),[P,M]=_.useState(""),[I,D]=_.useState(""),[F,q]=_.useState(""),[G,V]=_.useState(""),[H,K]=_.useState("rich"),[Z,oe]=_.useState(""),[re,ae]=_.useState(""),[J,te]=_.useState(""),[ce,ve]=_.useState(!1),[me,he]=_.useState(null),ge=H==="rich"?Z:re;_.useEffect(()=>{t!=null&&t.email&&(q(Je=>Je||t.email),V(Je=>Je||t.email),te(Je=>Je||t.email))},[t==null?void 0:t.email]);const{data:Ee}=rt({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:Je}=await U.from("brokerages").select("id, name").order("name");return Je||[]}}),{data:Ne}=rt({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:Je}=await U.from("programs").select("id, name").order("created_at",{ascending:!1});return Je||[]}}),{data:Pe}=rt({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:Je,error:ut}=await U.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(ut)throw ut;return Je}}),{data:Oe}=rt({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:Je,error:ut}=await U.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(ut)throw ut;return Je}}),ke=async Je=>{E(!0);try{const{data:ut,error:lt}=await U.functions.invoke("admin-broadcast",{body:{action:"preview",filters:Je}});if(lt)throw lt;if(ut!=null&&ut.error)throw new Error(ut.error);S(ut)}catch(ut){s({title:"Could not load audience",description:ut.message,variant:"destructive"})}finally{E(!1)}};_.useEffect(()=>{if(r!=="filters")return;const Je=setTimeout(()=>ke(y),400);return()=>clearTimeout(Je)},[y,r]),_.useEffect(()=>{if(r!=="manual")return;const Je=setTimeout(async()=>{m(!0);try{const{data:ut,error:lt}=await U.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(lt)throw lt;u((ut==null?void 0:ut.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(Je)},[o,r]);const Ve=(Je,ut)=>b(lt=>({...lt,[Je]:ut})),_e=r==="manual"?i.length:(w==null?void 0:w.count)||0,Ae=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(Je=>Je.email)}:{recipient_mode:"filters",filters:y},Se=Je=>l(ut=>ut.some(lt=>lt.email.toLowerCase()===Je.email.toLowerCase())?ut.filter(lt=>lt.email.toLowerCase()!==Je.email.toLowerCase()):[...ut,Je]),We=async()=>{const Je=(p||P||I).trim();if(!Je||!ge.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}v(!0);try{const{error:ut}=await U.from("admin_broadcast_templates").insert({created_by:t.id,name:Je,subject:I,body_html:ge,editor_mode:H,from_email:F||null,reply_to_email:G||null,filters:y});if(ut)throw ut;f(""),s({title:"Template saved",description:`"${Je}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(ut){s({title:"Could not save template",description:ut.message,variant:"destructive"})}finally{v(!1)}},qe=Je=>{M(Je.name||""),D(Je.subject||""),Je.from_email&&q(Je.from_email),Je.reply_to_email&&V(Je.reply_to_email);const ut=Je.editor_mode==="html"?"html":"rich";K(ut),ut==="html"?ae(Je.body_html||""):oe(Je.body_html||""),Je.filters&&Object.keys(Je.filters).length&&b({...ize,...Je.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},Be=async Je=>{if(!await Qi(`Delete template "${Je.name}"?`))return;const{error:ut}=await U.from("admin_broadcast_templates").delete().eq("id",Je.id);if(ut){s({title:"Delete failed",description:ut.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},Ze=_.useMemo(()=>!!I.trim()&&!!ge.trim()&&!!F.trim()&&_e>0,[I,ge,F,_e]),$e=async()=>{if(!J||!I.trim()||!ge.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:Je,error:ut}=await U.functions.invoke("admin-broadcast",{body:{action:"test",to:J,subject:I,html:ge,from_email:F,reply_to:G||void 0}});if(ut)throw ut;if(Je!=null&&Je.error)throw new Error(Je.error);s({title:"Test sent",description:`Check ${J}`})}catch(Je){s({title:"Test failed",description:Je.message,variant:"destructive"})}},Xe=async()=>{const Je=_e;if(await Qi({title:"Send this broadcast?",description:`"${I}" will be emailed to ${Je} member${Je===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){ve(!0),he({total:Je,sent:0,failed:0});try{const{data:lt,error:qt}=await U.functions.invoke("admin-broadcast",{body:{action:"queue",name:P||I,subject:I,html:ge,from_email:F,reply_to:G||void 0,...Ae()}});if(qt)throw qt;if(lt!=null&<.error)throw new Error(lt.error);let zt=0,Zt=0,ms=lt.total,Dt=0;for(;ms>0;){const{data:It,error:qs}=await U.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:lt.broadcast_id,limit:40}});if(qs)throw qs;if(It!=null&&It.error)throw new Error(It.error);if(zt+=It.sent,Zt+=It.failed,ms=It.remaining,he({total:lt.total,sent:zt,failed:Zt}),It.throttled){const wt=Math.min(Math.max(Number(It.retry_after_ms)||15e3,5e3),45e3);await new Promise(Us=>setTimeout(Us,wt));continue}if(It.sent===0&&It.failed===0){if(++Dt>=3)break;await new Promise(wt=>setTimeout(wt,5e3))}else Dt=0}s({title:"Broadcast complete",description:`${zt} sent${Zt?`, ${Zt} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(lt){s({title:"Send failed",description:lt.message,variant:"destructive"})}finally{ve(!1)}}},nt=async Je=>{ve(!0);try{const{data:ut,error:lt}=await U.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:Je}});if(lt)throw lt;if(ut!=null&&ut.error)throw new Error(ut.error);let qt=0,zt=0,Zt=ut.requeued,ms=0;for(he({total:Zt,sent:0,failed:0});Zt>0;){const{data:Dt,error:It}=await U.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:Je,limit:25}});if(It)throw It;if(Dt!=null&&Dt.error)throw new Error(Dt.error);if(qt+=Dt.sent,zt+=Dt.failed,Zt=Dt.remaining,he({total:ut.requeued,sent:qt,failed:zt}),Dt.throttled){await new Promise(qs=>setTimeout(qs,Math.min(Math.max(Number(Dt.retry_after_ms)||15e3,5e3),45e3)));continue}if(Dt.sent===0&&Dt.failed===0){if(++ms>=3)break;await new Promise(qs=>setTimeout(qs,5e3))}else ms=0}s({title:"Retry complete",description:`${qt} sent${zt?`, ${zt} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(ut){s({title:"Retry failed",description:ut.message,variant:"destructive"})}finally{ve(!1)}};return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Xh,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(Qr,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"compose",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Wt,{value:"sms",className:"gap-2",children:[e.jsx(qi,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Wt,{value:"templates",className:"gap-2",children:[e.jsx(yj,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Wt,{value:"history",className:"gap-2",children:[e.jsx(O_,{className:"h-4 w-4"})," History"]})]}),e.jsx(Kt,{value:"sms",className:"space-y-6",children:e.jsx(RMn,{brokerages:Ee})}),e.jsx(Kt,{value:"compose",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/90 to-primary p-5 text-primary-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm opacity-90",children:[e.jsx(On,{className:"h-4 w-4"})," Audience"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-4xl font-bold",children:r==="manual"?i.length:C?"—":(w==null?void 0:w.count)??0}),e.jsx("span",{className:"text-sm opacity-90",children:r==="manual"?"members selected":"members match"})]})]}),e.jsxs(Le,{className:"space-y-4 pt-5",children:[e.jsx(Qr,{value:r,onValueChange:Je=>a(Je),children:e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Wt,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(On,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Wt,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"})," Individuals"]})]})}),r==="manual"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:o,onChange:Je=>c(Je.target.value),placeholder:"Search by name or email",className:"pl-8"})]})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(Je=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:Je.name||Je.email}),e.jsx("button",{type:"button",onClick:()=>Se(Je),"aria-label":`Remove ${Je.email}`,children:e.jsx(er,{className:"h-3 w-3"})})]},Je.email))}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto rounded-lg border p-1",children:h?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"Searching…"}):d.length===0?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"No members found."}):d.map(Je=>{const ut=i.some(lt=>lt.email.toLowerCase()===Je.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Se(Je),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${ut?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:Je.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:Je.email})]}),ut&&e.jsx(Mr,{className:"h-4 w-4 shrink-0 text-primary"})]},Je.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Account status"}),e.jsxs(ls,{value:y.status,onValueChange:Je=>Ve("status",Je),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All members"}),e.jsx(He,{value:"active",children:"Active (signed in)"}),e.jsx(He,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Membership"}),e.jsxs(ls,{value:y.billing,onValueChange:Je=>Ve("billing",Je),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any membership"}),e.jsx(He,{value:"trial",children:"On trial"}),e.jsx(He,{value:"paid",children:"Paid subscribers"}),e.jsx(He,{value:"grandfathered",children:"Grandfathered"}),e.jsx(He,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Role"}),e.jsxs(ls,{value:y.role,onValueChange:Je=>Ve("role",Je),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any role"}),e.jsx(He,{value:"user",children:"Members"}),e.jsx(He,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(He,{value:"coach",children:"Coaches"}),e.jsx(He,{value:"assistant",children:"Assistants"}),e.jsx(He,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsxs(ls,{value:y.brokerage,onValueChange:Je=>Ve("brokerage",Je),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{className:"max-h-72",children:[e.jsx(He,{value:"all",children:"All brokerages"}),e.jsx(He,{value:"none",children:"No brokerage"}),(Ee||[]).map(Je=>e.jsx(He,{value:Je.id,children:Je.name},Je.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Program enrollment"}),e.jsxs(ls,{value:y.program,onValueChange:Je=>Ve("program",Je),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{className:"max-h-72",children:[e.jsx(He,{value:"all",children:"Not filtered by program"}),e.jsx(He,{value:"any",children:"Enrolled in any program"}),(Ne||[]).map(Je=>e.jsx(He,{value:Je.id,children:Je.name},Je.id))]})]})]}),y.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Enrollment status"}),e.jsxs(ls,{value:y.programStatus,onValueChange:Je=>Ve("programStatus",Je),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"active",children:"Active enrollees (paid, reserved, completed)"}),e.jsx(He,{value:"any",children:"Any enrollment status"}),e.jsx(He,{value:"paid",children:"Paid"}),e.jsx(He,{value:"reserved",children:"Reserved"}),e.jsx(He,{value:"scheduled_for_charge",children:"Scheduled for charge"}),e.jsx(He,{value:"pending_payment_method",children:"Pending payment method"}),e.jsx(He,{value:"payment_failed",children:"Payment failed"}),e.jsx(He,{value:"completed",children:"Completed"}),e.jsx(He,{value:"canceled",children:"Canceled"}),e.jsx(He,{value:"refunded",children:"Refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Joined within"}),e.jsxs(ls,{value:y.joinedWithinDays?String(y.joinedWithinDays):"all",onValueChange:Je=>Ve("joinedWithinDays",Je==="all"?null:Number(Je)),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any time"}),e.jsx(He,{value:"30",children:"Last 30 days"}),e.jsx(He,{value:"60",children:"Last 60 days"}),e.jsx(He,{value:"90",children:"Last 90 days"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Respect opt-outs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip members who opted out of updates"})]}),e.jsx(mn,{checked:y.respectOptOut,onCheckedChange:Je=>Ve("respectOptOut",Je)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>b(ize),children:"Reset"}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ke(y),disabled:C,children:[C?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Gi,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(Ge=w==null?void 0:w.sample)!=null&&Ge.length?e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Sample recipients"}),e.jsx("div",{className:"space-y-1",children:w.sample.map(Je=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:Je.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:Je.email})]},Je.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-4",children:[e.jsx(Nt,{className:"text-base",children:"Message"}),e.jsxs(En,{children:["Personalize with merge tags: ",FMn.join(" ")]})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Internal name"}),e.jsx(pe,{value:P,onChange:Je=>M(Je.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Subject line"}),e.jsx(pe,{value:I,onChange:Je=>D(Je.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"From (must be a verified sender)"}),e.jsx(pe,{value:F,onChange:Je=>q(Je.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Reply-to"}),e.jsx(pe,{value:G,onChange:Je=>V(Je.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(Qr,{value:H,onValueChange:Je=>K(Je),children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"rich",className:"gap-2",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Wt,{value:"html",className:"gap-2",children:[e.jsx(GA,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Kt,{value:"rich",className:"mt-3",children:e.jsx(GN,{content:Z,onChange:oe,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Kt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Ps,{value:re,onChange:Je=>ae(Je.target.value),placeholder:"…paste your full email HTML here…",className:"min-h-[320px] font-mono text-xs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste full HTML from Canva, Beefree, Mailchimp, etc. It is sent exactly as written (merge tags still work)."})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(xa,{className:"h-4 w-4"})," Preview"]}),e.jsx(ze,{variant:"secondary",children:H==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Le,{children:e.jsx("iframe",{title:"Email preview",srcDoc:OMn(ge),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(be,{children:e.jsxs(Le,{className:"space-y-4 pt-6",children:[me&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[me.sent+me.failed," of ",me.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[me.sent," sent",me.failed?` • ${me.failed} failed`:""]})]}),e.jsx(Di,{value:me.total?(me.sent+me.failed)/me.total*100:0})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Send a test to"}),e.jsx(pe,{value:J,onChange:Je=>te(Je.target.value),className:"w-64"})]}),e.jsx(z,{variant:"outline",onClick:$e,disabled:ce,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs(z,{onClick:Xe,disabled:!Ze||ce,size:"lg",className:"gap-2",children:[ce?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),ce?"Sending…":`Send to ${_e} member${_e===1?"":"s"}`]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 border-t pt-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Save as template"}),e.jsx(pe,{value:p,onChange:Je=>f(Je.target.value),placeholder:P||I||"Template name",className:"w-64"})]}),e.jsxs(z,{variant:"outline",className:"gap-2",onClick:We,disabled:g,children:[g?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(tP,{className:"h-4 w-4"}),"Save template"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saves the subject, content, sender and current filters for reuse later."})]})]})})]})]})}),e.jsx(Kt,{value:"templates",className:"space-y-3",children:(Oe||[]).length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(yj,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No saved templates yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Compose an email, then use "Save template" to reuse it for future sends.'})]})}):(Oe||[]).map(Je=>e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:Je.name}),e.jsx(ze,{variant:"secondary",className:"text-xs",children:Je.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Je.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Ys(new Date(Je.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{size:"sm",className:"gap-2",onClick:()=>qe(Je),children:[e.jsx(Bo,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>Be(Je),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})},Je.id))}),e.jsx(Kt,{value:"history",className:"space-y-3",children:(Pe||[]).length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(on,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No broadcasts sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your sent member emails will show up here."})]})}):(Pe||[]).map(Je=>e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:Je.name}),e.jsxs(ze,{variant:Je.status==="sent"?"default":Je.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[Je.status==="sent"?e.jsx(Mr,{className:"h-3 w-3"}):e.jsx(Ho,{className:"h-3 w-3"}),Je.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Je.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ys(new Date(Je.created_at),"MMM d, yyyy h:mm a")," • from ",Je.from_email]})]}),e.jsxs("div",{className:"flex gap-6 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:Je.total_recipients}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:Je.sent_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:Je.failed_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[Je.open_count??0,Je.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((Je.open_count??0)/Je.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Opens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[Je.click_count??0,Je.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((Je.click_count??0)/Je.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),Je.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx(z,{size:"sm",variant:"outline",disabled:ce,onClick:()=>nt(Je.id),children:"Retry failed"})})]})]})},Je.id))})]})]})})}const BMn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function $Mn(){const s=$t(),t=_.useRef(null),[n,r]=_.useState(""),[a,i]=_.useState("all"),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:f=[],isLoading:g}=rt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:F,error:q}=await U.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(q)throw q;return F||[]}}),v=_.useMemo(()=>{const F=new Set(BMn);return f.forEach(q=>F.add(q.category)),Array.from(F).sort()},[f]),y=_.useMemo(()=>{const F=n.trim().toLowerCase();return f.filter(q=>a!=="all"&&q.category!==a?!1:F?q.title.toLowerCase().includes(F)||(q.description||"").toLowerCase().includes(F)||q.tags.some(G=>G.toLowerCase().includes(F)):!0)},[f,n,a]),b=()=>{p({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},w=()=>{b(),d(!0)},S=F=>{o(F),p({title:F.title,description:F.description||"",image_url:F.image_url,category:F.category,tags:F.tags.join(", "),is_active:F.is_active,is_featured:F.is_featured}),d(!0)},C=async F=>{var q;if(!F.type.startsWith("image/")){ne.error("Please choose an image file");return}if(F.size>15*1024*1024){ne.error("Image must be under 15MB");return}h(!0);try{const G=((q=F.name.split(".").pop())==null?void 0:q.toLowerCase())||"png",V=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${G}`,{error:H}=await U.storage.from("newsletter-content").upload(V,F,{cacheControl:"31536000",upsert:!1,contentType:F.type});if(H)throw H;const{data:K}=U.storage.from("newsletter-content").getPublicUrl(V);p(Z=>({...Z,image_url:K.publicUrl,title:Z.title||F.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ne.success("Uploaded")}catch(G){ne.error(G.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},E=mt({mutationFn:async()=>{var G;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const F=m.tags.split(",").map(V=>V.trim()).filter(Boolean),q={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:F,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:V}=await U.from("newsletter_graphics").update(q).eq("id",l.id);if(V)throw V}else{const{data:V}=await U.auth.getUser(),{error:H}=await U.from("newsletter_graphics").insert({...q,created_by:(G=V.user)==null?void 0:G.id});if(H)throw H}},onSuccess:()=>{ne.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:F=>ne.error(F.message||"Save failed")}),P=mt({mutationFn:async F=>{const{error:q}=await U.from("newsletter_graphics").delete().eq("id",F);if(q)throw q},onSuccess:()=>{ne.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:F=>ne.error(F.message||"Delete failed")}),M=async F=>{const{error:q}=await U.from("newsletter_graphics").update({is_active:!F.is_active}).eq("id",F.id);q?ne.error(q.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},I=async F=>{const{error:q}=await U.from("newsletter_graphics").update({is_featured:!F.is_featured}).eq("id",F.id);q?ne.error(q.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},D=F=>{navigator.clipboard.writeText(F),ne.success("URL copied")};return e.jsxs($s,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Xh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(be,{children:e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:F=>r(F.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(ls,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-full md:w-56",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All categories"}),v.map(F=>e.jsx(He,{value:F,children:F},F))]})]}),e.jsxs(z,{onClick:w,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(N0,{className:"h-4 w-4"})," Add Graphic"]})]})}),g?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-16 text-center",children:[e.jsx(nc,{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:f.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),f.length===0&&e.jsxs(z,{onClick:w,className:"gap-1.5",children:[e.jsx(N0,{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:y.map(F=>e.jsxs(be,{className:`overflow-hidden group ${F.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:F.image_url,alt:F.title,loading:"lazy",className:"w-full h-full object-cover"}),F.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(Ia,{className:"h-3 w-3 fill-current"})," Featured"]}),!F.is_active&&e.jsx(ze,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Le,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:F.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:F.category})]}),F.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:F.tags.slice(0,3).map(q=>e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:q},q))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>S(F),title:"Edit",children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(F),title:F.is_featured?"Unfeature":"Feature",children:e.jsx(Ia,{className:`h-3.5 w-3.5 ${F.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(F.image_url),title:"Copy URL",children:e.jsx(Sa,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:F.is_active,onCheckedChange:()=>M(F)}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await Qi(`Delete "${F.title}"?`)&&P.mutate(F.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})]})]},F.id))})]}),e.jsx(Is,{open:c,onOpenChange:d,children:e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:F=>{var G;const q=(G=F.target.files)==null?void 0:G[0];q&&C(q)}}),m.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:m.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx(z,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>p(F=>({...F,image_url:""})),children:e.jsx(er,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var F;return(F=t.current)==null?void 0:F.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(bt,{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(Ra,{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(ee,{htmlFor:"g-title",children:"Title *"}),e.jsx(pe,{id:"g-title",value:m.title,onChange:F=>p(q=>({...q,title:F.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ps,{id:"g-desc",value:m.description,onChange:F=>p(q=>({...q,description:F.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(ee,{children:"Category"}),e.jsxs(ls,{value:m.category,onValueChange:F=>p(q=>({...q,category:F})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:v.map(F=>e.jsx(He,{value:F,children:F},F))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(pe,{id:"g-tags",value:m.tags,onChange:F=>p(q=>({...q,tags:F.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(mn,{checked:m.is_featured,onCheckedChange:F=>p(q=>({...q,is_featured:F}))})]}),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(mn,{checked:m.is_active,onCheckedChange:F=>p(q=>({...q,is_active:F}))})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending&&e.jsx(bt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const Djt={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 UMn(){const{user:s}=hs(),{toast:t}=_i(),n=zn(),r=$t(),[a,i]=_.useState(""),[l,o]=_.useState("popular"),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(!1),{data:v=[],isLoading:y}=rt({queryKey:["wishlist-items",l,f],queryFn:async()=>{let E=U.from("wishlist_items").select("*");f&&s&&(E=E.eq("user_id",s.id)),l==="latest"?E=E.order("created_at",{ascending:!1}):l==="popular"?E=E.order("vote_count",{ascending:!1}):l==="trending"&&(E=E.order("vote_count",{ascending:!1}));const{data:P,error:M}=await E;if(M)throw M;const I=[...new Set((P==null?void 0:P.map(K=>K.user_id))||[])],{data:D}=await U.from("profiles").select("id, name").in("id",I),F=new Map((D==null?void 0:D.map(K=>[K.id,K]))||[]);let q=[];if(s){const{data:K}=await U.from("wishlist_votes").select("item_id").eq("user_id",s.id);q=(K==null?void 0:K.map(Z=>Z.item_id))||[]}const G=(P==null?void 0:P.map(K=>K.id))||[],{data:V}=await U.from("wishlist_comments").select("item_id").in("item_id",G),H=new Map;return V==null||V.forEach(K=>{H.set(K.item_id,(H.get(K.item_id)||0)+1)}),P==null?void 0:P.map(K=>{const Z=F.get(K.user_id),oe=(Z==null?void 0:Z.name)||"Unknown";return{...K,user_name:oe,user_initials:oe.split(" ").map(re=>re[0]).join("").toUpperCase().slice(0,2),has_voted:q.includes(K.id),comment_count:H.get(K.id)||0}})}}),b=mt({mutationFn:async({title:E,description:P})=>{const{error:M}=await U.from("wishlist_items").insert({user_id:s.id,title:E,description:P});if(M)throw M},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),p(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),w=mt({mutationFn:async({itemId:E,hasVoted:P})=>{if(P){const{error:M}=await U.from("wishlist_votes").delete().eq("item_id",E).eq("user_id",s.id);if(M)throw M;return{itemId:E,wasAdded:!1}}else{const{error:M}=await U.from("wishlist_votes").insert({item_id:E,user_id:s.id});if(M)throw M;return{itemId:E,wasAdded:!0}}},onSuccess:async E=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),E!=null&&E.wasAdded){const P=v.find(I=>I.id===E.itemId),M=((P==null?void 0:P.vote_count)||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:E.itemId,voteCount:M}}).catch(console.error)}},onError:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),S=v.filter(E=>E.title.toLowerCase().includes(a.toLowerCase())||E.description.toLowerCase().includes(a.toLowerCase())),C=()=>{if(!u.trim()||!m.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}b.mutate({title:u.trim(),description:m.trim()})};return e.jsx($s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(yS,{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(Is,{open:c,onOpenChange:d,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:E=>h(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:E=>p(E.target.value),rows:4})]}),e.jsx(z,{onClick:C,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(bt,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search ideas...",value:a,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Qr,{value:l,onValueChange:E=>o(E),children:e.jsxs(Jr,{children:[e.jsx(Wt,{value:"popular",children:"Most Popular"}),e.jsx(Wt,{value:"latest",children:"Latest"}),e.jsx(Wt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(z,{variant:f?"default":"outline",size:"sm",onClick:()=>g(!f),children:f?"Show All Ideas":"My Ideas"})}),y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):S.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(yS,{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(z,{onClick:()=>d(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:S.map(E=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${E.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:P=>{P.stopPropagation(),w.mutate({itemId:E.id,hasVoted:E.has_voted||!1})},className:Ct("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",E.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(ap,{className:Ct("h-4 w-4",E.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:E.vote_count})]}),e.jsx(ja,{className:"h-10 w-10 bg-primary/20",children:e.jsx(Na,{className:"bg-primary/20 text-primary text-sm font-medium",children:E.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:E.title}),e.jsx(ze,{className:Ct("text-xs",Djt[E.status].color),children:Djt[E.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:E.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:E.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(E.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(qi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:E.comment_count})]})]})},E.id))})]})})}const Rjt={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 qMn(){const{itemId:s}=Mi(),t=zn(),{user:n}=hs(),{toast:r}=_i(),a=$t(),[i,l]=_.useState(""),{data:o=!1}=rt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:v,error:y}=await U.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!y&&!!v},enabled:!!n}),{data:c,isLoading:d}=rt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:v,error:y}=await U.from("wishlist_items").select("*").eq("id",s).single();if(y)throw y;const{data:b}=await U.from("profiles").select("name").eq("id",v.user_id).single();let w=!1;if(n){const{data:S}=await U.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();w=!!S}return{...v,user_name:(b==null?void 0:b.name)||"Unknown",user_initials:((b==null?void 0:b.name)||"U").split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),has_voted:w}}}),{data:u=[],isLoading:h}=rt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:v,error:y}=await U.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(y)throw y;const b=[...new Set((v==null?void 0:v.map(C=>C.user_id))||[])],{data:w}=await U.from("profiles").select("id, name").in("id",b),S=new Map((w==null?void 0:w.map(C=>[C.id,C]))||[]);return v==null?void 0:v.map(C=>{const E=S.get(C.user_id),P=(E==null?void 0:E.name)||"Unknown";return{...C,user_name:P,user_initials:P.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),m=mt({mutationFn:async v=>{if(v){const{error:y}=await U.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(y)throw y;return{wasAdded:!1}}else{const{error:y}=await U.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(y)throw y;return{wasAdded:!0}}},onSuccess:async v=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),v!=null&&v.wasAdded&&c){const y=(c.vote_count||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:y}}).catch(console.error)}},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),p=mt({mutationFn:async v=>{const{error:y}=await U.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:v});if(y)throw y},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),f=mt({mutationFn:async v=>{const{error:y}=await U.from("wishlist_comments").delete().eq("id",v);if(y)throw y},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),g=()=>{i.trim()&&p.mutate(i.trim())};return d?e.jsx($s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(ln,{className:"h-8 w-32 mb-6"}),e.jsx(ln,{className:"h-48 w-full mb-6"}),e.jsx(ln,{className:"h-32 w-full"})]})}):c?e.jsx($s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),e.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:()=>m.mutate(c.has_voted),className:Ct("flex flex-col items-center justify-center min-w-[60px] py-3 px-4 rounded-lg border transition-colors",c.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(ap,{className:Ct("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:Ct("text-xs",Rjt[c.status].color),children:Rjt[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(ja,{className:"h-6 w-6",children:e.jsx(Na,{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(qEe,{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(z,{onClick:g,disabled:!i.trim()||p.isPending,size:"icon",className:"h-auto",children:p.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(v=>e.jsx(ln,{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(ja,{className:"h-8 w-8",children:e.jsx(Na,{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(gst,{content:v.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===v.user_id&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>f.mutate(v.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]},v.id))})]})]})}):e.jsx($s,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(z,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const Fjt={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"}},Ojt=["open","under_review","planned","in_progress","launched","declined"];function VMn(){const{toast:s}=_i(),t=zn(),n=$t(),[r,a]=_.useState(""),[i,l]=_.useState("all"),[o,c]=_.useState(!1),[d,u]=_.useState(null),{data:h=[],isLoading:m}=rt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:y,error:b}=await U.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const w=[...new Set((y==null?void 0:y.map(I=>I.user_id))||[])],{data:S}=await U.from("profiles").select("id, name, email").in("id",w),C=new Map((S==null?void 0:S.map(I=>[I.id,I]))||[]),E=(y==null?void 0:y.map(I=>I.id))||[],{data:P}=await U.from("wishlist_comments").select("item_id").in("item_id",E),M=new Map;return P==null||P.forEach(I=>{M.set(I.item_id,(M.get(I.item_id)||0)+1)}),y==null?void 0:y.map(I=>{const D=C.get(I.user_id);return{...I,user_name:(D==null?void 0:D.name)||"Unknown",user_email:(D==null?void 0:D.email)||"",comment_count:M.get(I.id)||0}})}}),p=mt({mutationFn:async({itemId:y,status:b})=>{const{error:w}=await U.from("wishlist_items").update({status:b}).eq("id",y);if(w)throw w},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:y=>{s({title:"Error",description:y.message,variant:"destructive"})}}),f=mt({mutationFn:async y=>{const{error:b}=await U.from("wishlist_items").delete().eq("id",y);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:y=>{s({title:"Error",description:y.message,variant:"destructive"})}}),g=h.filter(y=>{const b=y.title.toLowerCase().includes(r.toLowerCase())||y.description.toLowerCase().includes(r.toLowerCase())||y.user_name.toLowerCase().includes(r.toLowerCase()),w=i==="all"||y.status===i;return b&&w}),v={total:h.length,open:h.filter(y=>y.status==="open").length,inProgress:h.filter(y=>y.status==="in_progress").length,launched:h.filter(y=>y.status==="launched").length,highVotes:h.filter(y=>y.vote_count>=10).length};return e.jsx($s,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(ka,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search ideas, users...",value:r,onChange:y=>a(y.target.value),className:"pl-10"})]}),e.jsxs(ls,{value:i,onValueChange:y=>l(y),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),Ojt.map(y=>e.jsx(He,{value:y,children:Fjt[y].label},y))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(y=>e.jsx(ln,{className:"h-16 w-full"},y))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[60px]",children:"Votes"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Tt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(Qa,{children:g.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):g.map(y=>e.jsxs(fn,{className:Ct(y.vote_count>=10&&"bg-primary/5"),children:[e.jsx(yt,{children:e.jsx(ze,{variant:y.vote_count>=10?"default":"secondary",children:y.vote_count})}),e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:y.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:y.description})]})}),e.jsx(yt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:y.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y.user_email})]})}),e.jsx(yt,{className:"hidden sm:table-cell",children:y.comment_count}),e.jsx(yt,{children:e.jsxs(ls,{value:y.status,onValueChange:b=>p.mutate({itemId:y.id,status:b}),children:[e.jsx(rs,{className:"w-[140px] h-8",children:e.jsx(cs,{})}),e.jsx(as,{children:Ojt.map(b=>e.jsx(He,{value:b,children:Fjt[b].label},b))})]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${y.id}`,"_blank"),children:e.jsx(mr,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(y.id),c(!0)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})})]},y.id))})]})}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{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(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(z,{variant:"destructive",onClick:()=>d&&f.mutate(d),disabled:f.isPending,children:f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function HMn(){const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(!1),[I,D]=_.useState(""),[F,q]=_.useState("once"),[G,V]=_.useState([]),[H,K]=_.useState([]),[Z,oe]=_.useState(!1),[re,ae]=_.useState(!1),[J,te]=_.useState([]),[ce,ve]=_.useState({total:0,dismissed:0});_.useEffect(()=>{me()},[]);const me=async()=>{const{data:nt,error:Ge}=await U.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ge?(ne.error("Failed to fetch briefs"),console.error(Ge)):n(nt||[]),a(!1)},he=()=>{f(""),v(""),b(""),S(""),E(""),M(!1),D(new Date().toISOString().slice(0,16)),q("once"),V([]),K([]),c(null)},ge=()=>{he(),l(!0)},Ee=async nt=>{c(nt),f(nt.title),v(nt.description||""),b(nt.video_url||""),S(nt.graphic_url||""),E(nt.graphic_link_url||""),M(nt.is_published),D(nt.publish_date.slice(0,16)),q(nt.show_frequency);const{data:Ge}=await U.from("levelup_brief_links").select("*").eq("brief_id",nt.id).order("sort_order");V((Ge==null?void 0:Ge.map(ut=>({title:ut.title,url:ut.url})))||[]);const{data:Je}=await U.from("levelup_brief_polls").select("*").eq("brief_id",nt.id).order("sort_order");if(Je){const ut=[];for(const lt of Je){const{data:qt}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",lt.id).order("sort_order");ut.push({question:lt.question,poll_type:lt.poll_type,options:(qt==null?void 0:qt.map(zt=>zt.option_text))||[]})}K(ut)}l(!0)},Ne=async nt=>{var Je;const Ge=(Je=nt.target.files)==null?void 0:Je[0];if(Ge){oe(!0);try{const ut=await U.functions.invoke("bunny-upload",{body:{action:"create",title:Ge.name.replace(/\.[^/.]+$/,"")}});if(ut.error)throw ut.error;const{videoId:lt,libraryId:qt}=ut.data,zt=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:lt}});if(zt.error)throw zt.error;const{uploadUrl:Zt,apiKey:ms}=zt.data,Dt=new XMLHttpRequest;await new Promise((qs,wt)=>{Dt.upload.addEventListener("progress",Us=>{if(Us.lengthComputable){const Es=Math.round(Us.loaded/Us.total*100);console.log("Upload progress:",Es)}}),Dt.addEventListener("load",()=>{Dt.status>=200&&Dt.status<300?qs():wt(new Error(`Upload failed with status ${Dt.status}`))}),Dt.addEventListener("error",()=>wt(new Error("Upload failed"))),Dt.open("PUT",Zt),Dt.setRequestHeader("AccessKey",ms),Dt.send(Ge)});const It=`https://player.mediadelivery.net/embed/${qt}/${lt}`;b(It),ne.success("Video uploaded successfully! It may take a few minutes to process.")}catch(ut){console.error("Upload error:",ut),ne.error("Failed to upload video")}finally{oe(!1)}}},Pe=async()=>{if(!p.trim()){ne.error("Title is required");return}try{let nt;if(o){const{error:Ge}=await U.from("levelup_briefs").update({title:p,description:g||null,video_url:y||null,graphic_url:w||null,graphic_link_url:C||null,is_published:P,publish_date:I,show_frequency:F}).eq("id",o.id);if(Ge)throw Ge;nt=o.id,await U.from("levelup_brief_links").delete().eq("brief_id",nt);const{data:Je}=await U.from("levelup_brief_polls").select("id").eq("brief_id",nt);if(Je)for(const ut of Je)await U.from("levelup_brief_poll_options").delete().eq("poll_id",ut.id);await U.from("levelup_brief_polls").delete().eq("brief_id",nt)}else{const{data:Ge,error:Je}=await U.from("levelup_briefs").insert({title:p,description:g||null,video_url:y||null,graphic_url:w||null,graphic_link_url:C||null,is_published:P,publish_date:I,show_frequency:F,created_by:s==null?void 0:s.id}).select().single();if(Je)throw Je;nt=Ge.id}if(G.length>0){const Ge=G.map((Je,ut)=>({brief_id:nt,title:Je.title,url:Je.url,sort_order:ut}));await U.from("levelup_brief_links").insert(Ge)}for(let Ge=0;Ge0){const qt=Je.options.map((zt,Zt)=>({poll_id:ut.id,option_text:zt,sort_order:Zt}));await U.from("levelup_brief_poll_options").insert(qt)}}ne.success(o?"Brief updated":"Brief created"),l(!1),he(),me()}catch(nt){console.error("Error saving brief:",nt),ne.error("Failed to save brief")}},Oe=async nt=>{if(await Qi("Are you sure you want to delete this brief?"))try{const{error:Ge}=await U.from("levelup_briefs").delete().eq("id",nt);if(Ge)throw Ge;ne.success("Brief deleted"),me()}catch(Ge){console.error("Error deleting brief:",Ge),ne.error("Failed to delete brief")}},ke=async nt=>{m(nt);const{count:Ge}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",nt.id),{count:Je}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",nt.id).not("dismissed_at","is",null);ve({total:Ge||0,dismissed:Je||0});const{data:ut}=await U.from("levelup_brief_polls").select("*").eq("brief_id",nt.id).order("sort_order");if(ut){const lt=[];for(const qt of ut){const{data:zt}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",qt.id).order("sort_order"),{data:Zt}=await U.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",qt.id),ms=[...new Set((Zt==null?void 0:Zt.map(Us=>Us.user_id))||[])];let Dt={};if(ms.length>0){const{data:Us}=await U.from("profiles").select("id, name, email").in("id",ms);Us&&Us.forEach(Es=>{Dt[Es.id]=Es.name||Es.email||"Unknown"})}const It=(Zt||[]).map(Us=>({optionId:Us.option_id,userName:Dt[Us.user_id]||"Unknown",userId:Us.user_id})),qs={};let wt=0;zt&&zt.forEach(Us=>{const Es=(Zt==null?void 0:Zt.filter(kn=>kn.option_id===Us.id).length)||0;qs[Us.id]=Es,wt+=Es}),lt.push({...qt,options:zt||[],results:qs,respondents:It,totalResponses:qt.poll_type==="single"?new Set(Zt==null?void 0:Zt.map(Us=>Us.user_id)).size:wt})}te(lt)}u(!0)},Ve=()=>{V([...G,{title:"",url:""}])},_e=(nt,Ge,Je)=>{const ut=[...G];ut[nt][Ge]=Je,V(ut)},Ae=nt=>{V(G.filter((Ge,Je)=>Je!==nt))},Se=()=>{K([...H,{question:"",poll_type:"single",options:["",""]}])},We=(nt,Ge)=>{const Je=[...H];Je[nt].question=Ge,K(Je)},qe=(nt,Ge)=>{const Je=[...H];Je[nt].poll_type=Ge,K(Je)},Be=nt=>{const Ge=[...H];Ge[nt].options.push(""),K(Ge)},Ze=(nt,Ge,Je)=>{const ut=[...H];ut[nt].options[Ge]=Je,K(ut)},$e=(nt,Ge)=>{const Je=[...H];Je[nt].options=Je[nt].options.filter((ut,lt)=>lt!==Ge),K(Je)},Xe=nt=>{K(H.filter((Ge,Je)=>Je!==nt))};return e.jsxs($s,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(z,{onClick:ge,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Frequency"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:r?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(nt=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:nt.title}),e.jsx(yt,{children:e.jsx(ze,{variant:nt.is_published?"default":"secondary",children:nt.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"capitalize",children:nt.show_frequency.replace("_"," ")}),e.jsx(yt,{children:Ys(new Date(nt.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>ke(nt),children:e.jsx(wl,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>Ee(nt),children:e.jsx(Cp,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>Oe(nt.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},nt.id))})]})})})]}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(Qr,{defaultValue:"content",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-4",children:[e.jsx(Wt,{value:"content",children:"Content"}),e.jsx(Wt,{value:"media",children:"Media"}),e.jsx(Wt,{value:"links",children:"Links"}),e.jsx(Wt,{value:"polls",children:"Polls"})]}),e.jsxs(Kt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:p,onChange:nt=>f(nt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:g,onChange:nt=>v(nt),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Publish Date"}),e.jsx(pe,{type:"datetime-local",value:I,onChange:nt=>D(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Show Frequency"}),e.jsxs(ls,{value:F,onValueChange:q,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"once",children:"Once (until dismissed)"}),e.jsx(He,{value:"every_login",children:"Every login"}),e.jsx(He,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(mn,{checked:P,onCheckedChange:M}),e.jsx(ee,{children:"Publish immediately"})]})]}),e.jsxs(Kt,{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(ee,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(pe,{type:"file",accept:"video/*",onChange:Ne,disabled:Z})}),Z&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Or paste embed URL"}),e.jsx(pe,{value:y,onChange:nt=>b(nt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),y&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:y,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(ee,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(pe,{type:"file",accept:"image/*",onChange:async nt=>{var Je;const Ge=(Je=nt.target.files)==null?void 0:Je[0];if(Ge){ae(!0);try{const ut=Ge.name.split(".").pop(),lt=`brief-graphics/${Date.now()}.${ut}`,{error:qt}=await U.storage.from("banner-images").upload(lt,Ge,{upsert:!0});if(qt)throw qt;const{data:zt}=U.storage.from("banner-images").getPublicUrl(lt);S(zt.publicUrl),ne.success("Image uploaded!")}catch(ut){console.error(ut),ne.error("Failed to upload image")}finally{ae(!1)}}},disabled:re})}),re&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Or paste Image URL"}),e.jsx(pe,{value:w,onChange:nt=>S(nt.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Click-through Link (optional)"}),e.jsx(pe,{value:C,onChange:nt=>E(nt.target.value),placeholder:"https://example.com/landing-page"})]}),w&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:w,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(Kt,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Quick Links"}),e.jsxs(z,{variant:"outline",size:"sm",onClick:Ve,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),G.map((nt,Ge)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(pe,{value:nt.title,onChange:Je=>_e(Ge,"title",Je.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(pe,{value:nt.url,onChange:Je=>_e(Ge,"url",Je.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>Ae(Ge),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]},Ge)),G.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(Kt,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Polls"}),e.jsxs(z,{variant:"outline",size:"sm",onClick:Se,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),H.map((nt,Ge)=>e.jsx(be,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(pe,{value:nt.question,onChange:Je=>We(Ge,Je.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(ls,{value:nt.poll_type,onValueChange:Je=>qe(Ge,Je),children:[e.jsx(rs,{className:"w-32",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"single",children:"Single"}),e.jsx(He,{value:"multi",children:"Multi-select"})]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>Xe(Ge),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[nt.options.map((Je,ut)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:Je,onChange:lt=>Ze(Ge,ut,lt.target.value),placeholder:`Option ${ut+1}`}),nt.options.length>2&&e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>$e(Ge,ut),children:e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"})})]},ut)),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>Be(Ge),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ge)),H.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(z,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(z,{onClick:Pe,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(Is,{open:d,onOpenChange:u,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Rs,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Le,{children:e.jsx("p",{className:"text-2xl font-bold",children:ce.total})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Le,{children:e.jsx("p",{className:"text-2xl font-bold",children:ce.dismissed})})]})]}),J.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),J.map(nt=>e.jsxs(be,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:nt.question}),e.jsx("div",{className:"space-y-2",children:nt.options.map(Ge=>{const Je=nt.results[Ge.id]||0,ut=nt.totalResponses>0?Math.round(Je/nt.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:Ge.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[Je," (",ut,"%)"]})]}),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:`${ut}%`}})}),Je>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(nt.respondents||[]).filter(lt=>lt.optionId===Ge.id).map((lt,qt)=>e.jsx(ze,{variant:"secondary",className:"text-xs font-normal",children:lt.userName},qt))})]},Ge.id)})})]},nt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const GMn=()=>{const{user:s}=hs(),{toast:t}=_i(),n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=_.useState(null),[h,m]=_.useState(""),{data:p=[],isLoading:f}=rt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:C,error:E}=await U.from("additional_services").select("*").order("publish_date",{ascending:!1});if(E)throw E;return C}}),g=mt({mutationFn:async C=>{let E=C.existingImageUrl;if(C.image){const M=C.image.name.split(".").pop(),I=`${Date.now()}-${Math.random().toString(36).substring(7)}.${M}`,{error:D}=await U.storage.from("service-images").upload(I,C.image);if(D)throw D;const{data:F}=U.storage.from("service-images").getPublicUrl(I);E=F.publicUrl}const P={name:C.item.name,description:C.item.description||null,preview_image_url:E,signup_link_url:C.item.signup_link_url,publish_date:C.item.publish_date?new Date(C.item.publish_date).toISOString():new Date().toISOString(),is_published:C.item.is_published,created_by:s==null?void 0:s.id};if(C.itemId){const{error:M}=await U.from("additional_services").update(P).eq("id",C.itemId);if(M)throw M}else{const{error:M}=await U.from("additional_services").insert(P);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),y()},onError:C=>{t({title:"Error saving service",description:C.message,variant:"destructive"})}}),v=mt({mutationFn:async C=>{const{error:E}=await U.from("additional_services").delete().eq("id",C);if(E)throw E},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:C=>{t({title:"Error deleting service",description:C.message,variant:"destructive"})}}),y=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},b=C=>{l(C),c({name:C.name,description:C.description||"",signup_link_url:C.signup_link_url,publish_date:C.publish_date?new Date(C.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:C.is_published}),m(C.preview_image_url||""),a(!0)},w=C=>{var P;const E=(P=C.target.files)==null?void 0:P[0];E&&(u(E),m(URL.createObjectURL(E)))},S=C=>{if(C.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}g.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx($s,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(C=>C.is_published).length})})]})]}),e.jsxs(Is,{open:r,onOpenChange:C=>{a(C),C||y()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:o.name,onChange:C=>c({...o,name:C.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(GN,{content:o.description,onChange:C=>c({...o,description:C}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(pe,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:C=>c({...o,signup_link_url:C.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:C=>c({...o,publish_date:C.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(mn,{id:"is_published",checked:o.is_published,onCheckedChange:C=>c({...o,is_published:C})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(z,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(nc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(pe,{type:"file",accept:"image/*",onChange:w,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:g.isPending,children:g.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:f?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Signup Link"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:p.map(C=>e.jsxs(fn,{children:[e.jsx(yt,{children:C.preview_image_url?e.jsx("img",{src:C.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(nc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(yt,{className:"font-medium",children:C.name}),e.jsx(yt,{children:e.jsxs("a",{href:C.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(mr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(yt,{children:new Date(C.publish_date).toLocaleDateString()}),e.jsx(yt,{children:e.jsx(ze,{variant:C.is_published?"default":"secondary",children:C.is_published?"Published":"Draft"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>b(C),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:async()=>{await Qi("Are you sure you want to delete this service?")&&v.mutate(C.id)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},C.id))})]})})})]})})};function WMn(){const{toast:s}=_i(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});_.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:y}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(y)throw y;n(v.coupons||[])}catch(v){console.error("Error fetching coupons:",v),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},m=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const 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:y,error:b}=await U.functions.invoke("stripe-manage-coupons",{body:v});if(b)throw b;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)}},p=async v=>{if(await Qi("Are you sure you want to delete this coupon?"))try{const{error:y}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:v}});if(y)throw y;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(y){console.error("Error deleting coupon:",y),s({title:"Error",description:y.message||"Failed to delete coupon",variant:"destructive"})}},f=v=>v.percent_off?`${v.percent_off}% off`:v.amount_off?`$${(v.amount_off/100).toFixed(2)} off`:"N/A",g=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($s,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(Is,{open:o,onOpenChange:c,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create New Coupon"}),e.jsx(_r,{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(ee,{children:"Promotion Code (what users will type)"}),e.jsx(pe,{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(ee,{children:"Coupon Name (internal label)"}),e.jsx(pe,{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(ee,{children:"Discount Type"}),e.jsxs(ls,{value:d.discountType,onValueChange:v=>{const y=v==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:v,duration:y})},children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(z_,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(He,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Nd,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{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(ee,{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(pe,{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(ee,{children:"Duration"}),e.jsxs(ls,{value:d.duration,onValueChange:v=>u({...d,duration:v}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"once",children:"Once (first payment only)"}),e.jsx(He,{value:"repeating",children:"Multiple months"}),e.jsxs(He,{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(ee,{children:"Number of Months"}),e.jsx(pe,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:v=>u({...d,durationInMonths:v.target.value})})]}),e.jsx(z,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Active Coupons"}),e.jsx(En,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Le,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Promo Code"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Redemptions"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:t.map(v=>{var y;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-mono font-medium",children:((y=v.promotion_codes)==null?void 0:y.length)>0?v.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(yt,{children:v.name||"-"}),e.jsx(yt,{children:f(v)}),e.jsx(yt,{children:g(v)}),e.jsx(yt,{children:v.times_redeemed}),e.jsx(yt,{children:e.jsx(ze,{variant:v.valid?"default":"secondary",children:v.valid?"Active":"Inactive"})}),e.jsx(yt,{className:"text-right",children:e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>p(v.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})})]},v.id)})})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"How to Use Coupons"})}),e.jsxs(Le,{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 oze={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 KMn(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),[l,o]=_.useState(null),{data:c,isLoading:d,refetch:u}=rt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:y,error:b}=await U.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return y}}),{data:h}=rt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:y,error:b}=await U.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((y||[]).map(async S=>{const{data:C}=await U.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",S.id),{data:E}=await U.from("user_roles").select("user_id").eq("role","brokerage_manager"),P=(E==null?void 0:E.map(D=>D.user_id))||[],M=(C==null?void 0:C.filter(D=>P.includes(D.id)))||[],I=(C==null?void 0:C.length)||0;return{...S,managers:M,agentCount:I}}))}}),{data:m}=rt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:y,error:b}=await U.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return y}}),p=y=>{if(y.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(y.brokerage_id&&!y.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(y.is_trial&&y.trial_expires_at)return new Date(y.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(y.subscription_status==="active"||y.subscription_status==="trialing"){const b=oze[y.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:y.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return y.subscription_status==="canceled"||y.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},f=c==null?void 0:c.filter(y=>{var w,S;if(!(((w=y.name)==null?void 0:w.toLowerCase().includes(s.toLowerCase()))||((S=y.email)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const C=y.subscription_source||"platform";if(a==="platform"&&C==="local_move_website"||a==="local_move_website"&&C!=="local_move_website")return!1}switch(p(y),n){case"active":return y.subscription_status==="active";case"trialing":return y.subscription_status==="trialing"||y.is_trial&&new Date(y.trial_expires_at)>new Date;case"grandfathered":return y.is_grandfathered;case"brokerage":return y.brokerage_id&&!y.subscription_product_id&&!y.is_grandfathered;case"expired":return y.subscription_status==="canceled"||y.subscription_status==="past_due"||y.is_trial&&new Date(y.trial_expires_at)<=new Date;case"none":return!y.subscription_status||y.subscription_status==="none";default:return!0}}),g={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(y=>y.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(y=>y.subscription_status==="trialing"||y.is_trial&&new Date(y.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(y=>y.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(y=>y.brokerage_id&&!y.subscription_product_id&&!y.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(y=>y.subscription_status==="active"&&y.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(y=>y.subscription_status==="active"&&(y.subscription_product_id==="prod_Tc08MupgoVySDG"||y.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},v=y=>{window.open(`https://dashboard.stripe.com/customers/${y}`,"_blank")};return e.jsx($s,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(z,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(Gi,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{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:g.totalUsers})]})}),e.jsx(be,{className:"border-green-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j0,{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:g.activeSubscriptions})]})}),e.jsx(be,{className:"border-blue-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zr,{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:g.trials})]})}),e.jsx(be,{className:"border-purple-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kf,{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:g.grandfathered})]})}),e.jsx(be,{className:"border-orange-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oi,{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:g.brokerageMembers})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jj,{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:g.individualSubscribers})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oi,{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:g.brokerageSubscribers})]})})]}),e.jsxs(Qr,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"users",children:"All Users"}),e.jsx(Wt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Wt,{value:"websites",className:"gap-2",children:[e.jsx(Wo,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Kt,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:y=>t(y.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:a,onValueChange:y=>i(y),children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(cs,{placeholder:"Source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Sources"}),e.jsx(He,{value:"platform",children:"Platform"}),e.jsx(He,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(ls,{value:n,onValueChange:y=>r(y),children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(cs,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"active",children:"Active Subscriptions"}),e.jsx(He,{value:"trialing",children:"Trials"}),e.jsx(He,{value:"grandfathered",children:"Grandfathered"}),e.jsx(He,{value:"brokerage",children:"Brokerage Members"}),e.jsx(He,{value:"expired",children:"Expired/Canceled"}),e.jsx(He,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Plan"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"End Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:d?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(f==null?void 0:f.length)===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):f==null?void 0:f.map(y=>{var S,C;const b=p(y),w=oze[y.subscription_product_id];return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:y.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.email})]})}),e.jsx(yt,{children:e.jsx(ze,{variant:b.variant,children:b.badge})}),e.jsx(yt,{children:e.jsx("span",{className:"text-sm",children:y.is_grandfathered?"Legacy Access":y.brokerage_id&&!y.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||b.status})}),e.jsx(yt,{children:(S=y.brokerages)!=null&&S.name?e.jsx("span",{className:"text-sm",children:y.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(yt,{children:y.subscription_end_date?e.jsx("span",{className:"text-sm",children:Ys(new Date(y.subscription_end_date),"MMM d, yyyy")}):y.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Ys(new Date(y.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[y.stripe_customer_id&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>v(y.stripe_customer_id),children:e.jsx(mr,{className:"h-4 w-4"})}),e.jsxs(Is,{children:[e.jsx(rl,{asChild:!0,children:e.jsx(z,{variant:"outline",size:"sm",onClick:()=>o(y),children:"Details"})}),e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Subscription Details"}),e.jsxs(_r,{children:[y.name," (",y.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:b.variant,className:"mt-1",children:b.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:y.is_grandfathered?"Grandfathered (Legacy)":y.brokerage_id&&!y.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||"None"})]}),y.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((C=y.brokerages)==null?void 0:C.name)||"Unknown"})]}),y.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:Ys(new Date(y.subscription_end_date),"MMMM d, yyyy")})]}),y.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:Ys(new Date(y.trial_expires_at),"MMMM d, yyyy")})]}),y.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:y.stripe_customer_id})]})]}),y.stripe_customer_id&&e.jsxs(z,{className:"w-full",onClick:()=>v(y.stripe_customer_id),children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},y.id)})})]})})})]}),e.jsx(Kt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(y=>{var w,S;const b=(w=y.managers)==null?void 0:w.some(C=>C.subscription_status==="active"&&(C.subscription_product_id==="prod_Tc08MupgoVySDG"||C.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(be,{children:[e.jsx(_t,{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(oi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:y.name}),e.jsxs(En,{children:[y.agentCount," agents"]})]})]}),e.jsx(ze,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Le,{children:((S=y.managers)==null?void 0:S.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),y.managers.map(C=>{const E=oze[C.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:C.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.email})]}),e.jsx("div",{className:"text-right",children:E?e.jsxs("div",{children:[e.jsx(ze,{variant:"default",children:E.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:E.price})]}):e.jsx(ze,{variant:"outline",children:"No Subscription"})})]},C.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},y.id)})})}),e.jsx(Kt,{value:"websites",className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Wo,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(En,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Setup Fee"}),e.jsx(Tt,{children:"Monthly"}),e.jsx(Tt,{children:"Next Renewal"}),e.jsx(Tt,{children:"Started"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:m?m.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(y=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:y.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.agent_email})]})}),e.jsx(yt,{children:e.jsx(ze,{variant:y.status==="active"?"default":y.status==="canceled"?"destructive":"outline",children:y.status})}),e.jsx(yt,{children:y.setup_fee_paid?e.jsxs(ze,{variant:"secondary",children:["Paid · $",(y.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(ze,{variant:"outline",children:"Unpaid"})}),e.jsxs(yt,{className:"font-medium",children:["$",(y.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(yt,{children:y.current_period_end?e.jsx("span",{className:"text-sm",children:Ys(new Date(y.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(yt,{children:e.jsx("span",{className:"text-sm",children:Ys(new Date(y.created_at),"MMM d, yyyy")})}),e.jsx(yt,{className:"text-right",children:y.stripe_customer_id&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>v(y.stripe_customer_id),children:e.jsx(mr,{className:"h-4 w-4"})})})]},y.id)):e.jsx(fn,{children:e.jsx(yt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function YMn(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(""),[l,o]=_.useState("all"),[c,d]=_.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});_.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:f,error:g}=await U.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(g)throw g;t(f||[]);const v=(f==null?void 0:f.filter(w=>w.status==="qualified").length)||0,y=(f==null?void 0:f.filter(w=>w.status==="pending").length)||0,b=(f==null?void 0:f.filter(w=>w.status==="cancelled").length)||0;d({total:(f==null?void 0:f.length)||0,qualified:v,pending:y,cancelled:b,totalDiscounts:v*25})}catch(f){console.error("Error fetching referrals:",f),ne.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ne.loading("Processing qualifications...");const{error:f}=await U.functions.invoke("process-referral-qualifications");if(f)throw f;ne.dismiss(),ne.success("Qualifications processed successfully"),u()}catch(f){ne.dismiss(),console.error("Error processing qualifications:",f),ne.error("Failed to process qualifications")}},m=s.filter(f=>{var y,b,w,S,C,E;const g=((b=(y=f.referrer_brokerage)==null?void 0:y.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((S=(w=f.referred_brokerage)==null?void 0:w.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((E=(C=f.referred_user)==null?void 0:C.email)==null?void 0:E.toLowerCase().includes(a.toLowerCase())),v=l==="all"||f.status===l;return g&&v}),p=f=>{switch(f){case"qualified":return e.jsxs(ze,{className:"bg-green-100 text-green-800",children:[e.jsx(Xl,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(ze,{variant:"secondary",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(ze,{variant:"destructive",children:[e.jsx(Bd,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(ze,{children:f})}};return e.jsx($s,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(z,{onClick:h,variant:"outline",children:[e.jsx(Gi,{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(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{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(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xl,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),e.jsx(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zr,{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(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bd,{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(be,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nd,{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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"All Referrals"}),e.jsx(En,{children:"View and manage all referral relationships"})]}),e.jsxs(Le,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by brokerage or email...",value:a,onChange:f=>i(f.target.value),className:"pl-10"})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"Filter by status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"pending",children:"Pending"}),e.jsx(He,{value:"qualified",children:"Qualified"}),e.jsx(He,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Referrer"}),e.jsx(Tt,{children:"Referred"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Qualified Date"}),e.jsx(Tt,{children:"Discount"})]})}),e.jsx(Qa,{children:m.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(f=>{var g,v,y,b;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:((g=f.referrer_brokerage)==null?void 0:g.name)||"Unknown"}),e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((v=f.referred_brokerage)==null?void 0:v.name)||((y=f.referred_user)==null?void 0:y.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=f.referred_user)==null?void 0:b.email})]})}),e.jsx(yt,{children:Ys(new Date(f.signup_date),"MMM d, yyyy")}),e.jsx(yt,{children:p(f.status)}),e.jsx(yt,{children:f.qualified_date?Ys(new Date(f.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(yt,{children:f.discount_applied?e.jsx(ze,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},f.id)})})]})]})]})]})})}const lze=[{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"}],ZMn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function XMn(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(null),[c,d]=_.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});_.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:b,error:w}=await U.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(w)throw w;t(b||[])}catch(b){console.error("Error fetching checklist items:",b),ne.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=b=>{o(b),d({title:b.title,description:b.description||"",action_type:b.action_type,target_role:b.target_role,is_active:b.is_active}),i(!0)},p=async()=>{if(!c.title.trim()){ne.error("Title is required");return}try{if(l){const{error:b}=await U.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(b)throw b;ne.success("Checklist item updated")}else{const b=s.filter(S=>S.target_role===c.target_role).reduce((S,C)=>Math.max(S,C.sort_order),-1),{error:w}=await U.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:b+1});if(w)throw w;ne.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),ne.error("Failed to save checklist item")}},f=async b=>{if(await Qi("Are you sure you want to delete this checklist item?"))try{const{error:w}=await U.from("onboarding_checklist_items").delete().eq("id",b);if(w)throw w;ne.success("Checklist item deleted"),u()}catch(w){console.error("Error deleting checklist item:",w),ne.error("Failed to delete checklist item")}},g=async b=>{try{const{error:w}=await U.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(w)throw w;ne.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(w){console.error("Error toggling item:",w),ne.error("Failed to update item")}},v=s.filter(b=>b.target_role==="brokerage_manager"),y=s.filter(b=>b.target_role==="agent");return e.jsxs($s,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(z,{onClick:h,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Le,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:v.map((b,w)=>{var S;return e.jsxs(fn,{children:[e.jsx(yt,{className:"text-muted-foreground",children:w+1}),e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",children:((S=lze.find(C=>C.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(yt,{children:e.jsx(mn,{checked:b.is_active,onCheckedChange:()=>g(b)})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>f(b.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Le,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:y.map((b,w)=>{var S;return e.jsxs(fn,{children:[e.jsx(yt,{className:"text-muted-foreground",children:w+1}),e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",children:((S=lze.find(C=>C.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(yt,{children:e.jsx(mn,{checked:b.is_active,onCheckedChange:()=>g(b)})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>f(b.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(Is,{open:a,onOpenChange:i,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:c.title,onChange:b=>d({...c,title:b.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",value:c.description,onChange:b=>d({...c,description:b.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(ee,{children:"Target Role"}),e.jsxs(ls,{value:c.target_role,onValueChange:b=>d({...c,target_role:b}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:ZMn.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Action Type"}),e.jsxs(ls,{value:c.action_type,onValueChange:b=>d({...c,action_type:b}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:lze.map(b=>e.jsx(He,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(z,{onClick:p,children:l?"Save Changes":"Create Item"})]})]})})]})}function QMn(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("name"),[l,o]=_.useState("asc"),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(""),{data:v}=rt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:D,error:F}=await U.from("brokerages").select("id, name").order("name");if(F)throw F;return D}}),y=async D=>{let q=[],G=0,V=!0;for(;V;){const{data:H,error:K}=await D(G,G+1e3-1);if(K)throw K;H&&H.length>0?(q=[...q,...H],G+=1e3,V=H.length===1e3):V=!1}return q},{data:b,isLoading:w}=rt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const D=await y((Ee,Ne)=>U.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ee,Ne)),{data:F}=await U.from("brokerages").select("id, name"),q=new Map((F==null?void 0:F.map(Ee=>[Ee.id,Ee.name]))||[]),[{data:G},{data:V},{data:H},{data:K},{data:Z},{data:oe},{data:re}]=await Promise.all([U.rpc("get_admin_contact_counts"),U.rpc("get_admin_video_counts"),U.rpc("get_admin_popby_counts"),U.rpc("get_admin_listing_counts"),U.rpc("get_admin_deal_counts"),U.rpc("get_admin_portal_counts"),U.rpc("get_admin_sendable_card_counts")]),ae=new Map;G==null||G.forEach(Ee=>ae.set(Ee.owner_user_id,Ee.contact_count));const J=new Map;V==null||V.forEach(Ee=>J.set(Ee.owner_user_id,Ee.video_count));const te=new Map;H==null||H.forEach(Ee=>te.set(Ee.owner_user_id,Ee.popby_count));const ce=new Map;K==null||K.forEach(Ee=>ce.set(Ee.agent_id,Ee.listing_count));const ve=new Map;Z==null||Z.forEach(Ee=>ve.set(Ee.owner_user_id,Ee.deal_count));const me=new Map;oe==null||oe.forEach(Ee=>me.set(Ee.owner_user_id,{total:Ee.portal_count,active:Ee.active_portal_count}));const he=new Map;return re==null||re.forEach(Ee=>he.set(Ee.owner_user_id,{total:Ee.card_count,sent:Ee.sent_card_count,views:Ee.total_card_views})),D.map(Ee=>{const Ne=me.get(Ee.id),Pe=he.get(Ee.id);return{id:Ee.id,name:Ee.name||"Unknown",email:Ee.email||"",brokerage_id:Ee.brokerage_id,brokerage_name:Ee.brokerage_id&&q.get(Ee.brokerage_id)||null,contact_count:ae.get(Ee.id)||0,video_count:J.get(Ee.id)||0,popby_count:te.get(Ee.id)||0,listing_count:ce.get(Ee.id)||0,deal_count:ve.get(Ee.id)||0,portal_count:(Ne==null?void 0:Ne.total)||0,active_portal_count:(Ne==null?void 0:Ne.active)||0,card_count:(Pe==null?void 0:Pe.total)||0,sent_card_count:(Pe==null?void 0:Pe.sent)||0,total_card_views:(Pe==null?void 0:Pe.views)||0,created_at:Ee.created_at}})}}),S=_.useMemo(()=>{if(!b)return[];let D=b.filter(F=>{const q=s.toLowerCase(),G=!s||F.name.toLowerCase().includes(q)||F.email.toLowerCase().includes(q),V=n==="all"||n==="none"&&!F.brokerage_id||F.brokerage_id===n,H=parseInt(c)||0,K=parseInt(u)||0,Z=parseInt(m)||0,oe=parseInt(f)||0,re=F.contact_count>=H&&F.video_count>=K&&F.popby_count>=Z&&F.listing_count>=oe;return G&&V&&re});return D.sort((F,q)=>{let G=0;return a==="name"?G=F.name.localeCompare(q.name):G=F[a]-q[a],l==="asc"?G:-G}),D},[b,s,n,a,l,c,u,m,f]),C=D=>{a===D?o(l==="asc"?"desc":"asc"):(i(D),o("desc"))},E=()=>{const D=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],F=S.map(K=>[K.name,K.email,K.brokerage_name||"None",K.contact_count,K.video_count,K.popby_count,K.listing_count,K.deal_count,`${K.portal_count} (${K.active_portal_count})`,K.card_count,K.sent_card_count,K.total_card_views]),q=[D.join(","),...F.map(K=>K.map(Z=>`"${Z}"`).join(","))].join(` `),G=new Blob([q],{type:"text/csv"}),V=URL.createObjectURL(G),H=document.createElement("a");H.href=V,H.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,H.click(),URL.revokeObjectURL(V)},P=_.useMemo(()=>S.length?S.reduce((D,F)=>({contacts:D.contacts+F.contact_count,videos:D.videos+F.video_count,popbys:D.popbys+F.popby_count,listings:D.listings+F.listing_count,deals:D.deals+F.deal_count,portals:D.portals+F.portal_count,activePortals:D.activePortals+F.active_portal_count,cards:D.cards+F.card_count,sentCards:D.sentCards+F.sent_card_count,cardViews:D.cardViews+F.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},[S]),M=_.useMemo(()=>S.length?{portals:S.filter(D=>D.portal_count>0).length,cards:S.filter(D=>D.card_count>0).length}:{portals:0,cards:0},[S]),I=({field:D,children:F})=>e.jsx(Tt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>C(D),children:e.jsxs("div",{className:"flex items-center gap-1",children:[F,e.jsx(Og,{className:`h-3 w-3 ${a===D?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(UN,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(be,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(fj,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Le,{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:P.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:P.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(be,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Le,{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:P.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:P.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:P.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(En,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:E,children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:D=>t(D.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(ls,{value:n,onValueChange:r,children:[e.jsxs(rs,{children:[e.jsx(oi,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(cs,{placeholder:"Brokerage"})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Brokerages"}),e.jsx(He,{value:"none",children:"No Brokerage"}),v==null?void 0:v.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))]})]})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min contacts",value:c,onChange:D=>d(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min videos",value:u,onChange:D=>h(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min popbys",value:m,onChange:D=>p(D.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:S.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:P.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:P.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:P.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:P.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:P.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:P.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:P.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),w?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(I,{field:"name",children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(I,{field:"contact_count",children:"Contacts"}),e.jsx(I,{field:"video_count",children:"Videos"}),e.jsx(I,{field:"popby_count",children:"Popbys"}),e.jsx(I,{field:"listing_count",children:"Listings"}),e.jsx(I,{field:"deal_count",children:"Deals"}),e.jsx(I,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fj,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(I,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(Qa,{children:S.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):S.map(D=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:D.name}),e.jsx(yt,{className:"text-muted-foreground",children:D.email}),e.jsx(yt,{children:D.brokerage_name?e.jsx(ze,{variant:"secondary",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(yt,{children:e.jsx(ze,{variant:D.contact_count>0?"default":"outline",children:D.contact_count})}),e.jsx(yt,{children:e.jsx(ze,{variant:D.video_count>0?"default":"outline",children:D.video_count})}),e.jsx(yt,{children:e.jsx(ze,{variant:D.popby_count>0?"default":"outline",children:D.popby_count})}),e.jsx(yt,{children:e.jsx(ze,{variant:D.listing_count>0?"default":"outline",children:D.listing_count})}),e.jsx(yt,{children:e.jsx(ze,{variant:D.deal_count>0?"default":"outline",children:D.deal_count})}),e.jsx(yt,{children:D.portal_count>0?e.jsxs(ug,{children:[e.jsx(hg,{children:e.jsxs(ze,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[D.portal_count,D.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",D.active_portal_count," active)"]})]})}),e.jsxs(Tx,{children:[e.jsxs("p",{children:[D.portal_count," total portals"]}),e.jsxs("p",{children:[D.active_portal_count," currently active"]})]})]}):e.jsx(ze,{variant:"outline",children:"0"})}),e.jsx(yt,{children:D.card_count>0?e.jsxs(ug,{children:[e.jsx(hg,{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:D.card_count}),D.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Fr,{className:"h-3 w-3"}),D.sent_card_count]}),D.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(xa,{className:"h-3 w-3"}),D.total_card_views]})]})}),e.jsxs(Tx,{children:[e.jsxs("p",{children:[D.card_count," cards created"]}),e.jsxs("p",{children:[D.sent_card_count," sent"]}),e.jsxs("p",{children:[D.total_card_views," total views"]})]})]}):e.jsx(ze,{variant:"outline",children:"0"})})]},D.id))})]})})]})]})]})})}function JMn(){_i(),$t();const[s,t]=_.useState("user-analytics"),{data:n}=rt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:p,error:f}=await U.from("feature_flags").select("*").order("key");if(f)throw f;return p}}),{data:r,isLoading:a}=rt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:p,error:f}=await U.from("relationship_types").select("*").order("sort_order");if(f)throw f;return p}}),{data:i,isLoading:l}=rt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:p,error:f}=await U.from("action_types").select("*").order("sort_order");if(f)throw f;return p}}),{data:o,isLoading:c}=rt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:p,error:f}=await U.from("action_scripts").select("*, action_type:action_types(*)");if(f)throw f;return p}}),{data:d,isLoading:u}=rt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:p,error:f}=await U.from("touchpoint_plans").select("*").order("name");if(f)throw f;return p}}),{data:h,isLoading:m}=rt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:p,error:f}=await U.from("popby_items").select("*").is("owner_user_id",null).order("name");if(f)throw f;return p}});return e.jsx($s,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(Qr,{value:s,onValueChange:t,children:[e.jsxs(Jr,{className:"grid w-full grid-cols-9",children:[e.jsxs(Wt,{value:"user-analytics",className:"gap-2",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Wt,{value:"relationship-types",className:"gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Wt,{value:"action-types",className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Wt,{value:"scripts",className:"gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Wt,{value:"video-scripts",className:"gap-2",children:[e.jsx(Yh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Wt,{value:"plans",className:"gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Wt,{value:"popbys",className:"gap-2",children:[e.jsx(Ko,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Wt,{value:"settings",className:"gap-2",children:[e.jsx(Gc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Wt,{value:"feature-flags",className:"gap-2",children:[e.jsx(WA,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Kt,{value:"user-analytics",className:"mt-6",children:e.jsx(QMn,{})}),e.jsx(Kt,{value:"relationship-types",className:"mt-6",children:e.jsx(ePn,{types:r||[],isLoading:a})}),e.jsx(Kt,{value:"action-types",className:"mt-6",children:e.jsx(tPn,{types:i||[],isLoading:l})}),e.jsx(Kt,{value:"scripts",className:"mt-6",children:e.jsx(sPn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Kt,{value:"video-scripts",className:"mt-6",children:e.jsx(iPn,{})}),e.jsx(Kt,{value:"plans",className:"mt-6",children:e.jsx(nPn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Kt,{value:"popbys",className:"mt-6",children:e.jsx(aPn,{items:h||[],isLoading:m})}),e.jsx(Kt,{value:"settings",className:"mt-6",children:e.jsx(oPn,{})}),e.jsx(Kt,{value:"feature-flags",className:"mt-6",children:e.jsx(rPn,{flags:n||[]})})]})]})})}function ePn({types:s,isLoading:t}){const{toast:n}=_i(),r=$t(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=mt({mutationFn:async u=>{if(u.id){const{error:h}=await U.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 U.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 U.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Relationship Types"}),e.jsx(En,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(z,{onClick:()=>{i(null),o(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Le,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-12"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(u=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx(Zf,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(yt,{className:"font-medium",children:u.name}),e.jsx(yt,{className:"text-muted-foreground",children:u.description}),e.jsx(yt,{children:e.jsx(mn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(yt,{children:e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(Rs,{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(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"icon",children:"Icon"}),e.jsx(pe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function tPn({types:s,isLoading:t}){const{toast:n}=_i(),r=$t(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=mt({mutationFn:async u=>{if(u.id){const{error:h}=await U.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 U.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 U.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Action Types"}),e.jsx(En,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(z,{onClick:()=>{i(null),o(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Le,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Color"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(u=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:u.name}),e.jsx(yt,{className:"text-muted-foreground",children:u.description}),e.jsx(yt,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(yt,{children:e.jsx(mn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(yt,{children:e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(Rs,{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(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"icon",children:"Icon"}),e.jsx(pe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"color",children:"Color"}),e.jsx(pe,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function sPn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=_i(),a=$t(),[i,l]=_.useState(null),[o,c]=_.useState(!1),d=mt({mutationFn:async h=>{if(h.id){const{error:m}=await U.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(m)throw m}else{const{error:m}=await U.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(m)throw m}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=mt({mutationFn:async h=>{const{error:m}=await U.from("action_scripts").delete().eq("id",h);if(m)throw m},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Script Library"}),e.jsx(En,{children:"Create and manage scripts for each action type"})]}),e.jsxs(z,{onClick:()=>{l(null),c(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Le,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(h=>{var m;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:h.title}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",children:((m=h.action_type)==null?void 0:m.name)||"Unknown"})}),e.jsx(yt,{className:"text-muted-foreground",children:h.tone}),e.jsx(yt,{children:e.jsx(ze,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(yt,{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(ls,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select action type"})}),e.jsx(as,{children:t.map(h=>e.jsx(He,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(pe,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ps,{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(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function nPn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=_i(),i=$t(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(!1),[f,g]=_.useState(null),[v,y]=_.useState(null),{data:b}=rt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:I,error:D}=await U.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(D)throw D;return I},enabled:!!u}),w=mt({mutationFn:async I=>{if(I.id){const{error:D}=await U.from("touchpoint_plans").update({name:I.name,description:I.description,active:I.active}).eq("id",I.id);if(D)throw D}else{const{error:D}=await U.from("touchpoint_plans").insert([{name:I.name,description:I.description,active:!0}]);if(D)throw D}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),S=mt({mutationFn:async I=>{if(I.id){const{error:D}=await U.from("touchpoint_plan_items").update({action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}).eq("id",I.id);if(D)throw D}else{const{error:D}=await U.from("touchpoint_plan_items").insert([{plan_id:I.plan_id,month_number:I.month_number,action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}]);if(D)throw D}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),C=mt({mutationFn:async I=>{const{error:D}=await U.from("touchpoint_plan_items").delete().eq("id",I);if(D)throw D},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),E=mt({mutationFn:async I=>{const{data:D,error:F}=await U.from("action_scripts").insert([{...I,active:!0}]).select().single();if(F)throw F;return D},onSuccess:async I=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),f&&await S.mutateAsync({id:f.itemId,plan_id:u,month_number:f.month,action_type_id:f.actionTypeId,default_script_id:I.id}),p(!1),g(null),a({title:"Script created and assigned"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),P=(I,D,F)=>{g({month:I,actionTypeId:D,itemId:F}),p(!0)},M=I=>n.find(D=>D.id===I);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Touchpoint Plans"}),e.jsx(En,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(z,{onClick:()=>{o(null),d(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Le,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{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(I=>e.jsxs(be,{className:`cursor-pointer transition-colors ${u===I.id?"border-primary":""}`,onClick:()=>h(I.id),children:[e.jsx(_t,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Nt,{className:"text-base",children:I.name}),e.jsx(z,{variant:"ghost",size:"icon",onClick:D=>{D.stopPropagation(),o(I),d(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})})]})}),e.jsxs(Le,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:I.description}),e.jsx(ze,{variant:I.active?"default":"secondary",className:"mt-2",children:I.active?"Active":"Inactive"})]})]},I.id))})})]}),u&&e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Plan Schedule"}),e.jsx(En,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Le,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(I,D)=>D+1).map(I=>{const D=b==null?void 0:b.find(G=>G.month_number===I),F=D!=null&&D.default_script_id?M(D.default_script_id):null,q=n.filter(G=>G.action_type_id===(D==null?void 0:D.action_type_id)&&G.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",I]}),e.jsxs(ls,{value:(D==null?void 0:D.action_type_id)||"none",onValueChange:G=>{G==="none"&&D?C.mutate(D.id):G!=="none"&&S.mutate({id:D==null?void 0:D.id,plan_id:u,month_number:I,action_type_id:G,default_script_id:null})},children:[e.jsx(rs,{className:"w-40",children:e.jsx(cs,{placeholder:"No action"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No action"}),t.filter(G=>G.active).map(G=>e.jsx(He,{value:G.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[G.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:G.color}}),G.name]})},G.id))]})]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(ls,{value:D.default_script_id||"none",onValueChange:G=>{y(null),S.mutate({id:D.id,default_script_id:G==="none"?null:G})},children:[e.jsx(rs,{className:"w-56",children:e.jsx(cs,{placeholder:"Select script"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No default script"}),q.map(G=>e.jsxs(He,{value:G.id,children:[G.title," ",G.tone&&`(${G.tone})`]},G.id))]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>P(I,D.action_type_id,D.id),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"}),"New Script"]}),F&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>y((v==null?void 0:v.id)===F.id?null:F),children:(v==null?void 0:v.id)===F.id?"Hide":"Preview"})]})]}),v&&(D==null?void 0:D.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})]})]},I)})})})]}),e.jsx(Is,{open:c,onOpenChange:d,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(Rs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const D=new FormData(I.currentTarget);w.mutate({id:l==null?void 0:l.id,name:D.get("name"),description:D.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:w.isPending,children:[w.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(Is,{open:m,onOpenChange:p,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create New Script"}),e.jsxs(_r,{children:["Create a script for Month ",f==null?void 0:f.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const D=new FormData(I.currentTarget);E.mutate({title:D.get("title"),action_type_id:f.actionTypeId,tone:D.get("tone"),script_body:D.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(ee,{htmlFor:"script_title",children:"Title"}),e.jsx(pe,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_tone",children:"Tone"}),e.jsx(pe,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ps,{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(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:E.isPending,children:[E.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function rPn({flags:s}){const{toast:t}=_i(),n=$t(),r=async(a,i)=>{const{error:l}=await U.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Feature Flags"}),e.jsx(En,{children:"Control which features are enabled for members"})]}),e.jsx(Le,{children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Flag"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Notes"}),e.jsx(Tt,{children:"Last Updated"})]})}),e.jsx(Qa,{children:s.map(a=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-mono text-sm",children:a.key}),e.jsx(yt,{children:e.jsx(mn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(yt,{children:e.jsx(pe,{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(yt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function aPn({items:s,isLoading:t}){const{toast:n}=_i(),r=$t(),[a,i]=_.useState(null),[l,o]=_.useState(!1),c=mt({mutationFn:async h=>{if(h.id){const{error:m}=await U.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await U.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(m)throw m}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await U.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 U.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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Popby Ideas"}),e.jsx(En,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(z,{onClick:()=>{i(null),o(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Le,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{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(Ko,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(h=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:h.name}),e.jsx(yt,{className:"text-muted-foreground",children:h.description}),e.jsx(yt,{children:e.jsx(mn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(Rs,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function iPn(){var p;const{toast:s}=_i(),t=$t(),[n,r]=_.useState(null),[a,i]=_.useState(!1),{data:l,isLoading:o}=rt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:f,error:g}=await U.from("video_script_categories").select("*").order("sort_order");if(g)throw g;return f}}),{data:c,isLoading:d}=rt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:f,error:g}=await U.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(g)throw g;return f}}),u=mt({mutationFn:async f=>{var g,v;if(f.id){const{error:y}=await U.from("video_scripts").update({title:f.title,script_text:f.script_text,category_id:f.category_id,tags:((g=f.tags)==null?void 0:g.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",f.id);if(y)throw y}else{const{error:y}=await U.from("video_scripts").insert([{title:f.title,script_text:f.script_text,category_id:f.category_id||null,tags:((v=f.tags)==null?void 0:v.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(y)throw y}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:f=>s({title:"Error",description:f.message,variant:"destructive"})}),h=async f=>{await U.from("video_scripts").update({is_active:!f.is_active}).eq("id",f.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async f=>{await Qi("Delete this video script?")&&(await U.from("video_scripts").delete().eq("id",f),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Video Scripts"}),e.jsx(En,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(z,{onClick:()=>{r(null),i(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Le,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(Qa,{children:c==null?void 0:c.map(f=>{var g;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:f.title}),e.jsx(yt,{className:"text-muted-foreground",children:((g=f.category)==null?void 0:g.name)||"Uncategorized"}),e.jsx(yt,{children:e.jsx(mn,{checked:f.is_active,onCheckedChange:()=>h(f)})}),e.jsxs(yt,{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>{r(f),i(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>m(f.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]},f.id)})})]})}),e.jsx(Is,{open:a,onOpenChange:i,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:f=>{f.preventDefault();const g=new FormData(f.currentTarget);u.mutate({id:n==null?void 0:n.id,title:g.get("title"),script_text:g.get("script_text"),category_id:g.get("category_id")||null,tags:g.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"category_id",children:"Category"}),e.jsxs(ls,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select category"})}),e.jsx(as,{children:l==null?void 0:l.map(f=>e.jsx(He,{value:f.id,children:f.name},f.id))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ps,{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(ee,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(pe,{id:"tags",name:"tags",defaultValue:((p=n==null?void 0:n.tags)==null?void 0:p.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(hr,{className:"mt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function oPn(){const{toast:s}=_i(),[t,n]=_.useState(""),[r,a]=_.useState(!0),[i,l]=_.useState(!1);_.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await U.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 U.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(be,{children:e.jsx(Le,{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(En,{children:"Configure the map feature for popbys"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(pe,{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(z,{onClick:o,disabled:i,children:[i&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(ze,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const lPn=()=>{const[s,t]=_.useState(""),[n,r]=_.useState("grid"),a=zn(),{data:i=[],isLoading:l}=rt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await U.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx($s,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{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(z,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(op,{className:"h-4 w-4"})}),e.jsx(z,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(My,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(ln,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(ln,{className:"h-5 w-3/4 mb-2"}),e.jsx(ln,{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(z,{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(be,{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(Le,{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:ete(c.description)})]})]},c.id))})]})})},cPn=()=>{const{serviceId:s}=Mi(),t=zn(),{data:n,isLoading:r}=rt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await U.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx($s,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(ln,{className:"h-8 w-48"}),e.jsx(ln,{className:"h-64 w-full rounded-lg"}),e.jsx(ln,{className:"h-24 w-full"})]})}):n?e.jsx($s,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(z,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(be,{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(be,{children:e.jsxs(Le,{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(ya,{className:"h-4 w-4 mr-1"}),"Published ",Ys(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(z,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(mr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx($s,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(z,{onClick:()=>t("/additional-services"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},vZ=[{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 dPn(){const[s,t]=_.useState(vZ[0].id),n=vZ.find(r=>r.id===s)||vZ[0];return e.jsx($s,{title:"AI Toolkit",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(K4,{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(ls,{value:s,onValueChange:t,children:[e.jsx(rs,{className:"w-full",children:e.jsx(cs,{placeholder:"Select a tool"})}),e.jsx(as,{children:vZ.map(r=>e.jsx(He,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(Qr,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Jr,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:vZ.map(r=>e.jsx(Wt,{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 uPn(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const hPn=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,mPn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pPn={};function zjt(s,t){return(pPn.jsx?mPn:hPn).test(s)}const fPn=/[ \t\n\f\r]/g;function xPn(s){return typeof s=="object"?s.type==="text"?Bjt(s.value):!1:Bjt(s)}function Bjt(s){return s.replace(fPn,"")===""}class Uae{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Uae.prototype.normal={};Uae.prototype.property={};Uae.prototype.space=void 0;function _Yt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Uae(n,r,t)}function AWe(s){return s.toLowerCase()}class ew{constructor(t,n){this.attribute=n,this.property=t}}ew.prototype.attribute="";ew.prototype.booleanish=!1;ew.prototype.boolean=!1;ew.prototype.commaOrSpaceSeparated=!1;ew.prototype.commaSeparated=!1;ew.prototype.defined=!1;ew.prototype.mustUseProperty=!1;ew.prototype.number=!1;ew.prototype.overloadedBoolean=!1;ew.prototype.property="";ew.prototype.spaceSeparated=!1;ew.prototype.space=void 0;let gPn=0;const jc=mz(),Pg=mz(),EWe=mz(),ii=mz(),Em=mz(),F7=mz(),Ew=mz();function mz(){return 2**++gPn}const TWe=Object.freeze(Object.defineProperty({__proto__:null,boolean:jc,booleanish:Pg,commaOrSpaceSeparated:Ew,commaSeparated:F7,number:ii,overloadedBoolean:EWe,spaceSeparated:Em},Symbol.toStringTag,{value:"Module"})),cze=Object.keys(TWe);class Dnt extends ew{constructor(t,n,r,a){let i=-1;if(super(t,n),$jt(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&wPn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Ujt,kPn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Ujt.test(i)){let l=i.replace(_Pn,NPn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=Dnt}return new a(r,t)}function NPn(s){return"-"+s.toLowerCase()}function kPn(s){return s.charAt(1).toUpperCase()}const SPn=_Yt([wYt,yPn,kYt,SYt,CYt],"html"),Rnt=_Yt([wYt,vPn,kYt,SYt,CYt],"svg");function CPn(s){return s.join(" ").trim()}var Fnt={},qjt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,APn=/\n/g,EPn=/^\s*/,TPn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,MPn=/^:\s*/,PPn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,LPn=/^[;\s]*/,IPn=/^\s+|\s+$/g,DPn=` `,Vjt="/",Hjt="*",uF="",RPn="comment",FPn="declaration";function OPn(s,t){if(typeof s!="string")throw new TypeError("First argument must be a string");if(!s)return[];t=t||{};var n=1,r=1;function a(f){var g=f.match(APn);g&&(n+=g.length);var v=f.lastIndexOf(DPn);r=~v?f.length-v:r+f.length}function i(){var f={line:n,column:r};return function(g){return g.position=new l(f),d(),g}}function l(f){this.start=f,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(f){var g=new Error(t.source+":"+n+":"+r+": "+f);if(g.reason=f,g.filename=t.source,g.line=n,g.column=r,g.source=s,!t.silent)throw g}function c(f){var g=f.exec(s);if(g){var v=g[0];return a(v),s=s.slice(v.length),g}}function d(){c(EPn)}function u(f){var g;for(f=f||[];g=h();)g!==!1&&f.push(g);return f}function h(){var f=i();if(!(Vjt!=s.charAt(0)||Hjt!=s.charAt(1))){for(var g=2;uF!=s.charAt(g)&&(Hjt!=s.charAt(g)||Vjt!=s.charAt(g+1));)++g;if(g+=2,uF===s.charAt(g-1))return o("End of comment missing");var v=s.slice(2,g-2);return r+=2,a(v),s=s.slice(g),r+=2,f({type:RPn,comment:v})}}function m(){var f=i(),g=c(TPn);if(g){if(h(),!c(MPn))return o("property missing ':'");var v=c(PPn),y=f({type:FPn,property:Gjt(g[0].replace(qjt,uF)),value:v?Gjt(v[0].replace(qjt,uF)):uF});return c(LPn),y}}function p(){var f=[];u(f);for(var g;g=m();)g!==!1&&(f.push(g),u(f));return f}return d(),p()}function Gjt(s){return s?s.replace(IPn,uF):uF}var zPn=OPn,BPn=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Fnt,"__esModule",{value:!0});Fnt.default=UPn;const $Pn=BPn(zPn);function UPn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,$Pn.default)(s),a=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:l,value:o}=i;a?t(l,o,i):o&&(n=n||{},n[l]=o)}),n}var r8e={};Object.defineProperty(r8e,"__esModule",{value:!0});r8e.camelCase=void 0;var qPn=/^--[a-zA-Z0-9_-]+$/,VPn=/-([a-z])/g,HPn=/^[^-]+$/,GPn=/^-(webkit|moz|ms|o|khtml)-/,WPn=/^-(ms)-/,KPn=function(s){return!s||HPn.test(s)||qPn.test(s)},YPn=function(s,t){return t.toUpperCase()},Wjt=function(s,t){return"".concat(t,"-")},ZPn=function(s,t){return t===void 0&&(t={}),KPn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(WPn,Wjt):s=s.replace(GPn,Wjt),s.replace(VPn,YPn))};r8e.camelCase=ZPn;var XPn=Pp&&Pp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},QPn=XPn(Fnt),JPn=r8e;function MWe(s,t){var n={};return!s||typeof s!="string"||(0,QPn.default)(s,function(r,a){r&&a&&(n[(0,JPn.camelCase)(r,t)]=a)}),n}MWe.default=MWe;var eLn=MWe;const tLn=kd(eLn),AYt=EYt("end"),Ont=EYt("start");function EYt(s){return t;function t(n){const r=n&&n.position&&n.position[s]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function sLn(s){const t=Ont(s),n=AYt(s);if(t&&n)return{start:t,end:n}}function lee(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?Kjt(s.position):"start"in s||"end"in s?Kjt(s):"line"in s||"column"in s?PWe(s):""}function PWe(s){return Yjt(s&&s.line)+":"+Yjt(s&&s.column)}function Kjt(s){return PWe(s&&s.start)+"-"+PWe(s&&s.end)}function Yjt(s){return s&&typeof s=="number"?s:1}class S1 extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?a=t:!i.cause&&t&&(l=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=lee(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=l&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}S1.prototype.file="";S1.prototype.name="";S1.prototype.reason="";S1.prototype.message="";S1.prototype.stack="";S1.prototype.column=void 0;S1.prototype.line=void 0;S1.prototype.ancestors=void 0;S1.prototype.cause=void 0;S1.prototype.fatal=void 0;S1.prototype.place=void 0;S1.prototype.ruleId=void 0;S1.prototype.source=void 0;const znt={}.hasOwnProperty,nLn=new Map,rLn=/[A-Z]/g,aLn=new Set(["table","tbody","thead","tfoot","tr"]),iLn=new Set(["td","th"]),TYt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function oLn(s,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=fLn(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=pLn(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Rnt:SPn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=MYt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function MYt(s,t,n){if(t.type==="element")return lLn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return cLn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return uLn(s,t,n);if(t.type==="mdxjsEsm")return dLn(s,t);if(t.type==="root")return hLn(s,t,n);if(t.type==="text")return mLn(s,t)}function lLn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=Rnt,s.schema=a),s.ancestors.push(t);const i=LYt(s,t.tagName,!1),l=xLn(s,t);let o=$nt(s,t);return aLn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!xPn(c):!0})),PYt(s,l,i,t),Bnt(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function cLn(s,t){if(t.data&&t.data.estree&&s.evaluater){const r=t.data.estree.body[0];return r.type,s.evaluater.evaluateExpression(r.expression)}wse(s,t.position)}function dLn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);wse(s,t.position)}function uLn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=Rnt,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:LYt(s,t.name,!0),l=gLn(s,t),o=$nt(s,t);return PYt(s,l,i,t),Bnt(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function hLn(s,t,n){const r={};return Bnt(r,$nt(s,t)),s.create(t,s.Fragment,r,n)}function mLn(s,t){return t.value}function PYt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function Bnt(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function pLn(s,t,n){return r;function r(a,i,l,o){const d=Array.isArray(l.children)?n:t;return o?d(i,l,o):d(i,l)}}function fLn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=Ont(r);return t(a,i,l,o,{columnNumber:c?c.column-1:void 0,fileName:s,lineNumber:c?c.line:void 0},void 0)}}function xLn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&znt.call(t.properties,a)){const i=yLn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&iLn.has(t.tagName)?r=o:n[l]=o}}if(r){const i=n.style||(n.style={});i[s.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function gLn(s,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&s.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const o=l.properties[0];o.type,Object.assign(n,s.evaluater.evaluateExpression(o.argument))}else wse(s,t.position);else{const a=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&s.evaluater){const o=r.value.data.estree.body[0];o.type,i=s.evaluater.evaluateExpression(o.expression)}else wse(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function $nt(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:nLn;for(;++ra?0:a+t:t=t>a?a:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),s.splice(...l);else for(n&&s.splice(t,n);i0?(vC(s,s.length,0,t),s):t}const Qjt={}.hasOwnProperty;function SLn(s){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function qq(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const E4=UL(/[A-Za-z]/),ij=UL(/[\dA-Za-z]/),ELn=UL(/[#-'*+\--9=?A-Z^-~]/);function LWe(s){return s!==null&&(s<32||s===127)}const IWe=UL(/\d/),TLn=UL(/[\dA-Fa-f]/),MLn=UL(/[!-/:-@[-`{-~]/);function uc(s){return s!==null&&s<-2}function V_(s){return s!==null&&(s<0||s===32)}function oh(s){return s===-2||s===-1||s===32}const PLn=UL(new RegExp("\\p{P}|\\p{S}","u")),LLn=UL(/\s/);function UL(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function ZW(s){const t=[];let n=-1,r=0,a=0;for(;++n55295&&i<57344){const o=s.charCodeAt(n+1);i<56320&&o>56319&&o<57344?(l=String.fromCharCode(i,o),a=1):l="�"}else l=String.fromCharCode(i);l&&(t.push(s.slice(r,n),encodeURIComponent(l)),r=n+a+1,l=""),a&&(n+=a,a=0)}return t.join("")+s.slice(r)}function np(s,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return oh(c)?(s.enter(n),o(c)):t(c)}function o(c){return oh(c)&&i++l))return;const P=t.events.length;let M=P,I,D;for(;M--;)if(t.events[M][0]==="exit"&&t.events[M][1].type==="chunkFlow"){if(I){D=t.events[M][1].end;break}I=!0}for(y(r),E=P;Ew;){const C=n[S];t.containerState=C[1],C[0].exit.call(t,s)}n.length=w}function b(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function OLn(s,t,n){return np(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function e2t(s){if(s===null||V_(s)||LLn(s))return 1;if(PLn(s))return 2}function qnt(s,t,n){const r=[];let a=-1;for(;++a1&&s[n][1].end.offset-s[n][1].start.offset>1?2:1;const h={...s[r][1].end},m={...s[n][1].start};t2t(h,-c),t2t(m,c),l={type:c>1?"strongSequence":"emphasisSequence",start:h,end:{...s[r][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...s[n][1].start},end:m},i={type:c>1?"strongText":"emphasisText",start:{...s[r][1].end},end:{...s[n][1].start}},a={type:c>1?"strong":"emphasis",start:{...l.start},end:{...o.end}},s[r][1].end={...l.start},s[n][1].start={...o.end},d=[],s[r][1].end.offset-s[r][1].start.offset&&(d=Z2(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=Z2(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=Z2(d,qnt(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=Z2(d,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),s[n][1].end.offset-s[n][1].start.offset?(u=2,d=Z2(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,vC(s,r-1,n-r+3,d),n=r+d.length-u-2;break}}for(n=-1;++n0&&oh(E)?np(s,b,"linePrefix",i+1)(E):b(E)}function b(E){return E===null||uc(E)?s.check(s2t,g,S)(E):(s.enter("codeFlowValue"),w(E))}function w(E){return E===null||uc(E)?(s.exit("codeFlowValue"),b(E)):(s.consume(E),w)}function S(E){return s.exit("codeFenced"),t(E)}function C(E,P,M){let I=0;return D;function D(H){return E.enter("lineEnding"),E.consume(H),E.exit("lineEnding"),F}function F(H){return E.enter("codeFencedFence"),oh(H)?np(E,q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):q(H)}function q(H){return H===o?(E.enter("codeFencedFenceSequence"),G(H)):M(H)}function G(H){return H===o?(I++,E.consume(H),G):I>=l?(E.exit("codeFencedFenceSequence"),oh(H)?np(E,V,"whitespace")(H):V(H)):M(H)}function V(H){return H===null||uc(H)?(E.exit("codeFencedFence"),P(H)):M(H)}}}function ZLn(s,t,n){const r=this;return a;function a(l){return l===null?n(l):(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),i)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const uze={name:"codeIndented",tokenize:QLn},XLn={partial:!0,tokenize:JLn};function QLn(s,t,n){const r=this;return a;function a(d){return s.enter("codeIndented"),np(s,i,"linePrefix",5)(d)}function i(d){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?l(d):n(d)}function l(d){return d===null?c(d):uc(d)?s.attempt(XLn,l,c)(d):(s.enter("codeFlowValue"),o(d))}function o(d){return d===null||uc(d)?(s.exit("codeFlowValue"),l(d)):(s.consume(d),o)}function c(d){return s.exit("codeIndented"),t(d)}}function JLn(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):uc(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):np(s,i,"linePrefix",5)(l)}function i(l){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(l):uc(l)?a(l):n(l)}}const eIn={name:"codeText",previous:sIn,resolve:tIn,tokenize:nIn};function tIn(s){let t=s.length-4,n=3,r,a;if((s[n][1].type==="lineEnding"||s[n][1].type==="space")&&(s[t][1].type==="lineEnding"||s[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const a=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&bZ(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),bZ(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),bZ(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):s.interrupt(r.parser.constructs.flow,n,t)(l)}}function BYt(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(y){return y===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(y),s.exit(i),m):y===null||y===32||y===41||LWe(y)?n(y):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),g(y))}function m(y){return y===62?(s.enter(i),s.consume(y),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(s.exit("chunkString"),s.exit(o),m(y)):y===null||y===60||uc(y)?n(y):(s.consume(y),y===92?f:p)}function f(y){return y===60||y===62||y===92?(s.consume(y),p):p(y)}function g(y){return!u&&(y===null||y===41||V_(y))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(y)):u999||p===null||p===91||p===93&&!c||p===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(s.exit(i),s.enter(a),s.consume(p),s.exit(a),s.exit(r),t):uc(p)?(s.enter("lineEnding"),s.consume(p),s.exit("lineEnding"),u):(s.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||uc(p)||o++>999?(s.exit("chunkString"),u(p)):(s.consume(p),c||(c=!oh(p)),p===92?m:h)}function m(p){return p===91||p===92||p===93?(s.consume(p),o++,h):h(p)}}function UYt(s,t,n,r,a,i){let l;return o;function o(m){return m===34||m===39||m===40?(s.enter(r),s.enter(a),s.consume(m),s.exit(a),l=m===40?41:m,c):n(m)}function c(m){return m===l?(s.enter(a),s.consume(m),s.exit(a),s.exit(r),t):(s.enter(i),d(m))}function d(m){return m===l?(s.exit(i),c(l)):m===null?n(m):uc(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),np(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||uc(m)?(s.exit("chunkString"),d(m)):(s.consume(m),m===92?h:u)}function h(m){return m===l||m===92?(s.consume(m),u):u(m)}}function cee(s,t){let n;return r;function r(a){return uc(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):oh(a)?np(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const uIn={name:"definition",tokenize:mIn},hIn={partial:!0,tokenize:pIn};function mIn(s,t,n){const r=this;let a;return i;function i(p){return s.enter("definition"),l(p)}function l(p){return $Yt.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return a=qq(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(s.enter("definitionMarker"),s.consume(p),s.exit("definitionMarker"),c):n(p)}function c(p){return V_(p)?cee(s,d)(p):d(p)}function d(p){return BYt(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return s.attempt(hIn,h,h)(p)}function h(p){return oh(p)?np(s,m,"whitespace")(p):m(p)}function m(p){return p===null||uc(p)?(s.exit("definition"),r.parser.defined.push(a),t(p)):n(p)}}function pIn(s,t,n){return r;function r(o){return V_(o)?cee(s,a)(o):n(o)}function a(o){return UYt(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return oh(o)?np(s,l,"whitespace")(o):l(o)}function l(o){return o===null||uc(o)?t(o):n(o)}}const fIn={name:"hardBreakEscape",tokenize:xIn};function xIn(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return uc(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const gIn={name:"headingAtx",resolve:yIn,tokenize:vIn};function yIn(s,t){let n=s.length-2,r=3,a,i;return s[r][1].type==="whitespace"&&(r+=2),n-2>r&&s[n][1].type==="whitespace"&&(n-=2),s[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&s[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(a={type:"atxHeadingText",start:s[r][1].start,end:s[n][1].end},i={type:"chunkText",start:s[r][1].start,end:s[n][1].end,contentType:"text"},vC(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),s}function vIn(s,t,n){let r=0;return a;function a(u){return s.enter("atxHeading"),i(u)}function i(u){return s.enter("atxHeadingSequence"),l(u)}function l(u){return u===35&&r++<6?(s.consume(u),l):u===null||V_(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||uc(u)?(s.exit("atxHeading"),t(u)):oh(u)?np(s,o,"whitespace")(u):(s.enter("atxHeadingText"),d(u))}function c(u){return u===35?(s.consume(u),c):(s.exit("atxHeadingSequence"),o(u))}function d(u){return u===null||u===35||V_(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const bIn=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],r2t=["pre","script","style","textarea"],_In={concrete:!0,name:"htmlFlow",resolveTo:NIn,tokenize:kIn},wIn={partial:!0,tokenize:CIn},jIn={partial:!0,tokenize:SIn};function NIn(s){let t=s.length;for(;t--&&!(s[t][0]==="enter"&&s[t][1].type==="htmlFlow"););return t>1&&s[t-2][1].type==="linePrefix"&&(s[t][1].start=s[t-2][1].start,s[t+1][1].start=s[t-2][1].start,s.splice(t-2,2)),s}function kIn(s,t,n){const r=this;let a,i,l,o,c;return d;function d(ce){return u(ce)}function u(ce){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(ce),h}function h(ce){return ce===33?(s.consume(ce),m):ce===47?(s.consume(ce),i=!0,g):ce===63?(s.consume(ce),a=3,r.interrupt?t:ae):E4(ce)?(s.consume(ce),l=String.fromCharCode(ce),v):n(ce)}function m(ce){return ce===45?(s.consume(ce),a=2,p):ce===91?(s.consume(ce),a=5,o=0,f):E4(ce)?(s.consume(ce),a=4,r.interrupt?t:ae):n(ce)}function p(ce){return ce===45?(s.consume(ce),r.interrupt?t:ae):n(ce)}function f(ce){const ve="CDATA[";return ce===ve.charCodeAt(o++)?(s.consume(ce),o===ve.length?r.interrupt?t:q:f):n(ce)}function g(ce){return E4(ce)?(s.consume(ce),l=String.fromCharCode(ce),v):n(ce)}function v(ce){if(ce===null||ce===47||ce===62||V_(ce)){const ve=ce===47,me=l.toLowerCase();return!ve&&!i&&r2t.includes(me)?(a=1,r.interrupt?t(ce):q(ce)):bIn.includes(l.toLowerCase())?(a=6,ve?(s.consume(ce),y):r.interrupt?t(ce):q(ce)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(ce):i?b(ce):w(ce))}return ce===45||ij(ce)?(s.consume(ce),l+=String.fromCharCode(ce),v):n(ce)}function y(ce){return ce===62?(s.consume(ce),r.interrupt?t:q):n(ce)}function b(ce){return oh(ce)?(s.consume(ce),b):D(ce)}function w(ce){return ce===47?(s.consume(ce),D):ce===58||ce===95||E4(ce)?(s.consume(ce),S):oh(ce)?(s.consume(ce),w):D(ce)}function S(ce){return ce===45||ce===46||ce===58||ce===95||ij(ce)?(s.consume(ce),S):C(ce)}function C(ce){return ce===61?(s.consume(ce),E):oh(ce)?(s.consume(ce),C):w(ce)}function E(ce){return ce===null||ce===60||ce===61||ce===62||ce===96?n(ce):ce===34||ce===39?(s.consume(ce),c=ce,P):oh(ce)?(s.consume(ce),E):M(ce)}function P(ce){return ce===c?(s.consume(ce),c=null,I):ce===null||uc(ce)?n(ce):(s.consume(ce),P)}function M(ce){return ce===null||ce===34||ce===39||ce===47||ce===60||ce===61||ce===62||ce===96||V_(ce)?C(ce):(s.consume(ce),M)}function I(ce){return ce===47||ce===62||oh(ce)?w(ce):n(ce)}function D(ce){return ce===62?(s.consume(ce),F):n(ce)}function F(ce){return ce===null||uc(ce)?q(ce):oh(ce)?(s.consume(ce),F):n(ce)}function q(ce){return ce===45&&a===2?(s.consume(ce),K):ce===60&&a===1?(s.consume(ce),Z):ce===62&&a===4?(s.consume(ce),J):ce===63&&a===3?(s.consume(ce),ae):ce===93&&a===5?(s.consume(ce),re):uc(ce)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(wIn,te,G)(ce)):ce===null||uc(ce)?(s.exit("htmlFlowData"),G(ce)):(s.consume(ce),q)}function G(ce){return s.check(jIn,V,te)(ce)}function V(ce){return s.enter("lineEnding"),s.consume(ce),s.exit("lineEnding"),H}function H(ce){return ce===null||uc(ce)?G(ce):(s.enter("htmlFlowData"),q(ce))}function K(ce){return ce===45?(s.consume(ce),ae):q(ce)}function Z(ce){return ce===47?(s.consume(ce),l="",oe):q(ce)}function oe(ce){if(ce===62){const ve=l.toLowerCase();return r2t.includes(ve)?(s.consume(ce),J):q(ce)}return E4(ce)&&l.length<8?(s.consume(ce),l+=String.fromCharCode(ce),oe):q(ce)}function re(ce){return ce===93?(s.consume(ce),ae):q(ce)}function ae(ce){return ce===62?(s.consume(ce),J):ce===45&&a===2?(s.consume(ce),ae):q(ce)}function J(ce){return ce===null||uc(ce)?(s.exit("htmlFlowData"),te(ce)):(s.consume(ce),J)}function te(ce){return s.exit("htmlFlow"),t(ce)}}function SIn(s,t,n){const r=this;return a;function a(l){return uc(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),i):n(l)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function CIn(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(a8e,t,n)}}const AIn={name:"htmlText",tokenize:EIn};function EIn(s,t,n){const r=this;let a,i,l;return o;function o(ae){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(ae),c}function c(ae){return ae===33?(s.consume(ae),d):ae===47?(s.consume(ae),C):ae===63?(s.consume(ae),w):E4(ae)?(s.consume(ae),M):n(ae)}function d(ae){return ae===45?(s.consume(ae),u):ae===91?(s.consume(ae),i=0,f):E4(ae)?(s.consume(ae),b):n(ae)}function u(ae){return ae===45?(s.consume(ae),p):n(ae)}function h(ae){return ae===null?n(ae):ae===45?(s.consume(ae),m):uc(ae)?(l=h,Z(ae)):(s.consume(ae),h)}function m(ae){return ae===45?(s.consume(ae),p):h(ae)}function p(ae){return ae===62?K(ae):ae===45?m(ae):h(ae)}function f(ae){const J="CDATA[";return ae===J.charCodeAt(i++)?(s.consume(ae),i===J.length?g:f):n(ae)}function g(ae){return ae===null?n(ae):ae===93?(s.consume(ae),v):uc(ae)?(l=g,Z(ae)):(s.consume(ae),g)}function v(ae){return ae===93?(s.consume(ae),y):g(ae)}function y(ae){return ae===62?K(ae):ae===93?(s.consume(ae),y):g(ae)}function b(ae){return ae===null||ae===62?K(ae):uc(ae)?(l=b,Z(ae)):(s.consume(ae),b)}function w(ae){return ae===null?n(ae):ae===63?(s.consume(ae),S):uc(ae)?(l=w,Z(ae)):(s.consume(ae),w)}function S(ae){return ae===62?K(ae):w(ae)}function C(ae){return E4(ae)?(s.consume(ae),E):n(ae)}function E(ae){return ae===45||ij(ae)?(s.consume(ae),E):P(ae)}function P(ae){return uc(ae)?(l=P,Z(ae)):oh(ae)?(s.consume(ae),P):K(ae)}function M(ae){return ae===45||ij(ae)?(s.consume(ae),M):ae===47||ae===62||V_(ae)?I(ae):n(ae)}function I(ae){return ae===47?(s.consume(ae),K):ae===58||ae===95||E4(ae)?(s.consume(ae),D):uc(ae)?(l=I,Z(ae)):oh(ae)?(s.consume(ae),I):K(ae)}function D(ae){return ae===45||ae===46||ae===58||ae===95||ij(ae)?(s.consume(ae),D):F(ae)}function F(ae){return ae===61?(s.consume(ae),q):uc(ae)?(l=F,Z(ae)):oh(ae)?(s.consume(ae),F):I(ae)}function q(ae){return ae===null||ae===60||ae===61||ae===62||ae===96?n(ae):ae===34||ae===39?(s.consume(ae),a=ae,G):uc(ae)?(l=q,Z(ae)):oh(ae)?(s.consume(ae),q):(s.consume(ae),V)}function G(ae){return ae===a?(s.consume(ae),a=void 0,H):ae===null?n(ae):uc(ae)?(l=G,Z(ae)):(s.consume(ae),G)}function V(ae){return ae===null||ae===34||ae===39||ae===60||ae===61||ae===96?n(ae):ae===47||ae===62||V_(ae)?I(ae):(s.consume(ae),V)}function H(ae){return ae===47||ae===62||V_(ae)?I(ae):n(ae)}function K(ae){return ae===62?(s.consume(ae),s.exit("htmlTextData"),s.exit("htmlText"),t):n(ae)}function Z(ae){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(ae),s.exit("lineEnding"),oe}function oe(ae){return oh(ae)?np(s,re,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ae):re(ae)}function re(ae){return s.enter("htmlTextData"),l(ae)}}const Vnt={name:"labelEnd",resolveAll:LIn,resolveTo:IIn,tokenize:DIn},TIn={tokenize:RIn},MIn={tokenize:FIn},PIn={tokenize:OIn};function LIn(s){let t=-1;const n=[];for(;++t=3&&(d===null||uc(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),oh(d)?np(s,o,"whitespace")(d):o(d))}}const c_={continuation:{tokenize:KIn},exit:ZIn,name:"list",tokenize:WIn},HIn={partial:!0,tokenize:XIn},GIn={partial:!0,tokenize:YIn};function WIn(s,t,n){const r=this,a=r.events[r.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,l=0;return o;function o(p){const f=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:IWe(p)){if(r.containerState.type||(r.containerState.type=f,s.enter(f,{_container:!0})),f==="listUnordered")return s.enter("listItemPrefix"),p===42||p===45?s.check(oCe,n,d)(p):d(p);if(!r.interrupt||p===49)return s.enter("listItemPrefix"),s.enter("listItemValue"),c(p)}return n(p)}function c(p){return IWe(p)&&++l<10?(s.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(s.exit("listItemValue"),d(p)):n(p)}function d(p){return s.enter("listItemMarker"),s.consume(p),s.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,s.check(a8e,r.interrupt?n:u,s.attempt(HIn,m,h))}function u(p){return r.containerState.initialBlankLine=!0,i++,m(p)}function h(p){return oh(p)?(s.enter("listItemPrefixWhitespace"),s.consume(p),s.exit("listItemPrefixWhitespace"),m):n(p)}function m(p){return r.containerState.size=i+r.sliceSerialize(s.exit("listItemPrefix"),!0).length,t(p)}}function KIn(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(a8e,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,np(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!oh(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s.attempt(GIn,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,np(s,s.attempt(c_,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function YIn(s,t,n){const r=this;return np(s,a,"listItemIndent",r.containerState.size+1);function a(i){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(i):n(i)}}function ZIn(s){s.exit(this.containerState.type)}function XIn(s,t,n){const r=this;return np(s,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const l=r.events[r.events.length-1];return!oh(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const a2t={name:"setextUnderline",resolveTo:QIn,tokenize:JIn};function QIn(s,t){let n=s.length,r,a,i;for(;n--;)if(s[n][0]==="enter"){if(s[n][1].type==="content"){r=n;break}s[n][1].type==="paragraph"&&(a=n)}else s[n][1].type==="content"&&s.splice(n,1),!i&&s[n][1].type==="definition"&&(i=n);const l={type:"setextHeading",start:{...s[r][1].start},end:{...s[s.length-1][1].end}};return s[a][1].type="setextHeadingText",i?(s.splice(a,0,["enter",l,t]),s.splice(i+1,0,["exit",s[r][1],t]),s[r][1].end={...s[i][1].end}):s[r][1]=l,s.push(["exit",l,t]),s}function JIn(s,t,n){const r=this;let a;return i;function i(d){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(s.enter("setextHeadingLine"),a=d,l(d)):n(d)}function l(d){return s.enter("setextHeadingLineSequence"),o(d)}function o(d){return d===a?(s.consume(d),o):(s.exit("setextHeadingLineSequence"),oh(d)?np(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||uc(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const e8n={tokenize:t8n};function t8n(s){const t=this,n=s.attempt(a8e,r,s.attempt(this.parser.constructs.flowInitial,a,np(s,s.attempt(this.parser.constructs.flow,a,s.attempt(iIn,a)),"linePrefix")));return n;function r(i){if(i===null){s.consume(i);return}return s.enter("lineEndingBlank"),s.consume(i),s.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(i){if(i===null){s.consume(i);return}return s.enter("lineEnding"),s.consume(i),s.exit("lineEnding"),t.currentConstruct=void 0,n}}const s8n={resolveAll:VYt()},n8n=qYt("string"),r8n=qYt("text");function qYt(s){return{resolveAll:VYt(s==="text"?a8n:void 0),tokenize:t};function t(n){const r=this,a=this.parser.constructs[s],i=n.attempt(a,l,o);return l;function l(u){return d(u)?i(u):o(u)}function o(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),c}function c(u){return d(u)?(n.exit("data"),i(u)):(n.consume(u),c)}function d(u){if(u===null)return!0;const h=a[u];let m=-1;if(h)for(;++m-1){const o=l[0];typeof o=="string"?l[0]=o.slice(r):l.shift()}i>0&&l.push(s[a].slice(0,i))}return l}function y8n(s,t){let n=-1;const r=[];let a;for(;++n0){const ms=qt.tokenStack[qt.tokenStack.length-1];(ms[1]||o2t).call(qt,void 0,ms[0])}for(lt.position={start:PT(ut.length>0?ut[0][1].start:{line:1,column:1,offset:0}),end:PT(ut.length>0?ut[ut.length-2][1].end:{line:1,column:1,offset:0})},Zt=-1;++Zt0&&(r.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),s.patch(t,i),i=s.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},s.patch(t,i),i}function P8n(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function L8n(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function I8n(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=ZW(r.toLowerCase()),i=s.footnoteOrder.indexOf(r);let l,o=s.footnoteCounts.get(r);o===void 0?(o=0,s.footnoteOrder.push(r),l=s.footnoteOrder.length):l=i+1,o+=1,s.footnoteCounts.set(r,o);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};s.patch(t,c);const d={type:"element",tagName:"sup",properties:{},children:[c]};return s.patch(t,d),s.applyData(t,d)}function D8n(s,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function R8n(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function WYt(s,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const a=s.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const l=a[a.length-1];return l&&l.type==="text"?l.value+=r:a.push({type:"text",value:r}),a}function F8n(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return WYt(s,t);const a={src:ZW(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"img",properties:a,children:[]};return s.patch(t,i),s.applyData(t,i)}function O8n(s,t){const n={src:ZW(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return s.patch(t,r),s.applyData(t,r)}function z8n(s,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};s.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return s.patch(t,r),s.applyData(t,r)}function B8n(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return WYt(s,t);const a={href:ZW(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"a",properties:a,children:s.all(t)};return s.patch(t,i),s.applyData(t,i)}function $8n(s,t){const n={href:ZW(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:s.all(t)};return s.patch(t,r),s.applyData(t,r)}function U8n(s,t,n){const r=s.all(t),a=n?q8n(n):KYt(t),i={},l=[];if(typeof t.checked=="boolean"){const u=r[0];let h;u&&u.type==="element"&&u.tagName==="p"?h=u:(h={type:"element",tagName:"p",properties:{},children:[]},r.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o1}function V8n(s,t){const n={},r=s.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++a0){const l={type:"element",tagName:"tbody",properties:{},children:s.wrap(n,!0)},o=Ont(t.children[1]),c=AYt(t.children[t.children.length-1]);o&&c&&(l.position={start:o,end:c}),a.push(l)}const i={type:"element",tagName:"table",properties:{},children:s.wrap(a,!0)};return s.patch(t,i),s.applyData(t,i)}function Y8n(s,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,o=l?l.length:t.children.length;let c=-1;const d=[];for(;++c0,!0),r[0]),a=r.index+r[0].length,r=n.exec(t);return i.push(d2t(t.slice(a),a>0,!1)),i.join("")}function d2t(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===l2t||i===c2t;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===l2t||i===c2t;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function Q8n(s,t){const n={type:"text",value:X8n(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function J8n(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const eDn={blockquote:E8n,break:T8n,code:M8n,delete:P8n,emphasis:L8n,footnoteReference:I8n,heading:D8n,html:R8n,imageReference:F8n,image:O8n,inlineCode:z8n,linkReference:B8n,link:$8n,listItem:U8n,list:V8n,paragraph:H8n,root:G8n,strong:W8n,table:K8n,tableCell:Z8n,tableRow:Y8n,text:Q8n,thematicBreak:J8n,toml:qce,yaml:qce,definition:qce,footnoteDefinition:qce};function qce(){}const YYt=-1,i8e=0,dee=1,WTe=2,Hnt=3,Gnt=4,Wnt=5,Knt=6,ZYt=7,XYt=8,QYt=typeof self=="object"?self:globalThis,u2t=(s,t)=>{switch(s){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+s)}return new QYt[s](t)},tDn=(s,t)=>{const n=(a,i)=>(s.set(i,a),a),r=a=>{if(s.has(a))return s.get(a);const[i,l]=t[a];switch(i){case i8e:case YYt:return n(l,a);case dee:{const o=n([],a);for(const c of l)o.push(r(c));return o}case WTe:{const o=n({},a);for(const[c,d]of l)o[r(c)]=r(d);return o}case Hnt:return n(new Date(l),a);case Gnt:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case Wnt:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case Knt:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case ZYt:{const{name:o,message:c}=l;return n(typeof QYt[o]=="function"?u2t(o,c):new Error(c),a)}case XYt:return n(BigInt(l),a);case"BigInt":return n(Object(BigInt(l)),a);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:o}=new Uint8Array(l);return n(new DataView(o),l)}}return n(u2t(i,l),a)};return r},h2t=s=>tDn(new Map,s)(0),QR="",{toString:sDn}={},{keys:nDn}=Object,_Z=s=>{const t=typeof s;if(t!=="object"||!s)return[i8e,t];const n=sDn.call(s).slice(8,-1);switch(n){case"Array":return[dee,QR];case"Object":return[WTe,QR];case"Date":return[Hnt,QR];case"RegExp":return[Gnt,QR];case"Map":return[Wnt,QR];case"Set":return[Knt,QR];case"DataView":return[dee,n]}return n.includes("Array")?[dee,n]:s instanceof Error?[ZYt,s.name||"Error"]:[WTe,n]},Vce=([s,t])=>s===i8e&&(t==="function"||t==="symbol"),rDn=(s,t,n,r)=>{const a=(l,o)=>{const c=r.push(l)-1;return n.set(o,c),c},i=l=>{if(n.has(l))return n.get(l);let[o,c]=_Z(l);switch(o){case i8e:{let u=l;switch(c){case"bigint":o=XYt,u=l.toString();break;case"function":case"symbol":if(s)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return a([YYt],l)}return a([o,u],l)}case dee:{if(c){let m=l;return c==="DataView"?m=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(l)),a([c,[...m]],l)}const u=[],h=a([o,u],l);for(const m of l)u.push(i(m));return h}case WTe:{if(c)switch(c){case"BigInt":return a([c,l.toString()],l);case"Boolean":case"Number":case"String":return a([c,l.valueOf()],l)}if(t&&"toJSON"in l)return i(l.toJSON());const u=[],h=a([o,u],l);for(const m of nDn(l))(s||!Vce(_Z(l[m])))&&u.push([i(m),i(l[m])]);return h}case Hnt:return a([o,isNaN(l.getTime())?QR:l.toISOString()],l);case Gnt:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case Wnt:{const u=[],h=a([o,u],l);for(const[m,p]of l)(s||!(Vce(_Z(m))||Vce(_Z(p))))&&u.push([i(m),i(p)]);return h}case Knt:{const u=[],h=a([o,u],l);for(const m of l)(s||!Vce(_Z(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},m2t=(s,{json:t,lossy:n}={})=>{const r=[];return rDn(!(t||n),!!t,new Map,r)(s),r},KTe=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?h2t(m2t(s,t)):structuredClone(s):(s,t)=>h2t(m2t(s,t));function aDn(s,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function iDn(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function oDn(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||aDn,r=s.options.footnoteBackLabel||iDn,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&f.push({type:"text",value:" "});let b=typeof n=="string"?n:n(c,p);typeof b=="string"&&(b={type:"text",value:b}),f.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(b)?b:[b]})}const v=u[u.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const b=v.children[v.children.length-1];b&&b.type==="text"?b.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else u.push(...f);const y={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,y),o.push(y)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...KTe(l),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:s.wrap(o,!0)},{type:"text",value:` `}]}}const JYt=function(s){if(s==null)return uDn;if(typeof s=="function")return o8e(s);if(typeof s=="object")return Array.isArray(s)?lDn(s):cDn(s);if(typeof s=="string")return dDn(s);throw new Error("Expected function, string, or object as test")};function lDn(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let p=eZt,f,g,v;if((!t||i(c,d,u[u.length-1]||void 0))&&(p=xDn(n(c,u)),p[0]===p2t))return p;if("children"in c&&c.children){const y=c;if(y.children&&p[0]!==pDn)for(g=(r?y.children.length:-1)+l,v=u.concat(y);g>-1&&g0&&n.push({type:"text",value:` `}),n}function f2t(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function x2t(s,t){const n=yDn(s,t),r=n.one(s,void 0),a=oDn(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function jDn(s,t){return s&&"run"in s?async function(n,r){const a=x2t(n,{file:r,...t});await s.run(a,r)}:function(n,r){return x2t(n,{file:r,...s||t})}}function g2t(s){if(s)throw s}var lCe=Object.prototype.hasOwnProperty,sZt=Object.prototype.toString,y2t=Object.defineProperty,v2t=Object.getOwnPropertyDescriptor,b2t=function(t){return typeof Array.isArray=="function"?Array.isArray(t):sZt.call(t)==="[object Array]"},_2t=function(t){if(!t||sZt.call(t)!=="[object Object]")return!1;var n=lCe.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&lCe.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||lCe.call(t,a)},w2t=function(t,n){y2t&&n.name==="__proto__"?y2t(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},j2t=function(t,n){if(n==="__proto__")if(lCe.call(t,n)){if(v2t)return v2t(t,n).value}else return;return t[n]},NDn=function s(){var t,n,r,a,i,l,o=arguments[0],c=1,d=arguments.length,u=!1;for(typeof o=="boolean"&&(u=o,o=arguments[1]||{},c=2),(o==null||typeof o!="object"&&typeof o!="function")&&(o={});cl.length;let c;o&&l.push(a);try{c=s.apply(this,l)}catch(d){const u=d;if(o&&n)throw u;return a(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(i,a):c instanceof Error?a(c):i(c))}function a(l,...o){n||(n=!0,t(l,...o))}function i(l){a(null,l)}}const W5={basename:CDn,dirname:ADn,extname:EDn,join:TDn,sep:"/"};function CDn(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');qae(s);let n=0,r=-1,a=s.length,i;if(t===void 0||t.length===0||t.length>s.length){for(;a--;)if(s.codePointAt(a)===47){if(i){n=a+1;break}}else r<0&&(i=!0,r=a+1);return r<0?"":s.slice(n,r)}if(t===s)return"";let l=-1,o=t.length-1;for(;a--;)if(s.codePointAt(a)===47){if(i){n=a+1;break}}else l<0&&(i=!0,l=a+1),o>-1&&(s.codePointAt(a)===t.codePointAt(o--)?o<0&&(r=a):(o=-1,r=l));return n===r?r=l:r<0&&(r=s.length),s.slice(n,r)}function ADn(s){if(qae(s),s.length===0)return".";let t=-1,n=s.length,r;for(;--n;)if(s.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?s.codePointAt(0)===47?"/":".":t===1&&s.codePointAt(0)===47?"//":s.slice(0,t)}function EDn(s){qae(s);let t=s.length,n=-1,r=0,a=-1,i=0,l;for(;t--;){const o=s.codePointAt(t);if(o===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),o===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||n<0||i===0||i===1&&a===n-1&&a===r+1?"":s.slice(a,n)}function TDn(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function PDn(s,t){let n="",r=0,a=-1,i=0,l=-1,o,c;for(;++l<=s.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),a=l,i=0;continue}}else if(n.length>0){n="",r=0,a=l,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+s.slice(a+1,l):n=s.slice(a+1,l),r=l-a-1;a=l,i=0}else o===46&&i>-1?i++:i=-1}return n}function qae(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const LDn={cwd:IDn};function IDn(){return"/"}function OWe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function DDn(s){if(typeof s=="string")s=new URL(s);else if(!OWe(s)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+s+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(s.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return RDn(s)}function RDn(s){if(s.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=s.pathname;let n=-1;for(;++n0){let[p,...f]=u;const g=r[m][1];FWe(g)&&FWe(p)&&(p=mze(!0,g,p)),r[m]=[d,p,...f]}}}}const BDn=new Ynt().freeze();function gze(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function yze(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function vze(s,t){if(t)throw new Error("Cannot call `"+s+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function k2t(s){if(!FWe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function S2t(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function Hce(s){return $Dn(s)?s:new nZt(s)}function $Dn(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function UDn(s){return typeof s=="string"||qDn(s)}function qDn(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const VDn="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",C2t=[],A2t={allowDangerousHtml:!0},HDn=/^(https?|ircs?|mailto|xmpp)$/i,GDn=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function WDn(s){const t=KDn(s),n=YDn(s);return ZDn(t.runSync(t.parse(n),n),s)}function KDn(s){const t=s.rehypePlugins||C2t,n=s.remarkPlugins||C2t,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...A2t}:A2t;return BDn().use(A8n).use(n).use(jDn,r).use(t)}function YDn(s){const t=s.children||"",n=new nZt;return typeof t=="string"&&(n.value=t),n}function ZDn(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||XDn;for(const u of GDn)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+VDn+u.id,void 0);return tZt(s,d),oLn(s,{Fragment:e.Fragment,components:a,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function d(u,h,m){if(u.type==="raw"&&m&&typeof h=="number")return l?m.children.splice(h,1):m.children[h]={type:"text",value:u.value},h;if(u.type==="element"){let p;for(p in dze)if(Object.hasOwn(dze,p)&&Object.hasOwn(u.properties,p)){const f=u.properties[p],g=dze[p];(g===null||g.includes(u.tagName))&&(u.properties[p]=c(String(f||""),p,u))}}if(u.type==="element"){let p=n?!n.includes(u.tagName):i?i.includes(u.tagName):!1;if(!p&&r&&typeof h=="number"&&(p=!r(u,h,m)),p&&m&&typeof h=="number")return o&&u.children?m.children.splice(h,1,...u.children):m.children.splice(h,1),h}}}function XDn(s){const t=s.indexOf(":"),n=s.indexOf("?"),r=s.indexOf("#"),a=s.indexOf("/");return t===-1||a!==-1&&t>a||n!==-1&&t>n||r!==-1&&t>r||HDn.test(s.slice(0,t))?s:""}const QDn={a:({href:s,children:t})=>{const n=s||"",r=n.startsWith("/"),a="inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 font-medium text-primary no-underline transition-colors hover:bg-primary/20";return r?e.jsxs(or,{to:n,className:a,children:[t,e.jsx(QO,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(QO,{className:"h-3 w-3"})]})}},JDn=["What should I do first thing every morning in LevelUp?","How do I get my website showing up on Google?","Write me a follow-up text for a lead who toured a home last week","Where do I create social posts for a new listing?"];function eRn(){var h,m,p;const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(""),[i,l]=_.useState(!1),o=_.useRef(null),c=_.useRef(null),d=((h=s==null?void 0:s.user_metadata)==null?void 0:h.first_name)||((p=(m=s==null?void 0:s.user_metadata)==null?void 0:m.full_name)==null?void 0:p.split(" ")[0])||"";_.useEffect(()=>{var f;(f=c.current)==null||f.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async f=>{var b;const g=f.trim();if(!g||i)return;const v=[...t,{role:"user",content:g}];n([...v,{role:"assistant",content:""}]),a(""),l(!0);const y=new AbortController;o.current=y;try{const{data:w}=await U.auth.getSession(),S=(b=w.session)==null?void 0:b.access_token,C=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/levelup-assistant",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({messages:v,agentName:d}),signal:y.signal});if(!C.ok||!C.body){const D=await C.json().catch(()=>({error:"Something went wrong."}));throw new Error(D.error||"Something went wrong.")}const E=C.body.getReader(),P=new TextDecoder;let M="",I="";for(;;){const{done:D,value:F}=await E.read();if(D)break;M+=P.decode(F,{stream:!0});const q=M.split(` `);M=q.pop()||"";for(const G of q){const V=G.trim();if(!V.startsWith("data:"))continue;const H=V.slice(5).trim();if(!(!H||H==="[DONE]"))try{const K=JSON.parse(H);K.delta&&(I+=K.delta,n(Z=>{const oe=[...Z];return oe[oe.length-1]={role:"assistant",content:I},oe}))}catch{}}}I||n(D=>{const F=[...D];return F[F.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},F})}catch(w){w.name==="AbortError"?n(S=>S.filter((C,E)=>!(E===S.length-1&&!C.content))):(ne.error(w.message||"The assistant is unavailable right now."),n(S=>S.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx($s,{children:e.jsxs("div",{className:"mx-auto flex h-[calc(100vh-7rem)] w-full max-w-3xl flex-col p-4 md:p-6",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(K4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Ask LevelUp AI"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your in-app guide to the platform and your business."})]})]}),t.length>0&&e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n([]),children:[e.jsx(Dx,{className:"h-4 w-4"})," New chat"]})]}),e.jsx("div",{ref:c,className:"flex-1 space-y-5 overflow-y-auto rounded-2xl border bg-card/40 p-4",children:t.length===0?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-center",children:[e.jsx("span",{className:"mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10",children:e.jsx(K4,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"text-base font-semibold",children:d?`Hey ${d} — what can I help with?`:"What can I help with?"}),e.jsx("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:"I know every tool in LevelUp and can help you write, plan, and find things fast."}),e.jsx("div",{className:"mt-5 grid w-full max-w-lg gap-2 sm:grid-cols-2",children:JDn.map(f=>e.jsx("button",{onClick:()=>u(f),className:"rounded-xl border bg-background px-3 py-2.5 text-left text-sm transition-colors hover:border-primary/40 hover:bg-muted/50",children:f},f))})]}):t.map((f,g)=>e.jsx("div",{className:Ct("flex",f.role==="user"?"justify-end":"justify-start"),children:f.role==="user"?e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground",children:e.jsx("p",{className:"whitespace-pre-wrap break-words",children:f.content})}):e.jsx("div",{className:"max-w-full text-sm leading-relaxed text-foreground",children:f.content?e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-p:my-2 prose-ul:my-2 prose-headings:mt-4 prose-headings:mb-2",children:e.jsx(WDn,{components:QDn,children:f.content})}):e.jsx("span",{className:"animate-pulse text-muted-foreground",children:"Thinking…"})})},g))}),e.jsxs("div",{className:"mt-3 flex items-end gap-2 rounded-2xl border bg-background p-2",children:[e.jsx(Ps,{value:r,onChange:f=>a(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),u(r))},rows:1,placeholder:"Ask anything about LevelUp or your business…",className:"min-h-[44px] resize-none border-0 bg-transparent shadow-none focus-visible:ring-0"}),i?e.jsx(z,{size:"icon",variant:"secondary",onClick:()=>{var f;return(f=o.current)==null?void 0:f.abort()},children:e.jsx(jb,{className:"h-4 w-4"})}):e.jsx(z,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Fr,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-2 text-center text-[11px] text-muted-foreground",children:"LevelUp AI can make mistakes. Double-check anything important."})]})})}function tRn({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 Gce({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:Ct("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(yi,{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 sRn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),p=m<12?"Good morning":m<17?"Good afternoon":"Good evening",f=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[p,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(un,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(tRn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Gce,{icon:e.jsx(bu,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${f}% 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(Gc,{className:"h-3.5 w-3.5"})})}),e.jsx(Gce,{icon:e.jsx(vu,{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(Gce,{icon:e.jsx(Zr,{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(Gce,{icon:e.jsx(On,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const E2t="agent-os-onboarding-completed",Wce=[{icon:Xf,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:cf,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:On,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:gc,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:Ko,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:wl,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"]}],nRn=()=>{const[s,t]=_.useState(!1),[n,r]=_.useState(0),[a,i]=_.useState(!1);_.useEffect(()=>{if(!localStorage.getItem(E2t)){const f=setTimeout(()=>t(!0),500);return()=>clearTimeout(f)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(E2t,"true"),t(!1)},d=Wce[n],u=d.icon,h=n===Wce.length-1,m=p=>{p||c(),t(p)};return e.jsx(Is,{open:s,onOpenChange:m,children:e.jsxs(Ls,{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(Os,{className:"text-center sm:text-center pb-2",children:[e.jsx(Rs,{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(_r,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((p,f)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+f*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(Wr,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:p})]},f))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:Wce.map((p,f)=>e.jsx("button",{onClick:()=>{f!==n&&(i(!0),setTimeout(()=>{r(f),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${f===n?"w-8 bg-gradient-to-r "+d.bgGradient:f{const{user:s}=hs();return rt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},aRn=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Uh(new Date,r);await U.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await U.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"]}),la({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{la({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},iRn=()=>{const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),la({title:"Snooze cancelled"})},onError:t=>{la({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},oRn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function l8e({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=_.useState(null),l=aRn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Ys(Uh(new Date,d),"MMM d, yyyy");return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(_r,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:oRn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Ct("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(ya,{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(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const lRn={Crown:Kf,FileText:$r,Users:On,Globe:Wo,Star:Ia,Phone:va,MessageSquare:qi,PenTool:QA,Video:Xr,Gift:Ko};function cRn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=zn(),[c,d]=_.useState("name"),[u,h]=_.useState("asc"),[m,p]=_.useState(null),[f,g]=_.useState(""),v=C=>{c===C?h(E=>E==="asc"?"desc":"asc"):(d(C),h("asc"))},y=_.useMemo(()=>[...s].sort((C,E)=>{var M,I;let P=0;switch(c){case"name":{const D=`${C.contact.first_name} ${C.contact.last_name||""}`.toLowerCase(),F=`${E.contact.first_name} ${E.contact.last_name||""}`.toLowerCase();P=D.localeCompare(F);break}case"relationship_type":P=(C.relationshipTypeName||"").localeCompare(E.relationshipTypeName||"");break;case"action_type":P=(((M=C.actionType)==null?void 0:M.name)||"").localeCompare(((I=E.actionType)==null?void 0:I.name)||"");break;case"last_touch":P=(C.monthNumber||0)-(E.monthNumber||0);break}return u==="asc"?P:-P}),[s,c,u]),b=C=>lRn[C||"Phone"]||va,w=({field:C,children:E})=>e.jsxs(z,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>v(C),children:[E,c===C?u==="asc"?e.jsx(ap,{className:"ml-2 h-4 w-4"}):e.jsx(Vf,{className:"ml-2 h-4 w-4"}):e.jsx(Og,{className:"ml-2 h-4 w-4 opacity-50"})]}),S=(C,E,P)=>{p(C),g(`${E} ${P||""}`.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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[180px]",children:e.jsx(w,{field:"name",children:"Contact"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(w,{field:"relationship_type",children:"Type"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(w,{field:"action_type",children:"Action"})}),e.jsx(Tt,{className:"w-[130px]",children:"Phone"}),e.jsx(Tt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(Qa,{children:y.map((C,E)=>{var q,G,V,H,K,Z;const P=C.isSpecialDate,M=C.specialDateType,I=P?M==="birthday"?Hf:sa:b(((q=C.actionType)==null?void 0:q.icon)||null),D=C.contact.phone,F=C.contact.email;return e.jsxs(fn,{className:Ct("hover:bg-muted/50 transition-colors",P&&M==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",P&&M==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(yt,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${C.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[C.contact.first_name," ",C.contact.last_name]})})}),e.jsx(yt,{children:C.relationshipTypeName?e.jsx(ze,{variant:"secondary",className:"text-xs",children:C.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(yt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:P?e.jsx(ze,{className:Ct("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(Hf,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(I,{className:"h-3 w-3"}),(G=C.actionType)==null?void 0:G.name]})})}),e.jsx(yt,{children:D?e.jsx("span",{className:"text-sm font-mono",children:C.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[D&&e.jsx("a",{href:`tel:${C.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(va,{className:"h-3.5 w-3.5"})}),D&&e.jsx("a",{href:a(C.contact.phone,(V=C.script)==null?void 0:V.script_body,C.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(qi,{className:"h-3.5 w-3.5"})}),F&&(l?e.jsx("button",{onClick:()=>l({id:C.contact.id,first_name:C.contact.first_name,last_name:C.contact.last_name,email:C.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(on,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(C.contact.email,(H=C.script)==null?void 0:H.script_body,(K=C.script)==null?void 0:K.email_subject,(Z=C.actionType)==null?void 0:Z.name,C.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(on,{className:"h-3.5 w-3.5"})})),P&&e.jsxs("button",{onClick:()=>{const oe=`${C.contact.first_name}${C.contact.last_name?" "+C.contact.last_name:""}`,re=M==="birthday"?"birthday":"home_anniversary",ae=new URLSearchParams({cardType:re,contactId:C.contact.id,name:oe,...C.contact.address?{address:C.contact.address}:{},...M==="anniversary"&&C.contact.home_anniversary?{date:C.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${ae.toString()}`)},className:Ct("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(on,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>S(C.contact.id,C.contact.first_name,C.contact.last_name),title:"Snooze",children:e.jsx(S0,{className:"h-3.5 w-3.5"})}),e.jsxs(z,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var oe;return t(C.contact.id,C.actionType.id,(oe=C.script)==null?void 0:oe.id)},disabled:r,children:[e.jsx(Mr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${C.contact.id}-${E}`)})})]})}),e.jsx(l8e,{open:!!m,onOpenChange:C=>!C&&p(null),contactId:m||"",contactName:f})]})}function dRn(){const s=zn(),{data:t}=sBt(),{data:n}=fae(),r=bLe(),{isGmailConnected:a,gmailEmail:i}=bg(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(new Set),m=zf(new Date),p=Uh(m,30),f=C=>{if(!C)return null;const E=C.split(/[-/T]/);if(E.length<3)return null;const P=parseInt(E[1],10)-1,M=parseInt(E[2],10);return isNaN(P)||isNaN(M)?null:new Date(m.getFullYear(),P,M)},g=_.useMemo(()=>{if(!t)return[];const C=[];for(const E of t){if(E.birthday){const P=f(E.birthday);P&&(hm(P,m)||tC(P,m)&&wS(P,p))&&C.push({contact:E,type:"birthday",date:P,daysUntil:fv(P,m),dateStr:E.birthday})}if(E.home_anniversary){const P=f(E.home_anniversary);P&&(hm(P,m)||tC(P,m)&&wS(P,p))&&C.push({contact:E,type:"anniversary",date:P,daysUntil:fv(P,m),dateStr:E.home_anniversary})}if(E.wedding_anniversary){const P=f(E.wedding_anniversary);P&&(hm(P,m)||tC(P,m)&&wS(P,p))&&C.push({contact:E,type:"wedding_anniversary",date:P,daysUntil:fv(P,m),dateStr:E.wedding_anniversary})}}return C.sort((E,P)=>E.daysUntil-P.daysUntil),C},[t]),v=C=>C==="birthday"?"Birthday":C==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",y=async C=>{const E=(n==null?void 0:n.find(P=>P.name==="Call"))||(n==null?void 0:n[0]);if(E)try{await r.mutateAsync({contactId:C.contact.id,actionTypeId:E.id,notes:`${v(C.type)} outreach`}),h(P=>new Set(P).add(`${C.contact.id}-${C.type}`)),la({title:"Touch logged!",description:`Logged outreach for ${C.contact.first_name}`})}catch{la({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=C=>{const E=`${C.contact.first_name}${C.contact.last_name?" "+C.contact.last_name:""}`,P=C.type==="birthday"?"birthday":C.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:P,contactId:C.contact.id,name:E,...C.contact.address?{address:C.contact.address}:{},...(C.type==="anniversary"||C.type==="wedding_anniversary")&&C.dateStr?{date:C.dateStr}:{}});s(`/mission-control/card-studio?${M.toString()}`)},w=C=>C===0?"Today!":C===1?"Tomorrow":`${C} days`,S=C=>C===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":C<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":C<=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(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:[e.jsx(gc,{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:[g.length," event",g.length!==1?"s":""]})]})}),e.jsxs(Le,{className:"space-y-2",children:[g.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Hf,{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."})]}),g.map((C,E)=>{var D,F;const P=`${C.contact.id}-${C.type}`,M=u.has(P),I=`${((D=C.contact.first_name)==null?void 0:D[0])||""}${((F=C.contact.last_name)==null?void 0:F[0])||""}`.toUpperCase();return e.jsxs("div",{className:Ct("p-3 rounded-lg border transition-colors",C.daysUntil===0&&C.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":C.daysUntil===0&&(C.type==="anniversary"||C.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":C.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(ja,{className:Ct("h-10 w-10",C.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(Na,{className:Ct("text-xs font-medium",C.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:I})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:C.type==="birthday"?"🎂":C.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:[C.contact.first_name," ",C.contact.last_name||""]}),e.jsx(ze,{variant:"outline",className:Ct("text-[10px] shrink-0 whitespace-nowrap",S(C.daysUntil)),children:w(C.daysUntil)})]}),e.jsxs("div",{className:Ct("text-xs flex items-center gap-1.5 mt-0.5",C.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[C.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Hf,{className:"h-3 w-3"})," Birthday"]}):C.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(Fo,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ys(C.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[C.contact.phone&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${C.contact.phone}`,children:e.jsx(va,{className:"h-3.5 w-3.5"})})}),C.contact.phone&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${C.contact.phone}`,children:e.jsx(qi,{className:"h-3.5 w-3.5"})})}),C.contact.email&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:C.contact.id,first_name:C.contact.first_name,last_name:C.contact.last_name,email:C.contact.email}),d(!0)):window.location.href=`mailto:${C.contact.email}`},children:e.jsx(on,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${C.contact.id}`),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsxs(z,{variant:"ghost",size:"sm",className:Ct("h-7 px-2 gap-1 text-xs",C.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 ${C.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>b(C),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(z,{variant:"ghost",size:"icon",className:Ct("h-7 w-7",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>y(C),children:e.jsx(Mr,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${C.contact.id}`),children:e.jsx(xa,{className:"h-3.5 w-3.5"})})]})]},`${P}-${E}`)})]})]}),a&&l&&e.jsx(HN,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function uRn(s){const[t,n]=_.useState([]),[r,a]=_.useState(!1),{data:i,isLoading:l}=rt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await U.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await U.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(f=>f.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:f}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(f||[]).forEach(g=>{m[g.id]=g})}const p=u.map(f=>f.auth_user_id).filter(Boolean);if(p.length>0){const{data:f}=await U.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",p);(f||[]).forEach(g=>{const v=u.find(y=>y.auth_user_id===g.user_id);v&&!v.contact_id&&g.contact_id&&(v.contact_id=g.contact_id),v&&!m[v.contact_id||""]&&g.name&&(m[v.contact_id||v.auth_user_id||""]={first_name:g.name.split(" ")[0],last_name:g.name.split(" ").slice(1).join(" ")||null,email:null,phone:g.phone})})}return u.map(f=>{var g,v;return{...f,contact_name:m[f.contact_id||f.auth_user_id||""]?`${m[f.contact_id||f.auth_user_id||""].first_name} ${m[f.contact_id||f.auth_user_id||""].last_name||""}`.trim():null,contact_email:((g=m[f.contact_id||f.auth_user_id||""])==null?void 0:g.email)||null,contact_phone:((v=m[f.contact_id||f.auth_user_id||""])==null?void 0:v.phone)||null}})},enabled:!!s,refetchInterval:6e4});_.useEffect(()=>{if(!s)return;const u=U.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(f=>f.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(p=>p.id===h.new.id?{...p,...h.new}:p)):h.eventType==="DELETE"&&n(m=>m.filter(p=>p.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{U.removeChannel(u)}},[s]);const o=r&&t.length>0?hRn([...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 hRn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const mRn={property_view:{label:"Viewed",icon:xa,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Pl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:Fo,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function pRn(){const{user:s}=hs(),t=zn(),{isGmailConnected:n,gmailEmail:r}=bg(),{leadSite:a}=mf(),{count:i}=uRn(a==null?void 0:a.id),[l,o]=_.useState(!1),[c,d]=_.useState(null),{data:u,isLoading:h}=rt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await U.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return y},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(y=>y.visitor_name&&y.visitor_name!=="Site Visitor"),p=m.filter(y=>y.activity_type==="new_lead"),f=(u.activities||[]).filter(y=>y.activity_type==="property_view").length,g=(u.activities||[]).filter(y=>y.activity_type==="saved_listing").length,v=y=>{if(y.visitor_email)if(n){const b=(y.visitor_name||"").split(" ");d({id:y.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:y.visitor_email}),o(!0)}else window.location.href=`mailto:${y.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(Wo,{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(z,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(Da,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-emerald-500/5 border border-emerald-200 dark:border-emerald-800",children:[e.jsx(Pl,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:p.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(xa,{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:f}),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(Fo,{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:g}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),m.length>0?e.jsxs("div",{className:"space-y-2",children:[m.slice(0,5).map((y,b)=>{const w=mRn[y.activity_type],S=w.icon,C=Md(new Date(y.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 ${w.bgColor}`,children:e.jsx(S,{className:`h-3.5 w-3.5 ${w.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:()=>{y.contact_id&&t(`/mission-control/contacts/${y.contact_id}`)},children:y.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:w.label}),y.mls_number&&e.jsxs("span",{children:["· MLS# ",y.mls_number]}),y.lead_type&&e.jsxs("span",{children:["· ",y.lead_type]}),e.jsxs("span",{children:["· ",C]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[y.visitor_email&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>v(y),children:e.jsx(on,{className:"h-3.5 w-3.5"})}),y.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${y.visitor_phone}`,children:e.jsx(va,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${y.visitor_phone}`,children:e.jsx(qi,{className:"h-3.5 w-3.5"})})]}),y.contact_id&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${y.contact_id}`),children:e.jsx(yi,{className:"h-3.5 w-3.5"})})]})]},`${y.activity_type}-${y.occurred_at}-${b}`)}),m.length>5&&e.jsxs(z,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(Da,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(be,{children:e.jsxs(Le,{className:"p-6 text-center",children:[e.jsx(pm,{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:f>0?`${f} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(z,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Da,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(HN,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const T2t={Crown:Kf,FileText:$r,Users:On,Globe:Wo,Star:Ia,Phone:va,MessageSquare:qi,PenTool:QA,Video:Xr,Gift:Ko},fRn={"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 xRn(){var ut,lt,qt,zt,Zt,ms;const s=zn(),{user:t}=hs(),{data:n}=Q_(),{data:r}=nBt(),{data:a}=Rb(),{data:i}=fae(),{data:l}=Bet(),o=JBs(),c=_Le(),d=ZBs(90),u=bLe(),[h,m]=_.useState(null),[p,f]=_.useState(null),[g,v]=_.useState(!1),[y,b]=_.useState(""),[w,S]=_.useState(!1),[C,E]=_.useState(""),[P,M]=_.useState(lBt()),[I,D]=_.useState("cards"),[F,q]=_.useState(!1),[G,V]=_.useState(null),[H,K]=_.useState(null),[Z,oe]=_.useState(""),{isGmailConnected:re,gmailEmail:ae}=bg(),J=()=>{const Dt=parseInt(C,10);if(isNaN(Dt)||Dt<1){la({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(Dt),XBs(Dt),S(!1),la({title:"Goal updated",description:`Weekly touch goal set to ${Dt}`})},te=()=>{E(P.toString()),S(!0)};_.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:It}=await U.from("profiles").select("name").eq("id",t.id).single();It!=null&&It.name&&b(It.name.split(" ")[0])})()},[t==null?void 0:t.id]),_.useEffect(()=>{o.mutate()},[]);const ce=zf(new Date),ve=Uh(ce,7),me=Dt=>{if(!Dt)return null;const It=Dt.split(/[-/T]/);if(It.length<3)return null;const qs=parseInt(It[1],10)-1,wt=parseInt(It[2],10);return isNaN(qs)||isNaN(wt)?null:new Date(ce.getFullYear(),qs,wt)},he=(a==null?void 0:a.filter(Dt=>{const It=me(Dt.birthday),qs=me(Dt.home_anniversary);return It&&hm(It,ce)||qs&&hm(qs,ce)}))||[],ge=(a==null?void 0:a.filter(Dt=>{if(!Dt.birthday&&!Dt.home_anniversary)return!1;const It=qs=>{if(!qs)return!1;const wt=me(qs);return wt?tC(wt,ce)&&wS(wt,ve):!1};return It(Dt.birthday)||It(Dt.home_anniversary)}).slice(0,5))||[],Ee=[],Ne=(i==null?void 0:i.find(Dt=>Dt.name==="Call"))||(i==null?void 0:i[0]);for(const Dt of he){const It=me(Dt.birthday),qs=me(Dt.home_anniversary),wt=It&&hm(It,ce),Us=qs&&hm(qs,ce);wt&&Ee.push({contact:Dt,actionType:Ne||{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=(lt=(ut=Dt.tags)==null?void 0:ut[0])==null?void 0:lt.relationship_type)==null?void 0:qt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Us&&Ee.push({contact:Dt,actionType:Ne||{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:((ms=(Zt=(zt=Dt.tags)==null?void 0:zt[0])==null?void 0:Zt.relationship_type)==null?void 0:ms.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Oe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Dt,It)=>{var wt,Us,Es;const qs=i==null?void 0:i[It%((i==null?void 0:i.length)||1)];return qs?{contact:Dt,actionType:qs,planName:"Quick Touch",relationshipTypeName:((Es=(Us=(wt=Dt.tags)==null?void 0:wt[0])==null?void 0:Us.relationship_type)==null?void 0:Es.name)||"",monthNumber:0}:null}).filter(Boolean))||[],ke=[...Ee,...Oe],{data:Ve}=SW(7),_e=(Ve||[]).filter(Dt=>hm(new Date(Dt.completed_at),ce)).length,Ae=_e+ke.length,Se=(a==null?void 0:a.length)??0,We=Ee.length>0?`${Ee.length} celebration${Ee.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.`:ge.length>0?`${ge.length} milestone${ge.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",qe=async(Dt,It,qs)=>{await u.mutateAsync({contactId:Dt,actionTypeId:It,scriptUsedId:qs}),v(!1),f(null)},Be=Dt=>{Dt.script?(f(Dt),v(!0)):qe(Dt.contact.id,Dt.actionType.id)},Ze=Dt=>T2t[Dt||"Phone"]||va,$e=Dt=>T2t[Dt||"Users"]||On,Xe=(Dt,It)=>Dt.replace(/\{\{FirstName\}\}/g,It.first_name).replace(/\{\{LastName\}\}/g,It.last_name||"").replace(/\{\{AgentName\}\}/g,y||"there"),nt=(Dt,It)=>({Call:`Thinking of you, ${It}!`,Text:`Quick hello, ${It}`,Email:`Checking in, ${It}`,"Handwritten Note":`A note for ${It}`,Video:`Video message for ${It}`,Gift:`Something special for you, ${It}`})[Dt]||`Hello ${It}!`,Ge=(Dt,It,qs)=>{const wt=`sms:${Dt}`;if(It&&qs){const Us=Xe(It,qs);return`${wt}?body=${encodeURIComponent(Us)}`}return wt},Je=(Dt,It,qs,wt,Us)=>{const Es=`mailto:${Dt}`,kn=[];if(Us){const Sn=qs||nt(wt||"Email",Us.first_name);if(kn.push(`subject=${encodeURIComponent(Sn)}`),It){const bn=Xe(It,Us);kn.push(`body=${encodeURIComponent(bn)}`)}}return kn.length>0?`${Es}?${kn.join("&")}`:Es};return e.jsxs(e.Fragment,{children:[e.jsxs($s,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex 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(z,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Yh,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(On,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Library"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(Gc,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(sRn,{agentName:y,todayDone:_e,todayTotal:Ae,focusLine:We,weekDone:c.actionsThisWeek,weekGoal:P,streak:c.streak,staleCount:d.count,sphereCount:Se,onEditGoal:te,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(pRn,{}),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(yi,{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 It=$e(Dt.icon),qs=(r==null?void 0:r[Dt.id])||0,wt=h===Dt.id,Us=fRn[Dt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{wt?(m(null),s("/mission-control/contacts")):(m(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 ${wt?Us:"bg-card hover:bg-accent"} `,children:[e.jsx(It,{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 ${wt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:qs})]},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(z,{variant:I==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("cards"),title:"Card view",children:e.jsx(op,{className:"h-4 w-4"})}),e.jsx(z,{variant:I==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("table"),title:"Table view",children:e.jsx(My,{className:"h-4 w-4"})})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-4",children:ke.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(z,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):I==="table"?e.jsx(cRn,{actions:ke,onMarkComplete:qe,onViewScript:Be,isLoading:u.isPending,buildSmsLink:Ge,buildEmailLink:Je,onGmailCompose:re?Dt=>{V(Dt),q(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[ke.map((Dt,It)=>{var cr,Fs,cn,lr,Tn,Yn,fs;const qs=Dt.isSpecialDate,wt=Dt.specialDateType,Us=qs?wt==="birthday"?Hf:sa:Ze(((cr=Dt.actionType)==null?void 0:cr.icon)||null),Es=Dt.contact.phone,kn=Dt.contact.email,Sn=qs?wt==="birthday"?"#EC4899":"#8B5CF6":((Fs=Dt.actionType)==null?void 0:Fs.color)||"#3B82F6",bn=qs?wt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(cn=Dt.actionType)==null?void 0:cn.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${qs?"ring-2 ring-offset-2":""}`,style:qs?{"--tw-ring-color":Sn}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Sn},children:[e.jsx(Us,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:bn})]}),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(va,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ge(Dt.contact.phone,(lr=Dt.script)==null?void 0:lr.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(qi,{className:"h-3 w-3"}),"Text"]})]}),kn&&(re?e.jsxs("button",{onClick:()=>{V({id:Dt.contact.id,first_name:Dt.contact.first_name,last_name:Dt.contact.last_name,email:Dt.contact.email}),q(!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(on,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Je(Dt.contact.email,(Tn=Dt.script)==null?void 0:Tn.script_body,(Yn=Dt.script)==null?void 0:Yn.email_subject,(fs=Dt.actionType)==null?void 0:fs.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(on,{className:"h-3 w-3"}),"Email"]}))]}),qs&&e.jsxs("button",{onClick:()=>{const wn=`${Dt.contact.first_name}${Dt.contact.last_name?" "+Dt.contact.last_name:""}`,As=wt==="birthday"?"birthday":"home_anniversary",Ss=new URLSearchParams({cardType:As,contactId:Dt.contact.id,name:wn,...Dt.contact.address?{address:Dt.contact.address}:{},...wt==="anniversary"&&Dt.contact.home_anniversary?{date:Dt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Ss.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(on,{className:"h-3 w-3"}),"Send ",wt==="birthday"?"Birthday":"Anniversary"," Card"]}),!Es&&!kn&&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(z,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Be(Dt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(z,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{K(Dt.contact.id),oe(`${Dt.contact.first_name} ${Dt.contact.last_name||""}`.trim())},children:[e.jsx(S0,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(z,{size:"sm",className:"flex-1",onClick:()=>{var wn;return qe(Dt.contact.id,Dt.actionType.id,(wn=Dt.script)==null?void 0:wn.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Dt.contact.id+It)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"ghost",className:"h-full w-full",children:[e.jsx(lb,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(qd,{children:e.jsx(ua,{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(vu,{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 ",P," touches"]})]}),e.jsx(Di,{value:Math.min(c.actionsThisWeek/P*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>=P?"Goal hit for the week — anything else is bonus.":`${P-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(Is,{open:w,onOpenChange:S,children:e.jsxs(Ls,{className:"sm:max-w-[360px]",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Set Weekly Goal"}),e.jsx(_r,{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(ee,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(pe,{id:"weekly-goal-ic",type:"number",min:"1",value:C,onChange:Dt=>E(Dt.target.value),placeholder:"20",onKeyDown:Dt=>{Dt.key==="Enter"&&J()}})]}),e.jsx(z,{onClick:J,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(SBt,{}),e.jsx(dRn,{})]})]}),e.jsx(Is,{open:g,onOpenChange:v,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{className:"flex items-center gap-2",children:p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:p.actionType.color||"#3B82F6"}}),p.actionType.name," Script"]})})}),p&&p.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[p.contact.first_name," ",p.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:Xe(p.script.script_body,p.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",className:"flex-1",onClick:()=>v(!1),children:"Close"}),e.jsx(z,{className:"flex-1",onClick:()=>{var Dt;return qe(p.contact.id,p.actionType.id,(Dt=p.script)==null?void 0:Dt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(nRn,{})]}),re&&G&&e.jsx(HN,{open:F,onOpenChange:q,contact:G,gmailEmail:ae}),e.jsx(l8e,{open:!!H,onOpenChange:Dt=>!Dt&&K(null),contactId:H||"",contactName:Z})]})}const rN=s=>(s||"").trim(),rZt=["Home","Vacation home","Work","Mailing","Rental"];function M2t(s){return s?!!(rN(s.address2)||rN(s.address2_city)):!1}function gRn(s){const t=rN(s==null?void 0:s.address),n=rN(s==null?void 0:s.city);return{line:t,city:n,state:rN(s==null?void 0:s.state),zip:rN(s==null?void 0:s.zip_code)||rN(s==null?void 0:s.zip),label:"Home",isSecondary:!1,hasAddress:!!(t||n)}}function zWe(s){const t=rN(s==null?void 0:s.address2),n=rN(s==null?void 0:s.address2_city);return{line:t,city:n,state:rN(s==null?void 0:s.address2_state),zip:rN(s==null?void 0:s.address2_zip),label:rN(s==null?void 0:s.address2_label)||"Second address",isSecondary:!0,hasAddress:!!(t||n)}}function wZ(s){const t=zWe(s);return s!=null&&s.mail_to_secondary&&t.hasAddress?t:gRn(s)}function yRn(s){const t=[s.city,s.state].filter(Boolean).join(", ");return[s.line,[t,s.zip].filter(Boolean).join(" ")].filter(Boolean).join(", ")}const vRn=[{value:"bidirectional",label:"Two-Way",icon:Og,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:ap,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:Vf,tooltip:"Only pull BoldTrail → Agent OS"}];function YTe({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(Oq,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:vRn.map(a=>e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsxs(L7,{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(Tx,{children:a.tooltip})]},a.value))})]})}function bRn(){const s=$t(),[t,n]=_.useState(!1),[r,a]=_.useState(null),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(0),g=_.useRef(!1),{data:v}=rt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:I,error:D}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(D)throw D;return I}}),y=(v==null?void 0:v.sync_direction)||"bidirectional",b=d??y,w=mt({mutationFn:async()=>{const{data:I,error:D}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(D)throw D;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:I=>{u(null),a(I),n(!0)},onError:I=>{ne.error(I.message||"Failed to generate sync preview")}}),S=mt({mutationFn:async()=>{g.current=!1,m("Initializing sync..."),f(5);const{data:I,error:D}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:b}});if(D)throw D;if(I!=null&&I.error)throw new Error(I.error);const F=I;let q=F.sync_log_id,G=F.next_phase,V=F.next_offset,H=F.push_total||0,K=F.pull_total||0,Z=F.update_total||0,oe=0,re=0,ae=0;for(;G!=="finalize"&&!g.current;){const ce=H+K+Z;G==="fetch_bt"?m("Fetching BoldTrail contacts..."):G==="analyze"?(m("Analyzing contacts..."),f(15)):G==="push"?(m(`Pushing contacts to BoldTrail... (${oe}/${H})`),f(ce>0?oe/ce*90:0)):G==="pull"?(m(`Pulling contacts from BoldTrail... (${re}/${K})`),f(ce>0?(H+re)/ce*90:0)):G==="update"&&(m(`Updating existing contacts... (${ae}/${Z})`),f(ce>0?(H+K+ae)/ce*90:0));const{data:ve,error:me}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:G,offset:V,sync_log_id:q,sync_direction:b}});if(me)throw me;if(ve!=null&&ve.error)throw new Error(ve.error);const he=ve;oe+=he.chunk_pushed||0,re+=he.chunk_pulled||0,ae+=he.chunk_updated||0,he.push_total!==void 0&&(H=he.push_total||0),he.pull_total!==void 0&&(K=he.pull_total||0),he.update_total!==void 0&&(Z=he.update_total||0),he.progress&&m(he.progress),G=he.next_phase,V=he.next_offset}m("Finalizing sync..."),f(95);const{data:J,error:te}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:q,sync_direction:b}});if(te)throw te;return f(100),J},onSuccess:I=>{m(null),f(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 D=[`Pushed ${I.contacts_pushed||0}`,`pulled ${I.contacts_pulled||0}`,`updated ${I.contacts_updated||0}`,`skipped ${I.contacts_skipped||0} duplicates`];ne.success(`Sync complete! ${D.join(", ")}.`)},onError:I=>{m(null),f(0),ne.error(I.message||"Sync failed")}});if(!(v!=null&&v.connected))return null;const C=b==="pull_only"?0:(r==null?void 0:r.to_push)??0,E=b==="push_only"?0:(r==null?void 0:r.to_pull)??0,P=(r==null?void 0:r.to_update)??0,M=C>0||E>0||P>0;return e.jsxs(e.Fragment,{children:[e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{variant:"outline",size:"icon",onClick:()=>w.mutate(),disabled:w.isPending,className:"shrink-0",children:w.isPending?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(Og,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Tx,{children:"Sync with BoldTrail"})]}),e.jsx(Is,{open:t,onOpenChange:I=>{S.isPending||n(I)},children:e.jsxs(Ls,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Og,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(_r,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(YTe,{value:b,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 ${b==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:C}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:E}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Vf,{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:P}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(iq,{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(On,{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"]}),P>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(iq,{className:"h-3 w-3 inline mr-1"}),P," contacts have missing fields that will be filled from the other system"]}),C>0&&e.jsxs(f1,{open:i,onOpenChange:l,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3 text-emerald-600"}),C," contacts to push to BoldTrail"]}),e.jsx(cl,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(g1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((I,D)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:I.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:I.email})]},D)),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"]})]})})]}),E>0&&e.jsxs(f1,{open:o,onOpenChange:c,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vf,{className:"h-3 w-3 text-blue-600"}),E," contacts to pull from BoldTrail"]}),e.jsx(cl,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(g1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((I,D)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:I.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:I.email})]},D)),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&&!S.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."}),S.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Di,{value:p||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(z,{variant:"outline",onClick:()=>n(!1),disabled:S.isPending,children:"Cancel"}),e.jsxs(z,{onClick:()=>S.mutate(),disabled:S.isPending||!M,className:"gap-2",children:[S.isPending?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(Og,{className:"h-4 w-4"}),S.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const _Rn=[{key:"first_name",label:"First name"},{key:"last_name",label:"Last name"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Street address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip",label:"ZIP"},{key:"birthday",label:"Birthday"},{key:"home_anniversary",label:"Home anniversary"},{key:"wedding_anniversary",label:"Wedding anniversary"},{key:"spouse_name",label:"Spouse name"},{key:"spouse_email",label:"Spouse email"},{key:"spouse_birthday",label:"Spouse birthday"},{key:"company_name",label:"Company"},{key:"job_title",label:"Job title"},{key:"lead_source",label:"Lead source"},{key:"avatar_url",label:"Photo"}],wRn="id, first_name, last_name, email, phone, address, city, state, zip, birthday, home_anniversary, wedding_anniversary, spouse_name, spouse_email, spouse_birthday, company_name, job_title, lead_source, avatar_url, notes, created_at, updated_at";function ZTe(s){return Object.entries(s).filter(([t,n])=>t!=="id"&&n!==null&&n!==void 0&&String(n).trim()!=="").length}function jRn(s){return rt({queryKey:["contact-duplicates"],enabled:s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await U.rpc("find_duplicate_contacts",{_limit:200});if(n)throw n;return(t??[]).map(r=>({match_type:r.match_type,match_value:r.match_value,contact_ids:r.contact_ids??[],contacts:r.contacts??[]}))}})}function NRn(s,t){return rt({queryKey:["merge-candidates",[...s].sort().join(",")],enabled:t&&s.length>1,queryFn:async()=>{const{data:n,error:r}=await U.from("innercircle_contacts").select(wRn).in("id",s);if(r)throw r;return n??[]}})}function aZt(){const s=$t();return mt({mutationFn:async({primaryId:t,duplicateIds:n,overrides:r})=>{if(r&&Object.keys(r).length>0){const{error:l}=await U.from("innercircle_contacts").update({...r,updated_at:new Date().toISOString()}).eq("id",t);if(l)throw l}const a=[];let i=0;for(const l of n){if(l===t)continue;const{error:o}=await U.rpc("merge_innercircle_contacts",{_primary_id:t,_duplicate_id:l});o?a.push({id:l,message:o.message}):i+=1}return{merged:i,failed:a}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]}),s.invalidateQueries({queryKey:["contact-duplicates"]})}})}function P2t(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function Kce(s,t){const n=s==null?void 0:s[t];return n==null||String(n).trim()===""?null:String(n)}function iZt({open:s,onOpenChange:t,contactIds:n,onMerged:r}){const{data:a,isLoading:i}=NRn(n,s),l=aZt(),[o,c]=_.useState(null),[d,u]=_.useState({}),h=_.useMemo(()=>a??[],[a]);_.useEffect(()=>{if(!s){c(v=>v===null?v:null),u(v=>Object.keys(v).length===0?v:{});return}if(h.length&&!o){const v=[...h].sort((y,b)=>ZTe(b)-ZTe(y))[0];c(v.id)}},[s,h,o]),_.useEffect(()=>{u(v=>Object.keys(v).length===0?v:{})},[o]);const m=_.useMemo(()=>_Rn.map(v=>{const y=h.map(w=>({id:w.id,value:Kce(w,v.key)})).filter(w=>w.value!==null),b=Array.from(new Set(y.map(w=>w.value)));return{...v,values:y,distinct:b}}).filter(v=>v.distinct.length>1),[h]),p=h.find(v=>v.id===o)??null,f=async()=>{if(!p)return;const v={};for(const[y,b]of Object.entries(d)){const w=h.find(C=>C.id===b);if(!w)continue;const S=Kce(w,y);S!==null&&S!==Kce(p,y)&&(v[y]=w[y])}try{const y=await l.mutateAsync({primaryId:p.id,duplicateIds:h.filter(b=>b.id!==p.id).map(b=>b.id),overrides:v});y.failed.length?la({title:`Merged ${y.merged} of ${y.merged+y.failed.length}`,description:y.failed[0].message,variant:"destructive"}):la({title:`Merged into ${P2t(p)}`,description:"Nothing in their history was lost."}),t(!1),r==null||r()}catch(y){la({title:"Could not merge",description:y.message,variant:"destructive"})}},g=n.length>10;return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(u7,{className:"h-4 w-4"}),"Merge contacts"]}),e.jsx(_r,{children:"Choose the record to keep, then pick which details win. Notes, tags, history, deals and tasks from every record stay with the contact you keep."})]}),g?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:"You can merge up to 10 contacts at a time. Please narrow your selection."}):i?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):h.length<2?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:"Pick at least two contacts to merge."}):e.jsx(Ki,{className:"flex-1 -mx-2 px-2",children:e.jsxs("div",{className:"space-y-5 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which record should we keep?"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:h.map(v=>e.jsxs("button",{type:"button",onClick:()=>c(v.id),className:`rounded-lg border p-3 text-left transition-colors ${o===v.id?"border-primary bg-primary/5":"hover:bg-accent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:P2t(v)}),o===v.id&&e.jsx(ze,{variant:"secondary",children:"Keep"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.email||"No email"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.phone||"No phone"}),v.created_at&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Added ",new Date(String(v.created_at)).toLocaleDateString()]})]},v.id))})]}),m.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"These details differ — pick what to keep"}),m.map(v=>{var b;const y=d[v.key]??(p&&Kce(p,v.key)!==null?p.id:(b=v.values[0])==null?void 0:b.id);return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-2 text-xs uppercase tracking-wide text-muted-foreground",children:v.label}),e.jsx("div",{className:"flex flex-wrap gap-2",children:v.values.map(w=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,[v.key]:w.id})),className:`rounded-md border px-2.5 py-1.5 text-sm transition-colors ${y===w.id?"border-primary bg-primary/10 font-medium":"hover:bg-accent text-muted-foreground"}`,children:w.value},w.id))})]},v.key)})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["1 contact will be kept, ",h.length-1," will be removed. Nothing in their history is lost."]})]})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:l.isPending,children:"Cancel"}),e.jsxs(z,{onClick:f,disabled:!p||h.length<2||g||l.isPending,children:[l.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Merge — this can't be undone"]})]})]})})}const kRn={email:"Same email",phone:"Same phone",name:"Same name"};function SRn(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function CRn({open:s,onOpenChange:t}){const{data:n,isLoading:r,isError:a,error:i}=jRn(s),l=aZt(),[o,c]=_.useState(new Set),[d,u]=_.useState(null),[h,m]=_.useState(!1),p=_.useMemo(()=>(n??[]).filter(v=>v.contact_ids.length>1&&!o.has(v.contact_ids.join(","))),[n,o]),f=p.filter(v=>v.match_type!=="name"),g=async()=>{m(!0);let v=0,y=0;try{for(const b of f){const w=[...b.contacts].sort((E,P)=>ZTe(P)-ZTe(E))[0],S=(w==null?void 0:w.id)??b.contact_ids[0],C=await l.mutateAsync({primaryId:S,duplicateIds:b.contact_ids.filter(E=>E!==S)});v+=C.merged,y+=C.failed.length}la({title:`Merged ${v} duplicate${v===1?"":"s"}`,description:y?`${y} could not be merged.`:"Name-only matches still need your review.",variant:y?"destructive":void 0})}catch(b){la({title:"Could not finish merging",description:b.message,variant:"destructive"})}finally{m(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"flex h-[90dvh] max-h-[90dvh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Os,{className:"shrink-0",children:[e.jsx(Rs,{children:"Find duplicates"}),e.jsx(_r,{children:"We looked through your whole database for contacts that share an email, a phone number, or a name."})]}),r?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):a?e.jsx("p",{className:"py-6 text-sm text-destructive",children:(i==null?void 0:i.message)??"Could not check for duplicates."}):p.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No duplicates found. Your database looks clean."}):e.jsx("div",{className:"min-h-0 flex-1 -mx-2 overflow-y-auto overscroll-contain px-2 pr-3 touch-pan-y",children:e.jsx("div",{className:"space-y-3 pb-2",children:p.map(v=>{const y=v.contact_ids.join(",");return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",children:kRn[v.match_type]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:v.match_value}),e.jsxs("span",{className:"ml-auto text-xs text-muted-foreground",children:[v.contact_ids.length," records"]})]}),e.jsx("div",{className:"space-y-1",children:v.contacts.map(b=>e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-sm",children:[e.jsx("span",{className:"font-medium",children:SRn(b)}),b.email&&e.jsx("span",{className:"text-muted-foreground",children:b.email}),b.phone&&e.jsx("span",{className:"text-muted-foreground",children:b.phone}),b.created_at&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["added ",new Date(String(b.created_at)).toLocaleDateString()]})]},b.id))}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(z,{size:"sm",onClick:()=>u(v.contact_ids),children:"Review & merge"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>c(b=>new Set(b).add(y)),children:"Not a duplicate"})]})]},`${v.match_type}-${y}`)})})}),e.jsxs(hr,{className:"shrink-0 gap-2 sm:justify-between",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:h,children:"Close"}),f.length>0&&e.jsxs(z,{onClick:g,disabled:h,children:[h?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(un,{className:"mr-2 h-4 w-4"}),"Merge all safe matches (",f.length,")"]})]})]})}),e.jsx(iZt,{open:!!d,onOpenChange:v=>{v||u(null)},contactIds:d??[]})]})}const ARn=()=>{const{user:s}=hs();return rt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},c8e=s=>{const{user:t}=hs();return rt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=U.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})},Znt=()=>{const{user:s}=hs();return rt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},oZt=()=>{const{user:s}=hs();return rt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},ERn=()=>{const{data:s}=Rb();Q_();const{data:t}=c8e(),{data:n}=oZt(),{data:r}=Znt(),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=zf(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 g=d.tags.map(v=>i.get(v.relationship_type_id)).filter(v=>v!==void 0);g.length>0&&(u=Math.min(...g))}const h=a.get(d.id)||null,m=h?PN(o,zf(new Date(h))):null,p=m===null||m>=u,f=p&&m!==null?m-u:0;return{...d,lastPopby:h,daysSinceLastPopby:m,frequencyDays:u,isDue:p,daysOverdue:f}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},lZt=()=>ERn().filter(t=>t.isDue),TRn=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{error:r}=await U.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),la({title:"Popby item created!"})},onError:n=>{la({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},MRn=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await U.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 U.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await U.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id: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"]}),la({title:"Popby logged!"})},onError:n=>{la({title:"Error logging popby",description:n.message,variant:"destructive"})}})},PRn=()=>{const s=$t(),{user:t}=hs();return mt({mutationFn:async n=>{const{error:r}=await U.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"]}),la({title:"Frequency updated!"})},onError:n=>{la({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},LRn=()=>{const{data:s}=c8e(30),t=lZt(),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 IRn(){const{user:s}=hs();return rt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function cZt(s){const{data:t}=IRn(),{data:n}=oZt(),{data:r}=Znt(),{data:a}=rRn();return _.useMemo(()=>{const i=a==null?void 0:a.find(v=>v.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=zf(new Date);if(l&&!wS(l,o))return{nextTouchDate:l,daysUntil:PN(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,y)=>new Date(y.completed_at).getTime()-new Date(v.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(v=>v.contact_id===s.id&&v.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const v=s.tags.map(y=>{const b=r==null?void 0:r.find(w=>w.relationship_type_id===y.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(y=>y!==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 p=Uh(zf(u),h),f=PN(p,o);let g;return f<0?g="overdue":f<=7?g="due-soon":g="on-track",{nextTouchDate:p,daysUntil:f,status:g,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function L2t({contact:s}){const t=cZt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Ho,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:Zr,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:Mr,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:S0,text:`Snoozed until ${Ys(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:ya,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(ze,{variant:r.variant,className:Ct("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function DRn({contact:s,onLogTouch:t,onSnooze:n}){const r=cZt(s),a=iRn(),[i,l]=_.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(Ho,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(Zr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Mr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(S0,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(ya,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Ct("font-medium",o()),children:d()})]}),r.status==="snoozed"&&r.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",Ys(r.snoozedUntil,"MMMM d, yyyy")]}),r.status!=="snoozed"&&r.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",Ys(r.nextTouchDate,"MMMM d, yyyy")]}),r.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",Ys(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(z,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(er,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(z,{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(z,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(S0,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx(z,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(l8e,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const bze=768;function XW(){const[s,t]=_.useState(void 0);return _.useEffect(()=>{const n=window.matchMedia(`(max-width: ${bze-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function RRn(){const{user:s}=hs(),{hasLeadSite:t,leadSite:n}=mf(),{data:r,isLoading:a}=rt({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 U.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await U.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 FRn={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"}},ORn={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 BWe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=FRn[s.status],l=ORn[r],o=e.jsxs("div",{className:Ct("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Ct("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(UN,{children:e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:o}),e.jsx(Tx,{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:Ct("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(Di,{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 zRn=[{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:"address2_label",label:"Second Address Label",required:!1},{key:"address2",label:"Second Street Address",required:!1},{key:"address2_city",label:"Second City",required:!1},{key:"address2_state",label:"Second State",required:!1},{key:"address2_zip",label:"Second 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}],Yce=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]},BRn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=hs(),{toast:i}=_i(),l=_.useRef(null),[o,c]=_.useState("upload"),[d,u]=_.useState([]),[h,m]=_.useState([]),[p,f]=_.useState({}),[g,v]=_.useState([]),[y,b]=_.useState([]),[w,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState(!1),[I,D]=_.useState([]),[F,q]=_.useState(!1),[G,V]=_.useState(null);_.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Pe}=await U.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Pe||[])})()},[s,a==null?void 0:a.id]);const H=Pe=>{S(Oe=>Oe.includes(Pe)?Oe.filter(ke=>ke!==Pe):[...Oe,Pe])},K=async()=>{const Pe=C.trim();if(!(!Pe||!(a!=null&&a.id))){M(!0);try{const{data:Oe,error:ke}=await U.from("contact_custom_tags").insert({owner_user_id:a.id,name:Pe}).select("id, name, color").single();if(ke)throw ke;Oe&&(b(Ve=>[...Ve,Oe].sort((_e,Ae)=>_e.name.localeCompare(Ae.name))),S(Ve=>[...Ve,Oe.id]),E(""))}catch(Oe){i({title:"Could not create tag",description:Oe.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},Z=()=>{c("upload"),u([]),m([]),f({}),v([]),S([]),E(""),D([]),V(null),l.current&&(l.current.value="")},oe=()=>{Z(),t(!1)},re=Pe=>{const Oe=Pe.split(` `).map(We=>We.trim()).filter(We=>We);if(Oe.length===0)return{headers:[],data:[]};const ke=We=>{const qe=[];let Be="",Ze=!1;for(let $e=0;$e0&&(Ve[0]=Ve[0].replace(/^\uFEFF/,""));const _e=new Map,Ae=Ve.map((We,qe)=>{let Be=(We||"").trim();Be||(Be=`Column ${qe+1}`);const Ze=_e.get(Be)||0;return _e.set(Be,Ze+1),Ze===0?Be:`${Be} (${Ze+1})`}),Se=Oe.slice(1).map(ke);return{headers:Ae,data:Se}},ae=Pe=>{var Ve;const Oe=(Ve=Pe.target.files)==null?void 0:Ve[0];if(!Oe)return;const ke=new FileReader;ke.onload=_e=>{var Be;const Ae=(Be=_e.target)==null?void 0:Be.result,{headers:Se,data:We}=re(Ae);if(Se.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Se),m(We);const qe={};Se.forEach(Ze=>{const $e=Ze.toLowerCase().replace(/[_\s-]/g,"");$e.includes("firstname")||$e==="first"?qe.first_name=Ze:$e.includes("lastname")||$e==="last"?qe.last_name=Ze:$e.includes("spouse")&&$e.includes("email")?qe.spouse_email=Ze:$e.includes("spouse")||$e.includes("partner")?qe.spouse_name=Ze:$e.includes("email")?qe.email=Ze:$e.includes("phone")||$e.includes("mobile")||$e.includes("cell")?qe.phone=Ze:($e.includes("address")||$e.includes("street"))&&($e.includes("2")||$e.includes("second")||$e.includes("secondary"))?qe.address2=Ze:$e.includes("address")||$e.includes("street")?qe.address=Ze:$e==="city"?qe.city=Ze:$e==="state"||$e==="province"?qe.state=Ze:$e==="zip"||$e==="zipcode"||$e==="postalcode"?qe.zip=Ze:$e.includes("company")||$e.includes("organization")||$e.includes("business")?qe.company_name=Ze:$e.includes("jobtitle")||$e.includes("title")&&!$e.includes("spouse")?qe.job_title=Ze:$e.includes("birthday")||$e.includes("dob")||$e.includes("birthdate")?qe.birthday=Ze:$e.includes("anniversary")||$e.includes("homeanniversary")?qe.home_anniversary=Ze:($e.includes("notes")||$e.includes("comment"))&&(qe.notes=Ze)}),f(qe),c("mapping")},ke.readAsText(Oe)},J=(Pe,Oe)=>{f(ke=>{if(Oe==="none"){const{[Pe]:Ve,..._e}=ke;return _e}return{...ke,[Pe]:Oe}})},te=Pe=>{v(Oe=>Oe.includes(Pe)?Oe.filter(ke=>ke!==Pe):[...Oe,Pe])},ce=async()=>{if(!(a!=null&&a.id))return;const{data:Pe}=await U.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Oe=new Set((Pe||[]).filter(_e=>_e.email).map(_e=>_e.email.toLowerCase())),ke=new Set((Pe||[]).filter(_e=>_e.phone).map(_e=>_e.phone.replace(/[^0-9]/g,""))),Ve=h.map(_e=>{const Ae=$e=>{const Xe=p[$e];if(!Xe)return"";const nt=d.indexOf(Xe);return nt>=0?(_e[nt]||"").trim():""},Se=Ae("first_name"),We=Ae("email"),qe=Ae("phone"),Be=Se.length>0,Ze=!!(We&&Oe.has(We.toLowerCase())||qe&&ke.has(qe.replace(/[^0-9]/g,"")));return{first_name:Se,last_name:Ae("last_name"),email:We,phone:qe,address:Ae("address"),city:Ae("city"),state:Ae("state"),zip:Ae("zip"),address2_label:Ae("address2_label"),address2:Ae("address2"),address2_city:Ae("address2_city"),address2_state:Ae("address2_state"),address2_zip:Ae("address2_zip"),spouse_name:Ae("spouse_name"),spouse_email:Ae("spouse_email"),company_name:Ae("company_name"),job_title:Ae("job_title"),birthday:Ae("birthday"),home_anniversary:Ae("home_anniversary"),notes:Ae("notes"),isValid:Be,isDuplicate:Ze,error:Be?void 0:"First name is required"}});D(Ve),c("preview")},ve=Pe=>{const Oe=Pe.trim().split(/\s+/);return{first_name:Oe[0],last_name:Oe.length>1?Oe.slice(1).join(" "):null}},me=async()=>{if(!(a!=null&&a.id))return;const Pe=I.filter(_e=>_e.isValid);if(Pe.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}q(!0);let Oe=0,ke=0,Ve=0;try{for(const _e of Pe)try{let Ae=null;if(_e.email){const{data:qe}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",_e.email).maybeSingle();Ae=qe}if(!Ae&&_e.phone){const qe=_e.phone.replace(/[^0-9]/g,""),{data:Be}=await U.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Be){const Ze=Be.find($e=>$e.phone&&$e.phone.replace(/[^0-9]/g,"")===qe);Ze&&(Ae={id:Ze.id})}}const Se={owner_user_id:a.id,first_name:_e.first_name,last_name:_e.last_name||null,email:_e.email||null,phone:_e.phone||null,address:_e.address||null,city:_e.city||null,state:_e.state||null,zip:_e.zip||null,address2_label:_e.address2_label||null,address2:_e.address2||null,address2_city:_e.address2_city||null,address2_state:_e.address2_state||null,address2_zip:_e.address2_zip||null,spouse_name:_e.spouse_name||null,spouse_email:_e.spouse_email||null,company_name:_e.company_name||null,job_title:_e.job_title||null,birthday:Yce(_e.birthday),home_anniversary:Yce(_e.home_anniversary),notes:_e.notes||null};let We=null;if(Ae){const{data:qe}=await U.from("innercircle_contacts").select("*").eq("id",Ae.id).single();if(qe){const Be={},Ze=["last_name","email","phone","address","city","state","zip","address2_label","address2","address2_city","address2_state","address2_zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const $e of Ze){const Xe=qe[$e],nt=Se[$e];(!Xe||Xe==="")&&nt&&(Be[$e]=nt)}Object.keys(Be).length>0&&await U.from("innercircle_contacts").update(Be).eq("id",Ae.id)}We=Ae.id,ke++}else{const{data:qe,error:Be}=await U.from("innercircle_contacts").insert(Se).select("id").single();Be?(console.error("Insert error for contact:",_e.first_name,Be),Ve++):qe?(We=qe.id,g.length>0&&await U.from("innercircle_contact_tags").insert(g.map(Ze=>({contact_id:qe.id,relationship_type_id:Ze}))),Oe++):Ve++}if(We&&w.length>0&&await U.from("contact_custom_tag_assignments").upsert(w.map(qe=>({contact_id:We,tag_id:qe})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),We&&_e.spouse_name){const qe=ve(_e.spouse_name);let Be=null;if(_e.spouse_email){const{data:$e}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",_e.spouse_email).maybeSingle();Be=$e}if(!Be){const{data:$e}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",qe.first_name).eq("last_name",qe.last_name||_e.last_name||"").maybeSingle();Be=$e}let Ze=null;if(Be){Ze=Be.id;const $e=Yce(_e.home_anniversary);$e&&await U.from("innercircle_contacts").update({home_anniversary:$e}).eq("id",Be.id).is("home_anniversary",null)}else{const{data:$e}=await U.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:qe.first_name,last_name:qe.last_name||_e.last_name||null,email:_e.spouse_email||null,address:_e.address||null,city:_e.city||null,state:_e.state||null,zip:_e.zip||null,home_anniversary:Yce(_e.home_anniversary),spouse_name:`${_e.first_name}${_e.last_name?" "+_e.last_name:""}`,spouse_email:_e.email||null,notes:`Spouse of ${_e.first_name} ${_e.last_name||""} (imported via CSV)`.trim()}).select("id").single();$e&&(Ze=$e.id,Oe++)}Ze&&(await U.from("innercircle_contacts").update({spouse_contact_id:Ze}).eq("id",We),await U.from("innercircle_contacts").update({spouse_contact_id:We}).eq("id",Ze))}}catch(Ae){console.error("Error importing contact:",Ae),Ve++}V({created:Oe,updated:ke,failed:Ve}),c("result"),(Oe>0||ke>0)&&r(),i({title:"Import Complete",description:`${Oe} created, ${ke} updated${Ve>0?`, ${Ve} failed`:""}.`})}catch(_e){console.error("Import error:",_e),i({title:"Import Failed",description:_e.message||"Failed to import contacts",variant:"destructive"})}finally{q(!1)}},he=I.filter(Pe=>Pe.isValid).length,ge=I.filter(Pe=>!Pe.isValid).length,Ee=I.filter(Pe=>Pe.isValid&&Pe.isDuplicate).length,Ne=he-Ee;return e.jsx(Is,{open:s,onOpenChange:oe,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(xN,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(_r,{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:ae,className:"hidden"}),e.jsx(Ra,{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(z,{onClick:()=>{var Pe;return(Pe=l.current)==null?void 0:Pe.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(z,{variant:"outline",size:"sm",onClick:()=>{const Pe=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Oe=new Blob([Pe],{type:"text/csv"}),ke=URL.createObjectURL(Oe),Ve=document.createElement("a");Ve.href=ke,Ve.download="contact_import_template.csv",Ve.click(),URL.revokeObjectURL(ke)},children:[e.jsx(Ga,{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(ee,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:zRn.map(Pe=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ee,{className:"w-40 text-sm",children:[Pe.label,Pe.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ls,{value:p[Pe.key]||"none",onValueChange:Oe=>J(Pe.key,Oe),children:[e.jsx(rs,{className:"w-48",children:e.jsx(cs,{placeholder:"Select column..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"-- Not mapped --"}),d.map(Oe=>e.jsx(He,{value:Oe,children:Oe},Oe))]})]})]},Pe.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Pe=>e.jsx(ze,{variant:g.includes(Pe.id)?"default":"outline",className:"cursor-pointer",onClick:()=>te(Pe.id),children:Pe.name},Pe.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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."}),y.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:y.map(Pe=>{const Oe=w.includes(Pe.id);return e.jsxs(ze,{variant:Oe?"default":"outline",className:"cursor-pointer gap-1",style:Oe&&Pe.color?{backgroundColor:Pe.color,borderColor:Pe.color}:void 0,onClick:()=>H(Pe.id),children:[Pe.name,Oe&&e.jsx(er,{className:"h-3 w-3"})]},Pe.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:C,onChange:Pe=>E(Pe.target.value),onKeyDown:Pe=>{Pe.key==="Enter"&&(Pe.preventDefault(),K())},className:"max-w-xs"}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:K,disabled:!C.trim()||P,children:[P?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{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(Mr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Ne," new"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," existing (will merge gaps)"]})]}),ge>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs("span",{children:[ge," invalid"]})]})]}),Ee>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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Qa,{children:I.slice(0,100).map((Pe,Oe)=>e.jsxs(fn,{children:[e.jsx(yt,{children:Pe.first_name}),e.jsx(yt,{children:Pe.last_name}),e.jsx(yt,{children:Pe.email}),e.jsx(yt,{children:Pe.phone}),e.jsx(yt,{children:Pe.isValid?Pe.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:Pe.error||"Invalid"})})]},Oe))})]}),I.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",I.length," contacts"]})]})]}),o==="result"&&G&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Mr,{className:"h-12 w-12 mx-auto text-primary"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground",children:[G.created," created, ",G.updated," merged"]}),G.failed>0&&e.jsxs("p",{className:"text-destructive",children:[G.failed," failed to import"]})]}),e.jsxs(hr,{children:[o==="upload"&&e.jsx(z,{variant:"outline",onClick:oe,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"outline",onClick:Z,children:"Back"}),e.jsx(z,{onClick:ce,disabled:!p.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(z,{onClick:me,disabled:F||he===0,children:F?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${he} Contact${he!==1?"s":""}`})]}),o==="result"&&e.jsx(z,{onClick:oe,children:"Done"})]})]})})};function $Rn(){return"contacts"in navigator&&"ContactsManager"in window}function URn(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const p=h.substring(h.indexOf(":")+1).split(";");l=(p[0]||"").trim(),i=(p[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const p=h.substring(h.indexOf(":")+1).trim().split(" ");i=p[0]||"",l=p.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(f=>f.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function qRn({open:s,onOpenChange:t,onComplete:n}){hs();const{data:r}=Rb(),a=vLe(),i=_.useRef(null),[l,o]=_.useState("choose"),[c,d]=_.useState([]),[u,h]=_.useState(new Set),[m,p]=_.useState(0),[f,g]=_.useState(0),v=$Rn(),y=_.useCallback(D=>{if(!r)return D;const F=new Set(r.filter(G=>G.email).map(G=>G.email.toLowerCase())),q=new Set(r.filter(G=>G.phone).map(G=>G.phone.replace(/\D/g,"")));return D.map(G=>{var K,Z;const V=(K=G.email)==null?void 0:K.toLowerCase(),H=(Z=G.phone)==null?void 0:Z.replace(/\D/g,"");return V&&F.has(V)?{...G,isDuplicate:!0,duplicateField:"email"}:H&&H.length>=7&&q.has(H)?{...G,isDuplicate:!0,duplicateField:"phone"}:G})},[r]),b=async()=>{try{const D=["name","email","tel","address"],F=await navigator.contacts.select(D,{multiple:!0});if(!F||F.length===0)return;const q=F.map(H=>{var oe,re,ae,J;const Z=(((oe=H.name)==null?void 0:oe[0])||"").split(" ");return{first_name:Z[0]||"",last_name:Z.slice(1).join(" "),email:((re=H.email)==null?void 0:re[0])||"",phone:((ae=H.tel)==null?void 0:ae[0])||"",address:(J=H.address)!=null&&J[0]?[H.address[0].streetAddress,H.address[0].city,H.address[0].region,H.address[0].postalCode].filter(Boolean).join(", "):""}}),G=y(q);d(G);const V=new Set;G.forEach((H,K)=>{H.isDuplicate||V.add(K)}),h(V),o("preview")}catch(D){console.error("Contact Picker error:",D),la({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},w=D=>{var G;const F=(G=D.target.files)==null?void 0:G[0];if(!F)return;const q=new FileReader;q.onload=V=>{var re;const H=(re=V.target)==null?void 0:re.result,K=URn(H);if(K.length===0){la({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const Z=y(K);d(Z);const oe=new Set;Z.forEach((ae,J)=>{ae.isDuplicate||oe.add(J)}),h(oe),o("preview")},q.readAsText(F),i.current&&(i.current.value="")},S=async()=>{const D=c.filter((q,G)=>u.has(G));if(D.length===0)return;o("importing");let F=0;for(const q of D)try{await a.mutateAsync({first_name:q.first_name,last_name:q.last_name||void 0,email:q.email||void 0,phone:q.phone||void 0,address:q.address||void 0}),F++,g(Math.round(F/D.length*100))}catch(G){console.error(`Failed to import ${q.first_name} ${q.last_name}:`,G)}p(F),o("done")},C=D=>{h(F=>{const q=new Set(F);return q.has(D)?q.delete(D):q.add(D),q})},E=()=>{u.size===c.length?h(new Set):h(new Set(c.map((D,F)=>F)))},P=D=>{D||(o("choose"),d([]),h(new Set),p(0),g(0),l==="done"&&n()),t(D)},M=c.filter(D=>D.isDuplicate).length,I=u.size;return e.jsx(Is,{open:s,onOpenChange:P,children:e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(p1,{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(_r,{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(z,{onClick:b,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(p1,{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(z,{variant:v?"outline":"default",onClick:()=>{var D;return(D=i.current)==null?void 0:D.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Ra,{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:w,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(z,{variant:"ghost",size:"sm",onClick:E,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(Ki,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((D,F)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${D.isDuplicate?"opacity-60":""}`,onClick:()=>C(F),children:[e.jsx(za,{checked:u.has(F),onCheckedChange:()=>C(F),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:[D.first_name," ",D.last_name]}),D.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 (",D.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[D.phone&&e.jsx("div",{children:D.phone}),D.email&&e.jsx("div",{className:"truncate",children:D.email})]})]})]},F))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(z,{onClick:S,disabled:I===0,children:["Import ",I," Contact",I!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(bt,{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:[f,"% 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:`${f}%`}})})]}),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(Wr,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[m," contact",m!==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(z,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}const $We="mailStudioHandoff";function VRn(s){sessionStorage.setItem($We,JSON.stringify({...s,at:Date.now()}))}function Qwr(){const s=sessionStorage.getItem($We);if(sessionStorage.removeItem($We),!s)return null;try{const t=JSON.parse(s);return Date.now()-(t.at||0)>10*60*1e3?null:t}catch{return null}}const HRn="/mission-control/direct-mail";function d8e({build:s,label:t="Mail Studio",...n}){const{isAdmin:r}=hs(),a=zn();return r?e.jsxs(z,{variant:"outline",size:"sm",...n,onClick:()=>{const i=s();i&&(VRn(i),a(`${HRn}?handoff=1`))},children:[e.jsx(on,{className:"mr-1.5 h-3.5 w-3.5"}),t]}):null}function GRn(s){return rt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function WRn(){const{user:s}=hs();return rt({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 U.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 KRn(){const{user:s}=hs();return rt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await U.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function dZt(){const{user:s}=hs(),t=$t();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.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 uZt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function hZt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const YRn=100;function ZRn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=zn(),o=ha(),c=dZt(),[d,u]=_.useState([]),[h,m]=_.useState(!1),[p,f]=_.useState(""),[g,v]=_.useState(null),[y,b]=_.useState(""),[w,S]=_.useState(""),[C,E]=_.useState(!1),[P,M]=_.useState({done:0,total:0,failed:0}),I=n.filter(Z=>!!Z.email),D=n.length-I.length,F=I.length>YRn;_.useEffect(()=>{s&&(v(null),f(""),M({done:0,total:0,failed:0}))},[s]),_.useEffect(()=>{!s||!o||(m(!0),U.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:Z})=>{u(Z||[]),m(!1)}))},[s,o]),_.useEffect(()=>{if(!g)return;const Z=g.title||"a quick video";b(`I recorded a video for you — ${Z}`),S("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[g]);const q=d.filter(Z=>!p||(Z.title||"").toLowerCase().includes(p.toLowerCase())),G=(Z,oe)=>{if(!g)return"";const re=g.share_token?`https://video.relevelup.com/share/video/${g.share_token}`:"",ae=g.share_token?`https://video.relevelup.com/thumb/${g.share_token}`:g.thumbnail_url||"",J=g.title||"Video Message",ce=w.replace(/\{\{first_name\}\}/gi,Z).split(/\n\n+/).map(he=>`

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

`).join(""),ve=oe?hZt(oe):re,me=oe?``:"";return`
${ce}

▶ Watch Video

${me}
`},V=async()=>{if(!g)return;E(!0),M({done:0,total:I.length,failed:0});let Z=0,oe=0;for(const re of I)try{let ae;try{ae=(await c.mutateAsync({video_id:g.id,recipient_email:re.email,recipient_name:`${re.first_name} ${re.last_name||""}`.trim(),contact_id:re.id,sent_via:"gmail"})).share_token}catch(me){console.warn("Tracking record failed for",re.email,me)}const J=G(re.first_name,ae),te=y.replace(/\{\{first_name\}\}/gi,re.first_name),{data:ce,error:ve}=await U.functions.invoke("gmail-send",{body:{to:re.email,subject:te,body:J,contactId:re.id}});if(ve||!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||(ve==null?void 0:ve.message)||"Send failed");Z+=1}catch(ae){console.error("Failed to send to",re.email,ae),oe+=1}finally{M({done:Z+oe,total:I.length,failed:oe}),await new Promise(ae=>setTimeout(ae,250))}E(!1),oe===0?ne.success(`Video sent to ${Z} ${Z===1?"contact":"contacts"}!`):ne.warning(`Sent to ${Z}, ${oe} failed. Check console for details.`),t(!1),i==null||i()},H=()=>{if(!g)return;const Z=G("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:I.map(oe=>({email:oe.email,name:`${oe.first_name} ${oe.last_name||""}`.trim()})),initialSubject:y,initialBodyHtml:Z}}),t(!1)},K=!!g&&!!y.trim()&&I.length>0&&(F?a:r);return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5 text-primary"}),"Send Video to ",I.length," ",I.length===1?"Contact":"Contacts"]}),e.jsxs(_r,{children:[F?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(Nh,{className:"h-3.5 w-3.5"}),I.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),D>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",D," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[F&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:["Mass Email is not set up yet. Verify a sender address in Integrations → Mass Email before sending to ",I.length," recipients."]})]}),!F&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("div",{children:"Gmail isn't connected. Connect Gmail in Integrations to send videos."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Choose a video"}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search your video library...",value:p,onChange:Z=>f(Z.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(ln,{className:"h-14 w-full"}),e.jsx(ln,{className:"h-14 w-full"})]}):q.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."}):q.map(Z=>{const oe=(g==null?void 0:g.id)===Z.id;return e.jsxs("button",{type:"button",onClick:()=>v(Z),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${oe?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[Z.thumbnail_url?e.jsx("img",{src:Z.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Yh,{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(su,{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:Z.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Z.duration_seconds?`${Math.round(Z.duration_seconds)}s`:"",Z.created_at?` · ${new Date(Z.created_at).toLocaleDateString()}`:""]})]})]},Z.id)})})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(pe,{id:"bulk-video-subject",value:y,onChange:Z=>b(Z.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ps,{id:"bulk-video-message",value:w,onChange:Z=>S(Z.target.value),rows:4,className:"resize-y"})]}),C&&P.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",P.done," / ",P.total,P.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",P.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:C,children:"Cancel"}),F?e.jsxs(z,{onClick:H,disabled:!K,className:"gap-2",children:[e.jsx(Nh,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(z,{onClick:V,disabled:!K||C,className:"gap-2",children:[C?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),C?"Sending…":`Send to ${I.length}`]})]})]})]})})}function Vae(){const s=ha();return rt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function XRn(s){return rt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function QRn(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 mZt(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 JRn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function Xnt(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([U.from("drip_campaigns").select("*").eq("id",n).single(),U.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 U.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 U.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function pZt(s){return rt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function eFn(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function tFn(){const s=$t();return mt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await U.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 sFn(){const s=$t();return mt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await U.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function nFn(s){return rt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function rFn(s){return rt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await U.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 Qnt(){const s=$t();return mt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await U.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 aFn(){const s=$t();return mt({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 U.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 iFn=[{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"}],u8e={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"},oFn={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 lFn({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("desktop"),[f,g]=_.useState(""),[v,y]=_.useState(!1);_.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{var S,C;o(!0);try{const{data:E}=await U.auth.getSession();f||g(((C=(S=E==null?void 0:E.session)==null?void 0:S.user)==null?void 0:C.email)||"");const{data:P,error:M}=await U.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(M)throw M;if(w)return;d((P==null?void 0:P.html)||""),h((P==null?void 0:P.subject)||n)}catch{w||ne.error("Could not build preview")}finally{w||o(!1)}})(),()=>{w=!0}},[s,n,r,a]);const b=async()=>{if(f.trim()){y(!0);try{const{data:w,error:S}=await U.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:f.trim(),owner_user_id:a||void 0}});if(S)throw S;w!=null&&w.success?ne.success(`Test email sent to ${f.trim()}`):ne.error((w==null?void 0:w.error)||"Could not send test email",{duration:1e4})}catch{ne.error("Could not send test email")}finally{y(!1)}}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Os,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs(Rs,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(_r,{children:"Exactly how this email will look when it sends, with sample contact details filled in."})]}),e.jsxs("div",{className:"px-5 py-3 border-b shrink-0 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subject"}),e.jsx("div",{className:"text-sm font-medium",children:u||n||"(no subject)"}),e.jsxs("div",{className:"flex items-center gap-1.5 pt-1",children:[e.jsxs(z,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("desktop"),children:[e.jsx(yN,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs(z,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("mobile"),children:[e.jsx(p1,{className:"h-3.5 w-3.5 mr-1"})," Mobile"]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overscroll-contain bg-muted/30 p-4 min-h-0",children:l?e.jsxs("div",{className:"flex items-center justify-center py-16 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"})," Building preview…"]}):e.jsx("div",{className:"mx-auto bg-background rounded-lg overflow-hidden border",style:{maxWidth:m==="mobile"?390:"100%"},children:e.jsx("iframe",{title:"Email preview",srcDoc:c,sandbox:"",className:"w-full",style:{height:620,border:0,background:"#fff"}})})}),e.jsxs("div",{className:"border-t p-4 shrink-0 flex flex-col sm:flex-row sm:items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Send a test to"}),e.jsx(pe,{type:"email",value:f,onChange:w=>g(w.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:w=>w.key==="Enter"&&b()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(z,{onClick:b,disabled:v||!f.trim(),children:[v?e.jsx(bt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function pz({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=_.useState(!1),[d,u]=_.useState([]),[h,m]=_.useState(!1),[p,f]=_.useState("");_.useEffect(()=>{!o||!s||(m(!0),U.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:v})=>{u(v||[]),m(!1)}))},[o,s]);const g=d.filter(v=>!p||(v.title||v.recipient_name||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs(Is,{open:o,onOpenChange:c,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Yh,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Ls,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Rs,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:p,onChange:v=>f(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(ln,{className:"h-16 w-full"}),e.jsx(ln,{className:"h-16 w-full"})]}):g.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"}):g.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:y=>{const b=y.currentTarget.parentElement;if(b){y.currentTarget.remove();const w=document.createElement("span");w.innerHTML="🎬",w.className="text-lg",b.appendChild(w)}}}):e.jsx(Xr,{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 cFn(){return rt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function dFn(s){return rt({queryKey:["video-scripts",s],queryFn:async()=>{let t=U.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function uFn(){const{user:s}=hs();return rt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await U.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 hFn(){const{user:s}=hs(),t=$t();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.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 mFn(s){const{user:t}=hs();return rt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=U.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 pFn(s){return rt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await U.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 RC(){const{user:s}=hs(),t=$t();return mt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.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 fFn(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 xFn(){const s=$t();return mt({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 U.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 U.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await U.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function h8e(){const{user:s}=hs();return rt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await U.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 fZt(){const{data:s,isLoading:t}=h8e(),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 qL(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function VL(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function DN(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function gFn(){const{user:s}=hs(),t=$t();return mt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await U.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await U.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id: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 xZt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=Rb(),{data:a}=h8e(),i=RC(),l=_.useRef(null),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(!1),[y,b]=_.useState(0),[w,S]=_.useState("idle"),C=(a==null?void 0:a.total_storage_mb)||0,P=((a==null?void 0:a.max_storage_mb)||1024)-C,M=q=>{var H;const G=(H=q.target.files)==null?void 0:H[0];if(!G)return;if(!G.type.startsWith("video/")){ne.error("Please select a video file");return}const V=G.size/(1024*1024);if(V>500){ne.error("Video file must be less than 500MB");return}if(V>P){ne.error(`Not enough storage. You have ${P.toFixed(1)} MB remaining.`);return}c(G),d||u(G.name.replace(/\.[^/.]+$/,""))},I=async()=>{if(!o){ne.error("Please select a video file");return}v(!0),b(0),S("creating");try{const{data:q,error:G}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(G)throw new Error(G.message);const{videoId:V,libraryId:H}=q;S("uploading");const{data:K,error:Z}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:V,isAgentVideo:!0}});if(Z)throw new Error(Z.message);await new Promise((ae,J)=>{const te=new XMLHttpRequest;te.upload.addEventListener("progress",ce=>{if(ce.lengthComputable){const ve=Math.round(ce.loaded/ce.total*100);b(ve)}}),te.addEventListener("load",()=>{te.status>=200&&te.status<300?ae():J(new Error(`Upload failed with status ${te.status}`))}),te.addEventListener("error",()=>J(new Error("Upload failed"))),te.open("PUT",K.uploadUrl),te.setRequestHeader("AccessKey",K.apiKey),te.send(o)}),S("processing");const oe=o.size/(1024*1024),re=`https://iframe.mediadelivery.net/embed/${H}/${V}`;await i.mutateAsync({bunny_video_id:V,playback_url:re,file_size_mb:oe,title:d||o.name,notes:h||void 0,contact_id:p||void 0,status:"processing",touch_type:"video_upload"}),ne.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(re),D()}catch(q){console.error("Upload error:",q),ne.error(q instanceof Error?q.message:"Failed to upload video")}finally{v(!1),S("idle")}},D=()=>{g||(c(null),u(""),m(""),f(""),b(0),S("idle"),t(!1))},F=()=>{switch(w){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${y}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(Is,{open:s,onOpenChange:D,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Upload Video"}),e.jsx(_r,{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(ee,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Xr,{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"]})]}),!g&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:q=>{q.stopPropagation(),c(null)},children:e.jsx(er,{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 q;return(q=l.current)==null?void 0:q.click()},children:[e.jsx(Ra,{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:g})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",value:d,onChange:q=>u(q.target.value),placeholder:"Enter video title",disabled:g})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Associate with Contact (optional)"}),e.jsxs(ls,{value:p||"__none__",onValueChange:q=>f(q==="__none__"?"":q),disabled:g,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a contact"})}),e.jsxs(as,{children:[e.jsx(He,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(q=>e.jsxs(He,{value:q.id,children:[q.first_name," ",q.last_name||""]},q.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ps,{id:"notes",value:h,onChange:q=>m(q.target.value),placeholder:"Add any notes about this video",rows:2,disabled:g})]}),g&&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(bt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:F()})]}),e.jsx(Di,{value:w==="uploading"?y:w==="processing"?100:10})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:D,disabled:g,children:"Cancel"}),e.jsx(z,{onClick:I,disabled:!o||g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const yFn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],vFn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},I2t=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=>vFn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function gZt({open:s,onOpenChange:t,campaignId:n}){const[r,a]=_.useState(n??null),[i,l]=_.useState("details");_.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=XRn(o||void 0),{data:u,isLoading:h}=pZt(o||void 0),m=QRn(),p=mZt(),f=eFn(),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState("nurture"),[C,E]=_.useState("🌱"),[P,M]=_.useState("");_.useEffect(()=>{d?(v(d.name),b(d.description||""),S(d.category),E(d.icon),M(d.goal||"")):c||(v(""),b(""),S("nurture"),E("🌱"),M(""))},[d,c,s]);const I=oFn[w],D=async()=>{if(!g.trim()){ne.error("Give your campaign a name");return}try{if(c&&o)await p.mutateAsync({id:o,name:g,description:y,category:w,icon:C,goal:P,cover_color:I}),ne.success("Campaign updated");else{const q=await m.mutateAsync({name:g,description:y,category:w,icon:C,goal:P,cover_color:I});return ne.success("Campaign created — now add your first step!"),a(q.id),l("steps"),q}}catch(q){ne.error(q.message||"Failed to save")}},F=async()=>{if(!o){ne.error("Save the campaign first, then add steps");return}const q=((u==null?void 0:u.length)||0)+1;try{await f.mutateAsync({campaign_id:o,step_order:q,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:q===1?0:2,delay_hours:0})}catch{ne.error("Failed to add step")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${I} 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:C}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Rs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(_r,{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(Qr,{value:i,onValueChange:q=>l(q),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Jr,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Wt,{value:"details",children:"Details"}),e.jsxs(Wt,{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(Kt,{value:"details",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Campaign Name *"}),e.jsx(pe,{value:g,onChange:q=>v(q.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Description"}),e.jsx(Ps,{value:y,onChange:q=>b(q.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Goal (optional)"}),e.jsx(pe,{value:P,onChange:q=>M(q.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(ee,{className:"text-xs",children:"Category"}),e.jsxs(ls,{value:w,onValueChange:q=>S(q),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(u8e).map(([q,G])=>e.jsx(He,{value:q,children:G},q))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:yFn.map(q=>e.jsx("button",{type:"button",onClick:()=>E(q),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${C===q?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:q},q))})]})]}),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(Kt,{value:"steps",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(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(z,{size:"sm",onClick:F,disabled:f.isPending,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((q,G)=>e.jsx(bFn,{step:q,index:G,totalSteps:u.length},q.id)),e.jsxs(z,{variant:"outline",size:"sm",onClick:F,disabled:f.isPending,className:"w-full",children:[f.isPending?e.jsx(bt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(hr,{className:"border-t p-4 shrink-0",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(z,{onClick:D,disabled:m.isPending||p.isPending,children:[(m.isPending||p.isPending)&&e.jsx(bt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function bFn({step:s,index:t,totalSteps:n}){const r=tFn(),a=sFn(),i=ha(),[l,o]=_.useState(!1),[c,d]=_.useState(()=>({...s,body:I2t(s.body)})),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState(""),[v,y]=_.useState(!1),[b,w]=_.useState(!1);_.useEffect(()=>{d({...s,body:I2t(s.body)})},[s]);const S=JSON.stringify(c)!==JSON.stringify(s),C=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}),ne.success(`Step ${t+1} saved`)}catch{ne.error("Failed to save step")}finally{h(!1)}},E=async()=>{if(await Qi(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ne.success("Step deleted")}catch{ne.error("Failed to delete")}},P=I=>{d({...c,body:c.body+I})},M=()=>{if(c.delay_type==="calendar_anchor"){const D=c.anchor_field==="birthday"?"birthday":"home anniversary",F=c.anchor_offset_days||0;return F===0?`On their ${D}`:F<0?`${Math.abs(F)}d before ${D}`:`${F}d after ${D}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const I=[];return c.delay_days&&I.push(`${c.delay_days}d`),c.delay_hours&&I.push(`${c.delay_hours}h`),t===0?`After ${I.join(" ")||"0"}`:`+${I.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(ya,{className:"h-3 w-3"}):e.jsx(Zr,{className:"h-3 w-3"}),e.jsx("span",{children:M()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(on,{className:"h-3 w-3"}):e.jsx(qi,{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(h1,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(cl,{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(ee,{className:"text-xs",children:"Channel"}),e.jsxs(ls,{value:c.channel,onValueChange:I=>d({...c,channel:I}),children:[e.jsx(rs,{className:"mt-1 h-9",children:e.jsx(cs,{})}),e.jsx(as,{children:e.jsx(He,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Timing Type"}),e.jsxs(ls,{value:c.delay_type,onValueChange:I=>d({...c,delay_type:I}),children:[e.jsx(rs,{className:"mt-1 h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"relative",children:"⏱ Relative delay"}),e.jsx(He,{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(ee,{className:"text-xs",children:"Days delay"}),e.jsx(pe,{type:"number",min:0,value:c.delay_days,onChange:I=>d({...c,delay_days:parseInt(I.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Hours delay"}),e.jsx(pe,{type:"number",min:0,max:23,value:c.delay_hours,onChange:I=>d({...c,delay_hours:parseInt(I.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(ee,{className:"text-xs",children:"Anchor"}),e.jsxs(ls,{value:c.anchor_field||"birthday",onValueChange:I=>d({...c,anchor_field:I}),children:[e.jsx(rs,{className:"mt-1 h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"birthday",children:"🎂 Birthday"}),e.jsx(He,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(pe,{type:"number",value:c.anchor_offset_days||0,onChange:I=>d({...c,anchor_offset_days:parseInt(I.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject Line"}),e.jsx(pe,{value:c.subject,onChange:I=>d({...c,subject:I.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(ee,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ps,{value:c.body,onChange:I=>d({...c,body:I.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:"}),iFn.map(I=>e.jsx("button",{type:"button",onClick:()=>P(I.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:I.label},I.key))]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(Xr,{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(z,{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(pz,{userId:i||void 0,onSelect:I=>d({...c,video_url:I}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>y(!0),children:[e.jsx(Ra,{className:"h-3 w-3"})," Upload"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{g(""),p(!0)},children:[e.jsx(Kc,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(xZt,{open:v,onOpenChange:y,onUploadComplete:I=>d({...c,video_url:I})}),e.jsx(Is,{open:m,onOpenChange:p,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add video URL"}),e.jsx(_r,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(pe,{value:f,onChange:I=>g(I.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&f.trim()&&(d({...c,video_url:f.trim()}),p(!1))}}),e.jsxs(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(z,{disabled:!f.trim(),onClick:()=>{d({...c,video_url:f.trim()}),p(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:E,className:"text-destructive hover:text-destructive",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.channel==="email"&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>w(!0),children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs(z,{size:"sm",onClick:C,disabled:!S||u,children:[u&&e.jsx(bt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(lFn,{open:b,onOpenChange:w,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function _Fn({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Vae(),l=Qnt(),[o,c]=_.useState(""),[d,u]=_.useState(null),[h,m]=_.useState(!1),p=(a||[]).filter(v=>!v.is_starter),f=p.filter(v=>v.name.toLowerCase().includes(o.toLowerCase())||(v.description||"").toLowerCase().includes(o.toLowerCase())),g=async()=>{if(d)try{const v=await l.mutateAsync({campaignId:d,contactIds:n}),y=[`${v.enrolled} enrolled`];v.skipped>0&&y.push(`${v.skipped} skipped`),v.errors>0&&y.push(`${v.errors} errors`),ne.success(y.join(" · ")),t(!1),u(null),r==null||r()}catch(v){ne.error(v.message||"Failed to enroll contacts")}};return e.jsxs(Is,{open:s,onOpenChange:t,children:[e.jsxs(Ls,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(_r,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search campaigns...",value:o,onChange:v=>c(v.target.value),className:"pl-9 h-9"})]}),e.jsx(Ki,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):f.length===0?e.jsx("div",{className:"text-center py-8",children:p.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(z,{size:"sm",onClick:()=>m(!0),children:[e.jsx(sn,{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:f.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(Wr,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},v.id))})})]}),e.jsxs(hr,{className:"gap-2 sm:gap-2",children:[p.length>0&&e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:g,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(bt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(gZt,{open:h,onOpenChange:m})]})}function wFn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=zn(),{data:c}=Q_(),d=zBs(),u=$t(),{isGmailConnected:h}=bg(),{isReady:m}=NL(),{data:p}=hz(),f=Pnt(),g=yYt(),[v,y]=_.useState(!1),[b,w]=_.useState(!1),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(!1),[D,F]=_.useState(""),[q,G]=_.useState(!1),[V,H]=_.useState(null),K=s.size;if(K===0)return null;const Z=async ve=>{y(!0);try{const he=Array.from(s).map(Ee=>({contact_id:Ee,relationship_type_id:ve})),{error:ge}=await U.from("innercircle_contact_tags").upsert(he,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ge)throw ge;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),la({title:`Assigned type to ${K} contacts`}),n()}catch(me){la({title:"Error assigning type",description:me.message,variant:"destructive"})}finally{y(!1)}},oe=async ve=>{y(!0);try{const me=Array.from(s);for(const he of me)try{await g.mutateAsync({contactId:he,tagId:ve})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),la({title:`Tagged ${K} contacts`}),I(!1),F("")}catch(me){la({title:"Error adding tags",description:me.message,variant:"destructive"})}finally{y(!1)}},re=async()=>{if(D.trim()){y(!0);try{const ve=await f.mutateAsync({name:D.trim()});await oe(ve.id)}catch(ve){la({title:"Error creating tag",description:ve.message,variant:"destructive"}),y(!1)}}},ae=(p==null?void 0:p.filter(ve=>ve.name.toLowerCase().includes(D.toLowerCase())))||[],J=p==null?void 0:p.find(ve=>ve.name.toLowerCase()===D.trim().toLowerCase()),te=()=>{const ve=t.filter(Oe=>s.has(Oe.id)),me=["First Name","Last Name","Email","Phone","Street Address","City","State","ZIP","Full Address","Birthday","Home Anniversary","Notes","Relationship Types"],he=ve.map(Oe=>{var Be;const ke=Oe,Ve=ke.address||"",_e=ke.city||"",Ae=ke.state||"",Se=ke.zip||ke.zip_code||"",We=[_e,[Ae,Se].filter(Boolean).join(" ")].filter(Boolean).join(", "),qe=[Ve,We].filter(Boolean).join(", ");return[Oe.first_name,Oe.last_name||"",Oe.email||"",Oe.phone||"",Ve,_e,Ae,Se,qe,Oe.birthday||"",Oe.home_anniversary||"",Oe.notes||"",((Be=Oe.tags)==null?void 0:Be.map(Ze=>{var $e;return($e=Ze.relationship_type)==null?void 0:$e.name}).join("; "))||""]}),ge=[me.join(","),...he.map(Oe=>Oe.map(ke=>`"${(ke||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ee=new Blob([ge],{type:"text/csv"}),Ne=URL.createObjectURL(Ee),Pe=document.createElement("a");Pe.href=Ne,Pe.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Pe.click(),URL.revokeObjectURL(Ne),la({title:`Exported ${K} contacts`})},ce=async()=>{if(!await Qi(`Are you sure you want to delete ${K} contacts? This cannot be undone.`))return;const ve=Array.from(s);y(!0),H({done:0,total:ve.length});try{const me=await d.mutateAsync({ids:ve,onProgress:(he,ge)=>H({done:he,total:ge})});n(),la({title:`Deleted ${me.toLocaleString()} contacts`})}catch(me){const he=typeof(me==null?void 0:me.deleted)=="number"?me.deleted:0;la({title:"Error deleting contacts",description:he>0?`${he.toLocaleString()} of ${ve.length.toLocaleString()} were deleted before this failed: ${me.message}`:me.message,variant:"destructive"})}finally{H(null),y(!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:[K," selected"]}),V&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Deleting ",V.done.toLocaleString()," of ",V.total.toLocaleString(),"…"]}),e.jsxs(ls,{onValueChange:Z,disabled:v,children:[e.jsx(rs,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ip,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(as,{children:c==null?void 0:c.filter(ve=>ve.active).map(ve=>e.jsx(He,{value:ve.id,children:ve.name},ve.id))})]}),e.jsxs(hd,{open:M,onOpenChange:I,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",disabled:v,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(nd,{className:"w-56 p-2",align:"start",children:[e.jsx(pe,{placeholder:"Search or create tag...",value:D,onChange:ve=>F(ve.target.value),onKeyDown:ve=>{ve.key==="Enter"&&D.trim()&&!J?(ve.preventDefault(),re()):ve.key==="Enter"&&J&&(ve.preventDefault(),oe(J.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ae.map(ve=>e.jsxs("button",{onClick:()=>oe(ve.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:ve.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ve.name})]},ve.id)),D.trim()&&!J&&e.jsxs("button",{onClick:re,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(sn,{className:"h-3.5 w-3.5"}),'Create "',D.trim(),'"']}),ae.length===0&&!D.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>w(!0),disabled:v,children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>{const ve=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${ve}`)},disabled:v,children:[e.jsx(Nh,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>C(!0),disabled:v,children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:v,children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:v,children:[e.jsx(m1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:v,children:[e.jsx(G4,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),K>=2&&K<=10&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>G(!0),disabled:v,children:[e.jsx(u7,{className:"h-3.5 w-3.5 mr-1"}),"Merge"]}),e.jsx(d8e,{disabled:v,label:"Mail",build:()=>({source:"contacts",contactIds:Array.from(s).slice(0,500)})}),e.jsxs(z,{variant:"outline",size:"sm",onClick:te,disabled:v,children:[e.jsx(Ga,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:ce,disabled:v,className:"text-destructive hover:text-destructive",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(er,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(iZt,{open:q,onOpenChange:G,contactIds:Array.from(s),onMerged:n}),e.jsx(_Fn,{open:E,onOpenChange:P,contactIds:Array.from(s),onSuccess:n}),e.jsx(HN,{open:b,onOpenChange:w,bulkContacts:Array.from(s).map(ve=>{const me=t.find(he=>he.id===ve);return me?{id:me.id,first_name:me.first_name,last_name:me.last_name,email:me.email||""}:null}).filter(ve=>ve!==null&&ve.email!==""),onSendComplete:()=>{w(!1),n()}}),e.jsx(ZRn,{open:S,onOpenChange:C,contacts:Array.from(s).map(ve=>t.find(me=>me.id===ve)).filter(ve=>!!ve).map(ve=>({id:ve.id,first_name:ve.first_name,last_name:ve.last_name,email:ve.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{C(!1),n()}})]})}function D2t({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=zn(),{isReady:d}=NL(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(lb,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(ua,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(ua,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ua,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(ua,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ua,{onClick:()=>r(s.id,u),children:[e.jsx(S0,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ua,{onClick:()=>a(s.id),children:[e.jsx(m1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ua,{onClick:()=>l(s.id),children:[e.jsx(G4,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(ua,{onClick:()=>t(s),children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ua,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function R2t({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=Lnt(),a=vYt(),i=bYt(),[l,o]=_.useState(!1),[c,d]=_.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(m=>m!==void 0&&m!==!1),h=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(F_,{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(cl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(qd,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(ua,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(m.filters,m.sort_by),children:m.name}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:p=>{p.stopPropagation(),i.mutate(m.id)},children:e.jsx(Cn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(Iy,{})]}):e.jsx(ua,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(ua,{onClick:()=>o(!0),children:[e.jsx(tP,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{className:"max-w-sm",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(pe,{placeholder:"e.g. Buyers in 40205",value:c,onChange:m=>d(m.target.value),onKeyDown:m=>m.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(z,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const XTe=[{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"}],yZt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],jFn=[{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 NFn({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o,contactLeadSources:c}){const[d,u]=_.useState(r),[h,m]=_.useState(n?"behavior":"contact"),{data:p}=Q9(),f=_.useMemo(()=>{const y=new Map;return(p||[]).forEach(b=>{y.set(b.name.trim().toLowerCase(),{value:`name:${b.name}`,label:b.name})}),(c||[]).forEach(b=>{const w=b.trim().toLowerCase();!w||y.has(w)||y.set(w,{value:`name:${b}`,label:b})}),Array.from(y.values()).sort((b,w)=>b.label.localeCompare(w.label))},[p,c]);_.useEffect(()=>{s&&u(r)},[s,r]);const g=y=>u(b=>({...b,...y})),v=Object.entries(d).filter(([,y])=>y!==void 0&&y!==!1&&y!=="").length;return e.jsx(Wg,{open:s,onOpenChange:t,children:e.jsxs(gg,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(Dy,{children:[e.jsxs(Ry,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(Z9,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(Qr,{value:h,onValueChange:y=>m(y),className:"mt-4",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Wt,{value:"contact",className:"gap-1.5",children:[e.jsx(On,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Wt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(pm,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Wt,{value:"engagement",children:"Engagement"})]}),e.jsxs(Kt,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact Type"}),e.jsxs(ls,{value:i,onValueChange:l,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"All types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),o==null?void 0:o.map(y=>e.jsx(He,{value:y.id,children:y.name},y.id))]})]})]}),e.jsxs(N3,{title:"Contact Info Present",children:[e.jsx(Gv,{label:"Has email",checked:d.hasEmail===!0,onChange:y=>g({hasEmail:y||void 0})}),e.jsx(Gv,{label:"Has phone",checked:d.hasPhone===!0,onChange:y=>g({hasPhone:y||void 0})}),e.jsx(Gv,{label:"Has address",checked:d.hasAddress===!0,onChange:y=>g({hasAddress:y||void 0})}),e.jsx(Gv,{label:"Has birthday",checked:d.hasBirthday===!0,onChange:y=>g({hasBirthday:y||void 0})}),e.jsx(Gv,{label:"Has spouse",checked:d.hasSpouse===!0,onChange:y=>g({hasSpouse:y||void 0})}),e.jsx(Gv,{label:"Has company / job",checked:d.hasCompany===!0,onChange:y=>g({hasCompany:y||void 0})}),e.jsx(Gv,{label:"Has notes",checked:d.hasNotes===!0,onChange:y=>g({hasNotes:y||void 0})})]}),e.jsxs(N3,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(_ze,{label:"City",value:d.city||"",onChange:y=>g({city:y||void 0}),placeholder:"Any city"}),e.jsx(_ze,{label:"State",value:d.state||"",onChange:y=>g({state:y||void 0}),placeholder:"Any state"})]}),e.jsx(_ze,{label:"ZIP / Postal",value:d.zip||"",onChange:y=>g({zip:y||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(N3,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(ls,{value:d.birthdayMonth?String(d.birthdayMonth):"all",onValueChange:y=>g({birthdayMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any month"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any month"}),XTe.map(y=>e.jsx(He,{value:String(y.value),children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(ls,{value:d.anniversaryField||"home_anniversary",onValueChange:y=>g({anniversaryField:y}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Field"})}),e.jsx(as,{children:yZt.map(y=>e.jsx(He,{value:y.value,children:y.label},y.value))})]}),e.jsxs(ls,{value:d.anniversaryMonth?String(d.anniversaryMonth):"all",onValueChange:y=>g({anniversaryMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any month"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any month"}),XTe.map(y=>e.jsx(He,{value:String(y.value),children:y.label},y.value))]})]})]})]})]}),e.jsx(N3,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(F2t,{label:"From",value:d.dateAddedFrom,onChange:y=>g({dateAddedFrom:y||void 0})}),e.jsx(F2t,{label:"To",value:d.dateAddedTo,onChange:y=>g({dateAddedTo:y||void 0})})]})}),e.jsx(N3,{title:"Lead Source",children:e.jsxs(ls,{value:d.leadSourceId||"all",onValueChange:y=>g({leadSourceId:y==="all"?void 0:y}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"All sources"})}),e.jsxs(as,{className:"max-h-72",children:[e.jsx(He,{value:"all",children:"All sources"}),e.jsx(He,{value:"none",children:"No source"}),f.map(y=>e.jsx(He,{value:y.value,children:y.label},y.value))]})]})})]}),e.jsx(Kt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(N3,{title:"Last Active On Site",children:[e.jsx(C_,{value:d.lastActive||"",onValueChange:y=>g({lastActive:y||void 0}),className:"grid grid-cols-2 gap-2",children:jFn.map(y=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(am,{value:y.value}),e.jsx("span",{className:"text-sm",children:y.label})]},y.value))}),d.lastActive&&e.jsx(z,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>g({lastActive:void 0}),children:"Clear"})]}),e.jsxs(N3,{title:"Registration",children:[e.jsx(Gv,{label:"Registered on lead site",checked:d.registered==="yes",onChange:y=>g({registered:y?"yes":void 0})}),e.jsx(Gv,{label:"Anonymous visitors only",checked:d.registered==="no",onChange:y=>g({registered:y?"no":void 0})})]}),e.jsxs(N3,{title:"Property Activity",children:[e.jsx(Gv,{label:"Viewed any listing",checked:d.viewedListing==="any",onChange:y=>g({viewedListing:y?"any":void 0})}),e.jsx(Gv,{label:"Hot buyer — 3+ views in last 7 days",checked:d.viewedListing==="multiple7d",onChange:y=>g({viewedListing:y?"multiple7d":void 0})}),e.jsx(Gv,{label:"Saved a property",checked:!!d.savedProperty,onChange:y=>g({savedProperty:y||void 0})}),e.jsx(Gv,{label:"Has an active saved search / alert",checked:!!d.hasSavedSearch,onChange:y=>g({hasSavedSearch:y||void 0})})]}),e.jsxs(N3,{title:"Requests",children:[e.jsx(Gv,{label:"Requested a showing / asked a question",checked:!!d.requestedShowing,onChange:y=>g({requestedShowing:y||void 0})}),e.jsx(Gv,{label:"Requested a home valuation",checked:!!d.requestedValuation,onChange:y=>g({requestedValuation:y||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(Kt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Gv,{label:"Any website activity",checked:!!d.websiteActiveOnly,onChange:y=>g({websiteActiveOnly:y||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(F8t,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(z,{variant:"ghost",onClick:()=>u({}),disabled:v===0,children:"Clear behavior filters"}),e.jsx(z,{onClick:()=>{a(d),t(!1)},children:"Apply"})]})]})})}function N3({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Gv({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(mn,{checked:t,onCheckedChange:n})]})}function _ze({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{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(er,{className:"h-3 w-3"})})]})]})}function F2t({label:s,value:t,onChange:n}){const[r,a]=_.useState(!1),i=t?x0(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(hd,{open:r,onOpenChange:a,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-3.5 w-3.5"}),i?Ys(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{mode:"single",selected:i,onSelect:l=>{n(l?Ys(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function kFn({behavior:s,onRemove:t,onClearAll:n}){const r=SFn(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 SFn(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=XTe.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=XTe.find(i=>i.value===s.anniversaryMonth),a=((n=yZt.find(i=>i.value===(s.anniversaryField||"home_anniversary")))==null?void 0:n.label)||"Anniversary";t.push({key:"anniversaryMonth",label:`${a} in ${(r==null?void 0:r.label)||s.anniversaryMonth}`})}return s.dateAddedFrom&&t.push({key:"dateAddedFrom",label:`Added on/after ${Ys(x0(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Ys(x0(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}function CFn(){const[s,t]=_.useState(""),[n,r]=_.useState(!0);return _.useEffect(()=>{let a=!1;return(async()=>{const{data:i}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();a||(t((i==null?void 0:i.value)??""),r(!1))})(),()=>{a=!0}},[]),{token:s,loading:n}}function AFn(){const s=ha();return rt({queryKey:["sphere-map-contacts",s],queryFn:async()=>{if(!s)return[];const t=1e3,n=[];for(let r=0;;r+=t){const{data:a,error:i}=await U.rpc("get_sphere_map_contacts",{_owner:s}).order("id",{ascending:!0}).range(r,r+t-1);if(i)throw i;const l=a??[];if(n.push(...l),l.length{let n=0,r=0,a=0;for(let i=0;i<20;i++){const{data:l,error:o}=await U.functions.invoke("geocode-contacts",{body:{owner_user_id:s,limit:200}});if(o)throw o;if(n+=(l==null?void 0:l.processed)??0,r+=(l==null?void 0:l.matched)??0,a=(l==null?void 0:l.remaining)??0,!(l!=null&&l.processed))break}return{processed:n,matched:r,remaining:a}},onSuccess:n=>{t.invalidateQueries({queryKey:["sphere-map-contacts"]}),la({title:n.processed?`Mapped ${n.matched} of ${n.processed} addresses`:"Everything is already mapped",description:n.remaining?`${n.remaining} still to look up`:void 0})},onError:n=>la({title:"Could not map addresses",description:n.message,variant:"destructive"})})}function ejr(){const s=ha();return rt({queryKey:["contact-map-views",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_map_views").select("*").eq("owner_user_id",s).order("created_at");if(n)throw n;return t},enabled:!!s})}function tjr(){const s=ha(),t=$t();return mt({mutationFn:async n=>{const{error:r}=await U.from("contact_map_views").insert({...n,owner_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-map-views"]}),la({title:"View saved"})},onError:n=>la({title:"Could not save view",description:n.message,variant:"destructive"})})}function sjr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("contact_map_views").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["contact-map-views"]})})}function EFn(){const s=ha();return rt({queryKey:["contact-farms",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_farms").select("*").eq("owner_user_id",s).order("created_at");if(n)throw n;return t},enabled:!!s})}function njr(){const s=ha(),t=$t();return mt({mutationFn:async n=>{const{error:r}=await U.from("contact_farms").insert({...n,boundary:n.boundary,owner_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-farms"]}),la({title:"Farm saved"})},onError:n=>la({title:"Could not save farm",description:n.message,variant:"destructive"})})}function rjr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("contact_farms").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["contact-farms"]})})}function ajr(){const s=ha();return rt({queryKey:["popby-routes",s],queryFn:async()=>{const{data:t,error:n}=await U.from("popby_routes").select("*, stops:popby_route_stops(*)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}function ijr(){const s=ha(),t=$t();return mt({mutationFn:async({name:n,plannedDate:r,contactIds:a})=>{const{data:i,error:l}=await U.from("popby_routes").insert({owner_user_id:s,name:n,planned_date:r??null}).select().single();if(l)throw l;if(a.length){const{error:o}=await U.from("popby_route_stops").insert(a.map((c,d)=>({route_id:i.id,contact_id:c,sort_order:d})));if(o)throw o}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["popby-routes"]}),la({title:"Route created"})},onError:n=>la({title:"Could not create route",description:n.message,variant:"destructive"})})}function ojr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{error:r}=await U.from("popby_route_stops").update(n).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function ljr(){const s=$t();return mt({mutationFn:async t=>{for(const n of t){const{error:r}=await U.from("popby_route_stops").update({sort_order:n.sort_order}).eq("id",n.id);if(r)throw r}},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function cjr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("popby_routes").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function djr(){const s=ha();return rt({queryKey:["sphere-map-anchors",s],queryFn:async()=>{const[t,n]=await Promise.all([U.from("listings").select("id, property_address, city, state, latitude, longitude, status, slug").eq("agent_id",s).not("latitude","is",null),U.from("open_houses").select("id, property_address, city, state, event_date, slug, is_active").eq("agent_id",s).eq("is_active",!0)]);return{listings:t.data??[],openHouses:n.data??[]}},enabled:!!s})}function ujr(){const s=ha();return rt({queryKey:["sphere-map-listings",s],queryFn:async()=>{const t=[];for(let r=0;r<20;r++){const{data:a,error:i}=await U.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, slug, latitude, longitude, listing_class, photos:listing_photos(photo_url, is_primary, sort_order)").eq("agent_id",s).order("created_at",{ascending:!1}).range(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a??[];if(l.forEach(o=>{var h;const c=(o.photos??[]).slice().sort((m,p)=>(p.is_primary?1:0)-(m.is_primary?1:0)||(m.sort_order??0)-(p.sort_order??0)),{photos:d,...u}=o;t.push({...u,photo_url:((h=c[0])==null?void 0:h.photo_url)??null})}),l.length<1e3)break}return t},enabled:!!s,staleTime:6e4})}function hjr(){const s=ha();return rt({queryKey:["sphere-map-open-houses",s],queryFn:async()=>{const t=[];for(let r=0;r<10;r++){const{data:a,error:i}=await U.from("open_houses").select("id, slug, property_address, city, state, zip, event_date, start_time, end_time, price, beds, baths, sqft, photo_url, is_active, latitude, longitude").eq("agent_id",s).order("event_date",{ascending:!1}).range(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a??[];if(l.forEach(o=>t.push(o)),l.length<1e3)break}return t},enabled:!!s,staleTime:6e4})}function mjr(s){const{leadSiteId:t,filters:n,enabled:r}=s,a=JSON.stringify(n);return rt({queryKey:["sphere-map-idx",t,a],queryFn:async()=>{if(!t||!n.cities.length||!n.statuses.length)return[];const{data:i,error:l}=await U.functions.invoke("lead-site-search",{body:{leadSiteId:t,filterCities:n.cities,statuses:n.statuses,minPrice:n.minPrice??void 0,maxPrice:n.maxPrice??void 0,minBeds:n.minBeds??void 0,minBaths:n.minBaths??void 0,propertyType:n.propertyType??void 0,limit:250,pageSize:250}});if(l)throw l;return((i==null?void 0:i.listings)??[]).filter(c=>Number.isFinite(c.latitude)&&Number.isFinite(c.longitude))},enabled:r&&!!t,staleTime:5*60*1e3})}function vZt(s,t,n){const r=$t(),{token:a}=CFn();return mt({mutationFn:async i=>{var o,c;if(!a)throw new Error("Map is still loading. Try again in a moment.");let l=0;for(const d of i){const u=[d.property_address,d.city,d.state].filter(Boolean).join(", ");if(u)try{const m=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(u)}.json?access_token=${a}&limit=1&country=us`)).json(),p=(c=(o=m==null?void 0:m.features)==null?void 0:o[0])==null?void 0:c.center;if(!p)continue;const[f,g]=p,{error:v}=await U.from(s).update({latitude:g,longitude:f}).eq("id",d.id);v||l++}catch(h){console.error("Geocode error:",h)}}return l},onSuccess:i=>{r.invalidateQueries({queryKey:[t]}),la({title:i?`${i} ${i===1?n.one:n.many} placed on the map`:"No locations found",description:i?void 0:"Check the street address, city and state."})},onError:i=>la({title:"Could not look up addresses",description:i.message,variant:"destructive"})})}function pjr(){return vZt("listings","sphere-map-listings",{one:"listing",many:"listings"})}function fjr(){return vZt("open_houses","sphere-map-open-houses",{one:"open house",many:"open houses"})}const xjr={never:{label:"Never contacted",color:"#8b5cf6"},red:{label:"12+ months",color:"#ef4444"},orange:{label:"6–12 months",color:"#f97316"},yellow:{label:"3–6 months",color:"#eab308"},green:{label:"Recent",color:"#22c55e"}};function TFn(s){if(!s)return null;const t=new Date(s).getTime();return Number.isNaN(t)?null:Math.max(0,Math.floor((Date.now()-t)/864e5))}function gjr(s){return s===null?"never":s>=365?"red":s>=180?"orange":s>=90?"yellow":"green"}function MFn(s){return`${s.first_name??""} ${s.last_name??""}`.trim()||"Unnamed contact"}function PFn(s){return[s.address,[s.city,s.state].filter(Boolean).join(", "),s.zip].filter(Boolean).join(" · ")}function yjr(s){const t=new Map;return s.forEach(n=>{if(typeof n.latitude!="number"||typeof n.longitude!="number")return;const r=n.household_key||`${n.latitude.toFixed(5)},${n.longitude.toFixed(5)}`,a=t.get(r);a?a.push(n):t.set(r,[n])}),Array.from(t.entries()).map(([n,r])=>{const a=r.map(c=>TFn(c.last_touch_at)),i=a.some(c=>c===null)?null:Math.max(...a),l=Array.from(new Set(r.map(c=>c.last_name).filter(Boolean))),o=r.length===1?MFn(r[0]):l.length===1?`${r.map(c=>c.first_name).filter(Boolean).join(" & ")} ${l[0]}`:`${r.length} contacts`;return{key:n,lat:r[0].latitude,lng:r[0].longitude,contacts:r,label:o,addressLine:PFn(r[0]),gapDays:i}})}const LFn=3958.8;function bZt(s,t,n,r){const a=c=>c*Math.PI/180,i=a(n-s),l=a(r-t),o=Math.sin(i/2)**2+Math.cos(a(s))*Math.cos(a(n))*Math.sin(l/2)**2;return 2*LFn*Math.asin(Math.sqrt(o))}function IFn(s,t,n){let r=!1;for(let a=0,i=n.length-1;at!=d>t&&s<(c-l)*(t-o)/(d-o)+l&&(r=!r)}return r}function vjr(s,t,n,r=64){const a=[],i=t*Math.PI/180,l=n/69,o=n/(69*Math.max(.15,Math.cos(i)));for(let c=0;c<=r;c++){const d=c/r*Math.PI*2;a.push([s+o*Math.cos(d),t+l*Math.sin(d)])}return a}function bjr(s){const t=s.reduce((n,[r,a])=>({lng:n.lng+r,lat:n.lat+a}),{lng:0,lat:0});return{lng:t.lng/s.length,lat:t.lat/s.length}}function _jr(s,t){if(s.length<=2)return[...s];const n=[...s],r=[];let a={lat:s[0].lat,lng:s[0].lng};for(;n.length;){let i=0,l=1/0;n.forEach((c,d)=>{const u=bZt(a.lat,a.lng,c.lat,c.lng);u{const l=n.filter(o=>typeof o.latitude=="number"&&typeof o.longitude=="number");return s.map(o=>{var u;const c=((u=o.boundary)==null?void 0:u.ring)??[],d=new Set;if(c.length>=3)for(const h of l)IFn(h.longitude,h.latitude,c)&&d.add(h.id);return{id:o.id,name:o.name,color:o.color,contactIds:d,count:d.size}})},[s,n]),i=_.useMemo(()=>n.filter(l=>typeof l.latitude!="number"||typeof l.longitude!="number").length,[n]);return{neighborhoods:a,unmappedCount:i,isLoading:t||r}}function _Zt(s,t){const n=t instanceof Set?t:new Set(t);if(n.size===0)return null;const r=new Set;for(const a of s)n.has(a.id)&&a.contactIds.forEach(i=>r.add(i));return r}function RFn({selected:s,onChange:t,className:n}){const{neighborhoods:r,unmappedCount:a,isLoading:i}=Jnt(),l=new Set(s),o=c=>{const d=new Set(l);d.has(c)?d.delete(c):d.add(c),t(Array.from(d))};return e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:`gap-1.5 h-8 rounded-lg ${n??""}`,children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),"Neighborhoods",s.length>0&&e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:s.length})]})}),e.jsxs(nd,{align:"start",className:"w-72 p-0",children:[e.jsxs("div",{className:"p-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"Neighborhoods"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Areas you've drawn on the contacts map."})]}),i?e.jsxs("div",{className:"p-6 flex items-center justify-center text-sm text-muted-foreground gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):r.length===0?e.jsxs("div",{className:"p-4 space-y-2 text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:"You haven't drawn any neighborhoods yet."}),e.jsx(z,{asChild:!0,variant:"outline",size:"sm",className:"w-full",children:e.jsx(or,{to:"/mission-control/sphere-map",children:"Open the contacts map"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-64 overflow-y-auto p-2 space-y-1",children:r.map(c=>e.jsxs("button",{type:"button",onClick:()=>o(c.id),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-sm text-left",children:[e.jsx(za,{checked:l.has(c.id),className:"pointer-events-none"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:c.color}}),e.jsx("span",{className:"flex-1 truncate",children:c.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c.count})]},c.id))}),e.jsxs("div",{className:"p-2 border-t space-y-2",children:[a>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground px-1",children:[a.toLocaleString()," contacts don't have a mapped address yet, so they can't land in a neighborhood."," ",e.jsx(or,{to:"/mission-control/sphere-map",className:"underline",children:"Map them"})]}),s.length>0&&e.jsx(z,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t([]),children:"Clear neighborhoods"})]})]})]})]})}async function WB(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 jZ(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function FFn(){const{user:s}=hs(),{leadSite:t,hasLeadSite:n}=mf(),{data:r,isLoading:a}=rt({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=(y,b)=>{const w=i.get(y)||jZ();i.set(y,{...w,...b})},o=await WB((y,b)=>U.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(y,b)),c=new Map,d=new Map;o.forEach(y=>{if(!y.contact_id)return;c.set(y.id,y.contact_id),y.email&&d.set(y.email.toLowerCase(),y.contact_id);const b=i.get(y.contact_id);(!b||!b.lastActiveAt||y.last_seen_at>b.lastActiveAt)&&l(y.contact_id,{lastActiveAt:y.last_seen_at})});const u=await WB((y,b)=>U.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(y,b)),h=new Map;u.forEach(y=>{y.contact_id&&(h.set(y.user_id,y.contact_id),l(y.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await WB((y,b)=>U.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(y,b))).forEach(y=>{const b=y.visitor_id?c.get(y.visitor_id):null;if(!b)return;const w=i.get(b)||jZ();w.propertyViewCount+=1,y.viewed_at>=m&&(w.propertyViewCount7d+=1),i.set(b,w)}),(await WB((y,b)=>U.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(y,b))).forEach(y=>{const b=h.get(y.user_id);if(!b)return;const w=i.get(b)||jZ();w.savedListingCount+=1,i.set(b,w)}),(await WB((y,b)=>U.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(y,b))).forEach(y=>{const b=h.get(y.user_id);if(!b)return;const w=i.get(b)||jZ();w.activeSavedSearchCount+=1,i.set(b,w)}),(await WB((y,b)=>U.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(y,b))).forEach(y=>{if(!y.email)return;const b=d.get(y.email.toLowerCase());if(!b)return;const w=i.get(b)||jZ(),S=(y.lead_type||"").toLowerCase();(S.includes("showing")||S.includes("question")||S==="contact")&&(w.showingRequests+=1),(S.includes("valuation")||S.includes("cma")||S.includes("home_value"))&&(w.valuationRequests+=1),i.set(b,w)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const wZt="innercircle_geocode_cache_v1";function OFn(){try{return JSON.parse(localStorage.getItem(wZt)||"{}")}catch{return{}}}function zFn(s){try{localStorage.setItem(wZt,JSON.stringify(s))}catch{}}function BFn(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 $Fn({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=_.useRef(null),i=_.useRef(null),[l,o]=_.useState(""),[c,d]=_.useState(!0),[u,h]=_.useState([]),[m,p]=_.useState({done:0,total:0}),[f,g]=_.useState(!1),[v,y]=_.useState("heat");_.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{d(!0);const{data:S}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();w||(o((S==null?void 0:S.value)||""),d(!1))})(),()=>{w=!0}},[s]),_.useEffect(()=>{if(!s||!l)return;let w=!1;return(async()=>{const C=OFn(),E=n.map(V=>({c:V,addr:BFn(V)})).filter(V=>V.addr),P=[],M=[];for(const{c:V,addr:H}of E){const K=C[H];K!==null&&(K?P.push({id:V.id,name:`${V.first_name||""} ${V.last_name||""}`.trim(),city:V.city||null,state:V.state||null,zip:V.zip||V.zip_code||null,lat:K.lat,lng:K.lng}):M.push({c:V,addr:H}))}if(w||h(P),p({done:P.length,total:E.length}),M.length===0)return;g(!0);const I=6;let D=0;const F={...C},q=[...P],G=async()=>{var V;for(;D{w=!0}},[s,l,n]);const b=_.useMemo(()=>{const w=new Map;for(const S of n){const C=(S.city||"").trim();if(!C)continue;const E=(S.state||"").trim()||null,P=`${C.toLowerCase()}|${E||""}`,M=w.get(P);M?M.count++:w.set(P,{city:C,state:E,count:1})}return Array.from(w.values()).sort((S,C)=>C.count-S.count)},[n]);return _.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return Od.accessToken=l,i.current=new Od.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new Od.NavigationControl,"top-right"),()=>{var w;(w=i.current)==null||w.remove(),i.current=null}},[s,l]),_.useEffect(()=>{const w=i.current;if(!w||u.length===0)return;const S=()=>{const E={type:"FeatureCollection",features:u.map(M=>({type:"Feature",properties:{id:M.id,name:M.name},geometry:{type:"Point",coordinates:[M.lng,M.lat]}}))},P=w.getSource("contacts-src");if(P?P.setData(E):(w.addSource("contacts-src",{type:"geojson",data:E}),w.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]}}),w.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}}),w.on("click","contacts-points",M=>{var F;const I=(F=M.features)==null?void 0:F[0];if(!I)return;const D=I.geometry.coordinates.slice();new Od.Popup({offset:12}).setLngLat(D).setHTML(`
${I.properties.name||"Contact"}
`).addTo(w)}),w.on("mouseenter","contacts-points",()=>{w.getCanvas().style.cursor="pointer"}),w.on("mouseleave","contacts-points",()=>{w.getCanvas().style.cursor=""})),w.getLayer("contacts-heat")&&w.setLayoutProperty("contacts-heat","visibility",v==="heat"?"visible":"none"),w.getLayer("contacts-points")&&(w.setPaintProperty("contacts-points","circle-opacity",v==="points"?.9:0),w.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!w._fitDone){const M=new Od.LngLatBounds;u.forEach(I=>M.extend([I.lng,I.lat]));try{w.fitBounds(M,{padding:60,maxZoom:11,duration:600}),w._fitDone=!0}catch{}}};w.isStyleLoaded()?S():w.once("load",S)},[u,v]),e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Os,{className:"p-4 pb-2 border-b",children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(vu,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",b.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(bt,{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(z,{size:"sm",variant:v==="heat"?"default":"ghost",onClick:()=>y("heat"),className:"h-8",children:[e.jsx(vu,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(z,{size:"sm",variant:v==="points"?"default":"ghost",onClick:()=>y("points"),className:"h-8",children:[e.jsx(X4,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),f&&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(bt,{className:"h-3 w-3 animate-spin"}),"Mapping ",m.done," / ",m.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Ho,{className:"h-10 w-10 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Mapbox token is not set. Contact your administrator."})]})]})}),e.jsxs("div",{className:"w-full md:w-72 border-t md:border-t-0 md:border-l flex flex-col bg-muted/30 min-h-[200px]",children:[e.jsxs("div",{className:"p-3 border-b bg-background",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Ha,{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(Ki,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[b.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."}),b.slice(0,50).map((w,S)=>{var P;const C=((P=b[0])==null?void 0:P.count)||1,E=w.count/C*100;return e.jsx(be,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(w.city,w.state),t(!1)},children:e.jsxs(Le,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${E}%`}}),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:[w.city,w.state?`, ${w.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:S===0?"🔥 Hottest market":`Rank #${S+1}`})]}),e.jsx(ze,{variant:"secondary",className:"shrink-0",children:w.count})]})]})},`${w.city}-${w.state}-${S}`)})]})})]})]})]})})}function JR(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 O2t({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=zn(),c=wze(s,"birthday",7),d=wze(t,"anniversary",7),u=wze(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,p,f)=>{f.stopPropagation();const g=new URLSearchParams;a&&g.set("contactId",a),i&&g.set("name",i),l&&g.set("address",l),(m==="home_anniversary"||m==="wedding_anniversary")&&p&&g.set("date",p),g.set("cardType",m),o(`/mission-control/card-studio?${g.toString()}`)};return e.jsxs("div",{className:Ct("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:Ct("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:c.label}),a&&e.jsxs("button",{onClick:m=>h("birthday",s,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(on,{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:Ct("text-[10px] gap-0.5 font-medium",d.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:d.label}),a&&e.jsxs("button",{onClick:m=>h("home_anniversary",t,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(on,{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:Ct("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:m=>h("wedding_anniversary",n||null,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(on,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function z2t({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 B2t({count:s,className:t}){return!s||s<=0?null:e.jsxs(ze,{variant:"outline",className:Ct("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(mP,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function UFn(){const s=ha();return rt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await U.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 qFn(){const s=ha();return rt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_pipeline").select(` id, deal_name, contact_id, deal_type, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}const VFn="#6366F1";function $2t(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function HFn(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function jZt({label:s,color:t,className:n,onClick:r,title:a}){const i=t||VFn,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:$2t(i,14),color:HFn(i),boxShadow:`inset 0 0 0 1px ${$2t(i,22)}`},className:Ct("inline-flex h-6 max-w-[140px] items-center gap-1.5 rounded-full px-2.5 text-[11px] font-medium leading-none",r&&"transition-transform hover:scale-[1.03]",n),children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full",style:{backgroundColor:i},"aria-hidden":!0}),e.jsx("span",{className:"truncate",children:s})]})}function GFn({tags:s,max:t=2,className:n}){const[r,a]=_.useState(!1);if(!s||s.length===0)return null;const i=r?s:s.slice(0,t),l=s.length-i.length;return e.jsxs("div",{className:Ct("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx(jZt,{label:((c=o.tag)==null?void 0:c.name)||"Tag",color:(d=o.tag)==null?void 0:d.color},o.tag_id)}),l>0&&e.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),a(!0)},className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium leading-none text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:["+",l]})]})}function U2t({contactId:s,compact:t=!1}){const{data:n}=hz(),{data:r}=_Mn(s),a=Pnt(),i=yYt(),l=NMn(),[o,c]=_.useState(!1),[d,u]=_.useState(""),h=_.useRef(null),m=new Set((r==null?void 0:r.map(y=>y.tag_id))||[]),p=(n==null?void 0:n.filter(y=>y.name.toLowerCase().includes(d.toLowerCase())))||[],f=n==null?void 0:n.find(y=>y.name.toLowerCase()===d.trim().toLowerCase()),g=async y=>{m.has(y.id)?await l.mutateAsync({contactId:s,tagId:y.id}):await i.mutateAsync({contactId:s,tagId:y.id})},v=async()=>{if(!(!d.trim()||f))try{const y=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:y.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(y=>{var b,w,S;return e.jsxs(ze,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=y.tag)==null?void 0:b.color)||"#6366F1",color:((w=y.tag)==null?void 0:w.color)||"#6366F1"},children:[e.jsx(Ip,{className:"h-2.5 w-2.5"}),(S=y.tag)==null?void 0:S.name,e.jsx("button",{onClick:C=>{C.stopPropagation(),l.mutate({contactId:s,tagId:y.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(er,{className:"h-2.5 w-2.5"})})]},y.id)}),e.jsxs(hd,{open:o,onOpenChange:c,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:y=>y.stopPropagation(),children:[e.jsx(sn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(nd,{className:"w-56 p-2",align:"start",onClick:y=>y.stopPropagation(),children:[e.jsx(pe,{ref:h,placeholder:"Search or create tag...",value:d,onChange:y=>u(y.target.value),onKeyDown:y=>{y.key==="Enter"&&d.trim()&&!f?(y.preventDefault(),v()):y.key==="Enter"&&f&&!m.has(f.id)&&(y.preventDefault(),g(f))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[p.map(y=>e.jsxs("button",{onClick:()=>g(y),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:y.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:y.name}),m.has(y.id)&&e.jsx(Wr,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},y.id)),d.trim()&&!f&&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(sn,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),p.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function q2t({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(GFn,{tags:t,max:n})}const Zce=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function WFn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=hz(),a=Pnt(),i=jMn(),l=wMn(),[o,c]=_.useState(""),[d,u]=_.useState(Zce[0]),[h,m]=_.useState(null),[p,f]=_.useState(""),[g,v]=_.useState(""),y=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(Zce[0]),la({title:"Tag created"})}catch(C){la({title:"Error",description:C.message,variant:"destructive"})}},b=async C=>{if(p.trim())try{await i.mutateAsync({id:C,name:p.trim(),color:g}),m(null),la({title:"Tag updated"})}catch(E){la({title:"Error",description:E.message,variant:"destructive"})}},w=async(C,E)=>{if(await Qi(`Delete tag "${E}"? It will be removed from all contacts.`))try{await l.mutateAsync(C),la({title:"Tag deleted"})}catch(P){la({title:"Error",description:P.message,variant:"destructive"})}},S=C=>{m(C.id),f(C.name),v(C.color)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New tag name...",value:o,onChange:C=>c(C.target.value),onKeyDown:C=>C.key==="Enter"&&y(),className:"flex-1 h-9"}),e.jsxs(z,{size:"sm",onClick:y,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Zce.map(C=>e.jsx("button",{onClick:()=>u(C),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===C?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:C}},C))})]}),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(C=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===C.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:Zce.map(E=>e.jsx("button",{onClick:()=>v(E),className:`h-5 w-5 rounded-full border-2 ${g===E?"border-foreground":"border-transparent"}`,style:{backgroundColor:E}},E))}),e.jsx(pe,{value:p,onChange:E=>f(E.target.value),onKeyDown:E=>E.key==="Enter"&&b(C.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>b(C.id),children:e.jsx(Wr,{className:"h-4 w-4 text-primary"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(null),children:e.jsx(er,{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:C.color}}),e.jsx("span",{className:"flex-1 text-sm",children:C.name}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(C),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{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:()=>w(C.id,C.name),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})},C.id))]})]})})}function KFn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=Q9(),a=Wet(),i=qUs(),l=VUs(),[o,c]=_.useState(""),[d,u]=_.useState(null),[h,m]=_.useState(""),p=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(y){ne.error(y.message||"Failed to add lead source")}},f=async y=>{if(h.trim())try{await i.mutateAsync({id:y,name:h.trim()}),u(null)}catch(b){ne.error(b.message||"Failed to update")}},g=async(y,b)=>{if(await Qi(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(y)}catch(w){ne.error(w.message||"Failed to remove")}},v=y=>{u(y.id),m(y.name)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New lead source name...",value:o,onChange:y=>c(y.target.value),onKeyDown:y=>y.key==="Enter"&&p(),className:"flex-1 h-9"}),e.jsxs(z,{size:"sm",onClick:p,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(sn,{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(y=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===y.id?e.jsxs(e.Fragment,{children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&f(y.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>f(y.id),children:e.jsx(Wr,{className:"h-4 w-4 text-primary"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:y.name}),y.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>v(y),children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{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:()=>g(y.id,y.name),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]}),!y.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},y.id))]})]})})}function NZt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=Q9(),a=Wet(),[i,l]=_.useState(!1),[o,c]=_.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(ee,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(rs,{className:"flex-1",children:e.jsx(cs,{placeholder:"Select lead source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))]})]}),e.jsx(z,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(er,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{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(z,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function UWe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=zn(),c=ha(),[d,u]=_.useState(!1),[h,m]=_.useState(""),{data:p}=rt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:g,error:v}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(v)throw v;return g},enabled:!!t}),{data:f}=rt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let g=U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const b=h.replace(/[,()%]/g," ").trim();b&&(g=g.or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%,phone.ilike.%${b}%`))}const{data:v,error:y}=await g;if(y)throw y;return v},enabled:d&&!!c});if(t&&p){const g=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{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(Oo,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:g}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(z,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(rE,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Da,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{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(Oo,{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(hd,{open:d,onOpenChange:u,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(Oc,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(nd,{className:"w-72 p-2",align:"end",children:e.jsx(V2t,{search:h,setSearch:m,results:f,onSelect:g=>{a(g),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(hd,{open:d,onOpenChange:u,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(Oc,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(nd,{className:"w-72 p-2",align:"start",children:e.jsx(V2t,{search:h,setSearch:m,results:f,onSelect:g=>{a(g),u(!1),m("")}})})]})]}):null}function V2t({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(Rr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Ki,{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 YFn={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},ZFn={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 XFn({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:Ct("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:YFn[t]})]}),e.jsx("span",{className:Ct("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",ZFn[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const Xce=new Map;async function QFn(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 JFn(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(Xce.has(r))return Xce.get(r)??null;try{const i=`https://gravatar.com/avatar/${await QFn(n)}?s=${t}&d=404`;return Xce.set(r,i),i}catch{return Xce.set(r,null),null}}function eOn(s,t=256){const[n,r]=_.useState(null);return _.useEffect(()=>{let a=!0;if(!s){r(null);return}return JFn(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function ert({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=eOn(n?null:r,Math.max(64,a*2)),[u,h]=_.useState(!1);_.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:Ct("shrink-0 overflow-hidden bg-primary/10 text-primary flex items-center justify-center font-semibold select-none",c,i),style:{width:a,height:a,fontSize:Math.max(10,Math.round(a*.36))},children:m?e.jsx("img",{src:m,alt:`${s??""} ${t??""}`.trim()||"Contact photo",className:"h-full w-full object-cover",loading:"lazy",onError:()=>h(!0)}):e.jsx("span",{children:o})})}function tOn({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(ug,{children:[e.jsx(hg,{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(On,{className:"h-3 w-3"})})}),e.jsx(Tx,{children:r})]})}function sOn({totalLabel:s,stats:t,search:n,onSearchChange:r,onAddContact:a,onImportCsv:i,onImportPhone:l,onManageTags:o,onHeatMap:c,viewMode:d="my",onViewModeChange:u,showTeamTab:h,showLeadPondTab:m,extraActions:p}){const f=!!u&&(h||m);return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Contacts"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs("button",{onClick:c,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(vu,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs("button",{className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(Ra,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Import",e.jsx(cl,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onClick:i,children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"})," Import CSV"]}),e.jsxs(ua,{onClick:l,children:[e.jsx(p1,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(ua,{onClick:o,children:[e.jsx(Ip,{className:"mr-2 h-4 w-4"})," Manage Tags"]})]})]}),p]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(pe,{value:n,onChange:g=>r(g.target.value),placeholder:"Search by name, email, phone, or notes...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),f&&e.jsx("div",{className:"hub-glass inline-flex shrink-0 items-center gap-1 rounded-xl p-1",children:[{key:"my",label:"Mine",icon:On,show:!0},{key:"team",label:"Team",icon:On,show:!!h},{key:"lead-pond",label:"Pond",icon:m1,show:!!m}].filter(g=>g.show).map(g=>e.jsxs("button",{onClick:()=>u==null?void 0:u(g.key),className:Ct("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",d===g.key?"bg-background text-foreground shadow-sm":"hub-ink-muted"),children:[e.jsx(g.icon,{className:"h-3.5 w-3.5"}),g.label]},g.key))})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:t.map(g=>e.jsxs("button",{onClick:g.onClick,className:Ct("hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",g.active&&"ring-2 ring-white/40"),children:[e.jsx("span",{className:"text-xl font-bold",children:g.value}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:g.label})]},g.label))})]})})}function nOn({rows:s=8,columns:t=5}){return e.jsx(e.Fragment,{children:Array.from({length:s}).map((n,r)=>e.jsxs("tr",{className:"border-b border-border/60",children:[e.jsx("td",{className:"px-4 py-4",children:e.jsx(ln,{className:"h-4 w-4 rounded"})}),e.jsx("td",{className:"px-4 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ln,{className:"h-9 w-9 rounded-full"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ln,{className:"h-3.5 w-36"}),e.jsx(ln,{className:"h-3 w-24"})]})]})}),Array.from({length:Math.max(t-2,1)}).map((a,i)=>e.jsx("td",{className:"px-4 py-4",children:e.jsx(ln,{className:"h-3.5 w-20"})},i))]},r))})}function rOn({count:s=6}){return e.jsx("div",{className:"space-y-3",children:Array.from({length:s}).map((t,n)=>e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ln,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ln,{className:"h-4 w-2/5"}),e.jsx(ln,{className:"h-3 w-3/5"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(ln,{className:"h-6 w-16 rounded-full"}),e.jsx(ln,{className:"h-6 w-20 rounded-full"})]})]},n))})}function H2t({filtered:s,onAdd:t,onImport:n,onClearFilters:r}){return e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 px-6 py-14 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:"h-6 w-6",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",strokeLinecap:"round"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M19 8v6M22 11h-6",strokeLinecap:"round"})]})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:s?"No contacts match these filters":"Your database is empty"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s?"Try a different search or clear the filters to see everyone.":"Add someone manually or import your existing contacts to get started."})]}),e.jsx("div",{className:"mt-1 flex flex-wrap items-center justify-center gap-2",children:s?e.jsx("button",{onClick:r,className:"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground",children:"Clear filters"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:t,className:"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground",children:"Add contact"}),e.jsx("button",{onClick:n,className:"rounded-full border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-accent",children:"Import contacts"})]})})]})}function kZt(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 G2t(s){if(!s)return null;const t=Ou(s);if(!t)return null;const n=new Date;n.setHours(0,0,0,0);const r=new Date(n.getFullYear(),t.getMonth(),t.getDate());return rs.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",icon:Pl,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:Zr,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:aj,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Hf,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:sa,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:Px,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:Wo,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:"active-buyers",title:"Active Buyers",icon:Rr,color:"text-sky-600 dark:text-sky-400",match:(s,t)=>t.hasCriteria},{key:"missing-criteria",title:"No Home Search",icon:dq,color:"text-orange-600 dark:text-orange-400",match:(s,t)=>!t.hasCriteria},{key:"missing-info",title:"Missing Info",icon:nl,color:"text-slate-600 dark:text-slate-400",match:s=>kZt(s)}];function aOn({contacts:s,contactDealsMap:t,websiteActiveIds:n,criteriaContactIds:r,totalCount:a,activeKey:i,onSelectSegment:l,currentFilters:o,currentSortBy:c,activeViewId:d,onApplyView:u,onClearAll:h}){const{data:m}=Lnt(),p=vYt(),f=bYt(),[g,v]=_.useState(!1),[y,b]=_.useState(""),w=_.useMemo(()=>{const P={"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,"active-buyers":0,"missing-criteria":0};if(!s)return P;for(const M of s){const I={hasDeal:!!(t&&t[M.id]),daysToBirthday:G2t(M.birthday),daysToAnniv:G2t(M.home_anniversary),hasCriteria:!!(r!=null&&r.has(M.id))};for(const D of W2t)D.key!=="website-active"&&D.match(M,I)&&P[D.key]++}return P},[s,t,n,r]),S=!!o.search||!!o.type&&o.type!=="all"||!!o.status&&o.status!=="all"||!!o.behavior&&Object.values(o.behavior).some(P=>P!==void 0&&P!==!1),C=async()=>{y.trim()&&(await p.mutateAsync({name:y.trim(),filters:o,sort_by:c}),b(""),v(!1))},E="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:h,className:Ct(E,!i&&!d?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(On,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:a.toLocaleString()})]}),m==null?void 0:m.map(P=>{const M=d===P.id;return e.jsxs("div",{className:Ct(E,"group pr-1",M?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>u(P.id,P.filters,P.sort_by),children:P.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${P.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(P.id),M&&h()},children:e.jsx(er,{className:"h-3 w-3"})})]},P.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),W2t.map(P=>{const M=P.icon,I=w[P.key],D=i===P.key;return e.jsxs("button",{type:"button",onClick:()=>l(D?null:P.key),"aria-pressed":D,className:Ct(E,D?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!D&&I===0&&"opacity-55"),children:[e.jsx(M,{className:Ct("h-3.5 w-3.5",D?"":P.color)}),P.title,e.jsx("span",{className:"tabular-nums opacity-70",children:I.toLocaleString()})]},P.key)}),e.jsxs(z,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>v(!0),children:[e.jsx(tP,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(Is,{open:g,onOpenChange:v,children:e.jsxs(Ls,{className:"sm:max-w-sm",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Save this view"}),e.jsx(_r,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(pe,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:y,onChange:P=>b(P.target.value),onKeyDown:P=>P.key==="Enter"&&C()}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(z,{onClick:C,disabled:!y.trim()||p.isPending,children:"Save view"})]})]})})]})}const K2t=[{key:"relationship",label:"Relationship"},{key:"buyerCriteria",label:"Looking For"},{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"}],jze={relationship:!0,buyerCriteria:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},Y2t="innercircle:contact-columns:v1";function iOn(){const[s,t]=_.useState(()=>{try{const a=localStorage.getItem(Y2t);if(a)return{...jze,...JSON.parse(a)}}catch{}return jze});_.useEffect(()=>{try{localStorage.setItem(Y2t,JSON.stringify(s))}catch{}},[s]);const n=_.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=_.useCallback(()=>t(jze),[]);return{columns:s,toggle:n,reset:r}}function oOn({columns:s,onToggle:t,onReset:n}){const r=K2t.filter(a=>s[a.key]).length;return e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(p6,{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(nd,{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(Dx,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:K2t.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(za,{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."})]})]})}const Vq=1e3;function SZt(){const s=ha();return rt({queryKey:["contact-criteria-map",s],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const t=[];for(let r=0;;r+=Vq){const{data:a,error:i}=await U.from("contact_property_alerts").select("id, contact_id, is_active, min_price, max_price, min_beds, min_baths, min_sqft, max_sqft, cities, zip_codes, property_types, frequency, last_sent_at").eq("owner_user_id",s).range(r,r+Vq-1);if(i)throw i;const l=a||[];if(t.push(...l),l.length{const n=new Date(Date.now()-6048e5).toISOString(),r=[];for(let o=0;;o+=Vq){const{data:c,error:d}=await U.from("contact_property_alerts").select("id, contact_id").eq("owner_user_id",t).range(o,o+Vq-1);if(d)throw d;const u=c||[];if(r.push(...u),u.length[o.id,o.contact_id])),i={},l=r.map(o=>o.id);for(let o=0;o{const i={contact_id:n,owner_user_id:s,is_active:a.is_active??!0,min_price:a.min_price||null,max_price:a.max_price||null,min_beds:a.min_beds||null,min_baths:a.min_baths||null,min_sqft:a.min_sqft||null,max_sqft:a.max_sqft||null,cities:a.cities||[],zip_codes:a.zip_codes||[],property_types:a.property_types||[],frequency:a.frequency||"daily"};if(r){const{error:l}=await U.from("contact_property_alerts").update(i).eq("id",r);if(l)throw l}else{const{error:l}=await U.from("contact_property_alerts").insert(i);if(l)throw l}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["contact-criteria-map"]}),t.invalidateQueries({queryKey:["contact-property-alert",r.contactId]})}})}function dOn(){const s=$t();return mt({mutationFn:async({id:t})=>{const{error:n}=await U.from("contact_property_alerts").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["contact-criteria-map"]}),n.contactId&&s.invalidateQueries({queryKey:["contact-property-alert",n.contactId]})}})}const yU=s=>String(s??"").trim().toLowerCase();function uOn(s,t){const n=yU(s).replace(/[\s_-]+/g,""),r=yU(t).replace(/[\s_-]+/g,"");return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function hOn(s,t){var m,p,f;const n=[],r=[],a=t.price??null,i=t.bedrooms??null,l=t.bathrooms??null,o=t.sqft??null;if((((m=s.cities)==null?void 0:m.length)||0)>0||(((p=s.zip_codes)==null?void 0:p.length)||0)>0){const g=!!t.city&&(s.cities||[]).some(y=>yU(y)===yU(t.city)),v=!!t.zip&&(s.zip_codes||[]).some(y=>yU(y)===yU(t.zip));g?n.push(`Wants ${t.city}`):v?n.push(`Wants ${t.zip}`):(t.city||t.zip)&&r.push(`Looking in ${[...s.cities||[],...s.zip_codes||[]].slice(0,3).join(", ")}`)}a!==null&&(s.min_price&&as.max_price?r.push(`Over their $${Math.round(s.max_price/1e3)}k budget`):(s.min_price||s.max_price)&&n.push("In their price range")),s.min_beds&&(i!==null&&i0&&(s.min_sqft&&os.max_sqft?r.push("Over their max sqft"):(s.min_sqft||s.max_sqft)&&n.push("Size fits")),(((f=s.property_types)==null?void 0:f.length)||0)>0&&t.propertyType&&(s.property_types.some(v=>uOn(v,t.propertyType))?n.push(String(t.propertyType).replace(/_/g," ")):r.push(`Wants ${s.property_types.slice(0,2).join(" / ")}`));const d=r.length===0&&n.length>0,u=n.length+r.length,h=u===0?0:Math.round(n.length/u*100);return{matches:d,score:h,reasons:n,misses:r}}function mOn(s,t,n,r={}){const a=[];for(const i of s){const l=t[i.id];if(!l)continue;const o=hOn(l,n);(o.matches||r.includeNearMatches&&o.misses.length===1&&o.score>=50)&&a.push({contact:i,criteria:l,result:o})}return a.sort((i,l)=>l.result.score-i.result.score||i.result.misses.length-l.result.misses.length)}const Qce=s=>s>=1e3?`$${Math.round(s/1e3)}k`:`$${s}`;function CZt(s){var t,n,r;return s?!!(s.min_price||s.max_price||s.min_beds||s.min_baths||s.min_sqft||s.max_sqft||(t=s.cities)!=null&&t.length||(n=s.zip_codes)!=null&&n.length||(r=s.property_types)!=null&&r.length):!1}function pOn(s){var r;if(!s)return"";const t=[];s.min_price&&s.max_price?t.push(`${Qce(s.min_price)}–${Qce(s.max_price)}`):s.max_price?t.push(`up to ${Qce(s.max_price)}`):s.min_price&&t.push(`${Qce(s.min_price)}+`),s.min_beds&&t.push(`${s.min_beds}+ bd`),s.min_baths&&t.push(`${s.min_baths}+ ba`),s.min_sqft&&t.push(`${s.min_sqft.toLocaleString()}+ sqft`);const n=[...s.cities||[],...s.zip_codes||[]];return n.length&&t.push(n.length<=2?n.join(", "):`${n.slice(0,2).join(", ")} +${n.length-2}`),!n.length&&((r=s.property_types)!=null&&r.length)&&t.push(s.property_types.slice(0,2).join(", ")),t.join(" · ")}function Z2t({criteria:s,onEdit:t,showAlertState:n,matchCount:r,className:a,compact:i}){const l=pOn(s);return CZt(s)?e.jsxs("button",{type:"button",onClick:t?c=>{c.stopPropagation(),t()}:void 0,className:Ct("group/crit inline-flex max-w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left",t&&"hover:bg-accent transition-colors",a),title:l,children:[n?s!=null&&s.is_active?e.jsx($g,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):e.jsx(pS,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(Rr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:Ct("truncate",i?"text-[11px]":"text-xs","text-foreground/80"),children:l}),!!r&&r>0&&e.jsxs("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 text-[10px] font-semibold text-primary tabular-nums",children:[r," new"]})]}):t?e.jsxs("button",{type:"button",onClick:c=>{c.stopPropagation(),t()},className:Ct("inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-primary/40 px-2 py-0.5","text-[11px] text-muted-foreground hover:bg-primary/5 hover:text-primary transition-colors",a),children:[e.jsx(sn,{className:"h-3 w-3"}),"Add home search"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}const AZt=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function fOn(){const s=ha();return rt({queryKey:["agent-lead-site-config",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",s).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(n||!t)return{cities:[],zipCodes:[]};const r=t.theme_config||{},a=Array.isArray(r.searchCities)?r.searchCities:[];t.mls_market_area&&!a.includes(t.mls_market_area)&&a.unshift(t.mls_market_area);const i=Array.isArray(r.searchZipCodes)?r.searchZipCodes:[];return{cities:a,zipCodes:i}}})}function X2t({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=_.useState(!1),c=_.useRef(null),d=_.useRef(null);_.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.trim().toLowerCase()));return e.jsxs("div",{className:"relative",ref:d,children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(pe,{value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),n(s),o(!1))},placeholder:a})}),e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(sn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:c,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(Ha,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function EZt({value:s,onChange:t,hasIdx:n=!0,idxNote:r}){const[a,i]=_.useState(""),[l,o]=_.useState(""),{data:c}=fOn(),d=((c==null?void 0:c.cities)||[]).filter(f=>{var g;return!((g=s.cities)!=null&&g.includes(f))}),u=((c==null?void 0:c.zipCodes)||[]).filter(f=>{var g;return!((g=s.zip_codes)!=null&&g.includes(f))}),h=f=>{var v;const g=f.trim();g&&!((v=s.cities)!=null&&v.includes(g))&&t(y=>({...y,cities:[...y.cities||[],g]})),i("")},m=f=>{var v;const g=f.trim();g&&!((v=s.zip_codes)!=null&&v.includes(g))&&t(y=>({...y,zip_codes:[...y.zip_codes||[],g]})),o("")},p=f=>{t(g=>{const v=g.property_types||[];return{...g,property_types:v.includes(f)?v.filter(y=>y!==f):[...v,f]}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Nd,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{type:"number",placeholder:"Min price",value:s.min_price??"",onChange:f=>t(g=>({...g,min_price:f.target.value?Number(f.target.value):null}))}),e.jsx(pe,{type:"number",placeholder:"Max price",value:s.max_price??"",onChange:f=>t(g=>({...g,max_price:f.target.value?Number(f.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(W4,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(ls,{value:s.min_beds?String(s.min_beds):"any",onValueChange:f=>t(g=>({...g,min_beds:f==="any"?null:Number(f)})),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"any",children:"Any"}),[1,2,3,4,5].map(f=>e.jsxs(He,{value:String(f),children:[f,"+"]},f))]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ey,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(ls,{value:s.min_baths?String(s.min_baths):"any",onValueChange:f=>t(g=>({...g,min_baths:f==="any"?null:Number(f)})),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(f=>e.jsxs(He,{value:String(f),children:[f,"+"]},f))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Q4,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{type:"number",placeholder:"Min sqft",value:s.min_sqft??"",onChange:f=>t(g=>({...g,min_sqft:f.target.value?Number(f.target.value):null}))}),e.jsx(pe,{type:"number",placeholder:"Max sqft",value:s.max_sqft??"",onChange:f=>t(g=>({...g,max_sqft:f.target.value?Number(f.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(X2t,{value:a,onChange:i,onAdd:h,suggestions:d,placeholder:"Type a city and press Enter..."}),s.cities&&s.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:s.cities.map(f=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[f,e.jsx("button",{type:"button",onClick:()=>t(g=>{var v;return{...g,cities:(v=g.cities)==null?void 0:v.filter(y=>y!==f)}}),children:e.jsx(er,{className:"h-3 w-3"})})]},f))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(X2t,{value:l,onChange:o,onAdd:m,suggestions:u,placeholder:"Type a zip code and press Enter...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),s.zip_codes&&s.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:s.zip_codes.map(f=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[f,e.jsx("button",{type:"button",onClick:()=>t(g=>{var v;return{...g,zip_codes:(v=g.zip_codes)==null?void 0:v.filter(y=>y!==f)}}),children:e.jsx(er,{className:"h-3 w-3"})})]},f))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(sa,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:AZt.map(f=>{var g;return e.jsx(ze,{variant:(g=s.property_types)!=null&&g.includes(f)?"default":"outline",className:"cursor-pointer",onClick:()=>p(f),children:f},f)})})]}),n?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Email new matching listings"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatic alerts from your MLS feed"})]}),e.jsx(mn,{checked:s.is_active??!0,onCheckedChange:f=>t(g=>({...g,is_active:f}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Frequency"}),e.jsxs(ls,{value:s.frequency||"daily",onValueChange:f=>t(g=>({...g,frequency:f})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"daily",children:"Daily"}),e.jsx(He,{value:"weekly",children:"Weekly"})]})]})]})]}):e.jsxs("div",{className:"rounded-lg border border-dashed bg-muted/40 p-3 space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-2",children:[e.jsx(gS,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:"Saved here so you can match listings to this contact any time. Automatic new-listing emails need an IDX website."})]}),r]})]})}function xOn({open:s,onOpenChange:t,contactId:n,contactName:r,existing:a}){const{hasIdx:i}=mf(),l=cOn(),o=dOn(),[c,d]=_.useState({});_.useEffect(()=>{s&&d({is_active:(a==null?void 0:a.is_active)??!0,min_price:(a==null?void 0:a.min_price)??null,max_price:(a==null?void 0:a.max_price)??null,min_beds:(a==null?void 0:a.min_beds)??null,min_baths:(a==null?void 0:a.min_baths)??null,min_sqft:(a==null?void 0:a.min_sqft)??null,max_sqft:(a==null?void 0:a.max_sqft)??null,cities:(a==null?void 0:a.cities)??[],zip_codes:(a==null?void 0:a.zip_codes)??[],property_types:(a==null?void 0:a.property_types)??[],frequency:(a==null?void 0:a.frequency)??"daily"})},[s,a]);const u=async()=>{try{await l.mutateAsync({contactId:n,existingId:(a==null?void 0:a.id)??null,values:c}),ne.success(`Home search saved for ${r}`),t(!1)}catch(m){ne.error((m==null?void 0:m.message)||"Could not save home search")}},h=async()=>{if(a!=null&&a.id)try{await o.mutateAsync({id:a.id,contactId:n}),ne.success("Home search removed"),t(!1)}catch(m){ne.error((m==null?void 0:m.message)||"Could not remove home search")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:["Home search for ",r]}),e.jsx(_r,{children:"What are they looking for? This shows on your contacts dashboard so you can match new listings to them."})]}),e.jsx(EZt,{value:c,onChange:d,hasIdx:i,idxNote:e.jsx(z,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(or,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs(hr,{className:"gap-2 sm:gap-2",children:[(a==null?void 0:a.id)&&e.jsxs(z,{variant:"ghost",onClick:h,disabled:o.isPending,className:"text-destructive hover:text-destructive mr-auto",children:[o.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4 mr-1"}),"Remove"]}),e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:u,disabled:l.isPending,children:[l.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-1"}),"Save"]})]})]})})}const Wp=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),gOn=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function yOn(s,t){const n=s.address||[s.city,s.state].filter(Boolean).join(", ")||"a home";return t?`${t}, this one looks like your kind of home — ${n}`:`Thought of you: ${n}`}function vOn(s){const t=[];return s.bedrooms&&t.push(`${s.bedrooms} bedrooms`),s.bathrooms&&t.push(`${s.bathrooms} baths`),s.city&&t.push(`in ${s.city}`),`Hi {{first_name}}, This just came across my desk and it lines up with what you told me you're looking for${t.length?` — ${t.join(", ")}`:""}. I wanted you to see it before it gets busy. Want me to set up a private showing?`}function bOn(s,t,n){const r=(s.photos||[]).filter(Boolean),a=r[0]||"",i=r[1]||"",l=r[2]||"",o=s.publicUrl||"",c=[s.city,s.state].filter(Boolean).join(", ")+(s.zip?` ${s.zip}`:""),d=s.address||c||"A home worth seeing",u=s.price?gOn(Number(s.price)):"",h=(n==null?void 0:n.name)||"",m=(n==null?void 0:n.title)||"Real Estate Agent",p=(n==null?void 0:n.phone)||"",f=(n==null?void 0:n.email)||"",g=(n==null?void 0:n.avatar_url)||"",v=(n==null?void 0:n.brokerage_name)||"",y=h?h.split(" ").map(S=>S[0]).slice(0,2).join("").toUpperCase():"A",b=(S,C,E=!1)=>`
${Wp(S)}
${Wp(C)}
`,w=[];return s.bedrooms&&w.push(b(String(s.bedrooms),"Beds")),s.bathrooms&&w.push(b(String(s.bathrooms),"Baths")),s.sqft&&w.push(b(Number(s.sqft).toLocaleString(),"Sq Ft")),s.propertyType&&w.push(b(s.propertyType,"Type")),` ${Wp(d)}
${Wp([u,d].filter(Boolean).join(" · "))}
${a?` `:""} ${w.length?` `:""} ${t?` `:""} ${o?` `:""} ${i||l?` `:""} ${h?` `:""}
 
${o?``:""} ${Wp(d)} ${o?"":""}
${u?``:""}
A home matched to your search${Wp(u)}

${Wp(d)}

${s.address&&c?`

${Wp(c)}

`:""}
${w.join("")}

${Wp(t)}

View this home  →

See all the photos and details

${i?``:""} ${l?``:""}
${g?`${Wp(h)}`:`
${Wp(y)}
`}
${Wp(h)}
${Wp(m)}${v?` · ${Wp(v)}`:""}
${p?`${Wp(p)}`:""} ${p&&f?'  ·  ':""} ${f?`${Wp(f)}`:""}

You're receiving this because you asked to hear about homes that fit your search.

`}function _On({open:s,onOpenChange:t,property:n,recipient:r}){const{user:a}=hs(),i=ha(),{isGmailConnected:l,gmailEmail:o}=bg(),{isReady:c,settings:d}=NL(),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState(!1),[v,y]=_.useState(!1),{data:b}=rt({queryKey:["match-email-agent",i],enabled:!!i&&s,queryFn:async()=>{const{data:I}=await U.from("profiles").select("name, title, email, phone, avatar_url, brokerage_name").eq("id",i).maybeSingle();return I??null}});_.useEffect(()=>{!s||!r||(h(yOn(n,r.first_name)),p(vOn(n)),g(!1))},[s,r==null?void 0:r.id]);const w=_.useMemo(()=>m.replace(/\{\{first_name\}\}/gi,(r==null?void 0:r.first_name)||"there"),[m,r==null?void 0:r.first_name]),S=_.useMemo(()=>bOn(n,w,b??null),[n,w,b]),C=l||c,E=!!(r!=null&&r.email&&u.trim()&&C&&!v),P=async()=>{if(!(!E||!(r!=null&&r.email))){y(!0);try{if(l){const{data:I,error:D}=await U.functions.invoke("gmail-send",{body:{to:r.email,subject:u.trim(),body:S,contactId:r.id}});if(D)throw D;if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Failed to send")}else{const I=(d==null?void 0:d.display_name)||"ReLevelUp",D=`${I.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,{data:F,error:q}=await U.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:r.email,from_email:`${I} <${D}>`,subject:u.trim(),body_html:S,reply_to:(d==null?void 0:d.reply_to_email)||(b==null?void 0:b.email)||void 0,contact_id:r.id}});if(q)throw q;if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Failed to send")}if(a)try{await U.from("bulk_email_sends").insert({user_id:a.id,contact_id:r.id,contact_email:r.email,subject:u.trim(),source:"listing_match"})}catch{}ne.success(`Sent to ${r.first_name}`),t(!1)}catch(I){ne.error((I==null?void 0:I.message)||"Could not send the email")}finally{y(!1)}}},M=r?`${r.first_name} ${r.last_name||""}`.trim():"";return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"w-[95vw] max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-primary"}),"Email this home to ",M||"your buyer"]}),e.jsx(_r,{children:C?e.jsxs(e.Fragment,{children:["Sending from ",l?`your Gmail (${o})`:"your mass email sender","."]}):"Connect Gmail or set up mass email first."})]}),!C&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"You don't have an email sender connected yet. Connect Gmail in Settings, or finish mass email setup, and this will send straight from you."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-sm",children:[e.jsx("span",{className:"font-medium",children:M}),e.jsx(ze,{variant:"secondary",className:"font-normal",children:r==null?void 0:r.email})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"match-subject",className:"text-xs",children:"Subject"}),e.jsx(pe,{id:"match-subject",value:u,onChange:I=>h(I.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"match-message",className:"text-xs",children:"Your note"}),e.jsx(Ps,{id:"match-message",rows:6,value:m,onChange:I=>p(I.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Use ","{{first_name}}"," anywhere and we'll swap in their name."]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>g(I=>!I),children:[f?e.jsx(Yf,{className:"h-4 w-4 mr-2"}):e.jsx(xa,{className:"h-4 w-4 mr-2"}),f?"Hide preview":"Preview email"]}),f&&e.jsx(Ki,{className:"h-[380px] rounded-lg border",children:e.jsx("iframe",{title:"Email preview",srcDoc:S,className:"w-full h-[1200px] border-0"})})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:P,disabled:!E,children:[v?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send email"]})]})]})})}const wOn={city:"",state:"",zip:"",price:null,bedrooms:null,bathrooms:null,sqft:null,propertyType:"",address:""};function jOn({open:s,onOpenChange:t,contacts:n}){const r=zn(),{data:a}=SZt(),{data:i}=Met(),[l,o]=_.useState(wOn),[c,d]=_.useState(!0),[u,h]=_.useState(""),[m,p]=_.useState(null),f=S=>o(C=>({...C,...S})),g=S=>{h(S);const C=(i||[]).find(E=>E.id===S);C&&f({address:C.property_address||"",city:C.city||"",state:C.state||"",zip:"",price:C.price??null,bedrooms:C.bedrooms??null,bathrooms:C.bathrooms??null,sqft:C.square_footage??null,propertyType:C.property_type||""})},v=!!(l.city||l.zip||l.price),y=_.useMemo(()=>{const S=i==null?void 0:i.find(P=>P.id===u),C=Array.isArray(S==null?void 0:S.photos)?S.photos.slice().sort((P,M)=>!!M.is_primary!=!!P.is_primary?M.is_primary?1:-1:(P.sort_order??0)-(M.sort_order??0)).map(P=>P.photo_url).filter(Boolean):[],E=S&&S.is_public&&S.is_approved?`${window.location.origin}/public/listing/${S.slug||S.id}`:null;return{address:l.address||void 0,city:l.city||void 0,state:l.state||void 0,zip:l.zip||void 0,price:l.price,bedrooms:l.bedrooms,bathrooms:l.bathrooms,sqft:l.sqft,propertyType:l.propertyType||void 0,photos:C,publicUrl:E}},[i,u,l]),b=_.useMemo(()=>!a||!v?[]:mOn(n,a,l,{includeNearMatches:c}),[n,a,l,c,v]),w=_.useMemo(()=>Object.keys(a||{}).length,[a]);return e.jsxs(Wg,{open:s,onOpenChange:t,children:[e.jsxs(gg,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto",children:[e.jsxs(Dy,{children:[e.jsxs(Ry,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4 text-primary"}),"Who wants this house?"]}),e.jsx(Z9,{children:"Enter a property — or pick one of your listings — and we'll show the contacts whose saved home search fits. No IDX needed."})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs(Qr,{defaultValue:i!=null&&i.length?"listing":"manual",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsx(Wt,{value:"listing",children:"My listings"}),e.jsx(Wt,{value:"manual",children:"Enter a property"})]}),e.jsx(Kt,{value:"listing",className:"pt-3",children:i!=null&&i.length?e.jsxs(ls,{value:u,onValueChange:g,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose a listing…"})}),e.jsx(as,{children:i.map(S=>e.jsxs(He,{value:S.id,children:[[S.property_address,S.city].filter(Boolean).join(", "),S.price?` — ${lm(Number(S.price))}`:""]},S.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:`You don't have any Listing Exchange listings yet. Use "Enter a property" instead.`})}),e.jsx(Kt,{value:"manual",className:"pt-3",children:e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Saw something in your MLS? Type the basics here."})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Address (optional)"}),e.jsx(pe,{value:l.address||"",onChange:S=>f({address:S.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"City"}),e.jsx(pe,{value:l.city||"",onChange:S=>f({city:S.target.value}),placeholder:"Cypress"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Zip"}),e.jsx(pe,{value:l.zip||"",onChange:S=>f({zip:S.target.value}),placeholder:"90630"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Price"}),e.jsx(pe,{type:"number",value:l.price??"",onChange:S=>f({price:S.target.value?Number(S.target.value):null}),placeholder:"750000"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Sqft"}),e.jsx(pe,{type:"number",value:l.sqft??"",onChange:S=>f({sqft:S.target.value?Number(S.target.value):null}),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Beds"}),e.jsx(pe,{type:"number",value:l.bedrooms??"",onChange:S=>f({bedrooms:S.target.value?Number(S.target.value):null}),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Baths"}),e.jsx(pe,{type:"number",step:"0.5",value:l.bathrooms??"",onChange:S=>f({bathrooms:S.target.value?Number(S.target.value):null}),placeholder:"2"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Property type"}),e.jsxs(ls,{value:l.propertyType||"any",onValueChange:S=>f({propertyType:S==="any"?"":S}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"any",children:"Any"}),AZt.map(S=>e.jsx(He,{value:S,children:S},S))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w," ",w===1?"contact has":"contacts have"," a saved home search"]}),e.jsx(z,{variant:c?"secondary":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(S=>!S),children:c?"Including close matches":"Exact matches only"})]}),v?b.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(sa,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"No contacts match this property yet. Add home searches to your buyers so matches show up here."]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[b.length," ",b.length===1?"match":"matches"]}),b.map(({contact:S,result:C})=>{const E=`${S.first_name} ${S.last_name||""}`.trim();return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx(ert,{firstName:S.first_name,lastName:S.last_name||void 0,avatarUrl:S.avatar_url||void 0,email:S.email||void 0,size:36}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("button",{type:"button",className:"font-medium text-sm hover:underline",onClick:()=>r(`/mission-control/contacts/${S.id}`),children:E}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[C.reasons.slice(0,4).map(P=>e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:P},P)),C.misses.map(P=>e.jsx(ze,{variant:"outline",className:"text-[10px] text-muted-foreground",children:P},P))]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[S.email&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Email ${E}`,onClick:()=>p(S),children:e.jsx(on,{className:"h-4 w-4"})}),S.phone&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Text ${E}`,asChild:!0,children:e.jsx("a",{href:`sms:${S.phone}`,children:e.jsx(qi,{className:"h-4 w-4"})})})]})]},S.id)})]}):e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(Rr,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"Add a city, zip, or price to see matches."]})]})]}),e.jsx(_On,{open:!!m,onOpenChange:S=>!S&&p(null),property:y,recipient:m})]})}function NOn(){var wu;const s=zn(),[t,n]=Gl(),{user:r}=hs(),a=XW(),i=$t(),{columns:l,toggle:o,reset:c}=iOn(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:p}=yae(),{activeContactIds:f,hasLeadSite:g}=RRn(),{data:v}=UFn(),{data:y}=Q_(),{data:b}=qFn(),{data:w}=hz(),{data:S}=$ae(),{hasIdx:C}=mf(),{data:E}=SZt(),{data:P}=lOn(!!C),M=_.useMemo(()=>new Set(Object.entries(E||{}).filter(([,js])=>CZt(js)).map(([js])=>js)),[E]),[I,D]=_.useState(null),[F,q]=_.useState(!1),[G,V]=_.useState(new Set),[H,K]=_.useState("any"),Z=vLe(),oe=zet(),re=aBt(),ae=rBt(),[J,te]=_.useState(""),[ce,ve]=_.useState(!1),[me,he]=_.useState(d||"all"),[ge,Ee]=_.useState(u||"all"),[Ne,Pe]=_.useState("date-added"),[Oe,ke]=_.useState("all"),[Ve,_e]=_.useState({}),Ae=_.useMemo(()=>Object.values(Ve).filter(js=>js!==void 0&&js!==!1&&js!=="").length,[Ve]),[Se,We]=_.useState(!1),[qe,Be]=_.useState([]),{neighborhoods:Ze}=Jnt(),$e=_.useMemo(()=>_Zt(Ze,qe),[Ze,qe]),{behaviorMap:Xe,hasLeadSite:nt}=FFn(),[Ge,Je]=_.useState(h),[ut,lt]=_.useState(null),[qt,zt]=_.useState(!1),[Zt,ms]=_.useState(!1),[Dt,It]=_.useState(null),[qs,wt]=_.useState(""),[Us,Es]=_.useState(new Set),[kn,Sn]=_.useState(!1),[bn,cr]=_.useState(!1),Fs=Math.max(1,parseInt(t.get("page")||"1",10)||1),[cn,lr]=_.useState(Fs),Tn=_.useCallback(js=>{lr(Ma=>{const to=typeof js=="function"?js(Ma):js;return n(Ta=>{const so=new URLSearchParams(Ta);return to<=1?so.delete("page"):so.set("page",String(to)),so},{replace:!0}),to})},[]),[Yn,fs]=_.useState(50),[wn,As]=_.useState("my"),[Ss,pr]=_.useState(!1),[hn,Pn]=_.useState(!1),{data:Gs}=K_(),{addToLeadPond:an}=hHt(Gs==null?void 0:Gs.teamId),{ponds:tr}=yst(Gs==null?void 0:Gs.teamId),Lr=tr.filter(js=>js.has_access),[Yt,it]=_.useState(null),[gt,ft]=_.useState(""),Lt=!!((wu=Gs==null?void 0:Gs.team)!=null&&wu.lead_pond_enabled&&(Gs!=null&&Gs.teamId)),Mt=!!(Gs!=null&&Gs.teamId),[Qt,ks]=_.useState([]),[gs,Vt]=_.useState(!1),Vs=js=>{ks([js]),Vt(!0)},Zs=js=>{ks(js),Vt(!0)},Zn=(js,Ma)=>{Gs!=null&&Gs.teamId&&js.forEach(to=>{an.mutate({contact_id:to,team_id:Gs.teamId,pond_id:Ma||null})})},Or=js=>{var Ma;if(Gs!=null&&Gs.teamId){if(Lr.length>1){ft(Lr[0].id),it(js);return}Zn(js,((Ma=Lr[0])==null?void 0:Ma.id)||null)}},oa=js=>Or([js]),aa=js=>Or(js),Kr=_.useCallback(js=>{cr(!1),Es(Ma=>{const to=new Set(Ma);return to.has(js)?to.delete(js):to.add(js),to})},[]);_.useEffect(()=>{if(!(r!=null&&r.id))return;const js=U.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()=>{U.removeChannel(js)}},[i,r==null?void 0:r.id]),_.useEffect(()=>{u&&Ee(u)},[u]);const[Tr,Hr]=_.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1,birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]}),[Ba,Ja]=_.useState(!1);_.useEffect(()=>{h&&Je(!0)},[h]),_.useEffect(()=>{var js;ut&&Hr({first_name:ut.first_name||"",last_name:ut.last_name||"",email:ut.email||"",phone:ut.phone||"",address:ut.address||"",city:ut.city||"",state:ut.state||"",zip_code:ut.zip_code||"",address2_label:ut.address2_label||"",address2:ut.address2||"",address2_city:ut.address2_city||"",address2_state:ut.address2_state||"",address2_zip:ut.address2_zip||"",mail_to_secondary:!!ut.mail_to_secondary,birthday:ut.birthday||"",home_anniversary:ut.home_anniversary||"",spouse_name:ut.spouse_name||"",spouse_email:ut.spouse_email||"",lead_source_id:ut.lead_source_id||"",notes:ut.notes||"",tagIds:((js=ut.tags)==null?void 0:js.map(Ma=>Ma.relationship_type_id))||[]})},[ut]);const Ro=_.useMemo(()=>{const js=new Set;return w==null||w.forEach(Ma=>{(Ma.name==="Recruits"||Ma.name==="Brokerage Agents")&&js.add(Ma.id)}),js},[w]),ji=_.useMemo(()=>Array.from(G).some(js=>Ro.has(js)),[G,Ro]),Oa=_.useMemo(()=>{const js={};return(m||[]).forEach(Ma=>{js[Ma.id]=`${Ma.first_name||""} ${Ma.last_name||""}`.trim()}),js},[m]),Ao=_.useMemo(()=>{const js=new Set;return(m||[]).forEach(Ma=>{var Ta;const to=(((Ta=Ma.lead_source_ref)==null?void 0:Ta.name)||Ma.lead_source||"").trim();to&&js.add(to)}),Array.from(js).sort((Ma,to)=>Ma.localeCompare(to))},[m]),uo=_.useMemo(()=>{if(!m)return[];let js=m.filter(Ta=>{var zc,Dp,hp,_g,Dv,nx,Pi,vm,Yg,hh,mh;const so=Ta.synced_source;if(!ji&&(so==="recruit"||so==="brokerage_agent")||$e&&!$e.has(Ta.id))return!1;const pi=J===""||`${Ta.first_name} ${Ta.last_name}`.toLowerCase().includes(J.toLowerCase())||((zc=Ta.email)==null?void 0:zc.toLowerCase().includes(J.toLowerCase()))||((Dp=Ta.phone)==null?void 0:Dp.includes(J))||((hp=Ta.city)==null?void 0:hp.toLowerCase().includes(J.toLowerCase()))||((_g=Ta.state)==null?void 0:_g.toLowerCase().includes(J.toLowerCase()))||((Dv=Ta.address)==null?void 0:Dv.toLowerCase().includes(J.toLowerCase()))||((nx=Ta.zip_code)==null?void 0:nx.toLowerCase().includes(J.toLowerCase())),$m=me==="all"||((Pi=Ta.tags)==null?void 0:Pi.some(pd=>pd.relationship_type_id===me)),al=G.size===0||(()=>{const pd=(S==null?void 0:S.filter(fd=>fd.contact_id===Ta.id).map(fd=>fd.tag_id))||[];return H==="any"?pd.some(fd=>G.has(fd)):Array.from(G).every(fd=>pd.includes(fd))})(),vo=!!((vm=Ta.address)!=null&&vm.trim()||(Yg=Ta.city)!=null&&Yg.trim()||(hh=Ta.state)!=null&&hh.trim()||(mh=Ta.zip_code)!=null&&mh.trim()),$x=Oe==="all"||Oe==="has-address"&&vo||Oe==="no-address"&&!vo,il=Ta,yl=Ve,E1=(yl.hasEmail===void 0||!!il.email===yl.hasEmail)&&(yl.hasPhone===void 0||!!il.phone===yl.hasPhone)&&(yl.hasAddress===void 0||vo===yl.hasAddress)&&(yl.hasBirthday===void 0||!!il.birthday===yl.hasBirthday)&&(yl.hasSpouse===void 0||!!(il.spouse_name||il.spouse_contact_id||il.spouse_email)===yl.hasSpouse)&&(yl.hasCompany===void 0||!!(il.company_name||il.job_title)===yl.hasCompany)&&(yl.hasNotes===void 0||!!(il.notes&&il.notes.trim())===yl.hasNotes)&&(!yl.city||(il.city||"").toLowerCase().includes(yl.city.toLowerCase()))&&(!yl.state||(il.state||"").toLowerCase().includes(yl.state.toLowerCase()))&&(!yl.zip||((il.zip||"")+(il.zip_code||"")).toLowerCase().includes(yl.zip.toLowerCase()))&&(!yl.birthdayMonth||!!il.birthday&&Ou(il.birthday).getMonth()+1===yl.birthdayMonth)&&(!yl.anniversaryMonth||((yl.anniversaryField||"home_anniversary")==="home_anniversary"?!!il.home_anniversary&&Ou(il.home_anniversary).getMonth()+1===yl.anniversaryMonth:!!il.wedding_anniversary&&Ou(il.wedding_anniversary).getMonth()+1===yl.anniversaryMonth))&&(!yl.dateAddedFrom||!!il.created_at&&il.created_at.slice(0,10)>=yl.dateAddedFrom)&&(!yl.dateAddedTo||!!il.created_at&&il.created_at.slice(0,10)<=yl.dateAddedTo)&&(()=>{var Ux;const pd=yl.leadSourceId;if(!pd)return!0;const fd=(((Ux=il.lead_source_ref)==null?void 0:Ux.name)||il.lead_source||"").trim();return pd==="none"?!fd&&!il.lead_source_id:pd.startsWith("name:")?fd.toLowerCase()===pd.slice(5).toLowerCase():il.lead_source_id===pd})();return pi&&$m&&al&&$x&&E1});ge==="not-touched-90"?js=js.filter(Ta=>{const so=Ta.relationshipScore.daysSinceTouch;return so===null||so>90}):ge==="at-risk"?js=js.filter(Ta=>Ta.relationshipScore.status==="at-risk"):ge==="cooling"?js=js.filter(Ta=>Ta.relationshipScore.status==="cooling"):ge==="warm"?js=js.filter(Ta=>Ta.relationshipScore.status==="warm"):ge==="has-deal"?js=js.filter(Ta=>b&&b[Ta.id]):ge==="no-deal"?js=js.filter(Ta=>!b||!b[Ta.id]):ge==="open-house"?js=js.filter(Ta=>{var ho;return(((ho=Ta.lead_source_ref)==null?void 0:ho.name)||Ta.lead_source)==="Open House"}):ge==="website-active"?js=js.filter(Ta=>f.has(Ta.id)):ge==="never-contacted"?js=js.filter(Ta=>Ta.relationshipScore.daysSinceTouch===null):ge==="vips"?js=js.filter(Ta=>Ta.relationshipScore.score>=80):ge==="missing-info"?js=js.filter(Ta=>kZt(Ta)):ge==="birthdays-soon"?js=js.filter(Ta=>{const so=JR(Ta.birthday);return so!==null&&so<=30}):ge==="anniversary-soon"?js=js.filter(Ta=>{const so=JR(Ta.home_anniversary);return so!==null&&so<=30}):ge==="in-drip"?js=js.filter(Ta=>((v==null?void 0:v[Ta.id])??0)>0):ge==="not-in-drip"?js=js.filter(Ta=>((v==null?void 0:v[Ta.id])??0)===0):ge==="active-buyers"?js=js.filter(Ta=>M.has(Ta.id)):ge==="missing-criteria"&&(js=js.filter(Ta=>!M.has(Ta.id)));const Ma=Ve;if(Ma.lastActive||Ma.registered||Ma.viewedListing||Ma.savedProperty||Ma.hasSavedSearch||Ma.requestedShowing||Ma.requestedValuation||Ma.websiteActiveOnly){const Ta=Date.now(),so={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};js=js.filter(ho=>{const pi=Xe.get(ho.id);if(Ma.lastActive==="never"){if(pi!=null&&pi.lastActiveAt)return!1}else if(Ma.lastActive){const $m=Ta-so[Ma.lastActive];if(!(pi!=null&&pi.lastActiveAt)||new Date(pi.lastActiveAt).getTime()<$m)return!1}return!(Ma.registered==="yes"&&!(pi!=null&&pi.registered)||Ma.registered==="no"&&(pi!=null&&pi.registered)||Ma.viewedListing==="any"&&!(pi&&pi.propertyViewCount>0)||Ma.viewedListing==="multiple7d"&&!(pi&&pi.propertyViewCount7d>=3)||Ma.savedProperty&&!(pi&&pi.savedListingCount>0)||Ma.hasSavedSearch&&!(pi&&pi.activeSavedSearchCount>0)||Ma.requestedShowing&&!(pi&&pi.showingRequests>0)||Ma.requestedValuation&&!(pi&&pi.valuationRequests>0)||Ma.websiteActiveOnly&&!f.has(ho.id))})}return js=[...js].sort((Ta,so)=>{switch(Ne){case"important-dates":{const ho=JR(Ta.birthday),pi=JR(so.birthday),$m=JR(Ta.home_anniversary),al=JR(so.home_anniversary),vo=[ho,$m].filter(il=>il!==null).sort((il,yl)=>(il??1/0)-(yl??1/0))[0]??1/0,$x=[pi,al].filter(il=>il!==null).sort((il,yl)=>(il??1/0)-(yl??1/0))[0]??1/0;return vo-$x}case"last-touched":{const ho=Ta.relationshipScore.lastTouchDate,pi=so.relationshipScore.lastTouchDate;return!ho&&!pi?0:ho?pi?new Date(ho).getTime()-new Date(pi).getTime():1:-1}case"next-touch":{const ho=Ta.relationshipScore.daysSinceTouch,pi=so.relationshipScore.daysSinceTouch;return ho===null&&pi===null?0:ho===null?-1:pi===null?1:pi-ho}case"score":return Ta.relationshipScore.score-so.relationshipScore.score;case"date-added":{const ho=Ta.created_at,pi=so.created_at;return!ho&&!pi?0:ho?pi?new Date(pi).getTime()-new Date(ho).getTime():-1:1}case"last-name":{const ho=(Ta.last_name||"").toLowerCase(),pi=(so.last_name||"").toLowerCase();if(ho!==pi)return ho.localeCompare(pi);const $m=(Ta.first_name||"").toLowerCase(),al=(so.first_name||"").toLowerCase();return $m.localeCompare(al)}case"name":default:{const ho=`${Ta.first_name||""} ${Ta.last_name||""}`.toLowerCase(),pi=`${so.first_name||""} ${so.last_name||""}`.toLowerCase();return ho.localeCompare(pi)}}}),js},[m,J,me,G,H,ge,Ne,b,S,f,v,Oe,Ve,Xe,ji,M,$e]),Ua=uo.length,Eo=Math.max(1,Math.ceil(Ua/Yn)),Ji=Math.min(cn,Eo),qa=_.useMemo(()=>{const js=(Ji-1)*Yn;return uo.slice(js,js+Yn)},[uo,Ji,Yn]),ar=_.useMemo(()=>{const js=(m||[]).length;return{total:js,label:js===0?"Build your database — add or import your first contacts.":`${js.toLocaleString()} ${js===1?"person":"people"} in your database`}},[m]),ui=_.useMemo(()=>{const js=m||[],Ma=js.filter(ho=>{var pi;return((pi=ho.relationshipScore)==null?void 0:pi.status)==="at-risk"}).length,to=js.filter(ho=>{var $m;const pi=($m=ho.relationshipScore)==null?void 0:$m.daysSinceTouch;return typeof pi=="number"&&pi<=7}).length,Ta=new Date().getMonth()+1,so=js.filter(ho=>ho.birthday?String(ho.birthday).split(/[-/T]/).map(Number)[1]===Ta:!1).length;return[{label:"Total contacts",value:ar.total.toLocaleString(),onClick:()=>{Ee("all"),Tn(1)},active:ge==="all"},{label:"Needs attention",value:Ma,onClick:()=>{Ee("at-risk"),Tn(1)},active:ge==="at-risk"},{label:"Touched this week",value:to,onClick:()=>{Ee("warm"),Tn(1)},active:ge==="warm"},{label:"Birthdays this month",value:so,onClick:()=>{Ee("birthdays-soon"),Tn(1)},active:ge==="birthdays-soon"}]},[m,ar.total,ge,Tn]),zo=_.useCallback(js=>{const Ma=new URLSearchParams;J&&Ma.set("search",J),me!=="all"&&Ma.set("type",me),ge!=="all"&&Ma.set("filter",ge),G.size>0&&(Ma.set("tags",Array.from(G).join(",")),Ma.set("tagMode",H));const to=Ma.toString();s(`/mission-control/contacts/${js}${to?`?${to}`:""}`)},[s,J,me,ge,G,H]),gl=_.useRef(!1);_.useEffect(()=>{if(!gl.current){gl.current=!0;return}Tn(1)},[J,me,G,H,ge,Ne,Oe,Ve]);const tl=_.useCallback(()=>{cr(!1),Es(js=>js.size>0?new Set:new Set(qa.map(Ma=>Ma.id)))},[qa]),Ll=_.useCallback(()=>{cr(!0),Es(new Set(uo.map(js=>js.id)))},[uo]),[Ku,uh]=_.useState(null),ym=_.useCallback((js,Ma)=>{te(js.search||""),he(js.type||"all"),Ee(js.status||"all"),_e(js.behavior||{}),Pe(Ma||"name")},[]),Ld=()=>{Hr({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1,birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Bm=async js=>{js.preventDefault();const Ma={...Tr,lead_source_id:Tr.lead_source_id||null};ut?(await oe.mutateAsync({id:ut.id,...Ma}),lt(null)):(await Z.mutateAsync(Ma),Je(!1)),Ld()},Sl=async js=>{await Qi("Are you sure you want to delete this contact?")&&await re.mutateAsync(js)};return e.jsx($s,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(sOn,{totalLabel:ar.label,stats:ui,search:J,onSearchChange:te,onAddContact:()=>Je(!0),onImportCsv:()=>zt(!0),onImportPhone:()=>ms(!0),onManageTags:()=>pr(!0),onHeatMap:()=>ve(!0),viewMode:wn,onViewModeChange:js=>As(js),showTeamTab:!!Gs&&(Gs.team.contact_visibility==="full_team"||Gs.team.contact_visibility==="leader_only"&&Gs.role==="team_leader"),showLeadPondTab:!!(Gs!=null&&Gs.team.lead_pond_enabled),extraActions:e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>s("/mission-control/sphere-map"),children:[e.jsx(XQ,{className:"h-4 w-4"}),"Map view"]}),e.jsxs(z,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>q(!0),children:[e.jsx(Rr,{className:"h-4 w-4"}),"Match a listing"]}),e.jsxs(z,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>Sn(!0),children:[e.jsx(u7,{className:"h-4 w-4"}),"Find duplicates"]}),e.jsx(bRn,{})]})}),e.jsx(CRn,{open:kn,onOpenChange:Sn}),e.jsx(jOn,{open:F,onOpenChange:q,contacts:m||[]}),I&&e.jsx(xOn,{open:!!I,onOpenChange:js=>{js||D(null)},contactId:I.id,contactName:I.name,existing:(E==null?void 0:E[I.id])??null}),wn==="team"?e.jsx(dIe,{}):wn==="lead-pond"&&Gs?e.jsx(uIe,{teamId:Gs.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(aOn,{contacts:m,contactDealsMap:b,websiteActiveIds:f,criteriaContactIds:M,totalCount:(m||[]).length,activeViewId:Ku,currentFilters:{search:J,type:me,status:ge,behavior:Ve},currentSortBy:Ne,onApplyView:(js,Ma,to)=>{uh(js),ym(Ma,to),Tn(1)},onClearAll:()=>{uh(null),ym({search:"",type:"all",status:"all",behavior:{}},"name"),Tn(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","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[ge]??null,onSelectSegment:js=>{const to=js?{"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","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[js]:"all";Ee(to),Tn(1)}}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 sm:p-4 bg-background",children:[e.jsx("div",{className:"sm:hidden space-y-3",children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Wg,{children:[e.jsx(Yre,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(uP,{className:"h-4 w-4"}),"Filters & Views",(()=>{const js=(me!=="all"?1:0)+(ge!=="all"?1:0)+(Oe!=="all"?1:0)+G.size+Ae;return js>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:js}):null})()]})}),e.jsxs(gg,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(Dy,{className:"text-left",children:e.jsx(Ry,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(ls,{value:me,onValueChange:he,children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(cs,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),y==null?void 0:y.filter(js=>js.active).map(js=>e.jsx(He,{value:js.id,children:js.name},js.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(ls,{value:ge,onValueChange:Ee,children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(cs,{placeholder:"All Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"warm",children:"🟢 Warm"}),e.jsx(He,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(He,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(He,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(He,{value:"no-deal",children:"📭 No Deal"}),e.jsx(He,{value:"open-house",children:"🏠 Open House"}),g&&e.jsx(He,{value:"website-active",children:"🌐 Website Active"}),e.jsx(He,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(He,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(ls,{value:Oe,onValueChange:js=>ke(js),children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(cs,{placeholder:"All Addresses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Addresses"}),e.jsx(He,{value:"has-address",children:"Has Address"}),e.jsx(He,{value:"no-address",children:"No Address"})]})]})]}),w&&w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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:()=>K("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${H==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>K("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${H==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:w.map(js=>{const Ma=G.has(js.id);return e.jsxs("button",{onClick:()=>{V(to=>{const Ta=new Set(to);return Ta.has(js.id)?Ta.delete(js.id):Ta.add(js.id),Ta})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Ma?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:js.color}}),js.name]},js.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(ls,{value:Ne,onValueChange:Pe,children:[e.jsx(rs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"name",children:"Name (A-Z)"}),e.jsx(He,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(He,{value:"important-dates",children:"Important Dates"}),e.jsx(He,{value:"last-touched",children:"Last Touched"}),e.jsx(He,{value:"next-touch",children:"Next Touch Due"}),e.jsx(He,{value:"score",children:"Relationship Score"}),e.jsx(He,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs(z,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>We(!0),children:[e.jsx(un,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(z,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>pr(!0),children:[e.jsx(Ip,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(R2t,{currentFilters:{search:J,type:me,status:ge,behavior:Ve},currentSortBy:Ne,onApplySmartList:ym})}),e.jsx(z,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{he("all"),Ee("all"),ke("all"),V(new Set),_e({})},children:"Clear all filters"})]})]})]})})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[120px] text-sm text-muted-foreground",children:[Ua.toLocaleString()," ",Ua===1?"contact":"contacts"," shown"]}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsx(z,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(bj,{className:"h-4 w-4"})})}),e.jsxs(nd,{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(js=>e.jsx("button",{onClick:()=>Pe(js.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${Ne===js.v?"bg-accent font-medium text-primary":""}`,children:js.l},js.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(ls,{value:me,onValueChange:he,children:[e.jsx(rs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(cs,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),y==null?void 0:y.filter(js=>js.active).map(js=>e.jsx(He,{value:js.id,children:js.name},js.id))]})]}),e.jsxs(ls,{value:ge,onValueChange:Ee,children:[e.jsx(rs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(cs,{placeholder:"All Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"warm",children:"🟢 Warm"}),e.jsx(He,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(He,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(He,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(He,{value:"no-deal",children:"📭 No Deal"}),e.jsx(He,{value:"open-house",children:"🏠 Open House"}),g&&e.jsx(He,{value:"website-active",children:"🌐 Website Active"}),e.jsx(He,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(He,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(ls,{value:Oe,onValueChange:js=>ke(js),children:[e.jsx(rs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(cs,{placeholder:"All Addresses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Addresses"}),e.jsx(He,{value:"has-address",children:"Has Address"}),e.jsx(He,{value:"no-address",children:"No Address"})]})]}),w&&w.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(hd,{children:[e.jsx(md,{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(Ip,{className:"h-3.5 w-3.5"}),G.size===0?"Filter by Tags":`${G.size} tag${G.size>1?"s":""}`]})}),e.jsx(nd,{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:()=>K("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${H==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>K("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${H==="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:w.map(js=>{const Ma=G.has(js.id);return e.jsxs("button",{onClick:()=>{V(to=>{const Ta=new Set(to);return Ta.has(js.id)?Ta.delete(js.id):Ta.add(js.id),Ta})},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(za,{checked:Ma,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:js.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:js.name})]},js.id)})}),G.size>0&&e.jsx(z,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>V(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(ru,{children:[e.jsx(au,{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(Gc,{className:"h-3.5 w-3.5"})})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onClick:()=>pr(!0),children:[e.jsx(Ip,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ua,{onClick:()=>Pn(!0),children:[e.jsx(m1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R2t,{currentFilters:{search:J,type:me,status:ge,behavior:Ve},currentSortBy:Ne,onApplySmartList:ym}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsx(RFn,{selected:qe,onChange:Be}),e.jsxs(z,{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:()=>We(!0),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Advanced Filters",Ae>0&&e.jsx(ze,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Ae})]}),e.jsx(oOn,{columns:l,onToggle:o,onReset:c})]})]}),Ae>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(kFn,{behavior:Ve,onRemove:js=>_e(Ma=>{const to={...Ma};return delete to[js],to}),onClearAll:()=>_e({})})})]}),e.jsx(NFn,{open:Se,onOpenChange:We,hasLeadSite:nt||g,behavior:Ve,onApply:_e,selectedType:me,onSelectedTypeChange:he,relationshipTypes:y,contactLeadSources:Ao}),e.jsx(wFn,{selectedIds:Us,contacts:uo,onClearSelection:()=>{Es(new Set),cr(!1)},showLeadPondAction:Lt,onSendToLeadPond:aa,showTransferAction:Mt,onTransfer:Zs}),Us.size>0&&Us.size===qa.length&&!bn&&Ua>Yn&&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 ",qa.length," contacts on this page are selected."]}),e.jsxs(z,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:Ll,children:["Select all ",Ua.toLocaleString()," matching contacts"]})]}),bn&&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 ",Ua.toLocaleString()," matching contacts are selected.",e.jsx(z,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{Es(new Set),cr(!1)},children:"Clear selection"})]}),Ua>Yn&&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 ",(Ji-1)*Yn+1,"–",Math.min(Ji*Yn,Ua)," of ",Ua.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"outline",size:"sm",disabled:Ji<=1,onClick:()=>Tn(1),children:"First"}),e.jsx(z,{variant:"outline",size:"sm",disabled:Ji<=1,onClick:()=>Tn(js=>js-1),children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ji," of ",Eo]}),e.jsx(z,{variant:"outline",size:"sm",disabled:Ji>=Eo,onClick:()=>Tn(js=>js+1),children:e.jsx(yi,{className:"h-4 w-4"})}),e.jsx(z,{variant:"outline",size:"sm",disabled:Ji>=Eo,onClick:()=>Tn(Eo),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:p?e.jsx(rOn,{}):uo.length===0?e.jsx(be,{children:e.jsx(H2t,{filtered:!!J||me!=="all"||ge!=="all"||Oe!=="all"||G.size>0,onAdd:()=>Je(!0),onImport:()=>zt(!0),onClearFilters:()=>{te(""),he("all"),Ee("all"),ke("all"),V(new Set),_e({})}})}):qa.map(js=>{var to,Ta,so;const{relationshipScore:Ma}=js;return e.jsx(be,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>zo(js.id),children:e.jsx(Le,{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:[js.first_name," ",js.last_name]}),e.jsx(B2t,{count:(v==null?void 0:v[js.id])??0}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[js.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(on,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:js.email})]}),js.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(va,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:js.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(BWe,{score:Ma,size:"sm"}),e.jsx(L2t,{contact:js}),(((to=js.lead_source_ref)==null?void 0:to.name)||js.lead_source)&&e.jsx(ze,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Ta=js.lead_source_ref)==null?void 0:Ta.name)||js.lead_source}),(so=js.tags)==null?void 0:so.map(ho=>{var pi;return e.jsx(ze,{variant:"secondary",className:"text-xs",children:(pi=ho.relationship_type)==null?void 0:pi.name},ho.id)}),e.jsx(q2t,{contactId:js.id,tags:S==null?void 0:S.filter(ho=>ho.contact_id===js.id)}),e.jsx(z2t,{deal:b==null?void 0:b[js.id]})]}),e.jsx("div",{className:"mb-2",children:e.jsx(Z2t,{criteria:E==null?void 0:E[js.id],onEdit:()=>D({id:js.id,name:`${js.first_name}${js.last_name?" "+js.last_name:""}`}),showAlertState:!!C,matchCount:P==null?void 0:P[js.id],compact:!0})}),e.jsx(O2t,{birthday:js.birthday,homeAnniversary:js.home_anniversary,weddingAnniversary:js.wedding_anniversary,className:"mb-2",contactId:js.id,contactName:`${js.first_name}${js.last_name?" "+js.last_name:""}`,contactAddress:[js.address,js.city,js.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Ma.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),Ys(new Date(Ma.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),js.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),Ys(Ou(js.birthday),"MMM d")]}),js.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Ys(Ou(js.home_anniversary),"MMM d")]}),js.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(sn,{className:"h-3 w-3"}),"Added ",Ys(new Date(js.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ho=>ho.stopPropagation(),children:e.jsx(D2t,{contact:js,onEdit:lt,onDelete:Sl,onSnooze:(ho,pi)=>{It(ho),wt(pi)},showLeadPondAction:Lt,onSendToLeadPond:oa,showTransferAction:Mt,onTransfer:Vs})})]})})},js.id)})}):e.jsx(be,{children:e.jsx(Le,{className:"p-0 overflow-x-auto",children:e.jsxs(Za,{className:"min-w-[800px]",children:[e.jsx(Xa,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(fn,{className:"hover:bg-transparent",children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(za,{checked:qa.length>0&&qa.every(js=>Us.has(js.id)),onCheckedChange:()=>tl()})}),e.jsx(Tt,{children:e.jsxs("button",{onClick:()=>Pe(js=>js==="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",Ne==="name"&&e.jsx(yi,{className:"h-3 w-3 rotate-90 text-primary"}),Ne==="last-name"&&e.jsx(yi,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Tt,{children:"Relationship"}),l.buyerCriteria&&e.jsx(Tt,{className:"min-w-[170px] whitespace-nowrap",children:"Looking For"}),l.stage&&e.jsx(Tt,{children:"Stage"}),l.leadSource&&e.jsx(Tt,{children:"Lead Source"}),l.tags&&e.jsx(Tt,{children:"Tags"}),l.lastTouch&&e.jsx(Tt,{children:"Last Touch"}),l.nextAction&&e.jsx(Tt,{children:"Next Action"}),l.dealValue&&e.jsx(Tt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Tt,{children:"Email"}),l.phone&&e.jsx(Tt,{children:"Phone"}),l.address&&e.jsx(Tt,{children:"Address"}),l.birthday&&e.jsx(Tt,{children:"Birthday"}),e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(Qa,{children:p?e.jsx(nOn,{columns:2+Object.values(l).filter(Boolean).length}):uo.length===0?e.jsx(fn,{className:"hover:bg-transparent",children:e.jsx(yt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(H2t,{filtered:!!J||me!=="all"||ge!=="all"||Oe!=="all"||G.size>0,onAdd:()=>Je(!0),onImport:()=>zt(!0),onClearFilters:()=>{te(""),he("all"),Ee("all"),ke("all"),V(new Set),_e({})}})})}):qa.map(js=>{var Ta;const{relationshipScore:Ma}=js,to=b==null?void 0:b[js.id];return e.jsxs(fn,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${Us.has(js.id)?"bg-accent/30":""}`,onClick:()=>zo(js.id),children:[e.jsx(yt,{onClick:so=>so.stopPropagation(),children:e.jsx(za,{checked:Us.has(js.id),onCheckedChange:()=>Kr(js.id)})}),e.jsx(yt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ert,{firstName:js.first_name,lastName:js.last_name,avatarUrl:js.avatar_url,email:js.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:[js.first_name," ",js.last_name]}),e.jsx(tOn,{linked:!!js.spouse_contact_id||!!js.spouse_name,spouseName:js.spouse_contact_id&&Oa[js.spouse_contact_id]||js.spouse_name||null}),e.jsx(B2t,{count:(v==null?void 0:v[js.id])??0})]}),js.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:js.email}),js.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:js.phone})]})]})}),l.relationship&&e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(XFn,{score:Ma.score,status:Ma.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:Ma.status==="warm"?"Strong":Ma.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ma.daysSinceTouch===null?"Never contacted":Ma.daysSinceTouch===0?"Touched today":`${Ma.daysSinceTouch}d since touch`})]})]})}),l.buyerCriteria&&e.jsx(yt,{className:"min-w-[170px] max-w-[240px]",children:e.jsx(Z2t,{criteria:E==null?void 0:E[js.id],onEdit:()=>D({id:js.id,name:`${js.first_name}${js.last_name?" "+js.last_name:""}`}),showAlertState:!!C,matchCount:P==null?void 0:P[js.id]})}),l.stage&&e.jsx(yt,{children:e.jsx(z2t,{deal:to})}),l.leadSource&&e.jsx(yt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Ta=js.lead_source_ref)==null?void 0:Ta.name)||js.lead_source||"—"}),l.tags&&e.jsx(yt,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(q2t,{contactId:js.id,tags:S==null?void 0:S.filter(so=>so.contact_id===js.id)})})}),l.lastTouch&&e.jsx(yt,{children:Ma.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),Ys(new Date(Ma.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(yt,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(L2t,{contact:js}),e.jsx(O2t,{birthday:js.birthday,homeAnniversary:js.home_anniversary,weddingAnniversary:js.wedding_anniversary,contactId:js.id,contactName:`${js.first_name}${js.last_name?" "+js.last_name:""}`,contactAddress:[js.address,js.city,js.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(yt,{children:(()=>{const so=(to==null?void 0:to.sale_price)??(to==null?void 0:to.expected_price);return so?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:lm(Number(so))}),(to==null?void 0:to.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(to.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(yt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:js.email||"—"}),l.phone&&e.jsx(yt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:js.phone||"—"}),l.address&&e.jsx(yt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[js.address,js.city,js.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(yt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:js.birthday?(()=>{const[so,ho,pi]=String(js.birthday).split(/[-/T]/).map(Number);return ho&&pi?`${ho}/${pi}${so&&so>1900?`/${so}`:""}`:"—"})():"—"}),e.jsx(yt,{onClick:so=>so.stopPropagation(),children:e.jsx(D2t,{contact:js,onEdit:lt,onDelete:Sl,onSnooze:(so,ho)=>{It(so),wt(ho)},showLeadPondAction:Lt,onSendToLeadPond:oa,showTransferAction:Mt,onTransfer:Vs})})]},js.id)})})]})})}),Ua>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 ",(Ji-1)*Yn+1,"–",Math.min(Ji*Yn,Ua)," of ",Ua.toLocaleString()," contacts"]}),e.jsxs(ls,{value:String(Yn),onValueChange:js=>{fs(Number(js)),Tn(1)},children:[e.jsx(rs,{className:"w-[80px] h-8",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"50",children:"50"}),e.jsx(He,{value:"100",children:"100"}),e.jsx(He,{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(z,{variant:"outline",size:"sm",disabled:Ji<=1,onClick:()=>Tn(1),children:"First"}),e.jsx(z,{variant:"outline",size:"sm",disabled:Ji<=1,onClick:()=>Tn(js=>js-1),children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ji," of ",Eo]}),e.jsx(z,{variant:"outline",size:"sm",disabled:Ji>=Eo,onClick:()=>Tn(js=>js+1),children:e.jsx(yi,{className:"h-4 w-4"})}),e.jsx(z,{variant:"outline",size:"sm",disabled:Ji>=Eo,onClick:()=>Tn(Eo),children:"Last"})]})]}),e.jsx(Is,{open:Ge||!!ut,onOpenChange:js=>{js||(Je(!1),lt(null),Ld())},children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:ut?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Bm,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"first_name",children:"First Name *"}),e.jsx(pe,{id:"first_name",value:Tr.first_name,onChange:js=>Hr({...Tr,first_name:js.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:Tr.last_name,onChange:js=>Hr({...Tr,last_name:js.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:Tr.email,onChange:js=>Hr({...Tr,email:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:Tr.phone,onChange:js=>Hr({...Tr,phone:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address",children:"Address"}),e.jsx(pe,{id:"address",value:Tr.address,onChange:js=>Hr({...Tr,address:js.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:Tr.city,onChange:js=>Hr({...Tr,city:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:Tr.state,onChange:js=>Hr({...Tr,state:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"zip_code",children:"Zip"}),e.jsx(pe,{id:"zip_code",value:Tr.zip_code,onChange:js=>Hr({...Tr,zip_code:js.target.value})})]})]}),Ba?e.jsxs("div",{className:"space-y-4 rounded-lg border p-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_label",children:"Label"}),e.jsx(pe,{id:"address2_label",list:"contact-address-labels-new",value:Tr.address2_label,onChange:js=>Hr({...Tr,address2_label:js.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels-new",children:rZt.map(js=>e.jsx("option",{value:js},js))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:Tr.address2,onChange:js=>Hr({...Tr,address2:js.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_city",children:"City"}),e.jsx(pe,{id:"address2_city",value:Tr.address2_city,onChange:js=>Hr({...Tr,address2_city:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:Tr.address2_state,onChange:js=>Hr({...Tr,address2_state:js.target.value}),maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_zip",children:"Zip"}),e.jsx(pe,{id:"address2_zip",value:Tr.address2_zip,onChange:js=>Hr({...Tr,address2_zip:js.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(ee,{htmlFor:"mail_to_secondary",className:"text-sm font-normal",children:"Send mail here instead of the main address"}),e.jsx(mn,{id:"mail_to_secondary",checked:Tr.mail_to_secondary,onCheckedChange:js=>Hr({...Tr,mail_to_secondary:js})})]})]}):e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"justify-start px-0 text-primary",onClick:()=>Ja(!0),children:"+ Add another address"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"birthday",children:"Birthday"}),e.jsx(pe,{id:"birthday",type:"date",value:Tr.birthday,onChange:js=>Hr({...Tr,birthday:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:Tr.home_anniversary,onChange:js=>Hr({...Tr,home_anniversary:js.target.value})})]})]}),ut&&e.jsx(UWe,{contactId:ut.id,currentSpouseContactId:(ut==null?void 0:ut.spouse_contact_id)||null,currentSpouseName:(ut==null?void 0:ut.spouse_name)||null,currentSpouseEmail:(ut==null?void 0:ut.spouse_email)||null,onLink:js=>ae.mutate({contactId:ut.id,spouseContactId:js}),onUnlink:()=>ae.mutate({contactId:ut.id,spouseContactId:null}),isEditing:!0}),e.jsx(NZt,{value:Tr.lead_source_id,onChange:js=>Hr({...Tr,lead_source_id:js})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:y==null?void 0:y.filter(js=>js.active).map(js=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(za,{checked:Tr.tagIds.includes(js.id),onCheckedChange:Ma=>{Hr(Ma?{...Tr,tagIds:[...Tr.tagIds,js.id]}:{...Tr,tagIds:Tr.tagIds.filter(to=>to!==js.id)})}}),e.jsx("span",{className:"text-sm",children:js.name})]},js.id))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Ps,{id:"notes",value:Tr.notes,onChange:js=>Hr({...Tr,notes:js.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>{Je(!1),lt(null),Ld()},children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:Z.isPending||oe.isPending,children:[ut?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(BRn,{open:qt,onOpenChange:zt,relationshipTypes:(y==null?void 0:y.filter(js=>js.active))||[],onSuccess:()=>{zt(!1)}}),e.jsx(qRn,{open:Zt,onOpenChange:ms,onComplete:()=>ms(!1)}),e.jsx(l8e,{open:!!Dt,onOpenChange:js=>{js||It(null)},contactId:Dt||"",contactName:qs}),e.jsx(WFn,{open:Ss,onOpenChange:pr}),e.jsx(KFn,{open:hn,onOpenChange:Pn}),e.jsx($Fn,{open:ce,onOpenChange:ve,contacts:m||[],onCitySelect:js=>{te(js),Tn(1)}}),e.jsx(mHt,{open:gs,onOpenChange:Vt,contactIds:Qt,contactNames:Qt.map(js=>{const Ma=uo.find(to=>to.id===js);return Ma?`${Ma.first_name} ${Ma.last_name||""}`.trim():""}),onComplete:()=>{ks([]),Es(new Set),cr(!1)}}),e.jsx(Is,{open:!!Yt,onOpenChange:js=>!js&&it(null),children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Yt==null?void 0:Yt.length)||0," contact",((Yt==null?void 0:Yt.length)||0)===1?"":"s"," with your team."]}),e.jsxs(ls,{value:gt,onValueChange:ft,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a pond"})}),e.jsx(as,{children:Lr.map(js=>e.jsx(He,{value:js.id,children:js.name},js.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>it(null),children:"Cancel"}),e.jsx(z,{onClick:()=>{Yt&&Zn(Yt,gt),it(null)},disabled:!gt,children:"Share to Pond"})]})]})]})})]})]})})}const kOn=5*1024*1024;function SOn({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=_.useRef(null),o=$t(),[c,d]=_.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async f=>{const{error:g}=await U.from("innercircle_contacts").update({avatar_url:f}).eq("id",s);if(g)throw g;u()},m=async f=>{var g;if(!f.type.startsWith("image/")){la({title:"Please choose an image file",variant:"destructive"});return}if(f.size>kOn){la({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:v}=await U.auth.getUser(),y=(g=v.user)==null?void 0:g.id,b=(f.name.split(".").pop()||"jpg").toLowerCase(),w=`contacts/${y}/${s}-${Date.now()}.${b}`,{error:S}=await U.storage.from("avatars").upload(w,f,{upsert:!0,contentType:f.type});if(S)throw S;const{data:C}=U.storage.from("avatars").getPublicUrl(w);await h(C.publicUrl),la({title:"Photo updated"})}catch(v){la({title:"Upload failed",description:v.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},p=async()=>{d(!0);try{await h(null),la({title:"Photo removed"})}catch(f){la({title:"Could not remove photo",description:f.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var f;return(f=l.current)==null?void 0:f.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(ert,{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(bt,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(Lx,{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(bt,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs(z,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:p,disabled:c,children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var v;const g=(v=f.target.files)==null?void 0:v[0];g&&m(g)}})]})}const COn={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo",email:"Email",phone:"Phone"},AOn=4e3,EOn=5*60*1e3;function TOn({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var G;const{toast:i}=_i(),l=$t(),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(null),[g,v]=_.useState(!1),[y,b]=_.useState(null),[w,S]=_.useState(null),[C,E]=_.useState(0),P=_.useRef(null),[M,I]=_.useState({job_title:!0,company_name:!0,city:!0,state:!0,avatar_url:!1,email:!1,phone:!1});_.useEffect(()=>{if(!w||!s)return;P.current=Date.now(),E(0);let V=!1,H=null,K=null;const Z=async()=>{if(!V)try{const{data:oe,error:re}=await U.functions.invoke("enrich-contact",{body:{contact_id:n,batch_id:w}});if(re)throw re;if((oe==null?void 0:oe.status)==="pending"){E(Date.now()-(P.current||Date.now()));return}oe!=null&&oe.ok&&oe.found?(f(oe.profile),b(oe.matched_on??null),S(null)):(v(!0),S(null))}catch(oe){i({title:"Enrichment status check failed",description:(oe==null?void 0:oe.message)??"Please try again.",variant:"destructive"}),S(null)}};return Z(),H=setInterval(Z,AOn),K=setTimeout(()=>{V||(S(null),i({title:"Enrichment is taking longer than expected",description:"The provider has not finished processing yet. You can close this dialog and try again later.",variant:"default"}))},EOn),()=>{V=!0,H&&clearInterval(H),K&&clearTimeout(K)}},[w,s,n,i]);const D=async()=>{u(!0),v(!1),f(null),S(null);try{const{data:V,error:H}=await U.functions.invoke("enrich-contact",{body:{contact_id:n,linkedin_url:o.trim()||void 0}});if(H)throw H;if((V==null?void 0:V.status)==="pending"&&(V!=null&&V.batch_id)){S(V.batch_id);return}if(!(V!=null&&V.found)){v(!0);return}f(V.profile),b(V.matched_on??null)}catch(V){i({title:"Enrichment failed",description:(V==null?void 0:V.message)??"Please try again.",variant:"destructive"})}finally{u(!1)}},F=()=>{var H,K;if(!p)return[];const V=[];if(p.job_title&&V.push({key:"job_title",value:p.job_title}),p.company_name&&V.push({key:"company_name",value:p.company_name}),p.city&&V.push({key:"city",value:p.city}),p.state&&V.push({key:"state",value:p.state}),p.photo_url&&V.push({key:"avatar_url",value:p.photo_url}),(H=p.emails)!=null&&H.length&&V.push({key:"email",value:p.emails[0]}),(K=p.phones)!=null&&K.length&&V.push({key:"phone",value:p.phones[0]}),!p.city&&!p.state&&p.location){const[Z,oe]=p.location.split(",").map(re=>re.trim());Z&&V.push({key:"city",value:Z}),oe&&V.push({key:"state",value:oe})}return V},q=async()=>{const V={};for(const H of F())M[H.key]&&(V[H.key==="avatar_url"?"avatar_url":H.key]=H.value);if(Object.keys(V).length===0){i({title:"Nothing selected",description:"Pick at least one field to save."});return}m(!0);try{const{error:H}=await U.from("innercircle_contacts").update(V).eq("id",n);if(H)throw H;await l.invalidateQueries({queryKey:["contact",n]}),await l.invalidateQueries({queryKey:["contacts"]}),i({title:"Contact updated",description:`${Object.keys(V).length} field(s) saved.`}),t(!1)}catch(H){i({title:"Could not save",description:(H==null?void 0:H.message)??"Please try again.",variant:"destructive"})}finally{m(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Find person details — ",r]}),e.jsx(_r,{children:"Looks up public professional details (job title, company, social profiles) for this person and lets you choose what to save. This does not look up home or property data — use the Property tab for that."})]}),e.jsxs("div",{className:"space-y-4",children:[!p&&!w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"li-url",children:"LinkedIn URL (optional)"}),e.jsx(pe,{id:"li-url",placeholder:"https://linkedin.com/in/username",value:o,onChange:V=>c(V.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a?"We’ll match on the contact’s email, phone, or the LinkedIn URL above.":"This contact has no email — add a LinkedIn URL or phone number for the best match."})]}),w&&e.jsxs("div",{className:"rounded-lg border border-dashed p-4 text-sm text-center space-y-2",children:[e.jsx(bt,{className:"h-5 w-5 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:"Searching public profiles…"}),e.jsx("p",{className:"text-muted-foreground",children:"The enrichment provider is processing this lookup. This can take 10–30 seconds."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Elapsed: ",Math.floor(C/1e3),"s"]})]}),g&&e.jsx("div",{className:"rounded-lg border border-dashed p-4 text-sm text-muted-foreground",children:"No public profile matched this contact. Try adding a LinkedIn URL."}),p&&e.jsx(Ki,{className:"max-h-[45vh] pr-3",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[p.photo_url&&e.jsx("img",{src:p.photo_url,alt:p.full_name??"Profile photo",className:"h-14 w-14 rounded-full object-cover"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold truncate",children:p.full_name||r}),y&&e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:["matched via ",y]})]}),p.headline&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.headline}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-xs text-muted-foreground",children:[p.company_name&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),p.company_name]}),p.location&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ha,{className:"h-3 w-3"}),p.location]}),p.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Px,{className:"h-3 w-3"}),p.industry]})]}),p.linkedin_url&&e.jsxs("a",{href:p.linkedin_url,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(fg,{className:"h-3 w-3"})," LinkedIn ",e.jsx(mr,{className:"h-3 w-3"})]})]})]}),p.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-line",children:p.summary}),!!((G=p.experience)!=null&&G.length)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Experience"}),p.experience.map((V,H)=>e.jsxs("p",{className:"text-sm",children:[V.title," ",V.company?`· ${V.company}`:"",V.starts_at?e.jsxs("span",{className:"text-muted-foreground text-xs",children:[" (",V.starts_at,V.ends_at?` – ${V.ends_at}`:" – present",")"]}):null]},H))]}),F().length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-3 text-sm text-muted-foreground",children:"We found this person, but the public profile didn’t include any details we can save to the contact (job title, company, city, state, photo, email or phone). Try adding their LinkedIn address and searching again."}),F().length>0&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Save to contact"}),F().map(V=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(za,{checked:M[V.key],onCheckedChange:H=>I(K=>({...K,[V.key]:H===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[COn[V.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:V.value})]})]},V.key))]})]})})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Close"}),!p&&!w?e.jsxs(z,{onClick:D,disabled:d,children:[d?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),d?"Searching…":"Find profile"]}):w?e.jsxs(z,{disabled:!0,children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Searching…"]}):e.jsxs(z,{onClick:q,disabled:h||F().every(V=>!M[V.key]),children:[h&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save selected"]})]})]})})}const MOn=["jeremy@relevelup.com"];function POn(){const{user:s}=hs(),t=((s==null?void 0:s.email)||"").toLowerCase();return MOn.includes(t)}const Q2t="America/New_York";function LOn(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:Q2t,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:Q2t,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function IOn(s){const t=Date.now()-new Date(s).getTime(),n=Math.round(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.round(n/60);if(r<24)return`${r}h ago`;const a=Math.round(r/24);return a<30?`${a}d ago`:`${Math.round(a/30)}mo ago`}function DOn({contactId:s,ownerUserId:t,legacyNote:n}){const r=$t(),[a,i]=_.useState(""),{data:l=[],isLoading:o}=rt({queryKey:["contact-notes",s],queryFn:async()=>{const{data:u,error:h}=await U.from("innercircle_contact_notes").select("id, body, source, author_name, created_at").eq("contact_id",s).order("created_at",{ascending:!1});if(h)throw h;return u||[]},enabled:!!s}),c=mt({mutationFn:async u=>{var g,v,y;const{data:h}=await U.auth.getUser(),m=h.user,p=((g=m==null?void 0:m.user_metadata)==null?void 0:g.full_name)||[(v=m==null?void 0:m.user_metadata)==null?void 0:v.first_name,(y=m==null?void 0:m.user_metadata)==null?void 0:y.last_name].filter(Boolean).join(" ")||(m==null?void 0:m.email)||null,{error:f}=await U.from("innercircle_contact_notes").insert({contact_id:s,owner_user_id:t||(m==null?void 0:m.id),author_user_id:m==null?void 0:m.id,author_name:p,source:"agent",body:u});if(f)throw f},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),la({title:"Note added"})},onError:u=>la({title:"Could not add note",description:u.message,variant:"destructive"})}),d=mt({mutationFn:async u=>{const{error:h}=await U.from("innercircle_contact_notes").delete().eq("id",u);if(h)throw h},onSuccess:()=>r.invalidateQueries({queryKey:["contact-notes",s]})});return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(qi,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ps,{value:a,onChange:u=>i(u.target.value),placeholder:"Add a note — it's stamped with the date and time automatically.",rows:3,className:"resize-none"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{size:"sm",disabled:!a.trim()||c.isPending,onClick:()=>c.mutate(a.trim()),children:[c.isPending?e.jsx(bt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):null,"Add Note"]})})]}),o?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading notes…"}):l.length===0&&!n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet — add context about this relationship."}):e.jsxs("div",{className:"space-y-3",children:[l.map(u=>e.jsxs("div",{className:"group rounded-xl border border-border/60 bg-muted/30 p-3",children:[e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 font-medium text-foreground/80",children:[e.jsx(Zr,{className:"h-3 w-3"}),LOn(u.created_at)]}),e.jsxs("span",{children:["· ",IOn(u.created_at)]}),u.source!=="agent"?e.jsxs(ze,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(un,{className:"h-2.5 w-2.5"})," System"]}):u.author_name?e.jsxs("span",{children:["· ",u.author_name]}):null,e.jsx("button",{type:"button",onClick:()=>d.mutate(u.id),className:"ml-auto opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100","aria-label":"Delete note",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.body})]},u.id)),n&&e.jsxs("div",{className:"rounded-xl border border-dashed border-border/60 p-3",children:[e.jsx("div",{className:"mb-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Background (no timestamp)"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm text-muted-foreground",children:n})]})]})]})]})}const ROn="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function FOn({open:s,onOpenChange:t,contact:n}){var G;const{user:r}=hs(),a=zn(),i=$t(),{intakePage:l,isLoading:o}=jLe(),{isGmailConnected:c,gmailEmail:d}=bg(),u=bLe(),{data:h}=rt({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:V}=await U.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return V}}),m=(h==null?void 0:h.name)||((G=r==null?void 0:r.email)==null?void 0:G.split("@")[0])||"Your Agent",p=m.split(" ")[0],f=l?`https://contacts.relevelup.com/${l.slug}`:"",g=_.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,y]=_.useState("gmail"),[b,w]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState(!1);_.useEffect(()=>{s&&(w(`Quick favor, ${n.first_name} — can you update your info?`),C(g),y(c?"gmail":"system"))},[s,g,n.first_name,c]);const M=_.useMemo(()=>S.split(/\n\n+/).map(V=>`

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

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

A note from ${m}

${M}

Update Your Info

Takes about a minute — promise

Share My Info →

${V}

Sent with care by ${m}

Powered by ReLevelUp

`,F=async()=>{if(!l){ne.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!S.trim()){ne.error("Subject and message are required");return}P(!0);const V=await I(),H=D(V),K=async()=>{const{data:Z,error:oe}=await U.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:H,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(oe)throw oe;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Failed to send")};try{if(v==="gmail"&&c){const{data:Z,error:oe}=await U.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:H,contactId:n.id}});let re=Z&&Z.error?Z:null;if(oe){re={error:"send_failed",message:oe.message};const ae=oe.context;if(ae&&typeof ae.json=="function")try{re=await ae.clone().json()}catch{}}if(re)if(re.error==="insufficient_scope")await K(),ne.warning("Sent using system email — your Gmail connection is missing send permission. Reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3});else throw new Error(re.message||re.error||"Failed to send");else if(!(Z!=null&&Z.success))throw new Error("Failed to send")}else await K();try{await u.mutateAsync({contactId:n.id,actionTypeId:ROn,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(Z){console.warn("Failed to log activity:",Z)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ne.success("Connect Page invite sent!"),t(!1)}catch(Z){console.error("Send error:",Z),ne.error(Z instanceof Error?Z.message:"Failed to send invite")}finally{P(!1)}},q=S.split(/\n\n+/).filter(Boolean);return e.jsx(Is,{open:s,onOpenChange:V=>!E&&t(V),children:e.jsxs(Ls,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{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(bt,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(Qr,{value:v,onValueChange:V=>y(V),className:"mt-1.5",children:e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Wt,{value:"gmail",disabled:!c,children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Wt,{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(ee,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(pe,{id:"invite-subject",value:b,onChange:V=>w(V.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ps,{id:"invite-message",value:S,onChange:V=>C(V.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(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(mr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-xl border bg-muted/40 p-4 max-h-[380px] overflow-y-auto",children:e.jsxs("div",{className:"mx-auto max-w-[480px] rounded-2xl bg-white shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-6 py-7 text-center",children:[h!=null&&h.avatar_url?e.jsx("img",{src:h.avatar_url,alt:m,className:"mx-auto mb-3 h-14 w-14 rounded-full object-cover ring-2 ring-white/40"}):e.jsx("div",{className:"mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-full bg-white/20 text-xl font-bold text-white",children:p.charAt(0)}),e.jsxs("p",{className:"text-base font-bold text-white",children:["A note from ",m]})]}),e.jsx("div",{className:"px-6 py-5 space-y-3",children:q.map((V,H)=>e.jsx("p",{className:"text-[13px] leading-relaxed text-slate-600 whitespace-pre-line",children:V},H))}),e.jsx("div",{className:"px-6 pb-6",children:e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 px-5 py-6 text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-slate-400",children:"Update Your Info"}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-slate-800",children:"Takes about a minute — promise"}),e.jsx("span",{className:"mt-4 inline-block rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-7 py-3 text-sm font-semibold text-white",children:"Share My Info →"}),e.jsxs("p",{className:"mt-3 break-all text-[11px] text-slate-400",children:[f,"?t=…"]})]})}),e.jsx("div",{className:"border-t border-slate-100 px-6 py-4 text-center",children:e.jsxs("p",{className:"text-[11px] text-slate-400",children:["Sent with care by ",m]})})]})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Each invite includes a private link that pre-fills ",n.first_name,"'s current info, so their updates come straight back to this contact record."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:E,children:"Cancel"}),e.jsx(z,{onClick:F,disabled:E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Ho,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs(z,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(Oc,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function OOn(){const{user:s}=hs();return rt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function zOn(s){return rt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await U.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function BOn(s){return rt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await U.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function TZt(){const s=$t(),{user:t}=hs(),{leadSite:n}=mf();return mt({mutationFn:async r=>{const{data:a,error:i}=await U.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 $On(){const s=$t();return mt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await U.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 UOn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function qOn(){const{leadSite:s}=mf();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function VOn(){const{leadSite:s}=mf();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function HOn(){const s=$t();return mt({mutationFn:async({cmaId:t,comps:n})=>{if(await U.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 U.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function J2t(s,t){const n=t.filter(h=>{var m,p;return h.selected!==!1&&(((m=h.snapshot)==null?void 0:m.sqft)||h.sqft)&&(((p=h.snapshot)==null?void 0:p.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const m=h.snapshot||h;return(m.soldPrice||m.price)/m.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,m)=>h-m);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,m)=>h+m,0)/r.length,l=r.reduce((h,m)=>h+(m-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function GOn(s){return rt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function WOn(s){return rt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function trt(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 QW(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 MZt(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 PZt(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 LZt(){const s=$t();return mt({mutationFn:async({id:t,dealId:n})=>{await U.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await U.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 KOn(s){return rt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function IZt(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function YOn(){const s=ha();return rt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 ZOn(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 XOn(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 QOn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function SS(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function JOn({contactId:s}){const t=zn(),n=$t(),[r,a]=_.useState(null),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(null),g=QW(),v=IZt(),{data:y,isLoading:b}=rt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:I}=await U.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(I)throw I;if(!M||M.length===0)return[];const D=M.map(G=>G.id),{data:F,error:q}=await U.from("client_portals").select("*").in("deal_id",D).is("archived_at",null);if(q)throw q;return(F||[]).map(G=>({...G,deal:M.find(V=>V.id===G.deal_id)}))},enabled:!!s}),w=(y==null?void 0:y.map(M=>M.id))||[],{data:S}=rt({queryKey:["contact-portal-updates",w],queryFn:async()=>{if(w.length===0)return{};const{data:M,error:I}=await U.from("portal_updates").select("*").in("portal_id",w).order("created_at",{ascending:!1});if(I)throw I;const D={};return(M||[]).forEach(F=>{D[F.portal_id]||(D[F.portal_id]=F)}),D},enabled:w.length>0}),C=M=>{navigator.clipboard.writeText(SS(M)),a(M),ne.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},E=async(M,I)=>{if(!d.trim())return;const D=d.trim(),F=h.trim();await v.mutateAsync({portal_id:M,title:D,content:F||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]});try{const{data:q,error:G}=await U.functions.invoke("send-portal-notification",{body:{portal_id:M,update_title:D,update_content:F||null,portal_url:I?SS(I):void 0,force:!0}});if(G)throw G;q!=null&&q.emailSent?ne.success("Update posted & client emailed"):ne.success(`Update posted (${(q==null?void 0:q.reason)||"no email sent"})`)}catch(q){console.error("Portal notification failed:",q),ne.success("Update posted (notification failed to send)")}},P=async()=>{p&&(await g.mutateAsync({id:p.id,welcome_message:p.welcome_message,next_step_text:p.next_step_text,is_enabled:p.is_enabled,show_post_close_tips:p.show_post_close_tips,review_url:p.review_url}),l(!1),f(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ne.success("Portal settings updated!"))};return b||!y||y.length===0?null:e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Wo,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Le,{className:"space-y-3",children:y.map(M=>{var q,G,V;const I=((q=M.stage_mapping)==null?void 0:q.length)>0?M.stage_mapping:JPe(((G=M.deal)==null?void 0:G.deal_type)||"buyer"),D=I==null?void 0:I[M.current_stage_index??0],F=S==null?void 0:S[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:((V=M.deal)==null?void 0:V.deal_name)||"Portal"}),D&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",D.label||D.name]})]}),e.jsx(ze,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),F&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:F.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(F.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>C(M.slug),children:[r===M.slug?e.jsx(Wr,{className:"h-3 w-3 mr-1"}):e.jsx(Sa,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(SS(M.slug),"_blank"),children:[e.jsx(mr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(Is,{open:o,onOpenChange:c,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(qi,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:d,onChange:H=>u(H.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Details (optional)"}),e.jsx(Ps,{value:h,onChange:H=>m(H.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(z,{onClick:()=>E(M.id,M.slug),disabled:!d.trim()||v.isPending,className:"w-full",children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(Is,{open:i,onOpenChange:l,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{f({...M}),l(!0)},children:[e.jsx(Gc,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Portal Settings"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Portal Enabled"}),e.jsx(mn,{checked:p.is_enabled,onCheckedChange:H=>f({...p,is_enabled:H})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Welcome Message"}),e.jsx(Ps,{value:p.welcome_message||"",onChange:H=>f({...p,welcome_message:H.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Next Step"}),e.jsx(pe,{value:p.next_step_text||"",onChange:H=>f({...p,next_step_text:H.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review URL"}),e.jsx(pe,{value:p.review_url||"",onChange:H=>f({...p,review_url:H.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Show Post-Close Tips"}),e.jsx(mn,{checked:p.show_post_close_tips,onCheckedChange:H=>f({...p,show_post_close_tips:H})})]}),e.jsx(fc,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{onClick:P,disabled:g.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(z,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${M.deal_id}`),children:[e.jsx(Da,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),y.length>1&&e.jsx(fc,{})]},M.id)})})]})}function e7n({contactId:s}){const{data:t}=rt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await U.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=rt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await U.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!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(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{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(xa,{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(Le,{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(sa,{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(Zr,{className:"h-3 w-3"}),e.jsx("span",{title:Ys(new Date(l.viewed_at),"PPp"),children:Md(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}function t7n({contactId:s,contactName:t}){var F,q,G;const{user:n}=hs(),r=ha(),{hasIdx:a}=mf(),i=$t(),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,g]=_.useState(!1),[v,y]=_.useState(!1),{data:b,isLoading:w}=rt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:V,error:H}=await U.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(H)throw H;return V},enabled:!!s&&!!n}),[S,C]=_.useState({}),E=()=>{C({is_active:(b==null?void 0:b.is_active)??!0,min_price:(b==null?void 0:b.min_price)??null,max_price:(b==null?void 0:b.max_price)??null,min_beds:(b==null?void 0:b.min_beds)??null,min_baths:(b==null?void 0:b.min_baths)??null,min_sqft:(b==null?void 0:b.min_sqft)??null,max_sqft:(b==null?void 0:b.max_sqft)??null,cities:(b==null?void 0:b.cities)??[],zip_codes:(b==null?void 0:b.zip_codes)??[],property_types:(b==null?void 0:b.property_types)??[],frequency:(b==null?void 0:b.frequency)??"daily"}),o(!0)},P=mt({mutationFn:async()=>{const V={contact_id:s,owner_user_id:r,is_active:S.is_active??!0,min_price:S.min_price||null,max_price:S.max_price||null,min_beds:S.min_beds||null,min_baths:S.min_baths||null,min_sqft:S.min_sqft||null,max_sqft:S.max_sqft||null,cities:S.cities||[],zip_codes:S.zip_codes||[],property_types:S.property_types||[],frequency:S.frequency||"daily"};if(b!=null&&b.id){const{error:H}=await U.from("contact_property_alerts").update(V).eq("id",b.id);if(H)throw H}else{const{error:H}=await U.from("contact_property_alerts").insert(V);if(H)throw H}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),i.invalidateQueries({queryKey:["contact-criteria-map"]}),o(!1),ne.success("Home search saved!")},onError:V=>{ne.error(V.message||"Failed to save home search")}}),M=mt({mutationFn:async()=>{if(!(b!=null&&b.id))return;const{error:V}=await U.from("contact_property_alerts").delete().eq("id",b.id);if(V)throw V},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),i.invalidateQueries({queryKey:["contact-criteria-map"]}),o(!1),ne.success("Home search removed")}}),I=async()=>{if(b!=null&&b.id){g(!0),d(!0),h(""),p(null);try{const{data:V,error:H}=await U.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"preview"}});if(H)throw H;V!=null&&V.html?(h(V.html),p({count:V.listings_count||0,recipient:V.recipient,subject:V.subject})):p({count:0,message:(V==null?void 0:V.message)||"No matching listings found right now."})}catch(V){ne.error(V.message||"Failed to generate preview"),d(!1)}finally{g(!1)}}},D=async()=>{if(b!=null&&b.id&&await Qi(`Send property alert email to ${t} now?`)){y(!0);try{const{data:V,error:H}=await U.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"send"}});if(H)throw H;V!=null&&V.sent_count?(ne.success(`Sent ${V.sent_count} ${V.sent_count===1?"listing":"listings"} to ${V.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ne.info((V==null?void 0:V.message)||"No new matching listings to send right now.")}catch(V){ne.error(V.message||"Failed to send alert")}finally{y(!1)}}};return w?null:b&&!l?e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${a&&b.is_active?"bg-green-500/10":"bg-muted"}`,children:a?b.is_active?e.jsx($g,{className:"h-4 w-4 text-green-600"}):e.jsx(pS,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Rr,{className:"h-4 w-4 text-muted-foreground"})}),a?"Property Alerts":"Home Search",a&&e.jsxs(ze,{variant:b.is_active?"default":"secondary",className:"text-xs ml-auto",children:[b.is_active?"Active":"Paused"," · ",b.frequency]})]})}),e.jsxs(Le,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[b.min_price||b.max_price?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Nd,{className:"h-3 w-3"}),b.min_price?`$${(b.min_price/1e3).toFixed(0)}k`:"$0"," - ",b.max_price?`$${(b.max_price/1e3).toFixed(0)}k`:"Any"]}):null,b.min_beds?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(W4,{className:"h-3 w-3"}),b.min_beds,"+ beds"]}):null,b.min_baths?e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Ey,{className:"h-3 w-3"}),b.min_baths,"+ baths"]}):null,(F=b.cities)==null?void 0:F.map(V=>e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Ha,{className:"h-3 w-3"}),V]},V)),(q=b.zip_codes)==null?void 0:q.map(V=>e.jsx(ze,{variant:"outline",children:V},V)),(G=b.property_types)==null?void 0:G.map(V=>e.jsx(ze,{variant:"outline",children:V},V))]}),a&&b.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(b.last_sent_at).toLocaleDateString()]}),!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatic new-listing emails need an IDX website —"," ",e.jsx(or,{to:"/mission-control/website",className:"text-primary hover:underline",children:"explore IDX websites"}),"."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:I,disabled:f,children:[f?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(xa,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(z,{size:"sm",onClick:D,disabled:v||!b.is_active,title:b.is_active?"Send this alert email now":"Activate alert to send",children:[v?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsx(z,{variant:"outline",size:"sm",onClick:E,children:"Edit Search"}),e.jsxs(z,{variant:"destructive",size:"sm",onClick:()=>M.mutate(),disabled:M.isPending,children:[M.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(Is,{open:c,onOpenChange:d,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Property Alert Email Preview"}),(m==null?void 0:m.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:"})," ",m.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",m.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",m.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:f?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(bt,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):u?e.jsx("iframe",{srcDoc:u,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:(m==null?void 0:m.message)||"No matching listings found right now."})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>d(!1),children:"Close"}),u&&e.jsxs(z,{onClick:()=>{d(!1),D()},disabled:v||!b.is_active,children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]}):l?e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[a?e.jsx($g,{className:"h-4 w-4 text-primary"}):e.jsx(Rr,{className:"h-4 w-4 text-primary"}),b?"Edit":"Set up"," home search for ",t]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(EZt,{value:S,onChange:C,hasIdx:a,idxNote:e.jsx(z,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(or,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(z,{onClick:()=>P.mutate(),disabled:P.isPending,className:"flex-1",children:[P.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),b&&e.jsx(z,{variant:"destructive",size:"icon",onClick:()=>M.mutate(),disabled:M.isPending,children:e.jsx(er,{className:"h-4 w-4"})})]})]})]}):e.jsx(be,{className:"overflow-hidden",children:e.jsx(Le,{className:"p-4",children:e.jsxs("button",{onClick:E,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:a?e.jsx($g,{className:"h-4 w-4 text-primary"}):e.jsx(Rr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add Home Search"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a?`Automatically email ${t} new listings matching their criteria`:`Save what ${t} is looking for so you can match new listings to them`})]})]})})})}function s7n({contactId:s,contactName:t}){var K;const{user:n}=hs(),r=ha(),{hasLeadSite:a}=mf(),i=$t(),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState([]),[m,p]=_.useState(!1),[f,g]=_.useState(!1),[v,y]=_.useState(!1),[b,w]=_.useState(""),S=_.useRef(null),C=_.useRef(null),{data:E}=rt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:Z,error:oe}=await U.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(oe||!Z)return[];const re=Z.theme_config||{},ae=Array.isArray(re.searchCities)?re.searchCities:[];return Z.mls_market_area&&!ae.includes(Z.mls_market_area)&&ae.unshift(Z.mls_market_area),ae},enabled:!!r}),{data:P,isLoading:M}=rt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:Z,error:oe}=await U.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(oe)throw oe;return Z},enabled:!!s&&!!n});_.useEffect(()=>{const Z=oe=>{C.current&&!C.current.contains(oe.target)&&S.current&&!S.current.contains(oe.target)&&g(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[]);const I=()=>{p((P==null?void 0:P.market_report_enabled)??!1),h((P==null?void 0:P.market_report_cities)??[]),o(!0)},D=Z=>{const oe=(Z||c).trim();oe&&!u.includes(oe)&&h([...u,oe]),d(""),g(!1)},F=(E||[]).filter(Z=>!u.includes(Z)&&Z.toLowerCase().includes(c.toLowerCase())),q=mt({mutationFn:async()=>{const{data:Z,error:oe}=await U.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[]}});if(oe)throw new Error(oe.message||"Failed to generate preview");if(Z&&!Z.ok&&Z.error)throw new Error(Z.error);return Z},onSuccess:Z=>{w(Z.html),y(!0)},onError:Z=>{ne.error(Z.message||"Failed to generate preview")}}),G=mt({mutationFn:async()=>{const{data:Z,error:oe}=await U.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[],contactIds:[s]}});if(oe)throw new Error(oe.message||"Failed to send report");if(Z&&!Z.ok&&Z.error)throw new Error(Z.error);return Z},onSuccess:()=>{ne.success(`Market report sent to ${t}!`)},onError:Z=>{ne.error(Z.message||"Failed to send report")}}),V=mt({mutationFn:async()=>{const{error:Z}=await U.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(Z)throw Z},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ne.success(m?"Monthly market report enabled!":"Market report disabled")},onError:Z=>{ne.error(Z.message||"Failed to save")}}),H=mt({mutationFn:async()=>{const{error:Z}=await U.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(Z)throw Z},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),p(!1),h([]),ne.success("Market report removed")},onError:Z=>{ne.error(Z.message||"Failed to remove market report")}});return!a||M?null:P!=null&&P.market_report_enabled&&!l?e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{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(wl,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(ze,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Le,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((K=P.market_report_cities)==null?void 0:K.length)>0?P.market_report_cities.map(Z=>e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(Ha,{className:"h-3 w-3"}),Z]},Z)):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(z,{variant:"outline",size:"sm",onClick:()=>q.mutate(),disabled:q.isPending,className:"flex-1",children:[q.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(xa,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(z,{variant:"default",size:"sm",onClick:()=>G.mutate(),disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:I,className:"flex-1",children:"Manage"}),e.jsxs(z,{variant:"destructive",size:"sm",onClick:()=>H.mutate(),disabled:H.isPending,className:"flex-1",children:[H.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(er,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(Is,{open:v,onOpenChange:y,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(wl,{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:b}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(z,{onClick:()=>{y(!1),G.mutate()},disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(z,{variant:"outline",onClick:()=>y(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Send Monthly Report"}),e.jsx(mn,{checked:m,onCheckedChange:p})]}),m&&e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ha,{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(pe,{ref:S,value:c,onChange:Z=>{d(Z.target.value),g(!0)},onFocus:()=>g(!0),placeholder:"Type to search cities...",onKeyDown:Z=>{Z.key==="Enter"&&(Z.preventDefault(),F.length>0?D(F[0]):D())}}),e.jsx(cl,{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(z,{type:"button",variant:"outline",size:"sm",onClick:()=>D(),children:e.jsx(sn,{className:"h-4 w-4"})})]}),f&&F.length>0&&e.jsx("div",{ref:C,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:F.map(Z=>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:()=>D(Z),children:[e.jsx(Ha,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),Z]},Z))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(Z=>e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[Z,e.jsx("button",{onClick:()=>h(u.filter(oe=>oe!==Z)),children:e.jsx(er,{className:"h-3 w-3"})})]},Z))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(z,{onClick:()=>V.mutate(),disabled:V.isPending,className:"flex-1",children:[V.isPending?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(be,{className:"overflow-hidden",children:e.jsx(Le,{className:"p-4",children:e.jsxs("button",{onClick:I,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(wl,{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 n7n({contactId:s,contactName:t}){const n=$t(),[r,a]=_.useState(""),{data:i,isLoading:l}=rt({queryKey:["contact-email-prefs",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("innercircle_contacts").select("email, email_opt_out, email_opt_out_at, email_opt_out_reason").eq("id",s).single();if(u)throw u;return d}});_.useEffect(()=>{a((i==null?void 0:i.email_opt_out_reason)||"")},[i==null?void 0:i.email_opt_out_reason]);const o=mt({mutationFn:async({optOut:d,reasonText:u})=>{const{error:h}=await U.from("innercircle_contacts").update({email_opt_out:d,email_opt_out_at:d?new Date().toISOString():null,email_opt_out_reason:d&&u.trim()||null}).eq("id",s);if(h)throw h;return d},onSuccess:d=>{n.invalidateQueries({queryKey:["contact-email-prefs",s]}),n.invalidateQueries({queryKey:["contact",s]}),n.invalidateQueries({queryKey:["innercircle-contacts"]}),ne.success(d?`${t} will no longer receive newsletters or marketing emails`:`${t} is opted back in to marketing emails`)},onError:d=>ne.error(d.message)}),c=!!(i!=null&&i.email_opt_out);return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(cP,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx(ze,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Le,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{htmlFor:"opt-out-toggle",className:"text-sm font-medium",children:"Opt out of newsletters & marketing emails"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When on, this contact is skipped in newsletters, mass emails, drip campaigns, market reports and listing blasts. One-to-one emails still work."})]}),e.jsx(mn,{id:"opt-out-toggle",checked:c,disabled:o.isPending,onCheckedChange:d=>o.mutate({optOut:d,reasonText:r})})]}),c&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/40 p-3",children:[e.jsx(ee,{htmlFor:"opt-out-reason",className:"text-xs",children:"Reason (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"opt-out-reason",value:r,placeholder:"e.g. Asked to stop monthly newsletter",onChange:d=>a(d.target.value)}),e.jsx(z,{variant:"outline",size:"sm",disabled:o.isPending||r===((i==null?void 0:i.email_opt_out_reason)||""),onClick:()=>o.mutate({optOut:!0,reasonText:r}),children:"Save"})]}),(i==null?void 0:i.email_opt_out_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Opted out ",Ys(new Date(i.email_opt_out_at),"MMM d, yyyy")]})]})]})})]})}function r7n(s){return rt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await U.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(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 U.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await U.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",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 a7n(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 eNt(s){return s==="sent"?e.jsx(Mr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(nl,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(S0,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})}function i7n({contactId:s}){const t=zn(),{data:n,isLoading:r}=r7n(s),[a,i]=_.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(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(mP,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Le,{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(mP,{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"}),a7n(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: ",Md(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Md(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Md(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(yi,{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(Is,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(rl,{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:eNt(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(qi,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(on,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",Ys(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[eNt(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((u=c.campaign)==null?void 0:u.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:Ys(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx(z,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}const Nze=1e3,o7n=5e4;async function Jce(s){const t=[];for(let n=0;n{const n=t.id,r=await Jce(()=>{let p=U.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});return s&&(p=p.eq("contact_id",s)),p}),a=await Jce(()=>{let p=U.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});return s&&(p=p.eq("contact_id",s)),p}),i=await Jce(()=>U.from("email_campaigns").select("id, subject").eq("user_id",n).order("id")),l=i.map(p=>p.id),o=new Map(i.map(p=>[p.id,p.subject]));let c=[];if(l.length>0)for(let f=0;f{let y=U.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",g).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1});return s&&(y=y.eq("contact_id",s)),y});c.push(...v)}const d=r.map(p=>({id:`g-${p.id}`,channel:p.source==="portal_invite"?"Client Portal Invite":String(p.source||"").startsWith("card_studio")?"Card Studio":"Gmail",subject:p.subject,to_email:p.to_email,contact_id:p.contact_id,sent_at:p.sent_at,source:p.source})),u=a.map(p=>({id:`b-${p.id}`,channel:"Mass Email",subject:p.subject,to_email:p.contact_email,contact_id:p.contact_id,sent_at:p.sent_at,source:p.source,opened_at:p.opened_at,clicked_at:p.clicked_at})),h=c.map(p=>({id:`c-${p.id}`,channel:"Campaign",subject:o.get(p.campaign_id)||"(campaign)",to_email:p.email,contact_id:p.contact_id,sent_at:p.sent_at,source:null,campaign_id:p.campaign_id,opened_at:p.opened_at,clicked_at:p.clicked_at})),m=[...d,...u,...h];return m.sort((p,f)=>p.sent_at0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Le,{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(on,{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 ${l7n[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx(z,{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(or,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}const d7n={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY","district of columbia":"DC","puerto rico":"PR"},u7n={avenue:"ave",boulevard:"blvd",circle:"cir",court:"ct",drive:"dr",highway:"hwy",lane:"ln",parkway:"pkwy",place:"pl",road:"rd",square:"sq",street:"st",terrace:"ter",trail:"trl",way:"way","suite ":"ste ","unit ":"unit ","apartment ":"apt ","#":"unit "};function h7n(s){if(!s)return null;const t=s.trim();if(/^[A-Za-z]{2}$/.test(t))return t.toUpperCase();const n=t.toLowerCase();return d7n[n]||null}function m7n(s){return!s||!s.trim().match(/^\d{5}(-?\d{4})?$/)?null:s.trim().split("-")[0]}function p7n(s){let t=s.toLowerCase();for(const[n,r]of Object.entries(u7n))t=t.replace(new RegExp(`\\b${n}\\b`,"g"),r);return t}function f7n(s){const t=s.toLowerCase(),n=[/\b(apt|apartment|unit|suite|ste|#)\s*([A-Za-z0-9\-]+)\b/,/\b(floor|fl)\s*([A-Za-z0-9\-]+)\b/];for(const r of n){const a=t.match(r);if(a){const i=a[0].replace(/#/,"unit ").trim();return{street:s.replace(new RegExp(a[0],"i"),"").replace(/\s+/g," ").trim(),unit:i}}}return{street:s,unit:null}}function RZt(s,t,n,r){const a=[s,t,n,r].filter(Boolean).join(", ").trim(),i=h7n(n),l=m7n(r);let o=null,c=null;if(s){const f=f7n(s.trim());o=f.street,c=f.unit}const d=(t==null?void 0:t.trim())||null,u=[];o&&u.push(p7n(o)),c&&u.push(c.toLowerCase().replace(/\s+/g,"")),d&&u.push(d.toLowerCase()),i&&u.push(i.toLowerCase()),l&&u.push(l);const h=u.join(" | "),m=[!!o,!!d,!!i,!!l].filter(Boolean).length;let p="low";return m>=4?p="high":m>=2&&(p="medium"),{original:a,normalized:h,streetAddress:o,unitNumber:c,city:d,state:i,postalCode:l,confidence:p}}async function srt(){const{data:{user:s},error:t}=await U.auth.getUser();if(t||!s)throw new Error("Not authenticated");return s.id}async function x7n(s){const{data:t,error:n}=await U.from("contact_properties").select("*, property:properties(*)").eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw new Error(n.message);const r=t??[],a=Array.from(new Set(r.map(o=>o.property_id).filter(Boolean)));let i=[],l=[];if(a.length){const[o,c]=await Promise.all([U.from("property_field_locks").select("*").in("property_id",a),U.from("property_enrichment_events").select("*").in("property_id",a).order("created_at",{ascending:!1})]);if(o.error)throw new Error(o.error.message);if(c.error)throw new Error(c.error.message);i=o.data??[],l=c.data??[]}return r.map(o=>({property:o.property,relationship:o,locks:i.filter(c=>c.property_id===o.property_id),events:l.filter(c=>c.property_id===o.property_id)}))}async function g7n(s){const t=await srt(),{data:n,error:r}=await U.from("properties").insert({...s,owner_user_id:t}).select().single();if(r)throw new Error(r.message);return n}async function y7n(s,t,n={}){const a={owner_user_id:await srt(),contact_id:s,property_id:t,relationship_type:n.relationship_type??"unknown",is_primary_residence:n.is_primary_residence??!1,ownership_status:n.ownership_status??"unknown",relationship_started_at:n.relationship_started_at??null,relationship_ended_at:n.relationship_ended_at??null},{data:i,error:l}=await U.from("contact_properties").insert(a).select().single();if(l)throw new Error(l.message);return i}async function v7n(s){const{error:t}=await U.from("contact_properties").delete().eq("id",s);if(t)throw new Error(t.message)}async function tNt(s,t){const{data:n,error:r}=await U.from("contact_properties").update(t).eq("id",s).select().single();if(r)throw new Error(r.message);return n}function k3(s){return s==null||Number.isNaN(s)?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}function S3(s,t=""){return s==null||Number.isNaN(s)?"—":`${new Intl.NumberFormat("en-US").format(s)}${t}`}function sNt(s){return{never_enriched:"Never enriched",pending:"Pending",enriched:"Enriched",partially_enriched:"Partially enriched",not_found:"Not found",unsupported_active_listing:"Active listing — unsupported",incomplete_address:"Incomplete address",needs_review:"Needs review",failed:"Failed"}[s]??s}async function Njr(){const{data:{user:s}}=await U.auth.getUser();if(!s)throw new Error("Not authenticated");const t=s.id,n=new Date;n.setDate(n.getDate()-90);const r=n.toISOString(),[{count:a,error:i},{count:l,error:o},{count:c,error:d},{count:u,error:h},{count:m,error:p},{count:f,error:g},{count:v,error:y},{count:b,error:w},{count:S,error:C},{count:E,error:P}]=await Promise.all([U.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).not("address","is",null),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","enriched"),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","needs_review"),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","incomplete_address"),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","failed"),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).or(`last_enriched_at.is.null,last_enriched_at.lt.${r}`),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("owner_occupied_status","non_owner_occupied"),U.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).is("estimated_value",null),U.rpc("count_contacts_missing_property_data",{owner_id:t})]),M=[i,o,d,h,p,g,y,w,C,P].filter(Boolean);if(M.length)throw new Error(M.map(I=>I==null?void 0:I.message).join("; "));return{contactsWithAddresses:a??0,propertiesLinked:l??0,contactsMissingPropertyData:E??0,propertiesEnriched:c??0,propertiesNeedingReview:u??0,incompleteAddresses:m??0,enrichmentFailures:f??0,staleProperties:v??0,possibleNonOwnerOccupied:b??0,propertiesMissingValuation:S??0}}async function kjr(s={}){const{data:{user:t}}=await U.auth.getUser();if(!t)throw new Error("Not authenticated");const n=s.limit??25,r=s.offset??0,a=!!(s.enrichmentStatus&&s.enrichmentStatus!=="all")||!!s.staleBefore,i=s.missingOnly?"":a?"!inner":"",l=s.missingOnly?"":a?"!inner":"";let o=U.from("innercircle_contacts").select(`id, first_name, last_name, address, city, state, zip_code, zip, contact_properties${i}(id, property_id, properties${l}(id, enrichment_status, last_enriched_at))`,{count:"exact"}).eq("owner_user_id",t.id).not("address","is",null);s.city&&(o=o.ilike("city",`%${s.city}%`)),s.state&&(o=o.ilike("state",`%${s.state}%`)),s.postalCode&&(o=o.or(`zip_code.ilike.%${s.postalCode}%,zip.ilike.%${s.postalCode}%`)),s.missingOnly?o=o.is("contact_properties",null):a&&(s.enrichmentStatus&&s.enrichmentStatus!=="all"&&(o=o.eq("contact_properties.properties.enrichment_status",s.enrichmentStatus)),s.staleBefore&&(o=o.or(`last_enriched_at.is.null,last_enriched_at.lt.${s.staleBefore}`,{referencedTable:"contact_properties.properties"})));const{data:c,error:d,count:u}=await o.order("last_name",{ascending:!0}).range(r,r+n-1);if(d)throw new Error(d.message);return{contacts:(c??[]).map(m=>{const p=Array.isArray(m.contact_properties)?m.contact_properties[0]:m.contact_properties,f=p==null?void 0:p.properties;return{id:m.id,first_name:m.first_name,last_name:m.last_name,address:m.address,city:m.city,state:m.state,zip_code:m.zip_code??m.zip,linked_property_id:(p==null?void 0:p.property_id)??null,enrichment_status:(f==null?void 0:f.enrichment_status)??"never_enriched",last_enriched_at:(f==null?void 0:f.last_enriched_at)??null}}),count:u??0}}function b7n(s){switch(s){case"verified":return"default";case"high":return"default";case"medium":return"secondary";case"low":return"outline";default:return"outline"}}async function Sjr(s,t={}){const n=await srt();if(!s.length)throw new Error("Select at least one contact");const{data:r,error:a}=await U.from("innercircle_contacts").select("id, address, city, state, zip_code, zip").eq("owner_user_id",n).in("id",s);if(a)throw new Error(a.message);const i=r??[];if(!i.length)throw new Error("No matching contacts found");const{data:l,error:o}=await U.from("property_enrichment_runs").insert({owner_user_id:n,name:t.name??null,requested_source:t.requestedSource??"zillow_chatgpt_app",status:"ready",total_contacts:i.length,pending_count:i.length}).select("id").single();if(o)throw new Error(o.message);const c=i.map(u=>({owner_user_id:n,enrichment_run_id:l.id,contact_id:u.id,normalized_address:RZt(u.address,u.city,u.state,u.zip_code??u.zip).normalized||null,status:"pending"})),{error:d}=await U.from("property_enrichment_items").insert(c);if(d)throw new Error(d.message);return{runId:l.id,count:i.length}}const FZt=[{value:"owner",label:"Owner"},{value:"co_owner",label:"Co-owner"},{value:"household_member",label:"Household member"},{value:"former_owner",label:"Former owner"},{value:"buyer_prospect",label:"Buyer prospect"},{value:"seller_prospect",label:"Seller prospect"},{value:"tenant",label:"Tenant"},{value:"landlord",label:"Landlord"},{value:"unknown",label:"Unknown"}],OZt=[{value:"current",label:"Current"},{value:"former",label:"Former"},{value:"possible",label:"Possible"},{value:"unknown",label:"Unknown"}];function _7n({detail:s,onMutate:t}){const{property:n,relationship:r,events:a}=s,[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(r.relationship_type),[h,m]=_.useState(r.ownership_status),[p,f]=_.useState(r.is_primary_residence),g=mt({mutationFn:()=>tNt(r.id,{relationship_type:d,ownership_status:h,is_primary_residence:p}),onSuccess:()=>{ne.success("Property relationship updated"),c(!1),t()},onError:C=>ne.error(C instanceof Error?C.message:"Update failed")}),v=mt({mutationFn:()=>v7n(r.id),onSuccess:()=>{ne.success("Property unlinked"),t()},onError:C=>ne.error(C instanceof Error?C.message:"Unlink failed")}),y=a[0],b=n.primary_data_source||(y==null?void 0:y.source_name)||"Manual",w=n.last_enriched_at||(y==null?void 0:y.retrieved_at)||n.updated_at,S=[{id:"overview",title:"Property Overview",icon:sP,rows:[{label:"Property type",value:n.property_type||"—"},{label:"Bedrooms",value:S3(n.bedrooms)},{label:"Bathrooms",value:S3(n.bathrooms,"+")},{label:"Living area",value:S3(n.living_area_square_feet," sq ft")},{label:"Lot size",value:n.lot_size?`${S3(n.lot_size)} ${n.lot_size_units||""}`:"—"},{label:"Year built",value:S3(n.year_built)},{label:"Parcel ID",value:n.parcel_id||"—"},{label:"County",value:n.county||"—"}]},{id:"value",title:"Value & Valuation",icon:Nd,rows:[{label:"Estimated value",value:k3(n.estimated_value)},{label:"Value range",value:n.estimated_value_low&&n.estimated_value_high?`${k3(n.estimated_value_low)} – ${k3(n.estimated_value_high)}`:"—"},{label:"Rent estimate",value:k3(n.rent_estimate)},{label:"Data confidence",value:n.data_confidence}]},{id:"tax",title:"Tax Information",icon:Om,rows:[{label:"Tax-assessed value",value:k3(n.tax_assessed_value)},{label:"Assessed year",value:S3(n.tax_assessed_year)},{label:"Annual property tax",value:k3(n.latest_annual_property_tax)},{label:"Tax rate",value:n.property_tax_rate?`${(n.property_tax_rate*100).toFixed(2)}%`:"—"}]},{id:"ownership",title:"Ownership & Relationship",icon:Oo,rows:[{label:"Relationship",value:r.relationship_type.replace(/_/g," ")},{label:"Ownership status",value:r.ownership_status},{label:"Primary residence",value:r.is_primary_residence?"Yes":"No"},{label:"Owner-occupied status",value:n.owner_occupied_status.replace(/_/g," ")},{label:"Foreclosure status",value:n.foreclosure_status||"—"}]},{id:"sale",title:"Sale History",icon:O_,rows:[{label:"Last sale price",value:k3(n.last_sale_price)},{label:"Last sale date",value:n.last_sale_date||"—"}]},{id:"sources",title:"Data Sources",icon:zU,rows:[{label:"Primary source",value:b},{label:"Source URL",value:n.source_property_url?"View source":"—"},{label:"Last updated",value:w?new Date(w).toLocaleDateString():"—"}]},{id:"history",title:"Enrichment History",icon:ya,rows:a.length?a.slice(0,5).map(C=>({label:new Date(C.created_at).toLocaleDateString(),value:`${C.source_name} — ${sNt(C.status)}`})):[{label:"History",value:"No enrichment events yet"}]}];return e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Nt,{className:"flex items-start gap-2 text-base",children:[e.jsx(sa,{className:"mt-0.5 h-4 w-4 text-primary"}),e.jsx("span",{children:n.street_address||n.normalized_address})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),[n.city,n.state,n.postal_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.is_primary_residence&&e.jsxs(ze,{variant:"default",className:"gap-1",children:[e.jsx(Ia,{className:"h-3 w-3"})," Primary"]}),e.jsx(ze,{variant:b7n(n.data_confidence),children:n.data_confidence}),e.jsx(ze,{variant:"outline",children:sNt(n.enrichment_status)})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(ede,{label:"Estimated value",value:k3(n.estimated_value)}),e.jsx(ede,{label:"Tax assessed",value:k3(n.tax_assessed_value)}),e.jsx(ede,{label:"Bed / Bath",value:`${S3(n.bedrooms)} / ${S3(n.bathrooms)}`}),e.jsx(ede,{label:"Sq ft",value:S3(n.living_area_square_feet)})]}),e.jsxs(f1,{open:i,onOpenChange:l,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsx("span",{children:"Property details"}),e.jsx(cl,{className:Ct("h-4 w-4 transition-transform",i&&"rotate-180")})]})}),e.jsx(g1,{className:"space-y-4 pt-2",children:S.map(C=>e.jsxs("div",{className:"rounded-xl border border-border/70 bg-muted/30 p-4",children:[e.jsxs("h4",{className:"mb-3 flex items-center gap-2 text-sm font-semibold",children:[e.jsx(C.icon,{className:"h-4 w-4 text-primary"}),C.title]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:C.rows.map((E,P)=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:E.label}),e.jsx("span",{className:"text-sm font-medium",children:E.label==="Source URL"&&E.value!=="—"?e.jsx("a",{href:n.source_property_url||"#",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:E.value}):E.value})]},P))})]},C.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Is,{open:o,onOpenChange:c,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",children:[e.jsx(Mm,{className:"mr-1 h-3.5 w-3.5"})," Edit relationship"]})}),e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Edit property relationship"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Relationship type"}),e.jsxs(ls,{value:d,onValueChange:C=>u(C),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:FZt.map(C=>e.jsx(He,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Ownership status"}),e.jsxs(ls,{value:h,onValueChange:C=>m(C),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:OZt.map(C=>e.jsx(He,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:`primary-${r.id}`,type:"checkbox",checked:p,onChange:C=>f(C.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(ee,{htmlFor:`primary-${r.id}`,children:"Primary residence"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(z,{onClick:()=>g.mutate(),disabled:g.isPending,children:"Save changes"})]})]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>tNt(r.id,{is_primary_residence:!r.is_primary_residence}).then(()=>{ne.success(r.is_primary_residence?"Removed primary residence":"Marked as primary residence"),t()}).catch(C=>ne.error(C.message)),children:[e.jsx(Ia,{className:"mr-1 h-3.5 w-3.5"}),r.is_primary_residence?"Unmark primary":"Mark primary"]}),e.jsxs(z,{variant:"outline",size:"sm",className:"text-destructive hover:bg-destructive/10",onClick:()=>v.mutate(),disabled:v.isPending,children:[e.jsx(w0,{className:"mr-1 h-3.5 w-3.5"})," Unlink property"]})]})]})]})}function ede({label:s,value:t}){return e.jsxs("div",{className:"rounded-xl border border-border/70 bg-muted/30 p-3",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("p",{className:"text-sm font-semibold",children:t})]})}function w7n({contactId:s,defaultAddress:t,defaultCity:n,defaultState:r,defaultZip:a,onAdded:i}){const[l,o]=_.useState(!1),[c,d]=_.useState(t||""),[u,h]=_.useState(n||""),[m,p]=_.useState(r||""),[f,g]=_.useState(a||""),[v,y]=_.useState("owner"),[b,w]=_.useState("current"),[S,C]=_.useState(!1),E=mt({mutationFn:async()=>{const P=[c,u,m,f].filter(Boolean).join(", "),M=RZt(c,u,m,f);if(!M.normalized)throw new Error("Could not normalize address. Please check the fields.");const I=await g7n({original_address:P,normalized_address:M.normalized,street_address:M.streetAddress,unit_number:M.unitNumber,city:M.city,state:M.state,postal_code:M.postalCode,property_type:null,enrichment_status:"never_enriched",data_confidence:"unknown",owner_occupied_status:"unknown",photo_usage_authorized:!1,external_ids:{}});await y7n(s,I.id,{relationship_type:v,ownership_status:b,is_primary_residence:S})},onSuccess:()=>{ne.success("Property added"),o(!1),d(t||""),h(n||""),p(r||""),g(a||""),i()},onError:P=>ne.error(P instanceof Error?P.message:"Failed to add property")});return e.jsxs(Is,{open:l,onOpenChange:o,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(sn,{className:"mr-1 h-4 w-4"})," Add property"]})}),e.jsxs(Ls,{className:"sm:max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Add property to contact"})}),e.jsxs("div",{className:"grid gap-4 py-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ee,{htmlFor:"pi-street",children:"Street address"}),e.jsx(pe,{id:"pi-street",value:c,onChange:P=>d(P.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-city",children:"City"}),e.jsx(pe,{id:"pi-city",value:u,onChange:P=>h(P.target.value),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-state",children:"State"}),e.jsx(pe,{id:"pi-state",value:m,onChange:P=>p(P.target.value),placeholder:"State"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-zip",children:"ZIP"}),e.jsx(pe,{id:"pi-zip",value:f,onChange:P=>g(P.target.value),placeholder:"ZIP"})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Relationship type"}),e.jsxs(ls,{value:v,onValueChange:P=>y(P),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:FZt.map(P=>e.jsx(He,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Ownership status"}),e.jsxs(ls,{value:b,onValueChange:P=>w(P),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:OZt.map(P=>e.jsx(He,{value:P.value,children:P.label},P.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"pi-primary",type:"checkbox",checked:S,onChange:P=>C(P.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(ee,{htmlFor:"pi-primary",children:"Primary residence"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(z,{onClick:()=>E.mutate(),disabled:E.isPending||!c,children:E.isPending?"Saving...":"Save property"})]})]})]})}function j7n({contactId:s,contactAddress:t,contactCity:n,contactState:r,contactZip:a}){const i=$t(),{data:l,isLoading:o,error:c}=rt({queryKey:["contact-properties",s],queryFn:()=>x7n(s)}),d=()=>{i.invalidateQueries({queryKey:["contact-properties",s]})};if(o)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ln,{className:"h-10 w-48"}),e.jsx(ln,{className:"h-48 w-full"})]});if(c)return e.jsx(be,{className:"border-destructive/50 bg-destructive/5",children:e.jsxs(Le,{className:"flex items-center gap-3 py-6",children:[e.jsx(nl,{className:"h-5 w-5 text-destructive"}),e.jsx("p",{className:"text-sm",children:"Could not load property intelligence."})]})});const u=l??[];return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Property Intelligence"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Home and property details for this contact. Property details are filled in from your ChatGPT assistant or entered by hand — the "Find person details" button at the top of the page looks up work and social info, not property data.'})]}),e.jsx(w7n,{contactId:s,defaultAddress:t||void 0,defaultCity:n||void 0,defaultState:r||void 0,defaultZip:a||void 0,onAdded:d})]}),u.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-10 text-center",children:[e.jsx(sa,{className:"mb-3 h-10 w-10 text-muted-foreground/60"}),e.jsx("h4",{className:"text-base font-medium",children:"No properties linked yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the contact's property above, or run a ChatGPT enrichment to match addresses with public property data."}),t&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Contact address on file: ",t,n?`, ${n}`:"",r?`, ${r}`:"",a?` ${a}`:""]})]})}):e.jsx("div",{className:"space-y-4",children:u.map(h=>e.jsx(_7n,{detail:h,onMutate:d},h.relationship.id))})]})}function N7n({videoId:s}){var l;const{data:t,isLoading:n,error:r}=pFn(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ln,{className:"w-full aspect-video rounded-lg"}),e.jsx(ln,{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(nl,{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 k7n({contactId:s}){const t=zn(),[n,r]=_.useState(!1),{data:a,isLoading:i}=rt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await U.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),l=async(h,m)=>{const p=m==="done"?"todo":"done";await U.from("deal_tasks").update({status:p,completed_at:p==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=rt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await U.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Wr,{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(z,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Le,{className:"space-y-1",children:i?e.jsx(ln,{className:"h-8 w-full"}):d.length===0&&u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(h=>e.jsxs("button",{onClick:async()=>{await l(h.id,h.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[h.priority]," ",h.title]}),h.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(h.due_date),"MMM d")})]},h.id)),u.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[u.length," completed"]})})]})}),n&&e.jsx(S7n,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function S7n({contactId:s,open:t,onOpenChange:n}){const[r,a]=_.useState(""),[i,l]=_.useState("medium"),[o,c]=_.useState(),{data:d}=rt({queryKey:["session"],queryFn:async()=>{const{data:h}=await U.auth.getSession();return h.session}}),u=async()=>{var m;if(!r.trim()||!((m=d==null?void 0:d.user)!=null&&m.id))return;const{error:h}=await U.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Ys(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(Is,{open:t,onOpenChange:n,children:e.jsxs(Ls,{className:"sm:max-w-[400px]",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{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(ee,{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(ee,{children:"Due Date"}),e.jsx(pe,{type:"date",value:o?Ys(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(z,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function C7n({contactId:s}){const t=zn(),{data:n,isLoading:r}=rt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await U.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Px,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Le,{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(Da,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function A7n(){var Tn,Yn,fs,wn;const{contactId:s}=Mi(),{isAdmin:t}=hs(),{hasIdx:n}=mf(),r=zn(),[a]=Gl(),i=a.get("search")||"",l=a.get("type")||"all",o=a.get("status")||a.get("filter")||"all",c=a.get("tags")||"",d=a.get("tagMode")==="all"?"all":"any",u=_.useMemo(()=>new Set(c.split(",").map(As=>As.trim()).filter(Boolean)),[c]),{data:h,isLoading:m}=OBs(s||""),{data:p}=Q_(),{data:f}=fae(),{data:g}=SW(3650),{data:v}=c8e(365),{data:y}=GOn(s),{contactsWithScores:b}=yae(),{data:w}=$ae(),{score:S}=tqs(s||""),C=zet(),E=aBt(),P=bLe(),M=rBt(),[I,D]=_.useState(!1),[F,q]=_.useState("overview"),[G,V]=_.useState(!1),H=POn(),[K,Z]=_.useState({}),[oe,re]=_.useState(!1),[ae,J]=_.useState(!1),[te,ce]=_.useState(null),[ve,me]=_.useState(""),[he,ge]=_.useState(void 0),[Ee,Ne]=_.useState(""),[Pe,Oe]=_.useState(null),[ke,Ve]=_.useState(!1),[_e,Ae]=_.useState(null),[Se,We]=_.useState(!1),{isGmailConnected:qe,gmailEmail:Be}=bg(),{isReady:Ze}=NL(),$e=Ze||qe,Xe=TZt(),[nt,Ge]=_.useState(!1),{data:Je}=rt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:As}}=await U.auth.getUser();if(!As)return!1;const{data:Ss}=await U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",As.id);return(Ss||[]).some(pr=>pr.is_active&&pr.mls_provider_id&&!pr.no_mls_mode)}}),ut=async()=>{var Pn,Gs,an,tr;if(!h)return;const As=(Pn=h.address)==null?void 0:Pn.trim(),Ss=(Gs=h.city)==null?void 0:Gs.trim(),pr=(an=h.state)==null?void 0:an.trim().toUpperCase(),hn=((tr=h.zip_code)==null?void 0:tr.trim())||"";if(!As||!Ss||!pr){ne.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ge(!0);const Lr=await Xe.mutateAsync({subject:{address:As,city:Ss,state:pr,zip:hn},contactId:h.id,title:`${h.first_name||""} ${h.last_name||""}`.trim()+" — "+As});r(`/mission-control/cma/${Lr.id}`)}catch(Lr){ne.error("Could not create CMA: "+((Lr==null?void 0:Lr.message)||"unknown error"))}finally{Ge(!1)}},{data:lt}=rt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:As,error:Ss}=await U.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Ss)throw Ss;return As},enabled:!!s}),qt=As=>{if(!As)return null;const Ss=As.match(/Video ID:\s*([a-f0-9-]+)/i);return Ss?Ss[1]:null},zt=_.useMemo(()=>{if(!b)return[];const As=new Map;if(u.size>0&&w)for(const pr of w)As.has(pr.contact_id)||As.set(pr.contact_id,new Set),As.get(pr.contact_id).add(pr.tag_id);let Ss=b.filter(pr=>{var an,tr,Lr;const hn=i===""||`${pr.first_name} ${pr.last_name}`.toLowerCase().includes(i.toLowerCase())||((an=pr.email)==null?void 0:an.toLowerCase().includes(i.toLowerCase()))||((tr=pr.phone)==null?void 0:tr.includes(i)),Pn=l==="all"||((Lr=pr.tags)==null?void 0:Lr.some(Yt=>Yt.relationship_type_id===l));let Gs=!0;if(u.size>0){const Yt=As.get(pr.id)||new Set;d==="all"?Gs=Array.from(u).every(it=>Yt.has(it)):Gs=Array.from(u).some(it=>Yt.has(it))}return hn&&Pn&&Gs});return o==="not-touched-90"?Ss=Ss.filter(pr=>{const hn=pr.relationshipScore.daysSinceTouch;return hn===null||hn>90}):o==="at-risk"?Ss=Ss.filter(pr=>pr.relationshipScore.status==="at-risk"):o==="cooling"?Ss=Ss.filter(pr=>pr.relationshipScore.status==="cooling"):o==="warm"&&(Ss=Ss.filter(pr=>pr.relationshipScore.status==="warm")),Ss.map(pr=>pr.id)},[b,i,l,o,u,d,w]),Zt=zt.indexOf(s||""),ms=Zt>0?zt[Zt-1]:null,Dt=Zt1&&Zt!==-1,qs=As=>{const Ss=new URLSearchParams;i&&Ss.set("search",i),l!=="all"&&Ss.set("type",l),o!=="all"&&Ss.set("status",o),u.size>0&&(Ss.set("tags",Array.from(u).join(",")),Ss.set("tagMode",d));const pr=Ss.toString();return`/mission-control/contacts/${As}${pr?`?${pr}`:""}`},wt=_.useMemo(()=>{const As=((g==null?void 0:g.filter(pr=>pr.contact_id===s))||[]).map(pr=>{var an,tr,Lr;const hn=qt(pr.notes);let Pn=((an=pr.action_type)==null?void 0:an.name)||"Touch",Gs=pr.notes;if(Pn==="Other"&&((tr=pr.notes)!=null&&tr.startsWith("["))){const Yt=pr.notes.indexOf("]");Yt>0&&(Pn=pr.notes.substring(1,Yt),Gs=pr.notes.substring(Yt+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:pr.id,type:"touch",completed_at:pr.completed_at,name:Pn,color:((Lr=pr.action_type)==null?void 0:Lr.color)||"#3B82F6",notes:Gs,videoId:hn}}),Ss=((v==null?void 0:v.filter(pr=>pr.contact_id===s))||[]).map(pr=>({id:pr.id,type:"popby",completed_at:pr.completed_at,name:"Pop-by",color:"#F97316",notes:pr.notes,videoId:null}));return[...As,...Ss].sort((pr,hn)=>new Date(hn.completed_at).getTime()-new Date(pr.completed_at).getTime())},[g,v,s]),Us=As=>{var Ss;return{first_name:As.first_name||"",last_name:As.last_name||"",email:As.email||"",phone:As.phone||"",address:As.address||"",city:As.city||"",state:As.state||"",zip_code:As.zip_code||"",address2_label:As.address2_label||"",address2:As.address2||"",address2_city:As.address2_city||"",address2_state:As.address2_state||"",address2_zip:As.address2_zip||"",mail_to_secondary:!!As.mail_to_secondary,birthday:As.birthday||"",home_anniversary:As.home_anniversary||"",wedding_anniversary:As.wedding_anniversary||"",spouse_birthday:As.spouse_birthday||"",spouse_name:As.spouse_name||"",spouse_email:As.spouse_email||"",company_name:As.company_name||"",job_title:As.job_title||"",lead_source_id:As.lead_source_id||"",notes:As.notes||"",tagIds:((Ss=As.tags)==null?void 0:Ss.map(pr=>pr.relationship_type_id))||[]}};_.useEffect(()=>{D(!1),Z({})},[s]);const Es=_.useRef(null);_.useEffect(()=>{h!=null&&h.id&&Es.current!==h.id&&(Es.current=h.id,Z(Us(h)))},[h==null?void 0:h.id,h]);const kn=()=>{h&&(Z(Us(h)),re(M2t(h)),D(!0))},Sn=async()=>{await C.mutateAsync({id:s,...K,lead_source_id:K.lead_source_id||null}),D(!1)},bn=async()=>{await Qi("Are you sure you want to delete this contact?")&&(await E.mutateAsync(s),r("/mission-control/contacts"))},Fs=((Tn=f==null?void 0:f.find(As=>As.id===te))==null?void 0:Tn.name)==="Other",cn=async()=>{if(!te||Fs&&!Ee.trim())return;const As=he?new Date(he.getFullYear(),he.getMonth(),he.getDate(),12,0,0).toISOString():void 0,Ss=Fs?`[${Ee.trim()}]${ve?" — "+ve:""}`:ve;await P.mutateAsync({contactId:s,actionTypeId:te,notes:Ss,completedAt:As}),J(!1),ce(null),me(""),ge(void 0),Ne("")},lr=(As,Ss)=>{$e&&h?(Ae({email:As,name:Ss||`${h.first_name} ${h.last_name||""}`.trim()}),Ve(!0)):window.location.href=`mailto:${As}`};return m?e.jsx($s,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):h?e.jsxs(e.Fragment,{children:[e.jsx($s,{title:`${h.first_name} ${h.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-5 overflow-x-hidden pb-24 lg:pb-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>{window.history.length>1?r(-1):r("/mission-control/contacts")},children:[e.jsx(Wc,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),It&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>ms&&r(qs(ms)),disabled:!ms,children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[Zt+1," of ",zt.length]}),e.jsx(z,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Dt&&r(qs(Dt)),disabled:!Dt,children:e.jsx(yi,{className:"h-4 w-4"})})]})]}),e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-full bg-background p-1 shadow-lg ring-2 ring-white/20",children:e.jsx(SOn,{contactId:h.id,firstName:h.first_name,lastName:h.last_name,avatarUrl:h.avatar_url,email:h.email,size:72})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"truncate text-2xl font-bold sm:text-3xl",children:[h.first_name," ",h.last_name||""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[S&&e.jsxs("span",{className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold capitalize",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:S.status==="warm"?"#22c55e":S.status==="cooling"?"#f59e0b":"#ef4444"}}),S.status==="at-risk"?"At risk":S.status," · ",S.score]}),h.email_opt_out&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-destructive/90 px-2.5 py-1 text-[11px] font-semibold text-destructive-foreground",children:[e.jsx(cP,{className:"h-3 w-3"}),"Emails opted out"]}),(((Yn=h.lead_source_ref)==null?void 0:Yn.name)||h.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((fs=h.lead_source_ref)==null?void 0:fs.name)||h.lead_source}),(wn=h.tags)==null?void 0:wn.map(As=>{const Ss=p==null?void 0:p.find(pr=>pr.id===As.relationship_type_id);return Ss?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:Ss.name},As.id):null})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1.5 text-sm sm:flex-row sm:flex-wrap sm:items-center sm:gap-4",children:[h.email&&e.jsxs("button",{onClick:()=>lr(h.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(on,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:h.email})]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"inline-flex items-center gap-1.5 hub-ink-muted",children:[e.jsx(va,{className:"h-3.5 w-3.5"}),h.phone]}),(h.address||h.city)&&e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted",children:[e.jsx(Ha,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:[h.address,h.city,h.state].filter(Boolean).join(", ")})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[H&&e.jsxs("button",{onClick:()=>V(!0),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold transition-transform hover:scale-[1.02]",title:"Find public professional details (job, company, social profiles) for this person. Property data is on the Property tab.",children:[e.jsx(un,{className:"h-4 w-4"}),"Find person details"]}),e.jsxs("button",{onClick:()=>{kn(),q("details")},className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(Cp,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:bn,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(Cn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap",children:[h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(va,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Call"]}),h.phone&&e.jsxs("button",{onClick:()=>window.location.href=`sms:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(qi,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),h.email&&e.jsxs("button",{onClick:()=>lr(h.email,`${h.first_name} ${h.last_name||""}`.trim()),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(on,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Email"]}),e.jsxs("button",{onClick:()=>r(`/mission-control/video/record?contact_id=${s}`),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Xr,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Video"]}),e.jsxs("button",{onClick:()=>J(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(sn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),h.email&&e.jsxs("button",{onClick:()=>We(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(un,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(Qr,{value:F,onValueChange:As=>{As==="details"&&!I&&kn(),q(As)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(Jr,{className:"inline-flex h-10 w-auto",children:[e.jsx(Wt,{value:"overview",children:"Overview"}),e.jsx(Wt,{value:"details",children:"Details"}),e.jsx(Wt,{value:"activity",children:"Activity"}),e.jsx(Wt,{value:"marketing",children:"Marketing"}),t&&e.jsx(Wt,{value:"property-intel",children:"Property Intelligence"})]})}),e.jsx(Kt,{value:"overview",className:"mt-4 space-y-5",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-5 lg:col-span-2",children:[e.jsx(DRn,{contact:h,onLogTouch:()=>J(!0)}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(ya,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(Le,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:Ko,label:"Birthday",value:h.birthday},{icon:sa,label:"Home Anniversary",value:h.home_anniversary},{icon:Fo,label:"Wedding Anniversary",value:h.wedding_anniversary},{icon:Fo,label:"Spouse Birthday",value:h.spouse_birthday}].map(({icon:As,label:Ss,value:pr})=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/70 bg-muted/30 px-3 py-2.5",children:[e.jsx(As,{className:"h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:Ss}),e.jsx("p",{className:"truncate text-sm font-medium",children:pr?Ys(Ou(pr),Ou(pr).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},Ss))}),wt.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",Ys(new Date(wt[0].completed_at),"MMM d, yyyy")," (",wt[0].name,")",h.created_at&&` · Added ${Ys(new Date(h.created_at),"MMM d, yyyy")}`]})]})]}),(h.address||h.city)&&e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(sa,{className:"h-4 w-4 text-primary"}),"Home"]})}),e.jsxs(Le,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ha,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[h.address&&e.jsx("div",{children:h.address}),e.jsxs("div",{className:"text-muted-foreground",children:[[h.city,h.state].filter(Boolean).join(", "),h.zip_code?` ${h.zip_code}`:""]})]})]}),Je&&h.address&&h.city&&h.state&&e.jsxs(z,{size:"sm",variant:"outline",onClick:ut,disabled:nt,children:[nt?e.jsx(bt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(pj,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]}),M2t(h)&&e.jsx(Le,{className:"pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-dashed p-3",children:[e.jsx(Ha,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:zWe(h).label}),h.mail_to_secondary&&e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Mail goes here"})]}),e.jsx("div",{className:"text-muted-foreground",children:yRn(zWe(h))})]})]})})]}),e.jsx(DOn,{contactId:h.id,ownerUserId:h.owner_user_id,legacyNote:h.notes}),e.jsx(k7n,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"Tags"})}),e.jsx(Le,{children:e.jsx(U2t,{contactId:s})})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Oo,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsx(UWe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:h.spouse_name||null,currentSpouseEmail:h.spouse_email||null,onLink:As=>M.mutate({contactId:s,spouseContactId:As}),onUnlink:()=>M.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:Ct(!h.company_name&&!h.job_title&&"text-muted-foreground"),children:h.job_title&&h.company_name?`${h.job_title} at ${h.company_name}`:h.job_title||h.company_name||"No company on file"})]})]})]}),e.jsx(C7n,{contactId:s}),e.jsx(JOn,{contactId:s})]})]})}),e.jsx(Kt,{value:"details",className:"mt-4",children:e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"Edit Contact"})}),e.jsxs(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"first_name",children:"First Name"}),e.jsx(pe,{id:"first_name",value:K.first_name||"",onChange:As=>Z({...K,first_name:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:K.last_name||"",onChange:As=>Z({...K,last_name:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:K.email||"",onChange:As=>Z({...K,email:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:K.phone||"",onChange:As=>Z({...K,phone:As.target.value})})]})]})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address",children:"Street Address"}),e.jsx(pe,{id:"address",value:K.address||"",onChange:As=>Z({...K,address:As.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:K.city||"",onChange:As=>Z({...K,city:As.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:K.state||"",onChange:As=>Z({...K,state:As.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(pe,{id:"zip_code",value:K.zip_code||"",onChange:As=>Z({...K,zip_code:As.target.value}),placeholder:"12345"})]})]})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Second Address (optional)"}),!oe&&e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>re(!0),children:"Add another address"})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_label",children:"Label"}),e.jsx(pe,{id:"address2_label",list:"contact-address-labels",value:K.address2_label||"",onChange:As=>Z({...K,address2_label:As.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels",children:rZt.map(As=>e.jsx("option",{value:As},As))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:K.address2||"",onChange:As=>Z({...K,address2:As.target.value}),placeholder:"456 Lake Rd"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{htmlFor:"address2_city",children:"City"}),e.jsx(pe,{id:"address2_city",value:K.address2_city||"",onChange:As=>Z({...K,address2_city:As.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:K.address2_state||"",onChange:As=>Z({...K,address2_state:As.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_zip",children:"Zip Code"}),e.jsx(pe,{id:"address2_zip",value:K.address2_zip||"",onChange:As=>Z({...K,address2_zip:As.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mail_to_secondary",className:"text-sm",children:"Send mail here instead"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pop-bys and mailers will use this address."})]}),e.jsx(mn,{id:"mail_to_secondary",checked:!!K.mail_to_secondary,onCheckedChange:As=>Z({...K,mail_to_secondary:As})})]}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>{Z({...K,address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1}),re(!1)},children:"Remove second address"})]})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Important Dates"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"birthday",children:"Birthday"}),e.jsx(pe,{id:"birthday",type:"date",value:K.birthday||"",onChange:As=>Z({...K,birthday:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:K.home_anniversary||"",onChange:As=>Z({...K,home_anniversary:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(pe,{id:"wedding_anniversary",type:"date",value:K.wedding_anniversary||"",onChange:As=>Z({...K,wedding_anniversary:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(pe,{id:"spouse_birthday",type:"date",value:K.spouse_birthday||"",onChange:As=>Z({...K,spouse_birthday:As.target.value})})]})]})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Household & Work"}),e.jsx(UWe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:(h==null?void 0:h.spouse_name)||null,currentSpouseEmail:(h==null?void 0:h.spouse_email)||null,onLink:As=>M.mutate({contactId:s,spouseContactId:As}),onUnlink:()=>M.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"company_name",children:"Company"}),e.jsx(pe,{id:"company_name",value:K.company_name||"",onChange:As=>Z({...K,company_name:As.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"job_title",children:"Job Title"}),e.jsx(pe,{id:"job_title",value:K.job_title||"",onChange:As=>Z({...K,job_title:As.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(NZt,{value:K.lead_source_id||"",onChange:As=>Z({...K,lead_source_id:As})})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:p==null?void 0:p.filter(As=>As.active).map(As=>{var pr;const Ss=!!((pr=K.tagIds)!=null&&pr.includes(As.id));return e.jsxs("label",{className:Ct("inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",Ss?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(za,{checked:Ss,onCheckedChange:hn=>{var Pn;Z(hn?{...K,tagIds:[...K.tagIds||[],As.id]}:{...K,tagIds:(Pn=K.tagIds)==null?void 0:Pn.filter(Gs=>Gs!==As.id)})}}),As.name]},As.id)})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(U2t,{contactId:s})})]})]}),e.jsx(fc,{}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Ps,{id:"notes",value:K.notes||"",onChange:As=>Z({...K,notes:As.target.value}),rows:5})]}),e.jsxs("div",{className:"sticky bottom-0 -mx-6 flex flex-wrap items-center justify-end gap-2 border-t bg-card/95 px-6 py-3 backdrop-blur",children:[e.jsx(z,{variant:"outline",onClick:()=>{D(!1),q("overview")},children:"Cancel"}),e.jsxs(z,{onClick:Sn,disabled:C.isPending,children:[C.isPending?e.jsx(bt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Kt,{value:"activity",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(Nt,{className:"text-base",children:"Activity Log"}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>J(!0),children:[e.jsx(sn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Le,{children:wt.length>0?e.jsx("div",{className:"space-y-4",children:wt.map(As=>{var Ss;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full text-xs text-white",style:{backgroundColor:As.color},children:As.type==="popby"?e.jsx(Ko,{className:"h-4 w-4"}):(Ss=As.name)==null?void 0:Ss.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:As.name}),As.videoId&&e.jsxs(z,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Oe(As.videoId),children:[e.jsx(su,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(As.completed_at),"MMM d, yyyy h:mm a")}),As.notes&&!As.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:As.notes})]})]},As.id)})}):e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No activity logged yet"})})]})}),e.jsxs("div",{className:"space-y-5",children:[y&&y.length>0&&e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(qi,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-4",children:y.map(As=>{var Ss,pr;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(Ss=As.video)!=null&&Ss.thumbnail_url?e.jsx("img",{src:As.video.thumbnail_url,alt:As.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>Oe(As.video_id)}):e.jsx("div",{className:"flex h-12 w-16 cursor-pointer items-center justify-center rounded bg-muted transition-colors hover:bg-muted/80",onClick:()=>Oe(As.video_id),children:e.jsx(Xr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block truncate text-sm font-medium",children:["Replied to: ",((pr=As.video)==null?void 0:pr.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(As.created_at),"MMM d, yyyy h:mm a")}),As.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',As.message,'"']})]})]},As.id)})})})]}),lt&<.length>0&&e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Fr,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-3",children:lt.map(As=>e.jsxs(Is,{children:[e.jsx(rl,{asChild:!0,children:e.jsxs("button",{className:"flex w-full cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-sky-500/10 text-sky-600",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:As.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",As.to_email," · ",Ys(new Date(As.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(yi,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Ls,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-sky-500"}),As.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",As.to_email," · ",Ys(new Date(As.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:As.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${As.subject}`})})]})]},As.id))})})]}),e.jsx(c7n,{contactId:s})]})]})}),e.jsx(Kt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(n7n,{contactId:s,contactName:h.first_name}),e.jsx(e7n,{contactId:s}),n&&e.jsxs(e.Fragment,{children:[e.jsx(t7n,{contactId:s,contactName:h.first_name}),e.jsx(s7n,{contactId:s,contactName:h.first_name})]}),e.jsx(i7n,{contactId:s})]})}),t&&e.jsx(Kt,{value:"property-intel",className:"mt-4",children:e.jsx(j7n,{contactId:s,contactAddress:h.address,contactCity:h.city,contactState:h.state,contactZip:h.zip_code})})]}),e.jsxs("div",{className:"fixed inset-x-0 bottom-0 z-40 flex items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[calc(env(safe-area-inset-bottom)+0.5rem)] backdrop-blur lg:hidden",children:[h.phone&&e.jsx("a",{href:`tel:${h.phone}`,className:"flex-1",children:e.jsxs(z,{variant:"outline",className:"w-full",children:[e.jsx(va,{className:"mr-1 h-4 w-4"})," Call"]})}),h.phone&&e.jsxs(z,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${h.phone}`,children:[e.jsx(qi,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs(z,{className:"flex-1",onClick:()=>J(!0),children:[e.jsx(sn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(Is,{open:ae,onOpenChange:J,children:e.jsxs(Ls,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:f==null?void 0:f.filter(As=>As.active).map(As=>e.jsxs("button",{onClick:()=>ce(As.id),className:Ct("rounded-lg border p-3 text-left transition-all",te===As.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:As.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As.description})]},As.id))}),Fs&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ee,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(pe,{id:"custom-action-name",value:Ee,onChange:As=>Ne(As.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Date (optional — backdate if needed)"}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("mt-2 w-full justify-start text-left font-normal",!he&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),he?Ys(he,"PPP"):"Today (default)"]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{mode:"single",selected:he,onSelect:ge,disabled:As=>As>new Date,initialFocus:!0,className:Ct("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ps,{id:"action-notes",value:ve,onChange:As=>me(As.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(z,{onClick:cn,disabled:!te||Fs&&!Ee.trim()||P.isPending,className:"w-full",children:[e.jsx(Wr,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(Is,{open:!!Pe,onOpenChange:As=>!As&&Oe(null),children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Video Preview"})}),Pe&&e.jsx(N7n,{videoId:Pe})]})})]})}),H&&h&&e.jsx(TOn,{open:G,onOpenChange:V,contactId:h.id,contactName:`${h.first_name} ${h.last_name||""}`.trim(),hasEmail:!!h.email}),$e&&h&&_e&&e.jsx(HN,{open:ke,onOpenChange:Ve,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:_e.email},gmailEmail:Be}),h&&h.email&&e.jsx(FOn,{open:Se,onOpenChange:We,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:h.email}})]}):e.jsx($s,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(z,{onClick:()=>r("/mission-control/contacts"),children:"Back to Contacts"})]})})}function E7n({rangeDays:s}){const{user:t}=hs(),n=$t(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!1),{data:d=[],isLoading:u}=rt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let p=U.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const v=new Date(Date.now()-s*864e5).toISOString();p=p.gte("created_at",v)}const{data:f,error:g}=await p;if(g)throw g;return f||[]}}),{data:h}=rt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:p,error:f}=await U.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(f)throw f;return p||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:p,error:f}=await U.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(f)throw f;if(!p||p.length===0){ne.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:g}=await U.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!g)throw new Error("Original campaign not found");const{data:v,error:y}=await U.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:g.subject,body_html:g.body_html,from_email:g.from_email,reply_to_email:g.reply_to_email,total_recipients:p.length,status:"draft"}).select("id").single();if(y)throw y;const b=p.map(S=>({campaign_id:v.id,contact_id:S.contact_id,email:S.email,name:S.name,status:"pending"}));for(let S=0;S{const f=p.sent_count||0,g=f>0?p.open_count/f*100:0,v=f>0?p.click_count/f*100:0,y=p.sent_at?PN(new Date,new Date(p.sent_at)):0,b=p.status==="sent"&&y>=3&&f>0&&p.open_counta(p.id),children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>l(p),children:[e.jsx(p7,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),p.status==="sent"&&f>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(tde,{icon:e.jsx(Fr,{className:"h-3.5 w-3.5"}),label:"Sent",value:f,sub:`of ${p.total_recipients}`}),e.jsx(tde,{icon:e.jsx(xa,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:p.open_count,sub:`${g.toFixed(1)}%`,children:e.jsx(Di,{value:g,className:"h-1 mt-1"})}),e.jsx(tde,{icon:e.jsx(Gh,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:p.click_count,sub:`${v.toFixed(1)}%`,children:e.jsx(Di,{value:v,className:"h-1 mt-1"})}),e.jsx(tde,{icon:e.jsx(cP,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:p.bounce_count,sub:p.bounce_count>0?"review":"none"})]})]},p.id)})})]})}),e.jsx(Wg,{open:!!r,onOpenChange:p=>!p&&a(null),children:e.jsxs(gg,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(Dy,{children:e.jsx(Ry,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(p=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:p.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:p.email})]}),e.jsx("td",{className:"py-2 text-xs",children:p.opened_at?e.jsx(ze,{variant:"default",className:"text-xs",children:Ys(new Date(p.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:p.clicked_at?e.jsx(ze,{variant:"default",className:"text-xs bg-purple-600",children:Ys(new Date(p.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[p.status==="sent"&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"sent"}),p.status==="pending"&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:"queued"}),p.status==="failed"&&e.jsx(ze,{variant:"destructive",className:"text-xs",title:p.error_message||"",children:"failed"}),p.status==="suppressed"&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},p.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Ql,{open:!!i,onOpenChange:p=>!p&&l(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Resend to non-openers?"}),e.jsxs(ql,{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($l,{children:[e.jsx(Vl,{disabled:o,children:"Cancel"}),e.jsx(Ml,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(p7,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function tde({icon:s,label:t,value:n,sub:r,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:n.toLocaleString()}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),a]})}async function jse(){var r;const{data:{session:s}}=await U.auth.getSession(),t=s!=null&&s.expires_at?s.expires_at*1e3:0;if(!(s!=null&&s.access_token)||t-Date.now()<12e4){const{data:a,error:i}=await U.auth.refreshSession();if(i||!((r=a.session)!=null&&r.access_token))throw new Error("Your session expired. Please refresh the page (or sign in again) and try sending once more.");return a.session.access_token}return s.access_token}function T7n(){const{user:s}=hs(),t=zn(),n=$t(),{data:r=[],isLoading:a}=rt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const h=await jse(),p=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!p.success)throw new Error(p.error||`Failed to ${d}`);return p},l=mt({mutationFn:d=>i("cancel",d),onSuccess:()=>{ne.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ne.error(d.message)}),o=mt({mutationFn:d=>i("delete",d),onSuccess:()=>{ne.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ne.error(d.message)}),c=mt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await U.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ne.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ne.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(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zr,{className:"h-12 w-12 text-muted-foreground mb-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(M7n,{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 M7n({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]=_.useState(!1),[d,u]=_.useState(l||void 0),[h,m]=_.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),p=()=>{if(!d)return ne.error("Pick a date");const f=new Date(`${Ys(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(f).getTime()fm(f.target.value)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(z,{onClick:p,disabled:i,children:[i&&e.jsx(bt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Bd,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Cancel this scheduled send?"}),e.jsxs(ql,{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($l,{children:[e.jsx(Vl,{children:"Keep scheduled"}),e.jsx(Ml,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete this scheduled email?"}),e.jsx(ql,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Keep"}),e.jsx(Ml,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function P7n({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 sde({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:Ct("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(yi,{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 L7n({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(P7n,{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(sde,{icon:e.jsx(Mr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(sde,{icon:e.jsx(xa,{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(sde,{icon:e.jsx(Gh,{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(sde,{icon:e.jsx(Zr,{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 nNt=["Gmail","Mass Email","Campaign","Client Portal Invite","Card Studio"],I7n={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","Card Studio":"bg-amber-100 text-amber-700 border-amber-200"};function D7n(){const{user:s}=hs(),[t,n]=Gl(),{data:r=[],isLoading:a}=DZt(),[i,l]=_.useState(""),[o,c]=_.useState("all"),[d,u]=_.useState("30"),[h,m]=_.useState(!1),[p,f]=_.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:g}=bg(),{data:v=0}=rt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:P}=await U.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return P||0},refetchInterval:3e4});_.useEffect(()=>{const P=new URLSearchParams(t);p==="scheduled"?P.set("tab","scheduled"):P.delete("tab"),n(P,{replace:!0})},[p]);const y=_.useMemo(()=>Array.from(new Set(r.map(P=>P.contact_id).filter(Boolean))),[r]),{data:b}=rt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,y.length],enabled:y.length>0,queryFn:async()=>{const{data:P}=await U.from("innercircle_contacts").select("id, first_name, last_name").in("id",y),M=new Map;return(P||[]).forEach(I=>{M.set(I.id,[I.first_name,I.last_name].filter(Boolean).join(" ")||"Contact")}),M}}),w=_.useMemo(()=>{const P=d==="all"?null:Date.now()-parseInt(d)*864e5,M=i.trim().toLowerCase();return r.filter(I=>{if(o!=="all"&&I.channel!==o||P&&new Date(I.sent_at).getTime(){const P={};let M=0,I=0,D=0;return w.forEach(F=>{P[F.channel]=(P[F.channel]||0)+1,(F.channel==="Campaign"||F.channel==="Mass Email")&&(D++,F.opened_at&&M++,F.clicked_at&&I++)}),{byChannel:P,opened:M,clicked:I,trackable:D}},[w]),C=d==="all"?"All time":`Last ${d} days`,E=nNt.map(P=>S.byChannel[P]?`${S.byChannel[P]} ${P}`:null).filter(Boolean).join(" · ");return e.jsx($s,{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(Fr,{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:()=>f("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Fr,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>f("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Zr,{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(z,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(on,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(Qr,{value:p,onValueChange:P=>f(P),className:"space-y-5",children:[e.jsxs(Kt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(L7n,{total:w.length,opened:S.opened,clicked:S.clicked,trackable:S.trackable,scheduled:v,rangeLabel:C,channelSummary:E,onScheduledClick:()=>f("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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search subject, recipient, contact...",value:i,onChange:P=>l(P.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(ls,{value:o,onValueChange:c,children:[e.jsx(rs,{className:"w-[170px] rounded-full h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Channels"}),nNt.map(P=>e.jsx(He,{value:P,children:P},P))]})]}),e.jsxs(ls,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"w-[150px] rounded-full h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"7",children:"Last 7 days"}),e.jsx(He,{value:"30",children:"Last 30 days"}),e.jsx(He,{value:"90",children:"Last 90 days"}),e.jsx(He,{value:"365",children:"Last year"}),e.jsx(He,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(gS,{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(E7n,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):w.length===0?e.jsx(be,{className:"rounded-2xl",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(on,{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(be,{className:"rounded-2xl overflow-hidden",children:e.jsx(Le,{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(UN,{children:e.jsxs(ug,{children:[e.jsxs(hg,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(gS,{className:"h-3 w-3"})]}),e.jsx(Tx,{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:w.slice(0,500).map(P=>{const M=P.contact_id?b==null?void 0:b.get(P.contact_id):null,I=P.channel==="Campaign"||P.channel==="Mass Email";return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:Ys(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(ze,{variant:"outline",className:I7n[P.channel],children:P.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:P.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:P.to_email}),e.jsx("td",{className:"py-3 px-4",children:P.contact_id&&M?e.jsx(or,{to:`/mission-control/contacts/${P.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:I?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(Mr,{className:"h-3 w-3"})," Delivered"]}),P.opened_at&&e.jsxs(ze,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(xa,{className:"h-3 w-3"})," Opened"]}),P.clicked_at&&e.jsxs(ze,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Gh,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},P.id)})})]}),w.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",w.length," — narrow your filters to see more."]})]})})})]}),e.jsx(Kt,{value:"scheduled",className:"mt-0",children:e.jsx(T7n,{})})]}),e.jsx(HN,{open:h,onOpenChange:m,gmailEmail:g})]})})}const rNt={Crown:Kf,FileText:$r,Users:On,Globe:Wo,Star:Ia,Phone:va,MessageSquare:qi,PenTool:QA,Video:Xr,Gift:Ko},nde=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function R7n(){var lt,qt;const s=zn(),{user:t}=hs(),{data:n}=Q_(),{data:r}=$Bs(),{data:a}=KBs(),{data:i}=nBt(),{data:l}=fae(),{data:o}=BBs(),c=YBs(),d=UBs(),u=VBs(),h=HBs(),m=GBs(),p=WBs(),f=qBs(),[g,v]=_.useState(null),[y,b]=_.useState(!1),[w,S]=_.useState(null),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState([]),[F,q]=_.useState(null),[G,V]=_.useState(null),[H,K]=_.useState(null),[Z,oe]=_.useState(!1),[re,ae]=_.useState(""),[J,te]=_.useState(""),[ce,ve]=_.useState(""),[me,he]=_.useState(""),ge=(zt,Zt)=>a==null?void 0:a.some(ms=>ms.plan_id===zt&&ms.relationship_type_id===Zt&&ms.active),Ee=zt=>a==null?void 0:a.find(Zt=>Zt.relationship_type_id===zt&&Zt.active),Ne=async(zt,Zt)=>{const ms=ge(zt,Zt);await c.mutateAsync({planId:zt,relationshipTypeId:Zt,active:!ms})},Pe=(r==null?void 0:r.filter(zt=>zt.active&&!zt.owner_user_id))||[],Oe=(r==null?void 0:r.filter(zt=>zt.owner_user_id===(t==null?void 0:t.id)))||[],ke=n==null?void 0:n.find(zt=>zt.id===g),Ve=g?Ee(g):null,_e=r==null?void 0:r.find(zt=>zt.id===(Ve==null?void 0:Ve.plan_id)),Ae=async()=>{if(!C.trim())return;const zt=await d.mutateAsync({name:C,description:P});zt&&I.length>0&&await m.mutateAsync({planId:zt.id,items:I}),Be()},Se=async()=>{!C.trim()||!w||(await u.mutateAsync({id:w,name:C,description:P}),await m.mutateAsync({planId:w,items:I}),Be())},We=zt=>{var Zt;S(zt.id),E(zt.name),M(zt.description||""),D(((Zt=zt.items)==null?void 0:Zt.map(ms=>({month_number:ms.month_number,action_type_id:ms.action_type_id,default_script_id:ms.default_script_id||void 0,notes:ms.notes||void 0})))||[]),b(!0)},qe=async(zt,Zt)=>{if(zt.owner_user_id===(t==null?void 0:t.id)){We(zt);return}try{const ms=await f.mutateAsync({sourcePlanId:zt.id,newName:`${zt.name} (My Copy)`});if(!ms)return;await c.mutateAsync({planId:zt.id,relationshipTypeId:Zt,active:!1}),await c.mutateAsync({planId:ms.id,relationshipTypeId:Zt,active:!0}),S(ms.id),E(ms.name),M(ms.description||""),D((zt.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}))),b(!0)}catch{}},Be=()=>{b(!1),S(null),E(""),M(""),D([])},Ze=(zt,Zt)=>{V(Zt)},$e=(zt,Zt,ms)=>{D(Dt=>[...Dt.filter(qs=>qs.month_number!==zt),{month_number:zt,action_type_id:Zt,default_script_id:ms}]),q(null),V(null)},Xe=zt=>{D(Zt=>Zt.filter(ms=>ms.month_number!==zt))},nt=async()=>{if(!re.trim()||!J.trim()||!G)return;const zt=await p.mutateAsync({actionTypeId:G,title:re,scriptBody:J,emailSubject:ce||void 0,tone:me||void 0});zt&&F!==null&&$e(F,G,zt.id),oe(!1),ae(""),te(""),ve(""),he("")},Ge=G?o==null?void 0:o.filter(zt=>zt.action_type_id===G&&zt.active):[],Je=zt=>rNt[zt||"Phone"]||va,ut=zt=>rNt[zt||"Users"]||On;return e.jsxs($s,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Wc,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(z,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(sn,{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(zt=>zt.active).map(zt=>{const Zt=ut(zt.icon),ms=(i==null?void 0:i[zt.id])||0,Dt=Ee(zt.id),It=r==null?void 0:r.find(wt=>wt.id===(Dt==null?void 0:Dt.plan_id)),qs=g===zt.id;return e.jsxs("button",{onClick:()=>v(zt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${qs?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Zt,{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:zt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ms," contacts"]})]}),It?e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[e.jsx(Xl,{className:"h-3 w-3 mr-1"}),It.name.split(" ")[0]]}):e.jsx(ze,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},zt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:g&&ke?e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[(()=>{const zt=ut(ke.icon);return e.jsx(zt,{className:"h-5 w-5"})})(),ke.name," Touchpoint Plan"]}),e.jsxs(En,{children:["Choose a plan for your ",ke.name," contacts"]})]}),e.jsxs(Le,{className:"space-y-6",children:[_e&&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(Xl,{className:"h-4 w-4 text-green-500"}),"Currently using: ",_e.name]}),_e.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:_e.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",disabled:f.isPending||c.isPending,onClick:()=>qe(_e,g),children:[e.jsx(Y2,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>Ne(_e.id,g),children:"Disable"})]})]}),_e.items&&_e.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(ya,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:nde.map((zt,Zt)=>{var qs,wt;const ms=((qs=_e.items)==null?void 0:qs.filter(Us=>Us.month_number===Zt+1))||[],Dt=(wt=ms[0])==null?void 0:wt.action_type,It=Dt?Je(Dt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${ms.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:zt}),It&&e.jsx(It,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Dt==null?void 0:Dt.color)||"#3B82F6"}})]},Zt)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:_e?"Switch to a Different Plan":"Choose a Plan"}),Pe.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"}),Pe.map(zt=>{var ms;const Zt=(_e==null?void 0:_e.id)===zt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Zt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:zt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((ms=zt.items)==null?void 0:ms.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>K(zt.id),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:f.isPending,onClick:()=>{const Dt=`${zt.name} (Copy)`;f.mutate({sourcePlanId:zt.id,newName:Dt})},children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:Zt?"outline":"default",disabled:Zt||c.isPending,onClick:()=>Ne(zt.id,g),children:Zt?"Active":"Use This"})]})]},zt.id)})]}),Oe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Oe.map(zt=>{var ms;const Zt=(_e==null?void 0:_e.id)===zt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Zt?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:zt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((ms=zt.items)==null?void 0:ms.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>K(zt.id),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>We(zt),children:e.jsx(Y2,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(zt.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})}),e.jsx(z,{size:"sm",variant:Zt?"outline":"default",disabled:Zt||c.isPending,onClick:()=>Ne(zt.id,g),children:Zt?"Active":"Use This"})]})]},zt.id)})]}),Pe.length===0&&Oe.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(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ya,{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(be,{className:"bg-muted/50",children:e.jsx(Le,{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(Is,{open:y,onOpenChange:zt=>{zt?b(!0):Be()},children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:w?"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(ee,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(pe,{id:"plan-name",value:C,onChange:zt=>E(zt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ps,{id:"plan-description",value:P,onChange:zt=>M(zt.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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:nde.map((zt,Zt)=>{const ms=Zt+1,Dt=I.find(wt=>wt.month_number===ms),It=Dt?l==null?void 0:l.find(wt=>wt.id===Dt.action_type_id):null,qs=It?Je(It.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>q(F===ms?null:ms),className:` w-full p-3 rounded-lg border text-center transition-all ${Dt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${F===ms?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:zt}),qs?e.jsx(qs,{className:"h-5 w-5 mx-auto mt-1",style:{color:(It==null?void 0:It.color)||"#3B82F6"}}):e.jsx(sn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Dt&&e.jsx("button",{type:"button",onClick:wt=>{wt.stopPropagation(),Xe(ms)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(er,{className:"h-3 w-3"})})]},Zt)})}),F!==null&&!G&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",nde[F-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(zt=>zt.active).map(zt=>{const Zt=Je(zt.icon);return e.jsxs("button",{type:"button",onClick:()=>Ze(F,zt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Zt,{className:"h-4 w-4",style:{color:zt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:zt.name})]},zt.id)})})]}),F!==null&&G&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>V(null),children:[e.jsx(Wc,{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:()=>$e(F,G),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),Ge==null?void 0:Ge.map(zt=>e.jsx("button",{type:"button",onClick:()=>$e(F,G,zt.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:zt.title}),zt.tone&&e.jsx(ze,{variant:"secondary",className:"text-xs mt-1",children:zt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[zt.script_body.substring(0,100),"..."]})]})},zt.id)),e.jsxs("button",{type:"button",onClick:()=>oe(!0),className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed bg-background hover:bg-accent transition-colors text-left",children:[e.jsx(sn,{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"})]})]})]})]})]}),I.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[I.length," touchpoint",I.length!==1?"s":""," per year"]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:Be,children:"Cancel"}),e.jsxs(z,{onClick:w?Se:Ae,disabled:!C.trim()||d.isPending||u.isPending,children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),w?"Save Changes":"Create Plan"]})]})]})}),e.jsx(Is,{open:Z,onOpenChange:oe,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-title",children:"Script Title"}),e.jsx(pe,{id:"script-title",value:re,onChange:zt=>ae(zt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(ls,{value:me,onValueChange:he,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select tone..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"friendly",children:"Friendly"}),e.jsx(He,{value:"professional",children:"Professional"}),e.jsx(He,{value:"casual",children:"Casual"}),e.jsx(He,{value:"formal",children:"Formal"})]})]})]}),((qt=(lt=l==null?void 0:l.find(zt=>zt.id===G))==null?void 0:lt.name)==null?void 0:qt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(pe,{id:"script-email-subject",value:ce,onChange:zt=>ve(zt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ps,{id:"script-body",value:J,onChange:zt=>te(zt.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(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>oe(!1),children:"Cancel"}),e.jsxs(z,{onClick:nt,disabled:!re.trim()||!J.trim()||p.isPending,children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(Is,{open:!!H,onOpenChange:zt=>{zt||K(null)},children:e.jsx(Ls,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const zt=r==null?void 0:r.find(Dt=>Dt.id===H);if(!zt)return null;const Zt=zt.owner_user_id===(t==null?void 0:t.id),ms=[...zt.items||[]].sort((Dt,It)=>Dt.month_number-It.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[zt.name,!Zt&&e.jsx(ze,{variant:"secondary",children:"Template"})]}),zt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:zt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ms.length," touchpoint",ms.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Dt,It)=>It+1).map(Dt=>{const It=ms.find(Es=>Es.month_number===Dt),qs=It?l==null?void 0:l.find(Es=>Es.id===It.action_type_id):null,wt=It!=null&&It.default_script_id?o==null?void 0:o.find(Es=>Es.id===It.default_script_id):null,Us=qs?Je(qs.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${It?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:nde[Dt-1]}),It&&qs?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Us&&e.jsx(Us,{className:"h-4 w-4",style:{color:qs.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:qs.name}),wt&&e.jsx(ze,{variant:"outline",className:"text-xs",children:wt.title})]}),wt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:wt.script_body}),It.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:It.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},Dt)})})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>K(null),children:"Close"}),Zt?e.jsxs(z,{onClick:()=>{const Dt=r==null?void 0:r.find(It=>It.id===H);Dt&&(K(null),We(Dt))},children:[e.jsx(Y2,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(z,{disabled:f.isPending,onClick:()=>{f.mutate({sourcePlanId:zt.id,newName:`${zt.name} (Copy)`}),K(null)},children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const kze="https://cma.relevelup.com";function zZt({open:s,onOpenChange:t,cma:n}){var K;const{user:r}=hs(),{toast:a}=_i(),[i,l]=_.useState([]),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(""),[p,f]=_.useState(""),[g,v]=_.useState(""),[y,b]=_.useState(!1),[w,S]=_.useState(null),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(null);_.useEffect(()=>{!s||!r||(async()=>{var ve;const[Z,oe,re,ae,J]=await Promise.all([U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),U.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),U.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),U.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),U.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),te=(Z.data||[]).filter(me=>me.email&&me.email.includes("@"));l(te),S(oe.data||null),E(!!((ve=re.data)!=null&&ve.is_active)),M(!!(ae.data&&ae.data.length>0)),D(J.data||null);const ce=n.contact_id?te.find(me=>me.id===n.contact_id):null;ce&&(c(ce),m(ce.email))})()},[s,r,n.contact_id]),_.useEffect(()=>{var ae;if(!s)return;const Z=((ae=n.subject)==null?void 0:ae.address)||"your home",oe=((w==null?void 0:w.name)||"").split(" ")[0]||"your agent",re=(o==null?void 0:o.first_name)||"there";f(`Your home value report for ${Z}`),v(`Hi ${re}, I put together a fresh market analysis for ${Z}. 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, ${(w==null?void 0:w.name)||oe}`)},[s,o==null?void 0:o.id,w==null?void 0:w.name,(K=n.subject)==null?void 0:K.address]);const F=_.useMemo(()=>C?"Gmail (your inbox)":P?"Amazon SES":null,[C,P]),q=!!(h.trim()&&p.trim()&&g.trim()&&F&&!y),G=Z=>{c(Z),m(Z.email||""),u(!1)},V=Z=>{const oe=`${kze}/${n.share_token}?e=${Z}`,J=g.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(ve=>`

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

`).join(""),te=w!=null&&w.use_email_signature&&(w!=null&&w.email_signature)?`
${w.email_signature}
`:`
${w!=null&&w.name?`
${w.name}
`:""} ${w!=null&&w.brokerage_name?`
${w.brokerage_name}
`:""} ${w!=null&&w.phone?`
${w.phone}
`:""} ${w!=null&&w.email?``:""}
`,ce=``;return`
${J} ${te}
Prepared with LevelUp · ReLevelUp Real Estate
${ce}
`},H=async()=>{if(!(!r||!q)){b(!0);try{const{data:Z,error:oe}=await U.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:p.trim(),sent_via:C?"gmail":"ses"}).select("id").single();if(oe)throw oe;const re=V(Z.id);if(C){const{data:ae,error:J}=await U.functions.invoke("gmail-send",{body:{to:h.trim(),subject:p.trim(),body:re}});if(J)throw J;if(!(ae!=null&&ae.success))throw new Error((ae==null?void 0:ae.error)||"Gmail send failed")}else if(P){const ae=(I==null?void 0:I.display_name)||(w==null?void 0:w.name)||"ReLevelUp",J=`${ae.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:te,error:ce}=await U.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${ae} <${J}>`,subject:p.trim(),body_html:re,reply_to:(I==null?void 0:I.reply_to_email)||(w==null?void 0:w.email)||void 0}});if(ce)throw ce;if(!(te!=null&&te.success))throw new Error((te==null?void 0:te.error)||"SES send failed")}o&&!n.contact_id&&await U.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(Z){console.error("Send CMA error:",Z),a({title:"Send failed",description:Z.message||"Could not send email",variant:"destructive"})}finally{b(!1)}}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"w-5 h-5"}),"Send CMA to contact"]})}),F?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:F})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact"}),e.jsxs(hd,{open:d,onOpenChange:u,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{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(R_,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(nd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search contacts…"}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:"No contacts with email found."}),e.jsx(G_,{children:i.map(Z=>e.jsxs(c1,{value:`${Z.first_name} ${Z.last_name||""} ${Z.email}`,onSelect:()=>G(Z),children:[e.jsx(Wr,{className:Ct("w-4 h-4 mr-2",(o==null?void 0:o.id)===Z.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[Z.first_name," ",Z.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Z.email})]})]},Z.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"To email"}),e.jsx(pe,{type:"email",value:h,onChange:Z=>m(Z.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subject"}),e.jsx(pe,{value:p,onChange:Z=>f(Z.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Message"}),e.jsx(Ps,{rows:10,value:g,onChange:Z=>v(Z.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(mr,{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:`${kze}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${kze}/${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(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:H,disabled:!q,children:[y?e.jsx(bt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function F7n(s){const{user:t}=hs(),n=$t(),{data:r}=rt({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:l,error:o}=await U.from("lead_site_upgrade_requests").select("id, feature_key, status, created_at").eq("user_id",t.id);if(o)throw o;return l}}),a=mt({mutationFn:async({featureKey:l,notes:o})=>{const{error:c}=await U.from("lead_site_upgrade_requests").insert({user_id:t.id,site_id:s??null,feature_key:l,notes:o??null});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id]}),ne.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>ne.error((l==null?void 0:l.message)||"Could not send your request")});return{requestUpgrade:a,hasRequested:l=>!!(r!=null&&r.some(o=>o.feature_key===l&&o.status!=="declined")),isSending:a.isPending}}const O7n="free_luxury",z7n="free_beta";function BZt(s){const t=s==null?void 0:s.planTier;return t===O7n||t===z7n}const B7n={idx_search:{title:"MLS / IDX Home Search",description:"Let visitors search every active MLS listing in your market, with saved searches and instant alerts."},mls_listings:{title:"MLS Listing Feeds",description:"Automatically feature live MLS listings, new listings and sold comps on your homepage and city pages."},cma_reports:{title:"CMA Reports",description:"Build branded comparative market analyses with live MLS comps and share them with sellers."},custom_domain:{title:"Custom Branded Domain",description:"Point your own web address at your site instead of the free subdomain."},ai_content:{title:"AI Content Creation",description:"Auto-written blog posts, city guides and monthly market updates published to your site."}};function $7n({featureKey:s,siteId:t,bullets:n}){const r=B7n[s],{requestUpgrade:a,hasRequested:i,isSending:l}=F7n(t),o=i(s);return e.jsx("section",{className:"rounded-xl border border-amber-500/30 bg-gradient-to-br from-amber-500/10 via-card to-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-10 w-10 shrink-0 rounded-full bg-amber-500/15 flex items-center justify-center",children:e.jsx(Hl,{className:"h-5 w-5 text-amber-500"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:r.title}),e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full bg-amber-100 text-amber-700",children:"Upgrade"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.description}),n!=null&&n.length?e.jsx("ul",{className:"mt-4 space-y-2",children:n.map(c=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(un,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx(z,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function U7n({onCreated:s}){const[t,n]=_.useState(!1),[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),h=qOn(),m=TZt(),{toast:p}=_i(),[f,g]=_.useState([]),v=async()=>{var w;g([]);try{const S=await h.mutateAsync({address:r,city:i,state:o,zip:d});g(S.matches||[]),(w=S.matches)!=null&&w.length||p({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(S){p({title:"Search failed",description:S.message,variant:"destructive"})}},y=async w=>{const S=await m.mutateAsync({subject:w});n(!1),s(S.id)},b=async()=>{if(!r||!i||!o){p({title:"Address, city, state required"});return}const w=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(w.id)};return e.jsxs(Is,{open:t,onOpenChange:n,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Rs,{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(pe,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:w=>a(w.target.value)}),e.jsx(pe,{placeholder:"City",value:i,onChange:w=>l(w.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"ST",maxLength:2,value:o,onChange:w=>c(w.target.value.toUpperCase())}),e.jsx(pe,{placeholder:"ZIP",value:d,onChange:w=>u(w.target.value)})]})]}),e.jsxs(z,{onClick:v,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(bt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Rr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),f.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:[f.length," match(es) — pick the subject property:"]}),f.map((w,S)=>{var C;return e.jsxs("button",{onClick:()=>y(w),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:w.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.city,", ",w.state," ",w.zip," · ",w.bedrooms??"?"," bd / ",w.bathrooms??"?"," ba · ",((C=w.sqft)==null?void 0:C.toLocaleString())??"?"," sqft",w.mlsNumber?` · MLS# ${w.mlsNumber}`:""," · ",w.source_provider]})]},S)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(z,{variant:"outline",onClick:b,disabled:m.isPending,className:"w-full",children:[e.jsx(sa,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function q7n(){const{data:s,isLoading:t}=OOn(),n=UOn(),r=zn(),{toast:a}=_i(),[i,l]=_.useState(null),{isFreePlan:o,leadSite:c}=mf();return o?e.jsx($s,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-3xl space-y-6",children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx($r,{className:"w-7 h-7"})," CMAs"]}),e.jsx($7n,{featureKey:"cma_reports",siteId:c==null?void 0:c.id,bullets:["Pull live MLS comparables for any subject property","Interactive, shareable CMA presentations for sellers","Track when your seller opens and interacts with the report"]})]})}):e.jsx($s,{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($r,{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(U7n,{onCreated:d=>r(`/mission-control/cma/${d}`)})]}),t?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):s!=null&&s.length?e.jsx("div",{className:"grid gap-3",children:s.map(d=>{var u,h,m;return e.jsx(be,{className:"hover:shadow-md transition",children:e.jsxs(Le,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:d.title||((u=d.subject)==null?void 0:u.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(h=d.subject)==null?void 0:h.city,", ",(m=d.subject)==null?void 0:m.state," · ",d.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(ze,{variant:d.status==="shared"?"default":"secondary",className:"ml-1",children:d.status})]}),d.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",d.price_likely.toLocaleString()]}),d.price_low&&d.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",d.price_low.toLocaleString(),"–$",d.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${d.id}`),children:"Open"}),d.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>{const p=`https://cma.relevelup.com/${d.share_token}`;navigator.clipboard.writeText(p),a({title:"Share link copied"})},children:e.jsx(mr,{className:"w-4 h-4"})}),e.jsxs(z,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(on,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:async()=>{await Qi("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(Cn,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(be,{children:e.jsx(Le,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(zZt,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function V7n(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 aNt(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 H7n({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=_.useRef(null),i=_.useRef(null),l=_.useRef([]),[o,c]=_.useState(null);_.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=_.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 _.useEffect(()=>{if(!o||!a.current||i.current||!d)return;Od.accessToken=o;const u=new Od.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new Od.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:aNt(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]),_.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const m=u.getSource("radius");m&&m.setData(aNt(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),_.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 m=new Od.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new Od.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const p=new Od.LngLatBounds;p.extend([d.lng,d.lat]),t.forEach((v,y)=>{const b=Number(v.latitude),w=Number(v.longitude);if(!Number.isFinite(b)||!Number.isFinite(w))return;const S=V7n(v.status),C=document.createElement("div");C.style.cssText="width:22px;height:22px;";const E=document.createElement("div");E.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${S}; 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; `,E.onmouseenter=()=>{E.style.transform="scale(1.25)"},E.onmouseleave=()=>{E.style.transform="scale(1)"},r&&(E.onclick=()=>r(y)),C.appendChild(E);const P=v.soldPrice||v.price,M=new Od.Popup({offset:14}).setHTML(`
${v.address??""}
${v.status??""}`+(P?` · $${P.toLocaleString()}`:"")+"
"),I=new Od.Marker({element:C}).setLngLat([w,b]).setPopup(M).addTo(u);l.current.push(I),p.extend([w,b])});const g=n*1.60934/110.574;p.extend([d.lng,d.lat+g]),p.extend([d.lng,d.lat-g]);try{u.fitBounds(p,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let n_=null;function $Zt(){if(n_)return n_;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return n_={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},n_;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 n_={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},n_;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(n_={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},n_):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(n_={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},n_):(n_={canRunVirtualBg:!0,renderer:r},n_)}catch{return n_={canRunVirtualBg:!0},n_}}const G7n=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function W7n({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=_.useRef(null),[l,o]=_.useState(!1),[c,d]=_.useState(null),[u]=_.useState(()=>$Zt()),h=!u.canRunVirtualBg,{data:m=[],refetch:p}=rt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:w}}=await U.auth.getUser();if(!w)return[];const{data:S,error:C}=await U.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return C?(console.error("Failed to load backgrounds:",C),[]):(S||[]).map(E=>({...E,__ownerId:w.id}))}}),f=m.map(w=>({type:"image",label:w.name,imageUrl:w.image_url,thumbnail:w.thumbnail_url||w.image_url,id:w.id,deletable:!w.is_stock&&w.user_id===w.__ownerId})),g=[...G7n,...f],v=w=>w.type!==s.type?!1:w.type==="image"?w.imageUrl===s.imageUrl:!0,y=async w=>{if(!(!w.id||!w.imageUrl)&&window.confirm(`Delete the background "${w.label}"? This can't be undone.`)){d(w.id);try{const{error:S}=await U.from("video_backgrounds").delete().eq("id",w.id);if(S)throw S;const C="/video-backgrounds/",E=w.imageUrl.indexOf(C);if(E!==-1){const P=decodeURIComponent(w.imageUrl.slice(E+C.length).split("?")[0]);await U.storage.from("video-backgrounds").remove([P])}s.type==="image"&&s.imageUrl===w.imageUrl&&t({type:"none",mirror:s.mirror}),await p(),ne.success("Background deleted")}catch(S){console.error("Delete background error:",S),ne.error((S==null?void 0:S.message)||"Failed to delete background")}finally{d(null)}}},b=async w=>{var C;const S=(C=w.target.files)==null?void 0:C[0];if(S){if(!S.type.startsWith("image/")){ne.error("Please select an image file");return}if(S.size>5*1024*1024){ne.error("Image must be under 5MB");return}o(!0);try{const{data:{user:E}}=await U.auth.getUser();if(!E)throw new Error("Not authenticated");const P=S.name.split(".").pop()||"jpg",M=`${E.id}/${crypto.randomUUID()}.${P}`,{error:I}=await U.storage.from("video-backgrounds").upload(M,S,{contentType:S.type});if(I)throw I;const{data:D}=U.storage.from("video-backgrounds").getPublicUrl(M),F=D.publicUrl,{error:q}=await U.from("video_backgrounds").insert({name:S.name.replace(/\.[^.]+$/,""),image_url:F,thumbnail_url:F,category:"custom",is_stock:!1,user_id:E.id});if(q)throw q;await p(),t({type:"image",imageUrl:F,blurRadius:15}),ne.success("Background uploaded!")}catch(E){console.error("Upload error:",E),ne.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Ct("flex flex-col gap-1",a),children:[h&&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(nl,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:u.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(bt,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),g.map((w,S)=>{const C=v(w);return e.jsxs("div",{className:"relative flex-shrink-0 group",children:[e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:w.type,imageUrl:w.imageUrl,blurRadius:15,mirror:s.mirror}),className:Ct("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",C?"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:[w.type==="none"&&e.jsx(JO,{className:"h-4 w-4 text-muted-foreground"}),w.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"})}),w.type==="image"&&w.thumbnail&&e.jsx("img",{src:w.thumbnail,alt:w.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:w.label})]}),w.deletable&&e.jsx("button",{type:"button","aria-label":`Delete background ${w.label}`,disabled:r||c===w.id,onClick:E=>{E.stopPropagation(),y(w)},className:Ct("absolute -top-1 -right-1 h-5 w-5 rounded-full bg-background border shadow-sm","flex items-center justify-center text-muted-foreground hover:text-destructive hover:border-destructive","opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 transition-opacity"),children:c===w.id?e.jsx(bt,{className:"h-3 w-3 animate-spin"}):e.jsx(er,{className:"h-3 w-3"})})]},`${w.type}-${w.imageUrl||S}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var w;return(w=i.current)==null?void 0:w.click()},className:Ct("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(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(sn,{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:Ct("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(BQ,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var NG=typeof self<"u"?self:{};function UZt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=NG,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 VZt(s){NG.setTimeout(()=>{throw s},0)}var qWe,X7n=UZt(610401301,!1),oNt=UZt(748402147,!0);function lNt(){var s=NG.navigator;return s&&(s=s.userAgent)?s:""}const cNt=NG.navigator;function m8e(s){return m8e[" "](s),s}qWe=cNt&&cNt.userAgentData||null,m8e[" "]=function(){};const HZt={};let FX=null;function Q7n(s){const t=s.length;let n=3*t/4;n%3?n=Math.floor(n):"=.".indexOf(s[t-1])!=-1&&(n="=.".indexOf(s[t-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let a=0;return function(i,l){function o(d){for(;c>4),h!=64&&(l(u<<4&240|h>>2),m!=64&&l(h<<6&192|m))}}(s,function(i){r[a++]=i}),a!==n?r.subarray(0,a):r}function GZt(){if(!FX){FX={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));HZt[n]=r;for(let a=0;a0)&&(lNt().indexOf("Trident")!=-1||lNt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const dNt=/[-_.]/g,e9n={"-":"+",_:"/",".":"="};function t9n(s){return e9n[s]||""}function KZt(s){if(!WZt)return Q7n(s);s=dNt.test(s)?s.replace(dNt,t9n):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,ZZt(s=Error(),"incident"),VZt(s))}}function JW(){return typeof BigInt=="function"}var eK=typeof Symbol=="function"&&typeof Symbol()=="symbol";function FC(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 r9n=FC("jas",void 0,!0),uNt=FC(void 0,"0di"),NZ=FC(void 0,"1oa"),Aj=FC(void 0,Symbol()),a9n=FC(void 0,"0ub"),i9n=FC(void 0,"0ubs"),HWe=FC(void 0,"0ubsb"),o9n=FC(void 0,"0actk"),CG=FC("m_m","Pa",!0),hNt=FC();const XZt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},QZt=Object.defineProperties,Yo=eK?r9n:"Ga";var fz;const mNt=[];function Hae(s,t){eK||Yo in s||QZt(s,XZt),s[Yo]|=t}function Fy(s,t){eK||Yo in s||QZt(s,XZt),s[Yo]=t}function Gae(s){return Hae(s,34),s}function Nse(s){return Hae(s,8192),s}Fy(mNt,7),fz=Object.freeze(mNt);var AG={};function zj(s,t){return t===void 0?s.h!==k9&&!!(2&(0|s.v[Yo])):!!(2&t)&&s.h!==k9}const k9={};function art(s,t){if(s!=null){if(typeof s=="string")s=s?new lC(s,kG):N9();else if(s.constructor!==lC)if(nrt(s))s=s.length?new lC(new Uint8Array(s),kG):N9();else{if(!t)throw Error();s=void 0}}return s}let pNt=class{constructor(t,n,r){this.g=t,this.h=n,this.l=r}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}};var l9n=Object.freeze({});function JZt(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"),fNt=p8e(s=>typeof s=="string"),d9n=p8e(s=>typeof s=="boolean"),f8e=typeof NG.BigInt=="function"&&typeof NG.BigInt(0)=="bigint";function Ej(s){var t=s;if(fNt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(c9n(t)&&!Number.isSafeInteger(t))throw Error(String(t));return f8e?BigInt(s):s=d9n(s)?s?"1":"0":fNt(s)?s.trim()||"0":String(s)}var GWe=p8e(s=>f8e?s>=h9n&&s<=p9n:s[0]==="-"?xNt(s,u9n):xNt(s,m9n));const u9n=Number.MIN_SAFE_INTEGER.toString(),h9n=f8e?BigInt(Number.MIN_SAFE_INTEGER):void 0,m9n=Number.MAX_SAFE_INTEGER.toString(),p9n=f8e?BigInt(Number.MAX_SAFE_INTEGER):void 0;function xNt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Lf=t,Dg=(s-t)/4294967296>>>0}function EG(s){if(s<0){gNt(-s);const[t,n]=lrt(Lf,Dg);Lf=t>>>0,Dg=n>>>0}else gNt(s)}function irt(s){const t=x9n||(x9n=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Dg=0,Lf=t.getUint32(0,!0)}function tXt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:kse(s,t)}function g9n(s,t){return Ej(JW()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):kse(s,t))}function sXt(s,t){return JW()?Ej(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else JW()?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+yNt(n)+yNt(s));return n}function yNt(s){return s=String(s),"0000000".slice(s.length)+s}function ort(s,t){if(2147483648&t)if(JW())s=""+(BigInt(0|t)<>>0));else{const[n,r]=lrt(s,t);s="-"+kse(n,r)}else s=kse(s,t);return s}function x8e(s){if(s.length<16)EG(Number(s));else if(JW())s=BigInt(s),Lf=Number(s&BigInt(4294967295))>>>0,Dg=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Dg=Lf=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));Dg*=1e6,Lf=1e6*Lf+i,Lf>=4294967296&&(Dg+=Math.trunc(Lf/4294967296),Dg>>>=0,Lf>>>=0)}if(t){const[r,a]=lrt(Lf,Dg);Lf=r,Dg=a}}}function lrt(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function CS(s){return Array.prototype.slice.call(s)}const Wae=typeof BigInt=="function"?BigInt.asIntN:void 0,y9n=typeof BigInt=="function"?BigInt.asUintN:void 0,S9=Number.isSafeInteger,g8e=Number.isFinite,TG=Math.trunc,v9n=Ej(0);function OX(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 z4(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function Sse(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 nXt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const b9n=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function Kae(s){switch(typeof s){case"bigint":return!0;case"number":return g8e(s);case"string":return b9n.test(s);default:return!1}}function sK(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return g8e(s)?0|s:void 0}function rXt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return g8e(s)?s>>>0:void 0}function aXt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(x8e(s),ort(Lf,Dg))}function crt(s){if(s=TG(s),!S9(s)){EG(s);var t=Lf,n=Dg;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=tXt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function iXt(s){var t=TG(Number(s));return S9(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),aXt(s))}function oXt(s){var t=TG(Number(s));return S9(t)?Ej(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),JW()?Ej(Wae(64,BigInt(s))):Ej(aXt(s)))}function lXt(s){return S9(s)?s=Ej(crt(s)):(s=TG(s),S9(s)?s=String(s):(EG(s),s=ort(Lf,Dg)),s=Ej(s)),s}function QTe(s){const t=typeof s;return s==null?s:t==="bigint"?Ej(Wae(64,s)):Kae(s)?t==="string"?oXt(s):lXt(s):void 0}function cXt(s){if(typeof s!="string")throw Error();return s}function Yae(s){if(s!=null&&typeof s!="string")throw Error();return s}function kv(s){return s==null||typeof s=="string"?s:void 0}function drt(s,t,n,r){return s!=null&&s[CG]===AG?s:Array.isArray(s)?((r=(n=0|s[Yo])|32&r|2&r)!==n&&Fy(s,r),new t(s)):(n?2&r?((s=t[uNt])||(Gae((s=new t).v),s=t[uNt]=s),t=s):t=new t:t=void 0,t)}function _9n(s,t,n){if(t)e:{if(!Kae(t=s))throw VWe("int64");switch(typeof t){case"string":t=oXt(t);break e;case"bigint":t=Ej(Wae(64,t));break e;default:t=lXt(t)}}else t=QTe(s);return(s=t)==null?n?v9n:void 0:s}const w9n={};let j9n=function(){try{return m8e(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),Cze=class{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,n){return this.g.set(t,n),this.size=this.g.size,this}delete(t){return t=this.g.delete(t),this.size=this.g.size,t}clear(){this.g.clear(),this.size=this.g.size}has(t){return this.g.has(t)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(t,n){return this.g.forEach(t,n)}[Symbol.iterator](){return this.entries()}};const N9n=j9n?(Object.setPrototypeOf(Cze.prototype,Map.prototype),Object.defineProperties(Cze.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Cze):class extends Map{constructor(){super()}};function vNt(s){return s}function Aze(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var ME=class extends N9n{constructor(s,t,n=vNt,r=vNt){super(),this.J=0|s[Yo],this.K=t,this.S=n,this.fa=this.K?k9n:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return Aze(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 k9n(s,t,n,r,a,i){return s=drt(s,r,n,i),a&&(s=hrt(s)),s}function S9n(s){return[s,this.get(s)]}let C9n;function bNt(){return C9n||(C9n=new ME(Gae([]),void 0,void 0,void 0,w9n))}function y8e(s){return Aj?s[Aj]:void 0}function JTe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}ME.prototype.toJSON=void 0;var WWe=class{};const A9n={Ka:!0};function E9n(s,t){t<100||SG(i9n,1)}function v8e(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=Aj;!a&&eK&&l&&(i=s[l])&&JTe(i,E9n),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const f=m-h;(t??(t={}))[f]=p}else l[m]=p}if(c)for(let p in c){if((o=c[p])==null||(o=n(o,r))==null)continue;let f;m=+p,u&&!Number.isNaN(m)&&(f=m+h){f[v]=CS(y)}),f.da=p.da,f}(s)),l}function T9n(s){return s[0]=Cse(s[0]),s[1]=Cse(s[1]),s}function Cse(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return GWe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Yo];return s.length===0&&1&t?void 0:v8e(s,t,Cse)}if(s!=null&&s[CG]===AG)return dXt(s);if(s instanceof lC){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(WZt){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 ME?s=s.size!==0?s.V(T9n):void 0:void 0}return s}let M9n,P9n;function dXt(s){return v8e(s=s.v,0|s[Yo],Cse)}function O7(s,t){return uXt(s,t[0],t[1])}function uXt(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[Yo],oNt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(oNt)throw Error("carr");SG(o9n,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&Fy(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 Fy(s,64|a|r),s}function L9n(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[Yo];return s.length===0&&1&n?void 0:_Nt(s,n,t)}if(s!=null&&s[CG]===AG)return wNt(s);if(s instanceof ME){if(2&(t=s.J))return s;if(!s.size)return;if(n=Gae(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 um(s,t,n,r){aK(s),Py(s=s.v,0|s[Yo],t,n,r)}function Py(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[Yo]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function DF(){return l9n===void 0?2:4}function RF(s,t,n,r,a){let i=s.v,l=0|i[Yo];r=zj(s,l)?1:r,a=!!a||r===3,r===2&&rK(s)&&(i=s.v,l=0|i[Yo]);let o=(s=prt(i,t))===fz?7:0|s[Yo],c=frt(o,l);var d=!(4&c);if(d){4&c&&(s=CS(s),o=0,c=B7(c,l),l=Py(i,l,t,s));let u=0,h=0;for(;u{const o=drt(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!zj(r)&&xz(s,t),r}function Gu(s,t,n,r){let a=s.v,i=0|a[Yo];if((t=gXt(a,i,t,n,r))==null)return t;if(i=0|a[Yo],!zj(s,i)){const l=hrt(t);l!==t&&(rK(s)&&(a=s.v,i=0|a[Yo]),i=Py(a,i,n,t=l,r),xz(a,i))}return t}function yXt(s,t,n,r,a,i,l,o){var c=zj(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&rK(s)&&(n=0|(t=s.v)[Yo]);var d=(s=prt(t,a))===fz?7:0|s[Yo],u=frt(d,n);if(o=!(4&u)){var h=s,m=n;const p=!!(2&u);p&&(m|=2);let f=!p,g=!0,v=0,y=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 wrt(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function t6e(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],$7(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 I9n(s){return QP(s)}function $7(s,t){if(s.g=t,t>s.l)throw Error()}function bXt(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 _Xt(s,t){if(t==0)return N9();var n=bXt(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):f9n?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?N9():new lC(n,kG)}var jNt=[];function wXt(s,t,n,r){if(s6e.length){const a=s6e.pop();return a.o(r),a.g.init(s,t,n,r),a}return new D9n(s,t,n,r)}function jXt(s){s.g.clear(),s.l=-1,s.h=-1,s6e.length<100&&s6e.push(s)}function NXt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=bC(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function cCe(s){switch(s.h){case 0:s.h!=0?cCe(s):wrt(s.g);break;case 1:$7(s=s.g,s.g+8);break;case 2:if(s.h!=2)cCe(s);else{var t=bC(s.g);$7(s=s.g,s.g+t)}break;case 5:$7(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!NXt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}cCe(s)}break;default:throw Error()}}function Zae(s,t,n){const r=s.g.l;var a=bC(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 jrt(s){var t=bC(s.g),n=bXt(s=s.g,t);if(s=s.h,K7n){var r,a=s;(r=Sze)||(r=Sze=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(rde===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),rde=!0}catch{rde=!1}}throw!rde&&(Sze=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?RI():(o=s[i++],l<194||(192&o)!=128?(i--,RI()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?RI():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,RI()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?RI():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,RI()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):RI(),n.length>=8192&&(c=iNt(c,n),n.length=0)}i=iNt(c,n)}return i}function kXt(s){const t=bC(s.g);return _Xt(s.g,t)}function _8e(s,t,n){var r=bC(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let R9n;function kNt(s){return s?/^-?\d+$/.test(s)?(x8e(s),new YWe(Lf,Dg)):null:F9n||(F9n=new YWe(0,0))}var YWe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let F9n;function Hq(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 oK(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function w8e(s,t){if(t>=0)oK(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function Nrt(s){var t=Lf;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 MG(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function YN(s,t,n){oK(s.g,8*t+n)}function krt(s,t){return YN(s,t,2),t=s.g.end(),MG(s,t),t.push(s.h),t}function Srt(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 j8e(s,t,n){YN(s,t,2),oK(s.g,n.length),MG(s,s.g.end()),MG(s,n)}function n6e(s,t,n,r){n!=null&&(t=krt(s,t),r(n,s),Srt(s,t))}function OC(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var Crt=OC(),SXt=OC(),Art=OC(),Ert=OC(),Trt=OC(),CXt=OC(),O9n=OC(),N8e=OC(),AXt=OC(),EXt=OC();function zC(s,t,n){var r=s.v;Aj&&Aj in r&&(r=r[Aj])&&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 Zo=class{constructor(s,t){this.v=uXt(s,t,void 0,2048)}toJSON(){return dXt(this)}j(){var a;var s=vzn,t=this.v,n=s.g,r=Aj;if(eK&&r&&((a=t[r])==null?void 0:a[n])!=null&&SG(a9n,3),t=s.g,hNt&&Aj&&hNt===void 0&&(r=(n=this.v)[Aj])&&(r=r.da))try{r(n,t,A9n)}catch(i){VZt(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[Yo];return mrt(this,s,t)?urt(this,s,!0):new this.constructor(nK(s,t,!1))}};Zo.prototype[CG]=AG,Zo.prototype.toString=function(){return this.v.toString()};var lK=class{constructor(s,t,n){this.g=s,this.h=t,s=Crt,this.l=!!s&&n===s||!1}};function k8e(s,t){return new lK(s,t,Crt)}function TXt(s,t,n,r,a){n6e(s,n,IXt(t,r),a)}const z9n=k8e(function(s,t,n,r,a){return s.h===2&&(Zae(s,yrt(t,r,n),a),!0)},TXt),B9n=k8e(function(s,t,n,r,a){return s.h===2&&(Zae(s,yrt(t,r,n),a),!0)},TXt);var S8e=Symbol(),C8e=Symbol(),ZWe=Symbol(),SNt=Symbol(),CNt=Symbol();let MXt,PXt;function gz(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 M9n||(M9n=[0,void 0,!0]);case"number":return h>0?void 0:h===0?P9n||(P9n=[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,MXt??(MXt=i),PXt??(PXt=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 Prt(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=gz(C8e,Mrt,Prt,r).T),l||(l=Lrt(r)),a)}function Lrt(s){let t=s[ZWe];if(t!=null)return t;const n=gz(C8e,Mrt,Prt,s);return t=n.ma?(r,a)=>MXt(r,a,n):(r,a)=>{for(;NXt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=U9n(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,cCe(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=_Xt(o.g,c);l=void 0,o=r,c&&((l=o[Aj]??(o[Aj]=new WWe))[i]??(l[i]=[])).push(c)}}return(r=y8e(r))&&(r.da=n.qa[CNt]),!0},s[ZWe]=t,s[CNt]=$9n.bind(s),t}function $9n(s,t,n,r){var a=this[C8e];const i=this[ZWe],l=O7(void 0,a.T),o=y8e(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,m)=>{if(m.length!==0)if(d[h])for(const p of m){u=wXt(p);try{c=!0,i(l,u)}finally{jXt(u)}}else r==null||r(s,h,m)},t==null)JTe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[Yo];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=tK(u),m=(p,f)=>{if(PE(s,p,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}f!=null&&(u=Py(s,u,p,f,h)),delete o[p]};t==null?JZt(l,0|l[Yo],(p,f)=>{m(p,f)}):m(t,PE(l,t,h))}}}}function U9n(s){const t=(s=LXt(s))[0].g;if(s=s[1]){const n=Lrt(s),r=gz(C8e,Mrt,Prt,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function A8e(s,t,n){s[t]=n.h}function E8e(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=gz(S8e,A8e,E8e,r).T),a||(a=DXt(r)))}function DXt(s){let t=s[SNt];if(!t){const n=gz(S8e,A8e,E8e,s);t=(r,a)=>RXt(r,a,n),s[SNt]=t}return t}function RXt(s,t,n){JZt(s,0|s[Yo],(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=LXt(c))[0].h;if(c=c[1]){const u=DXt(c),h=gz(S8e,A8e,E8e,c).T;c=l.ma?PXt(h,u):(m,p,f)=>d(m,p,f,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||SG(HWe,3)}}),(s=y8e(s))&&JTe(s,(r,a,i)=>{for(MG(t,t.g.end()),r=0;r{n6e(s,n,O7([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),Hq(s.g,n.h,n.g);break;default:n=kNt(t),Hq(s.g,n.h,n.g)}}function zXt(s,t,n){(t=sK(t))!=null&&t!=null&&(YN(s,n,0),w8e(s.g,t))}function BXt(s,t,n){(t=nXt(t))!=null&&(YN(s,n,0),s.g.g.push(t?1:0))}function $Xt(s,t,n){(t=kv(t))!=null&&j8e(s,n,qZt(t))}function UXt(s,t,n,r,a){n6e(s,n,IXt(t,r),a)}function qXt(s,t,n){(t=t==null||typeof t=="string"||t instanceof lC?t:void 0)!=null&&j8e(s,n,brt(t,!0).buffer)}function VXt(s,t,n){(t=rXt(t))!=null&&t!=null&&(YN(s,n,0),oK(s.g,t))}function HXt(s,t,n){return(s.h===5||s.h===2)&&(t=iK(t,0|t[Yo],n),s.h==2?_8e(s,t6e,t):t.push(t6e(s.g)),!0)}var Bg=C1(function(s,t,n){return s.h===5&&(A1(t,n,t6e(s.g)),!0)},FXt,N8e),H9n=dK(HXt,function(s,t,n){if((t=cK(z4,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"))||(x8e(r),r=kse(Lf,Dg))),r;if(a==="number")return(r=TG(r))>=0&&S9(r)||(EG(r),r=tXt(Lf,Dg)),r}}(t),t!=null&&(typeof t=="string"&&NNt(t),t!=null))switch(YN(s,n,0),typeof t){case"number":s=s.g,EG(t),Hq(s,Lf,Dg);break;case"bigint":n=BigInt.asUintN(64,t),n=new KWe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),Hq(s.g,n.h,n.g);break;default:n=NNt(t),Hq(s.g,n.h,n.g)}},O9n),Cy=C1(function(s,t,n){return s.h===0&&(A1(t,n,QP(s.g)),!0)},zXt,Ert),Xae=dK(function(s,t,n){return(s.h===0||s.h===2)&&(t=iK(t,0|t[Yo],n),s.h==2?_8e(s,QP,t):t.push(QP(s.g)),!0)},function(s,t,n){if((t=cK(sK,t))!=null&&t.length){n=krt(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=wXt(n,void 0,void 0,i);try{const l=new s,o=l.v;Lrt(t)(o,n);var a=l}finally{jXt(n)}}return a}}function T8e(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}}}};RXt(this.v,t,gz(S8e,A8e,E8e,s)),MG(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=TNt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=Mze)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function ade(s,...t){if(t.length===0)return MNt(s[0]);let n=s[0];for(let r=0;r({index:uN(r,1)??0??-1,score:tg(r,2)??0,categoryName:kv(Bf(r,3))??""??"",displayName:kv(Bf(r,4))??""??""})),headIndex:t,headName:n}}function jzn(s){const t={classifications:LE(s,rzn,1).map(n=>{var r;return Urt(((r=Gu(n,eQt,4))==null?void 0:r.g())??[],uN(n,2)??0,kv(Bf(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(GWe(n)?n=Number(n):(n=Wae(64,n),n=GWe(n)?Number(n):String(n)),n):Kae(n)?typeof n=="number"?crt(n):iXt(n):void 0}(Bf(s,2,void 0,void 0,QTe))!=null&&(t.timestampMs=CQt(Bf(s,2,void 0,void 0,QTe)??hXt)),t}function AQt(s){var l,o;var t=RF(s,3,z4,DF()),n=RF(s,2,sK,DF()),r=RF(s,1,kv,DF()),a=RF(s,9,kv,DF());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function qNt(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 VNt(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 MQt(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 Qo(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 HNt(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]=MQt(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 GNt(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 k5(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function IT(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)}}T$.forVisionTasks=function(s,t=!1){return ode("vision",s??ade``,t)},T$.forTextTasks=function(s,t=!1){return ode("text",s??ade``,t)},T$.forGenAiTasks=function(s,t=!1){return ode("genai",s??ade``,t)},T$.forAudioTasks=function(s,t=!1){return ode("audio",s??ade``,t)},T$.isSimdSupported=function(s=!1){return EQt(s)};async function kzn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await VNt(i),!self.ModuleFactory||l&&(await VNt(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 Ize(s,t){const n=Gu(s.baseOptions,r6e,1)||new r6e;typeof t=="string"?(um(n,2,Yae(t)),um(n,1)):t instanceof Uint8Array&&(um(n,1,art(t,!1)),um(n,2)),Tl(s.baseOptions,0,1,n)}function WNt(s){try{const t=s.H.length;if(t===1)throw Error(s.H[0].message);if(t>1)throw Error("Encountered multiple errors: "+s.H.map(n=>n.message).join(", "))}finally{s.H=[]}}function Co(s,t){s.C=Math.max(s.C,t)}function I8e(s,t){s.B=new tw,Bj(s.B,2,"PassThroughCalculator"),df(s.B,"free_memory"),Cu(s.B,"free_memory_unused_out"),Jf(t,"free_memory"),ZN(t,s.B)}function PG(s,t){df(s.B,t),Cu(s.B,t+"_unused_out")}function D8e(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var tKe=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=Gu(this.baseOptions,r6e,1))!=null&&a.g()||(i=Gu(this.baseOptions,r6e,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=Gu(d.baseOptions,ONt,3);if(!h){var m=h=new ONt,p=new PNt;uee(m,4,dCe,p)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new X9n,uee(u,2,dCe,m)):(u=h,m=new PNt,uee(u,4,dCe,m))),Tl(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),Ize(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)Ize(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:m,value:p}=await d.read();if(m)break;u.push(p),h+=p.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const m of u)d.set(m,h),h+=m.length;return d}(c.modelAssetBuffer).then(d=>{Ize(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=Q9n(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,WNt(this)}finishProcessing(){this.g.finishProcessing(),WNt(this)}close(){this.B=void 0,this.g.closeGraph()}};function AP(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}tKe.prototype.close=tKe.prototype.close;class Szn{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 KNt(s,t,n){const r=s.g;if(n=AP(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 YNt(s,t){const n=s.g,r=AP(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=AP(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=AP(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 Szn(n,r,a,i)}function qrt(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function Czn(s,t,n,r){return qrt(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=YNt(s,!0)),n=s.u):(s.A||(s.A=YNt(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function PQt(s,t,n){return qrt(s,t),s=AP(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 LQt(s,t,n){qrt(s,t),s.B||(s.B=AP(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 Azn(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var IQt=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=AP(s.createProgram(),"Failed to create WebGL program"),this.X=KNt(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=KNt(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 LA(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 sKe(s){var t=LA(s,1);if(!t){if(t=LA(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=LG(s);var n=Vrt(s);if(LQt(n,r,DQt(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 sKe(this)}N(){return DQt(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=LG(this),a=Vrt(this);r.activeTexture(r.TEXTURE1),n=PQt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=RQt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),LQt(a,r,n),Czn(a,r,!1,()=>{FQt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),nKe(this)}),Azn(a),nKe(this)}}s.push(n)}return new n0(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&LG(this).deleteTexture(LA(this,2)),ZNt=-1}};n0.prototype.close=n0.prototype.close,n0.prototype.clone=n0.prototype.clone,n0.prototype.getAsWebGLTexture=n0.prototype.N,n0.prototype.getAsFloat32Array=n0.prototype.ia,n0.prototype.getAsUint8Array=n0.prototype.ja,n0.prototype.hasWebGLTexture=n0.prototype.R,n0.prototype.hasFloat32Array=n0.prototype.ka,n0.prototype.hasUint8Array=n0.prototype.Fa;var ZNt=250;function VS(...s){return s.map(([t,n])=>({start:t,end:n}))}const Ezn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((XNt=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:TQt()?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?'),Qo(this,r||"input_audio",i=>{Qo(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){k5(this,"__graph_config__",t=>{s(t)}),Qo(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),Qo(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){Qo(this,t,r=>{const[a,i]=HNt(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){Qo(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){Qo(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){Qo(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){Qo(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){Qo(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){Qo(this,t,r=>{Qo(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){Qo(this,t,r=>{GNt(this,Object.keys(s),a=>{GNt(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){Qo(this,n,a=>{Qo(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){Qo(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){Qo(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){Qo(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){Qo(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){Qo(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){Qo(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){Qo(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)Qo(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){Qo(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){Qo(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){Qo(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){Qo(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){Qo(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){Qo(this,t,n=>{Qo(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){Qo(this,n,r=>{Qo(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){Qo(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){Qo(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){Qo(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){Qo(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){Qo(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){Qo(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)Qo(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){k5(this,s,t),Qo(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){IT(this,s,t),Qo(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){k5(this,s,t),Qo(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){IT(this,s,t),Qo(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){k5(this,s,t),Qo(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){IT(this,s,t),Qo(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){k5(this,s,t),Qo(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){IT(this,s,t),Qo(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){k5(this,s,t),Qo(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){IT(this,s,t),Qo(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){k5(this,s,t),Qo(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){IT(this,s,t),Qo(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){k5(this,s,t),Qo(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){IT(this,s,t),Qo(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?'),k5(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),Qo(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 XNt{get ga(){return this.i}pa(s,t,n){Qo(this,t,r=>{const[a,i]=HNt(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){k5(this,s,t),Qo(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){IT(this,s,t),Qo(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var XNt,HS=class extends Ezn{};async function $u(s,t,n){return async function(r,a,i,l){return kzn(r,a,i,l)}(s,n.canvas??(TQt()?void 0:document.createElement("canvas")),t,n)}function OQt(s,t,n,r){if(s.U){const i=new aQt;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].");ll(i,1,(a.left+a.right)/2),ll(i,2,(a.top+a.bottom)/2),ll(i,4,a.right-a.left),ll(i,3,a.bottom-a.top)}else ll(i,1,.5),ll(i,2,.5),ll(i,4,1),ll(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(ll(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=MQt(t);n=tg(i,3)*o/l,a=tg(i,4)*l/o,ll(i,4,n),ll(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 GS(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'.");OQt(s,t,n,s.C+1)}function $C(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'.");OQt(s,t,n,r)}function IG(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 n0([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var $j=class extends tKe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new IQt}l(s,t=!0){if("runningMode"in s&&um(this.baseOptions,2,Sse(!!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()}};$j.prototype.close=$j.prototype.close;var k2=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Tl(s=this.h=new P8e,0,1,t=new Ox),ll(this.h,2,.5),ll(this.h,3,.3)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&ll(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&ll(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},GS(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},$C(this,s,n,t),this.j}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect_in"),ah(s,"detections");const t=new Wj;zC(t,dzn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect_in"),Cu(n,"DETECTIONS:detections"),n.o(t),ZN(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=sQt(i),this.j.detections.push(AQt(r));Co(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};k2.prototype.detectForVideo=k2.prototype.G,k2.prototype.detect=k2.prototype.F,k2.prototype.setOptions=k2.prototype.o,k2.createFromModelPath=async function(s,t){return $u(k2,s,{baseOptions:{modelAssetPath:t}})},k2.createFromModelBuffer=function(s,t){return $u(k2,s,{baseOptions:{modelAssetBuffer:t}})},k2.createFromOptions=function(s,t){return $u(k2,s,t)};var Hrt=VS([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]),Grt=VS([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]),Wrt=VS([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),zQt=VS([474,475],[475,476],[476,477],[477,474]),Krt=VS([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]),Yrt=VS([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),BQt=VS([469,470],[470,471],[471,472],[472,469]),Zrt=VS([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]),$Qt=[...Hrt,...Grt,...Wrt,...Krt,...Yrt,...Zrt],UQt=VS([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 QNt(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var fx=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Tl(s=this.h=new dQt,0,1,t=new Ox),this.A=new cQt,Tl(this.h,0,3,this.A),this.u=new P8e,Tl(this.h,0,2,this.u),IE(this.u,4,1),ll(this.u,2,.5),ll(this.A,2,.5),ll(this.h,4,.5)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"numFaces"in s&&IE(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&ll(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&ll(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&ll(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 QNt(this),GS(this,s,t),this.j}G(s,t,n){return QNt(this),$C(this,s,n,t),this.j}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect"),ah(s,"face_landmarks");const t=new Wj;zC(t,hzn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect"),Cu(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),ZN(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=Qae(i),this.j.faceLandmarks.push(L8e(r));Co(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{Co(this,r)}),this.outputFaceBlendshapes&&(ah(s,"blendshapes"),Cu(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=M8e(i),this.j.faceBlendshapes.push(Urt(r.g()??[]));Co(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{Co(this,r)})),this.outputFacialTransformationMatrixes&&(ah(s,"face_geometry"),Cu(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Gu(r=uzn(i),szn,2))&&this.j.facialTransformationMatrixes.push({rows:uN(r,1)??0??0,columns:uN(r,2)??0??0,data:RF(r,3,z4,DF()).slice()??[]});Co(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{Co(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};fx.prototype.detectForVideo=fx.prototype.G,fx.prototype.detect=fx.prototype.F,fx.prototype.setOptions=fx.prototype.o,fx.createFromModelPath=function(s,t){return $u(fx,s,{baseOptions:{modelAssetPath:t}})},fx.createFromModelBuffer=function(s,t){return $u(fx,s,{baseOptions:{modelAssetBuffer:t}})},fx.createFromOptions=function(s,t){return $u(fx,s,t)},fx.FACE_LANDMARKS_LIPS=Hrt,fx.FACE_LANDMARKS_LEFT_EYE=Grt,fx.FACE_LANDMARKS_LEFT_EYEBROW=Wrt,fx.FACE_LANDMARKS_LEFT_IRIS=zQt,fx.FACE_LANDMARKS_RIGHT_EYE=Krt,fx.FACE_LANDMARKS_RIGHT_EYEBROW=Yrt,fx.FACE_LANDMARKS_RIGHT_IRIS=BQt,fx.FACE_LANDMARKS_FACE_OVAL=Zrt,fx.FACE_LANDMARKS_CONTOURS=$Qt,fx.FACE_LANDMARKS_TESSELATION=UQt;var Xrt=VS([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 JNt(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function ekt(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 tkt(s,t=!0){const n=[];for(const a of s){var r=M8e(a);s=[];for(const i of r.g())r=t&&uN(i,1)!=null?uN(i,1)??0:-1,s.push({score:tg(i,2)??0,index:r,categoryName:kv(Bf(i,3))??""??"",displayName:kv(Bf(i,4))??""??""});n.push(s)}return n}var bw=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Tl(s=this.j=new mQt,0,1,t=new Ox),this.u=new Ort,Tl(this.j,0,2,this.u),this.D=new Frt,Tl(this.u,0,3,this.D),this.A=new hQt,Tl(this.u,0,2,this.A),this.h=new mzn,Tl(this.j,0,3,this.h),ll(this.A,2,.5),ll(this.u,4,.5),ll(this.D,2,.5)}get baseOptions(){return Gu(this.j,Ox,1)}set baseOptions(s){Tl(this.j,0,1,s)}o(s){var a,i,l,o;if(IE(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&ll(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&ll(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&ll(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new YB,n=t,r=eKe(s.cannedGesturesClassifierOptions,(a=Gu(this.h,YB,3))==null?void 0:a.l());Tl(n,0,2,r),Tl(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Gu(this.h,YB,3))==null||i.g());return s.customGesturesClassifierOptions?(Tl(n=t=new YB,0,2,r=eKe(s.customGesturesClassifierOptions,(l=Gu(this.h,YB,4))==null?void 0:l.l())),Tl(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Gu(this.h,YB,4))==null||o.g()),this.l(s)}Ha(s,t){return JNt(this),GS(this,s,t),ekt(this)}Ia(s,t,n){return JNt(this),$C(this,s,n,t),ekt(this)}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect"),ah(s,"hand_gestures"),ah(s,"hand_landmarks"),ah(s,"world_hand_landmarks"),ah(s,"handedness");const t=new Wj;zC(t,pzn,this.j);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect"),Cu(n,"HAND_GESTURES:hand_gestures"),Cu(n,"LANDMARKS:hand_landmarks"),Cu(n,"WORLD_LANDMARKS:world_hand_landmarks"),Cu(n,"HANDEDNESS:handedness"),n.o(t),ZN(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=Qae(i);const l=[];for(const o of LE(r,rQt,1))l.push({x:tg(o,1)??0,y:tg(o,2)??0,z:tg(o,3)??0,visibility:tg(o,4)??0});this.landmarks.push(l)}Co(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=Gq(i);const l=[];for(const o of LE(r,nQt,1))l.push({x:tg(o,1)??0,y:tg(o,2)??0,z:tg(o,3)??0,visibility:tg(o,4)??0});this.worldLandmarks.push(l)}Co(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...tkt(r,!1)),Co(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{Co(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...tkt(r)),Co(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function skt(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}bw.prototype.recognizeForVideo=bw.prototype.Ia,bw.prototype.recognize=bw.prototype.Ha,bw.prototype.setOptions=bw.prototype.o,bw.createFromModelPath=function(s,t){return $u(bw,s,{baseOptions:{modelAssetPath:t}})},bw.createFromModelBuffer=function(s,t){return $u(bw,s,{baseOptions:{modelAssetBuffer:t}})},bw.createFromOptions=function(s,t){return $u(bw,s,t)},bw.HAND_CONNECTIONS=Xrt;var _w=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Tl(s=this.h=new Ort,0,1,t=new Ox),this.u=new Frt,Tl(this.h,0,3,this.u),this.j=new hQt,Tl(this.h,0,2,this.j),IE(this.j,3,1),ll(this.j,2,.5),ll(this.u,2,.5),ll(this.h,4,.5)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"numHands"in s&&IE(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&ll(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&ll(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&ll(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],GS(this,s,t),skt(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],$C(this,s,n,t),skt(this)}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect"),ah(s,"hand_landmarks"),ah(s,"world_hand_landmarks"),ah(s,"handedness");const t=new Wj;zC(t,fzn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect"),Cu(n,"LANDMARKS:hand_landmarks"),Cu(n,"WORLD_LANDMARKS:world_hand_landmarks"),Cu(n,"HANDEDNESS:handedness"),n.o(t),ZN(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=Qae(i),this.landmarks.push(L8e(r));Co(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=Gq(i),this.worldLandmarks.push(mee(r));Co(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=M8e(c);const d=[];for(const u of r.g())d.push({score:tg(u,2)??0,index:uN(u,1)??0??-1,categoryName:kv(Bf(u,3))??""??"",displayName:kv(Bf(u,4))??""??""});o.push(d)}l.call(i,...o),Co(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};_w.prototype.detectForVideo=_w.prototype.G,_w.prototype.detect=_w.prototype.F,_w.prototype.setOptions=_w.prototype.o,_w.createFromModelPath=function(s,t){return $u(_w,s,{baseOptions:{modelAssetPath:t}})},_w.createFromModelBuffer=function(s,t){return $u(_w,s,{baseOptions:{modelAssetBuffer:t}})},_w.createFromOptions=function(s,t){return $u(_w,s,t)},_w.HAND_CONNECTIONS=Xrt;var qQt=VS([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 nkt(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function rkt(s){try{if(!s.D)return s.h;s.D(s.h)}finally{D8e(s)}}function cde(s,t){s=Qae(s),t.push(L8e(s))}var Kp=class extends $j{constructor(s,t){super(new HS(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Tl(s=this.j=new yQt,0,1,t=new Ox),this.I=new Frt,Tl(this.j,0,2,this.I),this.W=new xzn,Tl(this.j,0,3,this.W),this.u=new P8e,Tl(this.j,0,4,this.u),this.O=new cQt,Tl(this.j,0,5,this.O),this.A=new xQt,Tl(this.j,0,6,this.A),this.M=new gQt,Tl(this.j,0,7,this.M),ll(this.u,2,.5),ll(this.u,3,.3),ll(this.O,2,.5),ll(this.A,2,.5),ll(this.A,3,.3),ll(this.M,2,.5),ll(this.I,2,.5)}get baseOptions(){return Gu(this.j,Ox,1)}set baseOptions(s){Tl(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&ll(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&ll(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&ll(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&ll(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&ll(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&ll(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&ll(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,nkt(this),GS(this,s,r),rkt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,nkt(this),$C(this,s,a,t),rkt(this)}m(){var s=new Kj;Jf(s,"input_frames_image"),ah(s,"pose_landmarks"),ah(s,"pose_world_landmarks"),ah(s,"face_landmarks"),ah(s,"left_hand_landmarks"),ah(s,"left_hand_world_landmarks"),ah(s,"right_hand_landmarks"),ah(s,"right_hand_world_landmarks");const t=new Wj,n=new ANt;Bj(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))um(a,2,v8e(i,0,Cse));else{if(!(typeof i=="string"||i instanceof lC||nrt(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");S6(a,2,art(i,!1),N9())}}(n,this.j.g());const r=new tw;Bj(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),vrt(r,8,ANt,n),df(r,"IMAGE:input_frames_image"),Cu(r,"POSE_LANDMARKS:pose_landmarks"),Cu(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Cu(r,"FACE_LANDMARKS:face_landmarks"),Cu(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Cu(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Cu(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Cu(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),ZN(s,r),I8e(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{cde(a,this.h.poseLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=Gq(a),l.push(mee(a)),Co(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{Co(this,a)}),this.outputPoseSegmentationMasks&&(Cu(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),PG(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[IG(this,a,!0,!this.D)],Co(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],Co(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{cde(a,this.h.faceLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{Co(this,a)}),this.outputFaceBlendshapes&&(ah(s,"extra_blendshapes"),Cu(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=M8e(a),l.push(Urt(a.g()??[]))),Co(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{Co(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{cde(a,this.h.leftHandLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=Gq(a),l.push(mee(a)),Co(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{cde(a,this.h.rightHandLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=Gq(a),l.push(mee(a)),Co(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{Co(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Kp.prototype.detectForVideo=Kp.prototype.G,Kp.prototype.detect=Kp.prototype.F,Kp.prototype.setOptions=Kp.prototype.o,Kp.createFromModelPath=function(s,t){return $u(Kp,s,{baseOptions:{modelAssetPath:t}})},Kp.createFromModelBuffer=function(s,t){return $u(Kp,s,{baseOptions:{modelAssetBuffer:t}})},Kp.createFromOptions=function(s,t){return $u(Kp,s,t)},Kp.HAND_CONNECTIONS=Xrt,Kp.POSE_CONNECTIONS=qQt,Kp.FACE_LANDMARKS_LIPS=Hrt,Kp.FACE_LANDMARKS_LEFT_EYE=Grt,Kp.FACE_LANDMARKS_LEFT_EYEBROW=Wrt,Kp.FACE_LANDMARKS_LEFT_IRIS=zQt,Kp.FACE_LANDMARKS_RIGHT_EYE=Krt,Kp.FACE_LANDMARKS_RIGHT_EYEBROW=Yrt,Kp.FACE_LANDMARKS_RIGHT_IRIS=BQt,Kp.FACE_LANDMARKS_FACE_OVAL=Zrt,Kp.FACE_LANDMARKS_CONTOURS=$Qt,Kp.FACE_LANDMARKS_TESSELATION=UQt;var S2=class extends $j{constructor(s,t){super(new HS(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Tl(s=this.h=new vQt,0,1,t=new Ox)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return Tl(this.h,0,2,eKe(s,Gu(this.h,Drt,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},GS(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},$C(this,s,n,t),this.j}m(){var s=new Kj;Jf(s,"input_image"),Jf(s,"norm_rect"),ah(s,"classifications");const t=new Wj;zC(t,gzn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),df(n,"IMAGE:input_image"),df(n,"NORM_RECT:norm_rect"),Cu(n,"CLASSIFICATIONS:classifications"),n.o(t),ZN(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=jzn(azn(r)),Co(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};S2.prototype.classifyForVideo=S2.prototype.ta,S2.prototype.classify=S2.prototype.sa,S2.prototype.setOptions=S2.prototype.o,S2.createFromModelPath=function(s,t){return $u(S2,s,{baseOptions:{modelAssetPath:t}})},S2.createFromModelBuffer=function(s,t){return $u(S2,s,{baseOptions:{modelAssetBuffer:t}})},S2.createFromOptions=function(s,t){return $u(S2,s,t)};var ww=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect",!0),this.h=new bQt,this.embeddings={embeddings:[]},Tl(s=this.h,0,1,t=new Ox)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){var t=this.h,n=Gu(this.h,FNt,2);return n=n?n.clone():new FNt,s.l2Normalize!==void 0?um(n,1,Sse(s.l2Normalize)):"l2Normalize"in s&&um(n,1),s.quantize!==void 0?um(n,2,Sse(s.quantize)):"quantize"in s&&um(n,2),Tl(t,0,2,n),this.l(s)}za(s,t){return GS(this,s,t),this.embeddings}Aa(s,t,n){return $C(this,s,n,t),this.embeddings}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect"),ah(s,"embeddings_out");const t=new Wj;zC(t,yzn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect"),Cu(n,"EMBEDDINGS:embeddings_out"),n.o(t),ZN(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=lzn(r),this.embeddings=function(i){return{embeddings:LE(i,ozn,1).map(l=>{var d,u;const o={headIndex:uN(l,3)??0??-1,headName:kv(Bf(l,4))??""??""};var c=l.v;return gXt(c,0|c[Yo],RNt,Eze(l,1))!==void 0?(l=RF(l=Gu(l,RNt,Eze(l,1),void 0),1,z4,DF()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Gu(l,izn,Eze(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:CQt(Bf(i,2,void 0,void 0,QTe)??hXt)}}(r),Co(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ww.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=qNt(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=qNt(UNt(s.quantizedEmbedding),UNt(t.quantizedEmbedding))}return s},ww.prototype.embedForVideo=ww.prototype.Aa,ww.prototype.embed=ww.prototype.za,ww.prototype.setOptions=ww.prototype.o,ww.createFromModelPath=function(s,t){return $u(ww,s,{baseOptions:{modelAssetPath:t}})},ww.createFromModelBuffer=function(s,t){return $u(ww,s,{baseOptions:{modelAssetBuffer:t}})},ww.createFromOptions=function(s,t){return $u(ww,s,t)};var rKe=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 Tzn(s){var n,r;const t=function(a){return LE(a,tw,1)}(s.ca()).filter(a=>(kv(Bf(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=Gu(t[0],Wj,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=kv(Bf(a,1))??""})}function akt(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function ikt(s){try{const t=new rKe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{D8e(s)}}rKe.prototype.close=rKe.prototype.close;var Q1=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new $rt,this.A=new _Qt,Tl(this.h,0,3,this.A),Tl(s=this.h,0,1,t=new Ox)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?um(this.h,2,Yae(s.displayNamesLocale)):"displayNamesLocale"in s&&um(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){Tzn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,akt(this),GS(this,s,r),ikt(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,akt(this),$C(this,s,a,t),ikt(this)}Da(){return this.u}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect");const t=new Wj;zC(t,jQt,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect"),n.o(t),ZN(s,n),I8e(this,s),this.outputConfidenceMasks&&(ah(s,"confidence_masks"),Cu(n,"CONFIDENCE_MASKS:confidence_masks"),PG(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>IG(this,i,!0,!this.j)),Co(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],Co(this,r)})),this.outputCategoryMask&&(ah(s,"category_mask"),Cu(n,"CATEGORY_MASK:category_mask"),PG(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=IG(this,r,!1,!this.j),Co(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,Co(this,r)})),ah(s,"quality_scores"),Cu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,Co(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Q1.prototype.getLabels=Q1.prototype.Da,Q1.prototype.segmentForVideo=Q1.prototype.La,Q1.prototype.segment=Q1.prototype.segment,Q1.prototype.setOptions=Q1.prototype.o,Q1.createFromModelPath=function(s,t){return $u(Q1,s,{baseOptions:{modelAssetPath:t}})},Q1.createFromModelBuffer=function(s,t){return $u(Q1,s,{baseOptions:{modelAssetBuffer:t}})},Q1.createFromOptions=function(s,t){return $u(Q1,s,t)};var aKe=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()}};aKe.prototype.close=aKe.prototype.close;var S5=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new $rt,this.u=new _Qt,Tl(this.h,0,3,this.u),Tl(s=this.h,0,1,t=new Ox)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(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 NQt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new Lze;S6(i,3,Sse(!0),!1),S6(i,1,OX(t.keypoint.x),0),S6(i,2,OX(t.keypoint.y),0),uee(r,1,JWe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new bzn;for(i of t.scribble)S6(t=new Lze,3,Sse(!0),!1),S6(t,1,OX(i.x),0),S6(t,2,OX(i.y),0),vrt(o,1,Lze,t);uee(r,2,JWe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),GS(this,s,a);e:{try{const o=new aKe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{D8e(this)}l=void 0}return l}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"roi_in"),Jf(s,"norm_rect_in");const t=new Wj;zC(t,jQt,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),df(n,"IMAGE:image_in"),df(n,"ROI:roi_in"),df(n,"NORM_RECT:norm_rect_in"),n.o(t),ZN(s,n),I8e(this,s),this.outputConfidenceMasks&&(ah(s,"confidence_masks"),Cu(n,"CONFIDENCE_MASKS:confidence_masks"),PG(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>IG(this,i,!0,!this.j)),Co(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],Co(this,r)})),this.outputCategoryMask&&(ah(s,"category_mask"),Cu(n,"CATEGORY_MASK:category_mask"),PG(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=IG(this,r,!1,!this.j),Co(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,Co(this,r)})),ah(s,"quality_scores"),Cu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,Co(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};S5.prototype.segment=S5.prototype.segment,S5.prototype.setOptions=S5.prototype.o,S5.createFromModelPath=function(s,t){return $u(S5,s,{baseOptions:{modelAssetPath:t}})},S5.createFromModelBuffer=function(s,t){return $u(S5,s,{baseOptions:{modelAssetBuffer:t}})},S5.createFromOptions=function(s,t){return $u(S5,s,t)};var C2=class extends $j{constructor(s,t){super(new HS(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Tl(s=this.h=new kQt,0,1,t=new Ox)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?um(this.h,2,Yae(s.displayNamesLocale)):"displayNamesLocale"in s&&um(this.h,2),s.maxResults!==void 0?IE(this.h,3,s.maxResults):"maxResults"in s&&um(this.h,3),s.scoreThreshold!==void 0?ll(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&um(this.h,4),s.categoryAllowlist!==void 0?e6e(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&um(this.h,5),s.categoryDenylist!==void 0?e6e(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&um(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},GS(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},$C(this,s,n,t),this.j}m(){var s=new Kj;Jf(s,"input_frame_gpu"),Jf(s,"norm_rect"),ah(s,"detections");const t=new Wj;zC(t,_zn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),df(n,"IMAGE:input_frame_gpu"),df(n,"NORM_RECT:norm_rect"),Cu(n,"DETECTIONS:detections"),n.o(t),ZN(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=sQt(i),this.j.detections.push(AQt(r));Co(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};C2.prototype.detectForVideo=C2.prototype.G,C2.prototype.detect=C2.prototype.F,C2.prototype.setOptions=C2.prototype.o,C2.createFromModelPath=async function(s,t){return $u(C2,s,{baseOptions:{modelAssetPath:t}})},C2.createFromModelBuffer=function(s,t){return $u(C2,s,{baseOptions:{modelAssetBuffer:t}})},C2.createFromOptions=function(s,t){return $u(C2,s,t)};var iKe=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 okt(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function lkt(s){try{const t=new iKe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{D8e(s)}}iKe.prototype.close=iKe.prototype.close;var jw=class extends $j{constructor(s,t){super(new HS(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Tl(s=this.h=new SQt,0,1,t=new Ox),this.A=new gQt,Tl(this.h,0,3,this.A),this.j=new xQt,Tl(this.h,0,2,this.j),IE(this.j,4,1),ll(this.j,2,.5),ll(this.A,2,.5),ll(this.h,4,.5)}get baseOptions(){return Gu(this.h,Ox,1)}set baseOptions(s){Tl(this.h,0,1,s)}o(s){return"numPoses"in s&&IE(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&ll(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&ll(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&ll(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,okt(this),GS(this,s,r),lkt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,okt(this),$C(this,s,a,t),lkt(this)}m(){var s=new Kj;Jf(s,"image_in"),Jf(s,"norm_rect"),ah(s,"normalized_landmarks"),ah(s,"world_landmarks"),ah(s,"segmentation_masks");const t=new Wj;zC(t,wzn,this.h);const n=new tw;Bj(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),df(n,"IMAGE:image_in"),df(n,"NORM_RECT:norm_rect"),Cu(n,"NORM_LANDMARKS:normalized_landmarks"),Cu(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),ZN(s,n),I8e(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=Qae(i),this.landmarks.push(L8e(r));Co(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],Co(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=Gq(i),this.worldLandmarks.push(mee(r));Co(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],Co(this,r)}),this.outputSegmentationMasks&&(Cu(n,"SEGMENTATION_MASK:segmentation_masks"),PG(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>IG(this,i,!0,!this.u)),Co(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],Co(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};jw.prototype.detectForVideo=jw.prototype.G,jw.prototype.detect=jw.prototype.F,jw.prototype.setOptions=jw.prototype.o,jw.createFromModelPath=function(s,t){return $u(jw,s,{baseOptions:{modelAssetPath:t}})},jw.createFromModelBuffer=function(s,t){return $u(jw,s,{baseOptions:{modelAssetBuffer:t}})},jw.createFromOptions=function(s,t){return $u(jw,s,t)},jw.POSE_CONNECTIONS=qQt;let FF=null,zX=null;async function Mzn(){return FF||zX||(zX=(async()=>{const s=await T$.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return FF=await Q1.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}),FF})(),zX)}function Pzn(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const m=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/m}}for(let l=0;l=0&&(o-=i[d*n+l]);const h=Math.min(u,r-1)-Math.max(d+1,0)+1;t[c*n+l]=o/h}}}function Lzn(){FF&&(FF.close(),FF=null,zX=null)}const Izn=1280,Dzn=720;function Rzn(s,t){const n=_.useRef(null),r=_.useRef(null),a=_.useRef(null),i=_.useRef(0),l=_.useRef(t),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(null);l.current=t;const p=t.type!=="none"&&s!==null;return _.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const f=new Image;f.crossOrigin="anonymous",f.src=t.imageUrl,f.onload=()=>{a.current=f},f.onerror=()=>{a.current=null}}else t.type!=="image"&&(a.current=null)},[t.type,t.imageUrl]),_.useEffect(()=>{if(!p||!s){r.current&&(r.current.srcObject=null,r.current=null);return}const f=document.createElement("video");return f.srcObject=s,f.muted=!0,f.playsInline=!0,f.autoplay=!0,f.play().catch(()=>{}),r.current=f,()=>{f.srcObject=null,r.current=null}},[p,s]),_.useEffect(()=>{if(!p){c(null),m(null);return}let f=!1,g=null,v=null;const y=async()=>{u(!0),m(null);try{const w=await Mzn();if(f)return;u(!1);const S=r.current;if(!S||(await new Promise(Zt=>{if(S.videoWidth>0)return Zt();S.onloadedmetadata=()=>Zt(),setTimeout(Zt,2e3)}),f))return;const C=S.videoWidth||640,E=S.videoHeight||480,P=Math.max(C,E),M=Math.min(C,E),I=Math.min(1,Izn/P,Dzn/M),D=Math.max(2,Math.round(C*I/2)*2),F=Math.max(2,Math.round(E*I/2)*2),G=!$Zt().canRunVirtualBg,H=(G?192:256)/Math.max(D,F),K=Math.max(2,Math.round(D*H)),Z=Math.max(2,Math.round(F*H)),oe=G?90:55,re=G?24:30,ae=n.current;if(!ae)return;ae.width=D,ae.height=F;const J=ae.getContext("2d",{alpha:!1}),te=document.createElement("canvas");te.width=D,te.height=F;const ce=te.getContext("2d"),ve=document.createElement("canvas");ve.width=Math.max(2,Math.round(D/2)),ve.height=Math.max(2,Math.round(F/2));const me=ve.getContext("2d",{alpha:!1}),he=document.createElement("canvas");he.width=K,he.height=Z;const ge=he.getContext("2d",{alpha:!1}),Ee=document.createElement("canvas");Ee.width=K,Ee.height=Z;const Ne=Ee.getContext("2d"),Pe=Ne.createImageData(K,Z),Oe=Pe.data;for(let Zt=0;Ztke.addTrack(Zt)),f||c(ke);const _e=new Float32Array(K*Z),Ae=new Float32Array(K*Z),Se=new Float32Array(K*Z);let We=!1,qe=!1;const Be=2,Ze=.4;let $e=0;const Xe=(Zt,ms)=>{ge.drawImage(Zt,0,0,K,Z);const It=w.segmentForVideo(he,ms).confidenceMasks;if(!(!It||It.length===0)){Ae.fill(0);for(let qs=1;qs1?1:kn}}for(const qs of It)qs.close();if(Pzn(Ae,_e,K,Z,Be),We)for(let qs=0;qs<_e.length;qs++)_e[qs]=Ze*_e[qs]+(1-Ze)*Se[qs];Se.set(_e),We=!0;for(let qs=0,wt=3;qs<_e.length;qs++,wt+=4){const Us=(_e[qs]-.1)/.8;Oe[wt]=Us<=0?0:Us>=1?255:Us*255|0}Ne.putImageData(Pe,0,0),qe=!0}},nt=Zt=>{const ms=l.current;if(ms.type==="blur"){const Dt=Math.max(2,Math.round((ms.blurRadius??15)/2));me.filter=`blur(${Dt}px)`,me.drawImage(Zt,0,0,ve.width,ve.height),me.filter="none",J.drawImage(ve,0,0,D,F)}else if(ms.type==="image"&&a.current){const Dt=a.current,It=Dt.width/Dt.height,qs=D/F;let wt=0,Us=0,Es=Dt.width,kn=Dt.height;It>qs?(Es=Dt.height*qs,wt=(Dt.width-Es)/2):(kn=Dt.width/qs,Us=(Dt.height-kn)/2),J.drawImage(Dt,wt,Us,Es,kn,0,0,D,F)}else J.fillStyle="#000",J.fillRect(0,0,D,F)},Ge=()=>{if(f||!r.current)return;const Zt=r.current;if(Zt.readyState<2){zt(Zt);return}try{const ms=performance.now();ms-$e>=oe&&($e=ms,Xe(Zt,ms)),qe?(nt(Zt),ce.globalCompositeOperation="source-over",ce.clearRect(0,0,D,F),ce.drawImage(Zt,0,0,D,F),ce.globalCompositeOperation="destination-in",ce.drawImage(Ee,0,0,D,F),ce.globalCompositeOperation="source-over",l.current.mirror?(J.save(),J.translate(D,0),J.scale(-1,1),J.drawImage(te,0,0),J.restore()):J.drawImage(te,0,0)):J.drawImage(Zt,0,0,D,F)}catch{try{J.drawImage(Zt,0,0,D,F)}catch{}}zt(Zt)},Je=typeof S.requestVideoFrameCallback=="function",ut="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{clearInterval(id);id=null}}",lt=new Blob([ut],{type:"application/javascript"});v=URL.createObjectURL(lt),g=new Worker(v),g.onmessage=()=>{f||!document.hidden||Ge()};const qt=()=>{g&&(document.hidden?g.postMessage({type:"start",fps:re}):(g.postMessage({type:"stop"}),zt(r.current)))};document.addEventListener("visibilitychange",qt);const zt=Zt=>{f||document.hidden||(Je?Zt.requestVideoFrameCallback(()=>Ge()):i.current=requestAnimationFrame(Ge))};zt(S),b=()=>{document.removeEventListener("visibilitychange",qt)}}catch(w){console.error("[useVirtualBackground] init error:",w),f||(u(!1),m(w.message||"Failed to initialize virtual background"))}};let b=null;return y(),()=>{f=!0,i.current&&cancelAnimationFrame(i.current),b==null||b(),g&&(g.postMessage({type:"stop"}),g.terminate(),g=null),v&&URL.revokeObjectURL(v),c(null)}},[p,s]),_.useEffect(()=>()=>{Lzn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:p,error:h}}function YE({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,showBackgroundPicker:a=!0,className:i,teleprompterContent:l}){const o=_.useRef(null),c=_.useRef(null),d=_.useRef(null),[u,h]=_.useState(null),m=_.useRef([]),p=_.useRef(null),f=_.useRef(null),g=_.useRef(null),v=_.useRef(null),y=XW(),[b,w]=_.useState("camera"),S=_.useRef(null),C=_.useRef(null),E=_.useRef(null),P=_.useRef(null),M=_.useRef(null),I=_.useRef(null),[D,F]=_.useState(!0),[q,G]=_.useState(!0),[V,H]=_.useState(null),[K,Z]=_.useState(!1),[oe,re]=_.useState(!1),[ae,J]=_.useState(null),[te,ce]=_.useState(null),[ve,me]=_.useState(0),[he,ge]=_.useState("user"),[Ee,Ne]=_.useState(0),[Pe,Oe]=_.useState(!1),[ke,Ve]=_.useState(!0),[_e,Ae]=_.useState(null),[Se,We]=_.useState(!1),[qe,Be]=_.useState(null),Ze=_.useRef(null),[$e,Xe]=_.useState(()=>{try{const Gs=localStorage.getItem("video-bg-config");if(Gs)return JSON.parse(Gs)}catch{}return{type:"none"}});_.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify($e))}catch{}},[$e]);const[nt,Ge]=_.useState([]),[Je,ut]=_.useState([]),[lt,qt]=_.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[zt,Zt]=_.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});_.useEffect(()=>{try{localStorage.setItem("video-mic-id",lt)}catch{}},[lt]),_.useEffect(()=>{try{localStorage.setItem("video-cam-id",zt)}catch{}},[zt]),_.useEffect(()=>{var an,tr,Lr;if(!((an=navigator.mediaDevices)!=null&&an.enumerateDevices))return;const Gs=async()=>{try{const Yt=await navigator.mediaDevices.enumerateDevices();Ge(Yt.filter(it=>it.kind==="audioinput")),ut(Yt.filter(it=>it.kind==="videoinput"))}catch(Yt){console.warn("[VideoRecorder] enumerateDevices failed",Yt)}};return Gs(),(Lr=(tr=navigator.mediaDevices).addEventListener)==null||Lr.call(tr,"devicechange",Gs),()=>{var Yt,it;return(it=(Yt=navigator.mediaDevices).removeEventListener)==null?void 0:it.call(Yt,"devicechange",Gs)}},[V]);const{canvasRef:ms,compositedStream:Dt,isLoading:It,isActive:qs,error:wt}=Rzn(u,$e),Us=_.useRef(n);Us.current=n;const Es=_.useCallback(Gs=>{F(Gs)},[]),kn=_.useRef(D),Sn=_.useCallback(()=>{E.current&&(cancelAnimationFrame(E.current),E.current=null),P.current&&(P.current.terminate(),P.current=null),S.current&&(S.current.getTracks().forEach(Gs=>Gs.stop()),S.current=null),M.current&&(M.current.getTracks().forEach(Gs=>Gs.stop()),M.current=null),I.current&&(I.current.srcObject=null,I.current=null)},[]),bn=_.useCallback(async()=>{var Gs;try{const an=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});S.current=an;let tr=null;try{tr=await navigator.mediaDevices.getUserMedia({video:zt?{deviceId:{exact:zt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Lr=null;try{Lr=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...lt?{deviceId:{exact:lt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Lr.getAudioTracks().map(Kr=>Kr.label))}catch(Kr){console.warn("[VideoRecorder] No mic audio for screen recording",Kr);try{Lr=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Yt=an.getVideoTracks()[0],it=Yt.getSettings(),gt=it.width||1920,ft=it.height||1080,Lt=document.createElement("canvas");Lt.width=gt,Lt.height=ft,C.current=Lt;const Mt=Lt.getContext("2d");let Qt=null;tr&&(Qt=document.createElement("video"),Qt.srcObject=tr,Qt.muted=!0,Qt.playsInline=!0,Qt.autoplay=!0,await Qt.play(),I.current=Qt);const ks=document.createElement("video");ks.srcObject=an,ks.muted=!0,ks.playsInline=!0,ks.autoplay=!0,await ks.play();const gs=()=>{if(Mt.drawImage(ks,0,0,gt,ft),Qt&&Qt.readyState>=2){const Kr=Math.round(gt*.2),Tr=Math.round(Kr*(Qt.videoHeight/Qt.videoWidth||.75)),Hr=gt-Kr-20,Ba=ft-Tr-20,Ja=12;Mt.save(),Mt.beginPath(),Mt.moveTo(Hr+Ja,Ba),Mt.lineTo(Hr+Kr-Ja,Ba),Mt.quadraticCurveTo(Hr+Kr,Ba,Hr+Kr,Ba+Ja),Mt.lineTo(Hr+Kr,Ba+Tr-Ja),Mt.quadraticCurveTo(Hr+Kr,Ba+Tr,Hr+Kr-Ja,Ba+Tr),Mt.lineTo(Hr+Ja,Ba+Tr),Mt.quadraticCurveTo(Hr,Ba+Tr,Hr,Ba+Tr-Ja),Mt.lineTo(Hr,Ba+Ja),Mt.quadraticCurveTo(Hr,Ba,Hr+Ja,Ba),Mt.closePath(),Mt.clip(),Mt.translate(Hr+Kr,Ba),Mt.scale(-1,1),Mt.drawImage(Qt,0,0,Kr,Tr),Mt.restore(),Mt.strokeStyle="rgba(255,255,255,0.6)",Mt.lineWidth=2,Mt.beginPath(),Mt.moveTo(Hr+Ja,Ba),Mt.lineTo(Hr+Kr-Ja,Ba),Mt.quadraticCurveTo(Hr+Kr,Ba,Hr+Kr,Ba+Ja),Mt.lineTo(Hr+Kr,Ba+Tr-Ja),Mt.quadraticCurveTo(Hr+Kr,Ba+Tr,Hr+Kr-Ja,Ba+Tr),Mt.lineTo(Hr+Ja,Ba+Tr),Mt.quadraticCurveTo(Hr,Ba+Tr,Hr,Ba+Tr-Ja),Mt.lineTo(Hr,Ba+Ja),Mt.quadraticCurveTo(Hr,Ba,Hr+Ja,Ba),Mt.closePath(),Mt.stroke()}},Vt="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}}",Vs=new Blob([Vt],{type:"application/javascript"}),Zs=new Worker(URL.createObjectURL(Vs));P.current=Zs,Zs.onmessage=()=>gs(),Zs.postMessage({type:"start",fps:30}),gs();const Zn=Lt.captureStream(30),Or=[],oa=an.getAudioTracks();oa.length&&Or.push(...oa),Lr&&Or.push(...Lr.getAudioTracks());const aa=new MediaStream([...Zn.getVideoTracks(),...Or]);return M.current=aa,Yt.onended=()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),Sn()},aa}catch(an){return console.error("[VideoRecorder] Screen capture error:",an),an.name!=="NotAllowedError"&&((Gs=Us.current)==null||Gs.call(Us,"Failed to start screen capture: "+(an.message||"Unknown error"))),null}},[Sn]),cr=_.useCallback(async()=>{var an,tr;G(!0),Ae(null);const Gs=y&&D;console.log("[VideoRecorder] initCamera start",{isMobile:y,usePortraitMode:D,shouldBePortrait:Gs,facingMode:he});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");d.current&&(console.log("[VideoRecorder] stopping existing stream"),d.current.getTracks().forEach(Mt=>Mt.stop()));const Lr=y&&Gs?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Yt=zt?{...Lr,deviceId:{exact:zt}}:{...Lr,facingMode:{ideal:he}},it={echoCancellation:!0,noiseSuppression:!0,...lt?{deviceId:{exact:lt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Yt);const gt=await navigator.mediaDevices.getUserMedia({video:Yt,audio:it});if(console.log("[VideoRecorder] getUserMedia success"),gt.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");d.current=gt,h(gt),H(!0);const Lt=gt.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",Lt.width,"x",Lt.height),o.current){const Mt=o.current;Mt.srcObject=gt,Mt.muted=!0,Mt.playsInline=!0,Mt.autoplay=!0,Mt.setAttribute("muted",""),Mt.setAttribute("playsinline",""),Mt.setAttribute("autoplay","");try{(an=Mt.load)==null||an.call(Mt)}catch(ks){console.warn("[VideoRecorder] videoEl.load failed",ks)}const Qt=async()=>{try{return await Mt.play(),console.log("[VideoRecorder] preview play ok"),We(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Mt.readyState,videoWidth:Mt.videoWidth,videoHeight:Mt.videoHeight})},300),!0}catch(ks){return console.warn("[VideoRecorder] preview play blocked",ks),We(!0),!1}};await new Promise(ks=>{let gs=!1;const Vt=()=>{gs||(gs=!0,ks())},Vs=()=>{Qt().finally(Vt)};Mt.onloadedmetadata=Vs,Mt.onloadeddata=Vs,setTimeout(Vt,1500)})}try{f.current=new AudioContext;const Mt=f.current.createMediaStreamSource(gt);g.current=f.current.createAnalyser(),g.current.fftSize=256,Mt.connect(g.current);const Qt=()=>{if(g.current){const ks=new Uint8Array(g.current.frequencyBinCount);g.current.getByteFrequencyData(ks);const gs=ks.reduce((Vt,Vs)=>Vt+Vs)/ks.length;Ne(Math.min(100,gs/128*100))}v.current=requestAnimationFrame(Qt)};Qt()}catch(Mt){console.warn("Audio context not available:",Mt)}}catch(Lr){console.error("Camera initialization error:",Lr),H(!1);let Yt="Failed to access camera or microphone.";Lr.name==="NotAllowedError"?Yt="Camera permission denied. Please allow camera access in your browser settings.":Lr.name==="NotFoundError"?Yt="No camera found. Please connect a camera and try again.":Lr.name==="NotReadableError"?Yt="Camera is in use by another application. Please close other apps using the camera.":Lr.message&&(Yt=Lr.message),Ae(Yt),(tr=Us.current)==null||tr.call(Us,Yt)}finally{G(!1)}},[he,y,D,lt,zt]);_.useEffect(()=>{kn.current!==D&&V&&!K&&!te&&(kn.current=D,cr())},[D,V,K,te,cr]),_.useEffect(()=>(cr(),()=>{d.current&&d.current.getTracks().forEach(Gs=>Gs.stop()),p.current&&clearInterval(p.current),v.current&&cancelAnimationFrame(v.current),f.current&&f.current.close(),Ze.current&&clearInterval(Ze.current),te&&URL.revokeObjectURL(te),Sn()}),[cr,te]),_.useEffect(()=>{if(q||V!==!0||te)return;const Gs=d.current,an=o.current;!Gs||!an||qs||(an.srcObject!==Gs&&(an.srcObject=Gs,an.muted=!0,an.playsInline=!0,an.autoplay=!0,an.setAttribute("muted",""),an.setAttribute("playsinline",""),an.setAttribute("autoplay","")),an.play().then(()=>We(!1)).catch(tr=>{We(!0),console.warn("Live preview play blocked on mount:",tr)}))},[V,q,te,qs]),_.useEffect(()=>{r==null||r(K)},[K,r]);const Fs=_.useCallback(async()=>{if(te)return;const Gs=o.current;if(Gs)try{await Gs.play(),We(!1)}catch(an){We(!0),console.warn("Live preview still blocked (needs user gesture):",an)}},[te]),cn=_.useCallback(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),p.current&&(clearInterval(p.current),p.current=null),Sn(),Z(!1),re(!1)},[Sn]),lr=_.useCallback(async()=>{let Gs=null;if(b==="screen"){if(Gs=await bn(),!Gs)return}else Gs=qs&&Dt?Dt:d.current;if(!Gs)return;Fs(),m.current=[],me(0);const tr=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Yt=>MediaRecorder.isTypeSupported(Yt)),Lr=new MediaRecorder(Gs,tr?{mimeType:tr,videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3}:{videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3});Lr.ondataavailable=Yt=>{Yt.data.size>0&&m.current.push(Yt.data)},Lr.onstop=()=>{var ft;const Yt=Lr.mimeType||tr||((ft=m.current[0])==null?void 0:ft.type)||"video/webm",it=new Blob(m.current,{type:Yt});J(it);const gt=URL.createObjectURL(it);ce(gt)},c.current=Lr,Lr.start(1e3),Z(!0),p.current=setInterval(()=>{me(Yt=>Yt>=s-1?(cn(),s):Yt+1)},1e3)},[Fs,s,cn,qs,Dt,b,bn]),Tn=_.useCallback(()=>{Ze.current&&(clearInterval(Ze.current),Ze.current=null),Be(3);let Gs=3;Ze.current=setInterval(()=>{Gs-=1,Gs<=0?(Ze.current&&clearInterval(Ze.current),Ze.current=null,Be(null),lr()):Be(Gs)},1e3)},[lr]),Yn=_.useCallback(()=>{c.current&&c.current.state==="recording"&&(c.current.pause(),re(!0),p.current&&clearInterval(p.current))},[]),fs=_.useCallback(()=>{c.current&&c.current.state==="paused"&&(c.current.resume(),re(!1),p.current=setInterval(()=>{me(Gs=>Gs>=s-1?(cn(),s):Gs+1)},1e3))},[s,cn]),wn=_.useCallback(()=>{te&&URL.revokeObjectURL(te),J(null),ce(null),me(0),Oe(!1),Ve(!0),o.current&&d.current&&!qs&&(o.current.srcObject=d.current,o.current.muted=!0,Fs())},[Fs,te,qs]),As=_.useCallback(()=>{ge(Gs=>Gs==="user"?"environment":"user")},[]),Ss=_.useCallback(()=>{ae&&t(ae,ve)},[ae,ve,t]),pr=_.useCallback(()=>{o.current&&te&&(Pe?o.current.pause():(Ve(!1),o.current.muted=!1,o.current.play()),Oe(!Pe))},[te,Pe]);_.useEffect(()=>{if(!te)return;const Gs=o.current;if(!Gs)return;Ve(!1),Gs.pause(),Gs.removeAttribute("src"),Gs.srcObject=null,Gs.load(),Gs.src=te,Gs.currentTime=0,Gs.playsInline=!0,Gs.muted=!1,Gs.onended=()=>Oe(!1);const an=()=>{var Yt;const tr=Gs.error,Lr=tr?`Recorded video failed to play (code ${tr.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",tr),(Yt=Us.current)==null||Yt.call(Us,Lr)};return Gs.addEventListener("error",an),Gs.load(),()=>{Gs.removeEventListener("error",an)}},[te]);const hn=Gs=>{const an=Math.floor(Gs/60),tr=Gs%60;return`${an}:${tr.toString().padStart(2,"0")}`},Pn=b==="screen"?"aspect-video":y&&D?"aspect-[9/16]":"aspect-video";return q?e.jsx("div",{className:Ct("flex items-center justify-center bg-black rounded-lg",Pn,i),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(bt,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):V===!1?e.jsx("div",{className:Ct("flex items-center justify-center bg-black rounded-lg",Pn,i),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Ho,{className:"h-12 w-12 mx-auto mb-4 text-destructive"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Camera Access Required"}),e.jsx("p",{className:"text-gray-400 mb-4 text-sm",children:_e||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(z,{onClick:()=>cr(),variant:"secondary",className:"w-full",children:[e.jsx(Gi,{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:Ct("flex flex-col gap-2",i),children:[!K&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(z,{variant:b==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("camera"),children:[e.jsx(Lx,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(z,{variant:b==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("screen"),children:[e.jsx(m7,{className:"h-4 w-4"}),"Screen"]})]}),a&&b==="camera"&&!K&&!te&&e.jsx(W7n,{value:$e,onChange:Xe,isLoading:It,disabled:K}),!K&&!te&&(nt.length>0||Je.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[nt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(h7,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ls,{value:lt||"default",onValueChange:Gs=>qt(Gs==="default"?"":Gs),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(cs,{placeholder:"Default microphone"})}),e.jsxs(as,{children:[e.jsx(He,{value:"default",children:"Default microphone"}),nt.map(Gs=>e.jsx(He,{value:Gs.deviceId,children:Gs.label||`Microphone ${Gs.deviceId.slice(0,6)}`},Gs.deviceId))]})]})]}),Je.length>1&&b==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Lx,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ls,{value:zt||"default",onValueChange:Gs=>Zt(Gs==="default"?"":Gs),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(cs,{placeholder:"Default camera"})}),e.jsxs(as,{children:[e.jsx(He,{value:"default",children:"Default camera"}),Je.map(Gs=>e.jsx(He,{value:Gs.deviceId,children:Gs.label||`Camera ${Gs.deviceId.slice(0,6)}`},Gs.deviceId))]})]})]})]}),b==="camera"&&y&&!K&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(yN,{className:Ct("h-4 w-4",D?"text-muted-foreground":"text-primary")}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(mn,{id:"orientation-toggle",checked:D,onCheckedChange:Es}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(p1,{className:Ct("h-4 w-4",D?"text-primary":"text-muted-foreground")})]}),b==="screen"&&!K&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 px-4 bg-muted/50 rounded-lg text-sm text-muted-foreground",children:[e.jsx(m7,{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:Ct("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Fs()},children:[e.jsx("video",{ref:o,src:te??void 0,className:Ct("w-full bg-black",D&&!te?"object-contain":"object-cover",Pn,!te&&he==="user"!==($e.mirror??!1)&&"scale-x-[-1]",qs&&!te&&"hidden"),playsInline:!0,controls:!!te,muted:te?ke:!0,autoPlay:!te},te??"live"),qs&&!te&&e.jsx("canvas",{ref:ms,className:Ct("w-full bg-black",D?"object-contain":"object-cover",Pn,he==="user"!==($e.mirror??!1)&&"scale-x-[-1]")}),qs&&It&&!te&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60 z-20",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(bt,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!te&&Se&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(z,{type:"button",variant:"secondary",onClick:()=>void Fs(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),l&&!te&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:l}),qe!==null&&!te&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:qe},qe),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),K&&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:Ct("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:[hn(ve)," / ",hn(s)]})]}),K&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Di,{value:ve/s*100,className:"h-1 rounded-none"})}),!te&&e.jsxs("div",{className:"absolute bottom-20 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx(h7,{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:te?e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:wn,children:[e.jsx(Gi,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(z,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:pr,children:Pe?e.jsx(S0,{className:"h-5 w-5"}):e.jsx(su,{className:"h-5 w-5"})}),e.jsxs(z,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Ss,children:[e.jsx(Wr,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[b==="camera"?e.jsx(z,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:As,disabled:K||qe!==null,children:e.jsx(Dx,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!K&&qe===null?e.jsx(z,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:b==="screen"?lr:Tn,children:b==="screen"?e.jsx(m7,{className:"h-6 w-6"}):e.jsx(Xr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(z,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:oe?fs:Yn,children:oe?e.jsx(su,{className:"h-5 w-5"}):e.jsx(S0,{className:"h-5 w-5"})}),e.jsx(z,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:cn,children:e.jsx(jb,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function Fzn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=hs(),{toast:a}=_i(),[i,l]=_.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:m}=await U.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:p,error:f}=await U.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(f||!(p!=null&&p.signedUrl))throw f||new Error("Could not sign video URL");n(p.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(Is,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Rs,{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(bt,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(YE,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function Ozn({value:s,onChange:t}){const{user:n}=hs(),[r,a]=_.useState(!1);return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Xr,{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(Le,{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(er,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(su,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pz,{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(z,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(Xr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(Fzn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function tS(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function zzn({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=_.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});_.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:tS(i.bedrooms),bathrooms:tS(i.bathrooms),sqft:tS(i.sqft),yearBuilt:tS(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{className:"text-xs",children:"Beds"}),e.jsx(pe,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Baths"}),e.jsx(pe,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Sq Ft"}),e.jsx(pe,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Year Built"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Property Type"}),e.jsx(pe,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subtype"}),e.jsx(pe,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs(z,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(bt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Bo,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function Bzn({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=_.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});_.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=tS(a.price),c=tS(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:tS(a.bedrooms),bathrooms:tS(a.bathrooms),sqft:c,yearBuilt:tS(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{className:"text-xs",children:"Address"}),e.jsx(pe,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"City"}),e.jsx(pe,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"State"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Status"}),e.jsx(pe,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Price"}),e.jsx(pe,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Sq Ft"}),e.jsx(pe,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Beds"}),e.jsx(pe,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Baths"}),e.jsx(pe,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Year Built"}),e.jsx(pe,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs(z,{className:"w-full",onClick:l,disabled:!a.address.trim()||!tS(a.price)||!tS(a.sqft),children:[e.jsx(sn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function $zn(){var he,ge,Ee,Ne,Pe,Oe,ke;const{id:s}=Mi(),t=zn(),{toast:n}=_i(),{data:r,isLoading:a}=zOn(s),{data:i}=BOn(s),l=$On(),o=VOn(),c=HOn(),{leadSite:d,isLoading:u}=mf(),[h,m]=_.useState([]),[p,f]=_.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[g,v]=_.useState(null),[y,b]=_.useState(!1),[w,S]=_.useState({low:"",likely:"",high:"",note:""}),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[F,q]=_.useState(null),G=async Ve=>{var Be,Ze;if(!r||!(Ve!=null&&Ve.address)||!(Ve!=null&&Ve.city)||!(Ve!=null&&Ve.state))return Ve;let _e={...Ve};const Ae=async $e=>{const{data:Xe,error:nt}=await U.functions.invoke("cma-subject-lookup",{body:{address:$e.address,city:$e.city,state:$e.state,zip:$e.zip,latitude:$e.latitude,longitude:$e.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(nt)throw nt;return(Xe==null?void 0:Xe.matches)||[]},Se=$e=>{const nt=$e.find(lt=>Number.isFinite(Number(lt.latitude))&&Number.isFinite(Number(lt.longitude)))||$e[0];if(!nt)return;const Ge=typeof nt.match_type=="string"&&nt.match_type.startsWith("nearby-"),Je=Ge&&Number.isFinite(Number(_e.latitude))&&Number.isFinite(Number(_e.longitude)),ut=lt=>nt[lt]!==void 0&&nt[lt]!==null&&nt[lt]!==""&&nt[lt]!==0?nt[lt]:_e[lt];_e={..._e,bedrooms:ut("bedrooms"),bathrooms:ut("bathrooms"),sqft:ut("sqft"),yearBuilt:ut("yearBuilt"),lotSize:ut("lotSize"),propertyType:ut("propertyType"),propertySubType:ut("propertySubType"),source_provider:nt.source_provider??_e.source_provider,match_type:nt.match_type??_e.match_type,matched_mls_address:Ge?nt.address:_e.matched_mls_address,latitude:Je?_e.latitude:nt.latitude??_e.latitude,longitude:Je?_e.longitude:nt.longitude??_e.longitude,mlsNumber:Ge?_e.mlsNumber:nt.mlsNumber??_e.mlsNumber,photos:!Ge&&Array.isArray(nt.photos)&&nt.photos.length?nt.photos:_e.photos}};Se(await Ae(_e));const We=()=>Number.isFinite(Number(_e.latitude))&&Number.isFinite(Number(_e.longitude));if(!We()){const{data:$e}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),Xe=$e==null?void 0:$e.value;if(Xe){const nt=encodeURIComponent(`${_e.address}, ${_e.city}, ${_e.state} ${_e.zip||""}`.trim()),Je=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${nt}.json?access_token=${Xe}&limit=1&country=us`)).json(),ut=(Ze=(Be=Je==null?void 0:Je.features)==null?void 0:Be[0])==null?void 0:Ze.center;Array.isArray(ut)&&ut.length===2&&(_e.longitude=ut[0],_e.latitude=ut[1])}}if((!_e.bedrooms||!_e.bathrooms||!_e.sqft||!_e.yearBuilt)&&We())try{Se(await Ae(_e))}catch($e){console.warn("second-pass subject lookup failed",$e)}return JSON.stringify(_e)!==JSON.stringify(Ve)&&await l.mutateAsync({id:r.id,patch:{subject:_e}}),_e};_.useEffect(()=>{var Ae,Se;r!=null&&r.settings&&f({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ve=(Ae=r==null?void 0:r.settings)==null?void 0:Ae.priceOverride;Ve!=null&&Ve.enabled&&(b(!0),S({low:Ve.low!=null?String(Ve.low):"",likely:Ve.likely!=null?String(Ve.likely):"",high:Ve.high!=null?String(Ve.high):"",note:Ve.note??""}));const _e=(Se=r==null?void 0:r.settings)==null?void 0:Se.personalVideo;_e!=null&&_e.url&&q({url:_e.url,thumb:_e.thumb,label:_e.label})},[r==null?void 0:r.id]);const V=_.useRef(!1);_.useEffect(()=>{V.current||i!=null&&i.length&&(m(i.map(Ve=>({...Ve.snapshot,selected:Ve.selected,manual:Ve.manual,score:Ve.score}))),V.current=!0)},[i]);const H=_.useRef(null);_.useEffect(()=>{if(!r||u)return;const Ve=r.subject||{},_e=Number.isFinite(Number(Ve.latitude))&&Number.isFinite(Number(Ve.longitude)),Ae=!!(Number(Ve.bedrooms)||Number(Ve.bathrooms)||Number(Ve.sqft)||Number(Ve.yearBuilt));if(_e&&Ae)return;const Se=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;H.current!==Se&&(!Ve.address||!Ve.city||!Ve.state||(H.current=Se,(async()=>{try{await G(Ve)}catch(We){console.warn("subject enrich failed",We)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const K=_.useMemo(()=>r?J2t(r.subject,h):null,[r,h]),Z=async()=>{if(r)try{const Ve=await G(r.subject),_e=await o.mutateAsync({subject:Ve,filters:p,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(_e.comps.map(Ae=>({...Ae,selected:!0})).slice(0,12)),n({title:`Found ${_e.comps.length} comps`,description:`Top ${Math.min(12,_e.comps.length)} auto-selected.`})}catch(Ve){n({title:"Search failed",description:Ve.message,variant:"destructive"})}},oe=Ve=>{m(_e=>_e.map((Ae,Se)=>Se===Ve?{...Ae,selected:!Ae.selected}:Ae))},re=Ve=>{m(_e=>_e.filter((Ae,Se)=>Se!==Ve))},ae=async Ve=>{if(!r)return;const _e=Object.fromEntries(Object.entries(Ve).filter(([,Se])=>Se!=null&&Se!=="")),Ae={...r.subject,..._e,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Ae}}),n({title:"Subject details saved",description:Ae.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},J=Ve=>{m(_e=>[{...Ve,selected:!0,manual:!0},..._e]),n({title:"Manual comp added"})},te=async(Ve=!1)=>{if(!r)return;const _e=J2t(r.subject,h),Ae=Ze=>{const $e=Number(String(Ze).replace(/[^0-9.]/g,""));return Number.isFinite($e)&&$e>0?Math.round($e):null},Se=y?Ae(w.likely):null,We=y?Ae(w.low):null,qe=y?Ae(w.high):null,Be=y&&Se;await l.mutateAsync({id:r.id,patch:{settings:{...p,priceOverride:{enabled:y,low:We,likely:Se,high:qe,note:w.note||null},personalVideo:F},price_low:Be?We??Se:_e.low??null,price_likely:Be?Se:_e.likely??null,price_high:Be?qe??Se:_e.high??null,status:Ve?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ve?"CMA published":"CMA saved"})},ce=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx($s,{children:e.jsx("div",{className:"p-6",children:e.jsx(bt,{className:"w-6 h-6 animate-spin"})})});const ve=h.filter(Ve=>Ve.selected).length,me=!((he=r.subject)!=null&&he.bedrooms)||!((ge=r.subject)!=null&&ge.bathrooms)||!((Ee=r.subject)!=null&&Ee.sqft)||!((Ne=r.subject)!=null&&Ne.yearBuilt);return e.jsx($s,{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(z,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(ka,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>te(!1),disabled:l.isPending,children:[e.jsx(Bo,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(z,{onClick:()=>te(!0),disabled:l.isPending,children:[e.jsx(sd,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(ce),n({title:"Link copied"})},children:[e.jsx(mr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(z,{onClick:()=>E(!0),children:[e.jsx(on,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Subject Property"})}),e.jsxs(Le,{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:"})," ",((Pe=r.subject.sqft)==null?void 0:Pe.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),me&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs(z,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>M(!0),children:[e.jsx(Wa,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!me&&e.jsxs(z,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>M(!0),children:[e.jsx(Wa,{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(ee,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(pe,{type:"number",defaultValue:"",onBlur:async Ve=>{const _e=Number(Ve.target.value);_e>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:_e}}})}})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(pj,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Le,{className:"space-y-3",children:[K!=null&&K.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(y&&Number(w.likely)>0?Number(w.likely):K.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Oe=K.low)==null?void 0:Oe.toLocaleString()," – $",(ke=K.high)==null?void 0:ke.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",K.ppsf,"/sqft median · ",ve," 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(ee,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(mn,{id:"override-toggle",checked:y,onCheckedChange:b})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"My suggested price"}),e.jsx(pe,{type:"number",placeholder:"e.g. 750000",value:w.likely,onChange:Ve=>S(_e=>({..._e,likely:Ve.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Range low"}),e.jsx(pe,{type:"number",placeholder:"optional",value:w.low,onChange:Ve=>S(_e=>({..._e,low:Ve.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Range high"}),e.jsx(pe,{type:"number",placeholder:"optional",value:w.high,onChange:Ve=>S(_e=>({..._e,high:Ve.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ps,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:w.note,onChange:Ve=>S(_e=>({..._e,note:Ve.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(Ozn,{value:F,onChange:q}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Filters"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(p.sqftPct*100),"%"]}),e.jsx(Mx,{value:[p.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ve])=>f(_e=>({..._e,sqftPct:Ve/100}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Search radius: ",p.maxMiles," mi"]}),e.jsx(Mx,{value:[p.maxMiles],min:1,max:25,step:1,onValueChange:([Ve])=>f(_e=>({..._e,maxMiles:Ve}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Sold within: ",p.monthsBack," months"]}),e.jsx(Mx,{value:[p.monthsBack],min:1,max:24,step:1,onValueChange:([Ve])=>f(_e=>({..._e,monthsBack:Ve}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ve=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(za,{checked:p.statuses.includes(Ve),onCheckedChange:_e=>f(Ae=>({...Ae,statuses:_e?[...Ae.statuses,Ve]:Ae.statuses.filter(Se=>Se!==Ve)}))})," ",Ve]},Ve))]}),e.jsxs(z,{className:"w-full",onClick:Z,disabled:o.isPending,children:[o.isPending?e.jsx(bt,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(un,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(z,{variant:"outline",className:"w-full",onClick:()=>D(!0),children:[e.jsx(sn,{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(H7n,{subject:r.subject,comps:h,radiusMiles:p.maxMiles,onMarkerClick:Ve=>v(Ve)}),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:[ve," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ve,_e)=>{var Ae;return e.jsx(be,{className:Ve.selected?"":"opacity-50",children:e.jsxs(Le,{className:"p-3 flex gap-3 items-center",children:[e.jsx(za,{checked:Ve.selected,onCheckedChange:()=>oe(_e)}),e.jsxs("button",{type:"button",onClick:()=>v(_e),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(RAe,{photos:Ve.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:Ve.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ve.city,", ",Ve.state," · ",Ve.bedrooms??"?","bd/",Ve.bathrooms??"?","ba · ",((Ae=Ve.sqft)==null?void 0:Ae.toLocaleString())??"?"," sqft",Ve.yearBuilt?` · ${Ve.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(ze,{variant:"outline",className:"mr-1",children:Ve.status}),Ve.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Ve.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Ve.soldPrice||Ve.price||0).toLocaleString()]}),Ve.sqft&&(Ve.soldPrice||Ve.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Ve.soldPrice||Ve.price)/Ve.sqft),"/sqft"]}):null]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>v(_e),title:"View details",children:e.jsx(xa,{className:"w-4 h-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>re(_e),title:"Remove",children:e.jsx(Cn,{className:"w-4 h-4"})})]})},_e)})}):e.jsx(be,{children:e.jsx(Le,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[me&&e.jsx(z,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>D(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(I9t,{comp:g!=null?h[g]:null,open:g!=null,onClose:()=>v(null)}),e.jsx(zzn,{open:P,onOpenChange:M,subject:r.subject,onSave:ae,isSaving:l.isPending}),e.jsx(Bzn,{open:I,onOpenChange:D,subject:r.subject,onAdd:J}),e.jsx(zZt,{open:C,onOpenChange:E,cma:r})]})})}const eL="listing-presentations";function VQt(){const{user:s}=hs(),t=$t(),n=rt({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.from("listing_presentation_saved_templates").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(c)throw c;return o}}),r=()=>t.invalidateQueries({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id]}),a=mt({mutationFn:async o=>{const{data:c,error:d}=await U.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ne.success("Template saved")},onError:o=>ne.error(o.message||"Could not save the template")}),i=mt({mutationFn:async({id:o,...c})=>{const{error:d}=await U.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ne.success("Template updated")},onError:o=>ne.error(o.message||"Could not update the template")}),l=mt({mutationFn:async o=>{const{error:c}=await U.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ne.success("Template deleted")},onError:o=>ne.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function Uzn(){return rt({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function HQt(){const{user:s}=hs(),t=$t(),n=rt({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await U.from("listing_presentations").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(d)throw d;return c}}),r=()=>t.invalidateQueries({queryKey:["listing-presentations",s==null?void 0:s.id]}),a=mt({mutationFn:async c=>{const{data:d,error:u}=await U.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>ne.error(c.message||"Could not create presentation")}),i=mt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await U.from("listing_presentations").update(d).eq("id",c).select().single();if(h)throw h;return u},onSuccess:c=>{r(),t.invalidateQueries({queryKey:["listing-presentation",c.id]})},onError:c=>ne.error(c.message||"Could not save presentation")}),l=mt({mutationFn:async c=>{let d=null;const{data:u,error:h}=await U.from("listing_presentations").insert({owner_user_id:s.id,title:`${c.title} (Copy)`,template_id:c.template_id,status:"draft",property_address_line1:c.property_address_line1,city:c.city,state:c.state,postal_code:c.postal_code,list_price:c.list_price,beds:c.beds,baths:c.baths,sqft:c.sqft,agent_snapshot:c.agent_snapshot,co_agent:c.co_agent,custom_pages:c.custom_pages,services:c.services,page_settings:c.page_settings,photo_focal:c.photo_focal}).select().single();if(h)throw h;if(c.property_photo_path){d=`${s.id}/${u.id}/photo.jpg`;const{error:m}=await U.storage.from(eL).copy(c.property_photo_path,d);m||await U.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),ne.success("Presentation duplicated")},onError:c=>ne.error(c.message||"Could not duplicate")}),o=mt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await U.storage.from(eL).remove(d);const{error:u}=await U.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),ne.success("Presentation deleted")},onError:c=>ne.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function qzn(s){return rt({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function Vzn(s,t=3600){if(!s)return null;const{data:n,error:r}=await U.storage.from(eL).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const oKe={cover:{kicker:"A smarter launch for",headline:"",subhead:"",body:"A complete marketing plan designed to make your home stand out, reach more buyers, and create stronger interest."},welcome:{kicker:"The strategy",headline:"Your listing deserves more than a sign and an MLS entry.",subhead:"It deserves a coordinated launch that builds attention from day one.",body:""},agent:{kicker:"Your agent",headline:"Who you are working with.",subhead:"",body:""},overview:{kicker:"The plan",headline:"Every home gets listed. Very few get marketed.",subhead:"These are the steps we run on your home, in order, starting the day we sign.",body:""},closing:{kicker:"The commitment",headline:'Your home will never feel like "just another listing."',subhead:"",body:"It will be prepared carefully, presented professionally, launched strategically, and promoted with purpose — from the first photo to the final signature."}},Hzn={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function GQt(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=oKe[t],a=l=>{const o=n[l];return o??r[l]};return{kicker:a("kicker"),headline:a("headline"),subhead:a("subhead"),body:a("body")}}const WQt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function KQt(s){return{...WQt,...s||{}}}const Dze=[{layout:"story",name:"Story + photo",description:'Editorial two-column story next to a full-height photo. Great for "About Us".'},{layout:"testimonials",name:"Testimonial cards",description:'Up to four pull-quote cards. Great for "What Others Are Saying".'},{layout:"stats",name:"Numbers band",description:"Big stat tiles with a short lead paragraph. Great for a track record page."},{layout:"checklist",name:"Checklist",description:"Headline, intro copy, and an accent-marked list of promises or steps."},{layout:"statement",name:"Full-bleed statement",description:"A dark, photo-backed page with one powerful line. Great for a section break."}],YQt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function Qrt(s,t=0){const n={id:YQt(),layout:s,enabled:!0,order:t,placement:"after-agent",kicker:"",headline:"",subhead:"",body:"",bullets:[],testimonials:[],stats:[],imageUrl:null,imageSide:"right",dark:!1};switch(s){case"story":return{...n,kicker:"About us",headline:"A team built around one thing: your move.",subhead:"Who we are, how we work, and why sellers keep referring us.",body:"Share your background, your team, and what a seller can expect when they work with you. Two or three short paragraphs is the sweet spot — enough to build trust without turning the page into a resume."};case"testimonials":return{...n,kicker:"What others are saying",headline:"The people we have already moved.",subhead:"Real words from recent sellers and buyers.",testimonials:[{quote:"Add a real client quote here.",name:"Client name",detail:"Neighborhood or year"},{quote:"Add a second client quote here.",name:"Client name",detail:"Neighborhood or year"}]};case"stats":return{...n,kicker:"Track record",headline:"The numbers behind the plan.",body:"Add only numbers you can stand behind — sellers notice when the math is real.",stats:[{value:"",label:"Homes sold"},{value:"",label:"Avg. days on market"},{value:"",label:"List-to-sale price"}]};case"checklist":return{...n,kicker:"Our promise",headline:"What you can count on from us.",body:"A short intro to the list below.",bullets:["Add a promise, step, or service here","Add another line","Add another line"]};case"statement":return{...n,dark:!0,kicker:"Our approach",headline:"Every home has a story. We make sure buyers hear it.",body:""};default:return n}}function ZQt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...Qrt(t.layout||"story",n),...t,id:t.id||YQt(),order:typeof t.order=="number"?t.order:n,bullets:Array.isArray(t.bullets)?t.bullets:[],testimonials:Array.isArray(t.testimonials)?t.testimonials:[],stats:Array.isArray(t.stats)?t.stats:[]})).sort((t,n)=>t.order-n.order):[]}const lKe={hidden:["overview"]},cKe={x:.5,y:.5},_d=(s,t,n=!0)=>({key:s,label:t,enabled:n}),a6e=[{key:"photography",title:"Professional Photography",body:"Your home is photographed by a professional real estate photographer — HDR interiors, crisp exteriors, and the detail shots that make buyers stop scrolling. Every image is color-corrected and delivered ready for print and every portal.",enabled:!0,order:0,options:[_d("hdr","Full HDR interior and exterior photo set"),_d("drone","Aerial drone photography of the home and lot"),_d("twilight","Twilight exterior session for the hero image"),_d("staging","Virtual staging for vacant or transitional rooms",!1),_d("floorplan","Measured floor plan buyers can explore")]},{key:"video",title:"Video That Sells the Feeling",body:"Photos show the rooms. Video shows the life. We produce a cinematic walkthrough plus short-form vertical cuts built specifically for how buyers actually watch — on their phone, in the first ten seconds.",enabled:!0,order:1,options:[_d("walkthrough","Cinematic full-property walkthrough video"),_d("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),_d("oncamera","On-camera agent introduction to the home"),_d("neighborhood","Neighborhood and lifestyle b-roll")]},{key:"mls",title:"MLS Launch & Pricing Strategy",body:"We launch on the MLS with a carefully written description, complete data fields, and a pricing strategy built around live comparable activity — positioning your home to attract the strongest possible offers in the first two weeks.",enabled:!0,order:2,options:[_d("data","Complete, accurate MLS data so your home shows in every filter"),_d("copy","Copywriting that leads with the features buyers pay for"),_d("pricing","Pricing built on live comparable and absorption data"),_d("comingsoon","Coming-soon window to build demand before day one")]},{key:"syndication",title:"Maximum Exposure & Portal Distribution",body:"Your listing is pushed to the sites buyers already live on, with the data monitored so your photos, price, and details stay accurate everywhere they appear.",enabled:!0,order:3,options:[_d("zillow","Zillow — the highest-traffic buyer search portal"),_d("realtor","Realtor.com — direct MLS-sourced listing feed"),_d("homes","Homes.com — agent-attributed listing exposure"),_d("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),_d("routing","Buyer inquiries routed straight to me and answered fast")]},{key:"website",title:"Dedicated Property Website",body:"Your home gets its own single-property website with the full photo gallery, video, floor plan, neighborhood details, and a direct inquiry form — a link we can share in every ad, email, and social post.",enabled:!0,order:4,options:[_d("gallery","Full-screen gallery, video, and floor plan in one place"),_d("mobile","Mobile-first design with a one-tap inquiry form"),_d("link","Shareable link used across ads, email, and QR signage"),_d("traffic","Traffic tracked and reported back to you")]},{key:"social",title:"Social Media Campaign",body:"A launch that looks like a campaign, not a post. Organic content across my channels plus targeted paid placement aimed at qualified buyers and the agents who represent them.",enabled:!0,order:5,options:[_d("organic","Just-listed launch across feed, stories, and reels"),_d("ads","Geo-targeted paid campaigns aimed at active buyers"),_d("retarget","Retargeting so interested viewers keep seeing your home"),_d("agentsocial","Agent-to-agent promotion inside local networks")]},{key:"email",title:"Email, Database & Agent Outreach",body:"The fastest buyer is often already in someone’s database. Your listing goes directly to my buyers, past clients, and referral partners — and to the agents actively working your price range.",enabled:!0,order:6,options:[_d("database","Direct email to my buyer and past-client database"),_d("agents","Broadcast to area agents with matching buyers"),_d("referral","Referral partner network notified at launch"),_d("followup","Follow-up sequence to everyone who engages")]},{key:"openhouse",title:"Open Houses & Neighborhood Marketing",body:"Neighbors sell neighborhoods. We combine well-timed open houses with the local marketing that reaches the people most likely to know your next buyer.",enabled:!0,order:7,options:[_d("public","Strategically timed public open houses"),_d("broker","Broker open house for agents with active buyers"),_d("signin","Digital sign-in that captures every visitor"),_d("neighbors","Neighbor invitations and just-listed mailers"),_d("signage","Premium signage, riders, and directional placement")]},{key:"communication",title:"Communication & Weekly Reporting",body:"You will never wonder what is happening. You get a regular seller report with showing feedback, online traffic numbers, and market shifts, plus direct access to me by call, text, or email.",enabled:!0,order:8,options:[_d("weekly","Weekly seller report on the schedule you prefer"),_d("feedback","Showing feedback delivered as it comes in"),_d("analytics","Online traffic and engagement analytics"),_d("access","Direct access to me by call, text, or email")]}],Gzn=Object.fromEntries(a6e.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function dKe(s){return s!=null&&s.length?a6e.map(t=>{var a;const n=s.find(i=>i.key===t.key);if(!n)return{...t,options:(a=t.options)==null?void 0:a.map(i=>({...i}))};const r=(t.options||[]).map(i=>{var o;const l=(o=n.options)==null?void 0:o.find(c=>c.key===i.key);return l?{...i,enabled:l.enabled}:{...i}});return{...t,title:n.title||t.title,body:n.body||t.body,enabled:n.enabled,order:t.order,options:r}}):a6e.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const Wzn={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Vh(s){"@babel/helpers - typeof";return Vh=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},Vh(s)}var RS=Uint8Array,oj=Uint16Array,Jrt=Int32Array,eat=new RS([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]),tat=new RS([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]),ckt=new RS([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),XQt=function(s,t){for(var n=new oj(31),r=0;r<31;++r)n[r]=t+=1<>1|(Tp&21845)<<1;DT=(DT&52428)>>2|(DT&13107)<<2,DT=(DT&61680)>>4|(DT&3855)<<4,hKe[Tp]=((DT&65280)>>8|(DT&255)<<8)>>1}var pee=function(s,t,n){for(var r=s.length,a=0,i=new oj(t);a>c]=d}else for(o=new oj(r),a=0;a>15-s[a]);return o},C9=new RS(288);for(var Tp=0;Tp<144;++Tp)C9[Tp]=8;for(var Tp=144;Tp<256;++Tp)C9[Tp]=9;for(var Tp=256;Tp<280;++Tp)C9[Tp]=7;for(var Tp=280;Tp<288;++Tp)C9[Tp]=8;var i6e=new RS(32);for(var Tp=0;Tp<32;++Tp)i6e[Tp]=5;var Zzn=pee(C9,9,0),Xzn=pee(i6e,5,0),JQt=function(s){return(s+7)/8|0},Qzn=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new RS(s.subarray(t,n))},C3=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},kZ=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8,s[r+2]|=n>>16},Rze=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var p=new oj(m+1),f=mKe(n[u-1],p,0);if(f>t){var r=0,g=0,v=f-t,y=1<t)g+=y-(1<>=v;g>0;){var w=i[r].s;p[w]=0&&g;--r){var S=i[r].s;p[S]==t&&(--p[S],++g)}f=t}return{t:new RS(p),l:f}},mKe=function(s,t,n){return s.s==-1?Math.max(mKe(s.l,t,n+1),mKe(s.r,t,n+1)):t[s.s]=n},ukt=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new oj(++t),r=0,a=s[0],i=1,l=function(c){n[r++]=c},o=1;o<=t;++o)if(s[o]==a&&o!=t)++i;else{if(!a&&i>2){for(;i>138;i-=138)l(32754);i>2&&(l(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(l(a),--i;i>6;i-=6)l(8304);i>2&&(l(i-3<<5|8208),i=0)}for(;i--;)l(a);i=1,a=s[o]}return{c:n.subarray(0,r),n:t}},SZ=function(s,t){for(var n=0,r=0;r>8,s[a+2]=s[a]^255,s[a+3]=s[a+1]^255;for(var i=0;i4&&!D[ckt[q-1]];--q);var G=d+5<<3,V=SZ(a,C9)+SZ(i,i6e)+l,H=SZ(a,m)+SZ(i,g)+l+14+3*q+SZ(P,D)+2*P[16]+3*P[17]+7*P[18];if(c>=0&&G<=V&&G<=H)return eJt(t,u,s.subarray(c,c+d));var K,Z,oe,re;if(C3(t,u,1+(H15&&(C3(t,u,ce[M]>>5&127),u+=ce[M]>>12)}}else K=Zzn,Z=C9,oe=Xzn,re=i6e;for(var M=0;M255){var ve=me>>18&31;kZ(t,u,K[ve+257]),u+=Z[ve+257],ve>7&&(C3(t,u,me>>23&31),u+=eat[ve]);var he=me&31;kZ(t,u,oe[he]),u+=re[he],he>3&&(kZ(t,u,me>>5&8191),u+=tat[he])}else kZ(t,u,K[me]),u+=Z[me]}return kZ(t,u,K[256]),u+Z[256]},Jzn=new Jrt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),tJt=new RS(0),eBn=function(s,t,n,r,a,i){var l=i.z||s.length,o=new RS(r+l+5*(1+Math.ceil(l/7e3))+a),c=o.subarray(r,o.length-a),d=i.l,u=(i.r||0)&7;if(t){u&&(c[0]=i.r>>3);for(var h=Jzn[t-1],m=h>>13,p=h&8191,f=(1<7e3||D>24576)&&(K>423||!d)){u=hkt(s,c,0,S,C,E,M,D,q,I-q,u),D=P=M=0,q=I;for(var Z=0;Z<286;++Z)C[Z]=0;for(var Z=0;Z<30;++Z)E[Z]=0}var oe=2,re=0,ae=p,J=V-H&32767;if(K>2&&G==w(I-J))for(var te=Math.min(m,K)-1,ce=Math.min(32767,I),ve=Math.min(258,K);J<=ce&&--ae&&V!=H;){if(s[I+oe]==s[I+oe-J]){for(var me=0;meoe){if(oe=me,re=J,me>te)break;for(var he=Math.min(J,me-2),ge=0,Z=0;Zge&&(ge=Pe,H=Ee)}}}V=H,H=g[V],J+=V-H&32767}if(re){S[D++]=268435456|uKe[oe]<<18|dkt[re];var Oe=uKe[oe]&31,ke=dkt[re]&31;M+=eat[Oe]+tat[ke],++C[257+Oe],++E[ke],F=I+oe,++P}else S[D++]=s[I],++C[s[I]]}}for(I=Math.max(I,F);I=l&&(c[u/8|0]=d,Ve=l),u=eJt(c,u+1,s.subarray(I,Ve))}i.i=l}return Qzn(o,0,r+JQt(u)+a)},sJt=function(){var s=1,t=0;return{p:function(n){for(var r=s,a=t,i=n.length|0,l=0;l!=i;){for(var o=Math.min(l+2655,i);l>16),a=(a&65535)+15*(a>>16)}s=r,t=a},d:function(){return s%=65521,t%=65521,(s&255)<<24|(s&65280)<<8|(t&255)<<8|t>>8}}},tBn=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new RS(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return eBn(s,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(s.length)))*1.5):20:12+t.mem,n,r,a)},nJt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},sBn=function(s,t){var n=t.level,r=n==0?0:n<6?1:n==9?3:2;if(s[0]=120,s[1]=r<<6|(t.dictionary&&32),s[1]|=31-(s[0]<<8|s[1])%31,t.dictionary){var a=sJt();a.p(t.dictionary),nJt(s,2,a.d())}};function pKe(s,t){t||(t={});var n=sJt();n.p(s);var r=tBn(s,t,t.dictionary?6:2,4);return sBn(r,t),nJt(r,r.length-4,n.d()),r}var nBn=typeof TextDecoder<"u"&&new TextDecoder,rBn=0;try{nBn.decode(tJt,{stream:!0}),rBn=1}catch{}function aBn(s){if(Array.isArray(s))return s}function iBn(s,t){var n=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(n!=null){var r,a,i,l,o=[],c=!0,d=!1;try{if(i=(n=n.call(s)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(o.push(r.value),o.length!==t);c=!0);}catch(u){d=!0,a=u}finally{try{if(!c&&n.return!=null&&(l=n.return(),Object(l)!==l))return}finally{if(d)throw a}}return o}}function mkt(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=Array(t);n{const s=new Uint8Array(4),t=new Uint32Array(s.buffer);return!((t[0]=1)&s[0])})(),Fze={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class sat{constructor(t=uBn,n={}){zr(this,"buffer");zr(this,"byteLength");zr(this,"byteOffset");zr(this,"length");zr(this,"offset");zr(this,"lastWrittenByte");zr(this,"littleEndian");zr(this,"_data");zr(this,"_mark");zr(this,"_marks");let r=!1;typeof t=="number"?t=new ArrayBuffer(t):(r=!0,this.lastWrittenByte=t.byteLength);const a=n.offset?n.offset>>>0:0,i=t.byteLength-a;let l=a;(ArrayBuffer.isView(t)||t instanceof sat)&&(t.byteLength!==t.buffer.byteLength&&(l=t.byteOffset+a),t=t.buffer),r?this.lastWrittenByte=i:this.lastWrittenByte=0,this.buffer=t,this.length=i,this.byteLength=i,this.byteOffset=l,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,l,i),this._mark=0,this._marks=[]}available(t=1){return this.offset+t<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(t=1){return this.offset+=t,this}back(t=1){return this.offset-=t,this}seek(t){return this.offset=t,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const t=this._marks.pop();if(t===void 0)throw new Error("Mark stack empty");return this.seek(t),this}rewind(){return this.offset=0,this}ensureAvailable(t=1){if(!this.available(t)){const r=(this.offset+t)*2,a=new Uint8Array(r);a.set(new Uint8Array(this.buffer)),this.buffer=a.buffer,this.length=r,this.byteLength=r,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(t=1){return this.readArray(t,"uint8")}readArray(t,n){const r=Fze[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===hBn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new Fze[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new Fze[n](i);return this.offset+=r,l}readInt16(){const t=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}readUint16(){const t=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,t}readInt32(){const t=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}readUint32(){const t=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat32(){const t=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat64(){const t=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}readBigInt64(){const t=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,t}readBigUint64(){const t=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,t}readChar(){return String.fromCharCode(this.readInt8())}readChars(t=1){let n="";for(let r=0;rthis.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */const mBn=4,xkt=0,gkt=1,pBn=2;function uK(s){let t=s.length;for(;--t>=0;)s[t]=0}const fBn=0,rJt=1,xBn=2,gBn=3,yBn=258,nat=29,Jae=256,Ase=Jae+1+nat,Wq=30,rat=19,aJt=2*Ase+1,OF=15,Oze=16,vBn=7,aat=256,iJt=16,oJt=17,lJt=18,fKe=new Uint8Array([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]),uCe=new Uint8Array([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]),bBn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),cJt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_Bn=512,sA=new Array((Ase+2)*2);uK(sA);const fee=new Array(Wq*2);uK(fee);const Ese=new Array(_Bn);uK(Ese);const Tse=new Array(yBn-gBn+1);uK(Tse);const iat=new Array(nat);uK(iat);const o6e=new Array(Wq);uK(o6e);function zze(s,t,n,r,a){this.static_tree=s,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=a,this.has_stree=s&&s.length}let dJt,uJt,hJt;function Bze(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}const mJt=s=>s<256?Ese[s]:Ese[256+(s>>>7)],Mse=(s,t)=>{s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255},E_=(s,t,n)=>{s.bi_valid>Oze-n?(s.bi_buf|=t<>Oze-s.bi_valid,s.bi_valid+=n-Oze):(s.bi_buf|=t<{E_(s,n[t*2],n[t*2+1])},pJt=(s,t)=>{let n=0;do n|=s&1,s>>>=1,n<<=1;while(--t>0);return n>>>1},wBn=s=>{s.bi_valid===16?(Mse(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8)},jBn=(s,t)=>{const n=t.dyn_tree,r=t.max_code,a=t.stat_desc.static_tree,i=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,u,h,m,p,f,g=0;for(m=0;m<=OF;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,g++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,p=0,u>=o&&(p=l[u-o]),f=n[u*2],s.opt_len+=f*(m+p),i&&(s.static_len+=f*(a[u*2+1]+p)));if(g!==0){do{for(m=c-1;s.bl_count[m]===0;)m--;s.bl_count[m]--,s.bl_count[m+1]+=2,s.bl_count[c]--,g-=2}while(g>0);for(m=c;m!==0;m--)for(u=s.bl_count[m];u!==0;)h=s.heap[--d],!(h>r)&&(n[h*2+1]!==m&&(s.opt_len+=(m-n[h*2+1])*n[h*2],n[h*2+1]=m),u--)}},fJt=(s,t,n)=>{const r=new Array(OF+1);let a=0,i,l;for(i=1;i<=OF;i++)a=a+n[i-1]<<1,r[i]=a;for(l=0;l<=t;l++){let o=s[l*2+1];o!==0&&(s[l*2]=pJt(r[o]++,o))}},NBn=()=>{let s,t,n,r,a;const i=new Array(OF+1);for(n=0,r=0;r>=7;r{let t;for(t=0;t{s.bi_valid>8?Mse(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},ykt=(s,t,n,r)=>{const a=t*2,i=n*2;return s[a]{const r=s.heap[n];let a=n<<1;for(;a<=s.heap_len&&(a{let r,a,i=0,l,o;if(s.sym_next!==0)do r=s.pending_buf[s.sym_buf+i++]&255,r+=(s.pending_buf[s.sym_buf+i++]&255)<<8,a=s.pending_buf[s.sym_buf+i++],r===0?T4(s,a,t):(l=Tse[a],T4(s,l+Jae+1,t),o=fKe[l],o!==0&&(a-=iat[l],E_(s,a,o)),r--,l=mJt(r),T4(s,l,n),o=uCe[l],o!==0&&(r-=o6e[l],E_(s,r,o)));while(i{const n=t.dyn_tree,r=t.stat_desc.static_tree,a=t.stat_desc.has_stree,i=t.stat_desc.elems;let l,o,c=-1,d;for(s.heap_len=0,s.heap_max=aJt,l=0;l>1;l>=1;l--)$ze(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],$ze(s,n,1),o=s.heap[1],s.heap[--s.heap_max]=l,s.heap[--s.heap_max]=o,n[d*2]=n[l*2]+n[o*2],s.depth[d]=(s.depth[l]>=s.depth[o]?s.depth[l]:s.depth[o])+1,n[l*2+1]=n[o*2+1]=d,s.heap[1]=d++,$ze(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],jBn(s,t),fJt(n,c,s.bl_count)},bkt=(s,t,n)=>{let r,a=-1,i,l=t[0*2+1],o=0,c=7,d=4;for(l===0&&(c=138,d=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)i=l,l=t[(r+1)*2+1],!(++o{let r,a=-1,i,l=t[0*2+1],o=0,c=7,d=4;for(l===0&&(c=138,d=3),r=0;r<=n;r++)if(i=l,l=t[(r+1)*2+1],!(++o{let t;for(bkt(s,s.dyn_ltree,s.l_desc.max_code),bkt(s,s.dyn_dtree,s.d_desc.max_code),xKe(s,s.bl_desc),t=rat-1;t>=3&&s.bl_tree[cJt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t},SBn=(s,t,n,r)=>{let a;for(E_(s,t-257,5),E_(s,n-1,5),E_(s,r-4,4),a=0;a{let t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return xkt;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return gkt;for(n=32;n{wkt||(NBn(),wkt=!0),s.l_desc=new Bze(s.dyn_ltree,dJt),s.d_desc=new Bze(s.dyn_dtree,uJt),s.bl_desc=new Bze(s.bl_tree,hJt),s.bi_buf=0,s.bi_valid=0,xJt(s)},yJt=(s,t,n,r)=>{E_(s,(fBn<<1)+(r?1:0),3),gJt(s),Mse(s,n),Mse(s,~n),n&&s.pending_buf.set(s.window.subarray(t,t+n),s.pending),s.pending+=n},EBn=s=>{E_(s,rJt<<1,3),T4(s,aat,sA),wBn(s)},TBn=(s,t,n,r)=>{let a,i,l=0;s.level>0?(s.strm.data_type===pBn&&(s.strm.data_type=CBn(s)),xKe(s,s.l_desc),xKe(s,s.d_desc),l=kBn(s),a=s.opt_len+3+7>>>3,i=s.static_len+3+7>>>3,i<=a&&(a=i)):a=i=n+5,n+4<=a&&t!==-1?yJt(s,t,n,r):s.strategy===mBn||i===a?(E_(s,(rJt<<1)+(r?1:0),3),vkt(s,sA,fee)):(E_(s,(xBn<<1)+(r?1:0),3),SBn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),vkt(s,s.dyn_ltree,s.dyn_dtree)),xJt(s),r&&gJt(s)},MBn=(s,t,n)=>(s.pending_buf[s.sym_buf+s.sym_next++]=t,s.pending_buf[s.sym_buf+s.sym_next++]=t>>8,s.pending_buf[s.sym_buf+s.sym_next++]=n,t===0?s.dyn_ltree[n*2]++:(s.matches++,t--,s.dyn_ltree[(Tse[n]+Jae+1)*2]++,s.dyn_dtree[mJt(t)*2]++),s.sym_next===s.sym_end);var PBn=ABn,LBn=yJt,IBn=TBn,DBn=MBn,RBn=EBn,FBn={_tr_init:PBn,_tr_stored_block:LBn,_tr_flush_block:IBn,_tr_tally:DBn,_tr_align:RBn};const OBn=(s,t,n,r)=>{let a=s&65535|0,i=s>>>16&65535|0,l=0;for(;n!==0;){l=n>2e3?2e3:n,n-=l;do a=a+t[r++]|0,i=i+a|0;while(--l);a%=65521,i%=65521}return a|i<<16|0};var Pse=OBn;const zBn=()=>{let s,t=[];for(var n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=s&1?3988292384^s>>>1:s>>>1;t[n]=s}return t},BBn=new Uint32Array(zBn()),$Bn=(s,t,n,r)=>{const a=BBn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var d0=$Bn,DG={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},eie={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:UBn,_tr_stored_block:gKe,_tr_flush_block:qBn,_tr_tally:EP,_tr_align:VBn}=FBn,{Z_NO_FLUSH:TP,Z_PARTIAL_FLUSH:HBn,Z_FULL_FLUSH:GBn,Z_FINISH:aN,Z_BLOCK:jkt,Z_OK:iv,Z_STREAM_END:Nkt,Z_STREAM_ERROR:cC,Z_DATA_ERROR:WBn,Z_BUF_ERROR:Uze,Z_DEFAULT_COMPRESSION:KBn,Z_FILTERED:YBn,Z_HUFFMAN_ONLY:dde,Z_RLE:ZBn,Z_FIXED:XBn,Z_DEFAULT_STRATEGY:QBn,Z_UNKNOWN:JBn,Z_DEFLATED:R8e}=eie,e$n=9,t$n=15,s$n=8,n$n=29,r$n=256,yKe=r$n+1+n$n,a$n=30,i$n=19,o$n=2*yKe+1,l$n=15,pu=3,FM=258,dC=FM+pu+1,c$n=32,RG=42,oat=57,vKe=69,bKe=73,_Ke=91,wKe=103,zF=113,BX=666,vb=1,hK=2,A9=3,mK=4,d$n=3,BF=(s,t)=>(s.msg=DG[t],t),kkt=s=>s*2-(s>4?9:0),B6=s=>{let t=s.length;for(;--t>=0;)s[t]=0},u$n=s=>{let t,n,r,a=s.w_size;t=s.hash_size,r=t;do n=s.head[--r],s.head[r]=n>=a?n-a:0;while(--t);t=a,r=t;do n=s.prev[--r],s.prev[r]=n>=a?n-a:0;while(--t)};let h$n=(s,t,n)=>(t<{const t=s.state;let n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(s.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),s.next_out),s.next_out+=n,t.pending_out+=n,s.total_out+=n,s.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))},lj=(s,t)=>{qBn(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,Iw(s.strm)},sh=(s,t)=>{s.pending_buf[s.pending++]=t},CZ=(s,t)=>{s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255},jKe=(s,t,n,r)=>{let a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,t.set(s.input.subarray(s.next_in,s.next_in+a),n),s.state.wrap===1?s.adler=Pse(s.adler,t,a,n):s.state.wrap===2&&(s.adler=d0(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)},vJt=(s,t)=>{let n=s.max_chain_length,r=s.strstart,a,i,l=s.prev_length,o=s.nice_match;const c=s.strstart>s.w_size-dC?s.strstart-(s.w_size-dC):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+FM;let p=d[r+l-1],f=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==f||d[a+l-1]!==p||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;p=d[r+l-1],f=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead},FG=s=>{const t=s.w_size;let n,r,a;do{if(r=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-dC)&&(s.window.set(s.window.subarray(t,t+t-r),0),s.match_start-=t,s.strstart-=t,s.block_start-=t,s.insert>s.strstart&&(s.insert=s.strstart),u$n(s),r+=t),s.strm.avail_in===0)break;if(n=jKe(s.strm,s.window,s.strstart+s.lookahead,r),s.lookahead+=n,s.lookahead+s.insert>=pu)for(a=s.strstart-s.insert,s.ins_h=s.window[a],s.ins_h=MP(s,s.ins_h,s.window[a+1]);s.insert&&(s.ins_h=MP(s,s.ins_h,s.window[a+pu-1]),s.prev[a&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=a,a++,s.insert--,!(s.lookahead+s.insert{let n=s.pending_buf_size-5>s.w_size?s.w_size:s.pending_buf_size-5,r,a,i,l=0,o=s.strm.avail_in;do{if(r=65535,i=s.bi_valid+42>>3,s.strm.avail_outa+s.strm.avail_in&&(r=a+s.strm.avail_in),r>i&&(r=i),r>8,s.pending_buf[s.pending-2]=~r,s.pending_buf[s.pending-1]=~r>>8,Iw(s.strm),a&&(a>r&&(a=r),s.strm.output.set(s.window.subarray(s.block_start,s.block_start+a),s.strm.next_out),s.strm.next_out+=a,s.strm.avail_out-=a,s.strm.total_out+=a,s.block_start+=a,r-=a),r&&(jKe(s.strm,s.strm.output,s.strm.next_out,r),s.strm.next_out+=r,s.strm.avail_out-=r,s.strm.total_out+=r)}while(l===0);return o-=s.strm.avail_in,o&&(o>=s.w_size?(s.matches=2,s.window.set(s.strm.input.subarray(s.strm.next_in-s.w_size,s.strm.next_in),0),s.strstart=s.w_size,s.insert=s.strstart):(s.window_size-s.strstart<=o&&(s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,s.insert>s.strstart&&(s.insert=s.strstart)),s.window.set(s.strm.input.subarray(s.strm.next_in-o,s.strm.next_in),s.strstart),s.strstart+=o,s.insert+=o>s.w_size-s.insert?s.w_size-s.insert:o),s.block_start=s.strstart),s.high_wateri&&s.block_start>=s.w_size&&(s.block_start-=s.w_size,s.strstart-=s.w_size,s.window.set(s.window.subarray(s.w_size,s.w_size+s.strstart),0),s.matches<2&&s.matches++,i+=s.w_size,s.insert>s.strstart&&(s.insert=s.strstart)),i>s.strm.avail_in&&(i=s.strm.avail_in),i&&(jKe(s.strm,s.window,s.strstart,i),s.strstart+=i,s.insert+=i>s.w_size-s.insert?s.w_size-s.insert:i),s.high_water>3,i=s.pending_buf_size-i>65535?65535:s.pending_buf_size-i,n=i>s.w_size?s.w_size:i,a=s.strstart-s.block_start,(a>=n||(a||t===aN)&&t!==TP&&s.strm.avail_in===0&&a<=i)&&(r=a>i?i:a,l=t===aN&&s.strm.avail_in===0&&r===a?1:0,gKe(s,s.block_start,r,l),s.block_start+=r,Iw(s.strm)),l?A9:vb)},qze=(s,t)=>{let n,r;for(;;){if(s.lookahead=pu&&(s.ins_h=MP(s,s.ins_h,s.window[s.strstart+pu-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),n!==0&&s.strstart-n<=s.w_size-dC&&(s.match_length=vJt(s,n)),s.match_length>=pu)if(r=EP(s,s.strstart-s.match_start,s.match_length-pu),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=pu){s.match_length--;do s.strstart++,s.ins_h=MP(s,s.ins_h,s.window[s.strstart+pu-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart;while(--s.match_length!==0);s.strstart++}else s.strstart+=s.match_length,s.match_length=0,s.ins_h=s.window[s.strstart],s.ins_h=MP(s,s.ins_h,s.window[s.strstart+1]);else r=EP(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(r&&(lj(s,!1),s.strm.avail_out===0))return vb}return s.insert=s.strstart{let n,r,a;for(;;){if(s.lookahead=pu&&(s.ins_h=MP(s,s.ins_h,s.window[s.strstart+pu-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart),s.prev_length=s.match_length,s.prev_match=s.match_start,s.match_length=pu-1,n!==0&&s.prev_length4096)&&(s.match_length=pu-1)),s.prev_length>=pu&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-pu,r=EP(s,s.strstart-1-s.prev_match,s.prev_length-pu),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=MP(s,s.ins_h,s.window[s.strstart+pu-1]),n=s.prev[s.strstart&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=s.strstart);while(--s.prev_length!==0);if(s.match_available=0,s.match_length=pu-1,s.strstart++,r&&(lj(s,!1),s.strm.avail_out===0))return vb}else if(s.match_available){if(r=EP(s,0,s.window[s.strstart-1]),r&&lj(s,!1),s.strstart++,s.lookahead--,s.strm.avail_out===0)return vb}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(r=EP(s,0,s.window[s.strstart-1]),s.match_available=0),s.insert=s.strstart{let n,r,a,i;const l=s.window;for(;;){if(s.lookahead<=FM){if(FG(s),s.lookahead<=FM&&t===TP)return vb;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=pu&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+FM;do;while(r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&as.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=pu?(n=EP(s,1,s.match_length-pu),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=EP(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(lj(s,!1),s.strm.avail_out===0))return vb}return s.insert=0,t===aN?(lj(s,!0),s.strm.avail_out===0?A9:mK):s.sym_next&&(lj(s,!1),s.strm.avail_out===0)?vb:hK},p$n=(s,t)=>{let n;for(;;){if(s.lookahead===0&&(FG(s),s.lookahead===0)){if(t===TP)return vb;break}if(s.match_length=0,n=EP(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(lj(s,!1),s.strm.avail_out===0))return vb}return s.insert=0,t===aN?(lj(s,!0),s.strm.avail_out===0?A9:mK):s.sym_next&&(lj(s,!1),s.strm.avail_out===0)?vb:hK};function C5(s,t,n,r,a){this.good_length=s,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=a}const $X=[new C5(0,0,0,0,bJt),new C5(4,4,8,4,qze),new C5(4,5,16,8,qze),new C5(4,6,32,32,qze),new C5(4,4,16,16,ZB),new C5(8,16,32,32,ZB),new C5(8,16,128,128,ZB),new C5(8,32,128,256,ZB),new C5(32,128,258,1024,ZB),new C5(32,258,258,4096,ZB)],f$n=s=>{s.window_size=2*s.w_size,B6(s.head),s.max_lazy_match=$X[s.level].max_lazy,s.good_match=$X[s.level].good_length,s.nice_match=$X[s.level].nice_length,s.max_chain_length=$X[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=pu-1,s.match_available=0,s.ins_h=0};function x$n(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=R8e,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(o$n*2),this.dyn_dtree=new Uint16Array((2*a$n+1)*2),this.bl_tree=new Uint16Array((2*i$n+1)*2),B6(this.dyn_ltree),B6(this.dyn_dtree),B6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(l$n+1),this.heap=new Uint16Array(2*yKe+1),B6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*yKe+1),B6(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const tie=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.status!==RG&&t.status!==oat&&t.status!==vKe&&t.status!==bKe&&t.status!==_Ke&&t.status!==wKe&&t.status!==zF&&t.status!==BX?1:0},_Jt=s=>{if(tie(s))return BF(s,cC);s.total_in=s.total_out=0,s.data_type=JBn;const t=s.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?oat:t.wrap?RG:zF,s.adler=t.wrap===2?0:1,t.last_flush=-2,UBn(t),iv},wJt=s=>{const t=_Jt(s);return t===iv&&f$n(s.state),t},g$n=(s,t)=>tie(s)||s.state.wrap!==2?cC:(s.state.gzhead=t,iv),jJt=(s,t,n,r,a,i)=>{if(!s)return cC;let l=1;if(t===KBn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>e$n||n!==R8e||r<8||r>15||t<0||t>9||i<0||i>XBn||r===8&&l!==1)return BF(s,cC);r===8&&(r=9);const o=new x$n;return s.state=o,o.strm=s,o.status=RG,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<jJt(s,t,R8e,t$n,s$n,QBn),v$n=(s,t)=>{if(tie(s)||t>jkt||t<0)return s?BF(s,cC):cC;const n=s.state;if(!s.output||s.avail_in!==0&&!s.input||n.status===BX&&t!==aN)return BF(s,s.avail_out===0?Uze:cC);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(Iw(s),s.avail_out===0)return n.last_flush=-1,iv}else if(s.avail_in===0&&kkt(t)<=kkt(r)&&t!==aN)return BF(s,Uze);if(n.status===BX&&s.avail_in!==0)return BF(s,Uze);if(n.status===RG&&n.wrap===0&&(n.status=zF),n.status===RG){let a=R8e+(n.w_bits-8<<4)<<8,i=-1;if(n.strategy>=dde||n.level<2?i=0:n.level<6?i=1:n.level===6?i=2:i=3,a|=i<<6,n.strstart!==0&&(a|=c$n),a+=31-a%31,CZ(n,a),n.strstart!==0&&(CZ(n,s.adler>>>16),CZ(n,s.adler&65535)),s.adler=1,n.status=zF,Iw(s),n.pending!==0)return n.last_flush=-1,iv}if(n.status===oat){if(s.adler=0,sh(n,31),sh(n,139),sh(n,8),n.gzhead)sh(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),sh(n,n.gzhead.time&255),sh(n,n.gzhead.time>>8&255),sh(n,n.gzhead.time>>16&255),sh(n,n.gzhead.time>>24&255),sh(n,n.level===9?2:n.strategy>=dde||n.level<2?4:0),sh(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(sh(n,n.gzhead.extra.length&255),sh(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(s.adler=d0(s.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=vKe;else if(sh(n,0),sh(n,0),sh(n,0),sh(n,0),sh(n,0),sh(n,n.level===9?2:n.strategy>=dde||n.level<2?4:0),sh(n,d$n),n.status=zF,Iw(s),n.pending!==0)return n.last_flush=-1,iv}if(n.status===vKe){if(n.gzhead.extra){let a=n.pending,i=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let o=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+o),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>a&&(s.adler=d0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex+=o,Iw(s),n.pending!==0)return n.last_flush=-1,iv;a=0,i-=o}let l=new Uint8Array(n.gzhead.extra);n.pending_buf.set(l.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>a&&(s.adler=d0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=bKe}if(n.status===bKe){if(n.gzhead.name){let a=n.pending,i;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>a&&(s.adler=d0(s.adler,n.pending_buf,n.pending-a,a)),Iw(s),n.pending!==0)return n.last_flush=-1,iv;a=0}n.gzindexa&&(s.adler=d0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=_Ke}if(n.status===_Ke){if(n.gzhead.comment){let a=n.pending,i;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>a&&(s.adler=d0(s.adler,n.pending_buf,n.pending-a,a)),Iw(s),n.pending!==0)return n.last_flush=-1,iv;a=0}n.gzindexa&&(s.adler=d0(s.adler,n.pending_buf,n.pending-a,a))}n.status=wKe}if(n.status===wKe){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(Iw(s),n.pending!==0))return n.last_flush=-1,iv;sh(n,s.adler&255),sh(n,s.adler>>8&255),s.adler=0}if(n.status=zF,Iw(s),n.pending!==0)return n.last_flush=-1,iv}if(s.avail_in!==0||n.lookahead!==0||t!==TP&&n.status!==BX){let a=n.level===0?bJt(n,t):n.strategy===dde?p$n(n,t):n.strategy===ZBn?m$n(n,t):$X[n.level].func(n,t);if((a===A9||a===mK)&&(n.status=BX),a===vb||a===A9)return s.avail_out===0&&(n.last_flush=-1),iv;if(a===hK&&(t===HBn?VBn(n):t!==jkt&&(gKe(n,0,0,!1),t===GBn&&(B6(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Iw(s),s.avail_out===0))return n.last_flush=-1,iv}return t!==aN?iv:n.wrap<=0?Nkt:(n.wrap===2?(sh(n,s.adler&255),sh(n,s.adler>>8&255),sh(n,s.adler>>16&255),sh(n,s.adler>>24&255),sh(n,s.total_in&255),sh(n,s.total_in>>8&255),sh(n,s.total_in>>16&255),sh(n,s.total_in>>24&255)):(CZ(n,s.adler>>>16),CZ(n,s.adler&65535)),Iw(s),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?iv:Nkt)},b$n=s=>{if(tie(s))return cC;const t=s.state.status;return s.state=null,t===zF?BF(s,WBn):iv},_$n=(s,t)=>{let n=t.length;if(tie(s))return cC;const r=s.state,a=r.wrap;if(a===2||a===1&&r.status!==RG||r.lookahead)return cC;if(a===1&&(s.adler=Pse(s.adler,t,n,0)),r.wrap=0,n>=r.w_size){a===0&&(B6(r.head),r.strstart=0,r.block_start=0,r.insert=0);let c=new Uint8Array(r.w_size);c.set(t.subarray(n-r.w_size,n),0),t=c,n=r.w_size}const i=s.avail_in,l=s.next_in,o=s.input;for(s.avail_in=n,s.next_in=0,s.input=t,FG(r);r.lookahead>=pu;){let c=r.strstart,d=r.lookahead-(pu-1);do r.ins_h=MP(r,r.ins_h,r.window[c+pu-1]),r.prev[c&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=c,c++;while(--d);r.strstart=c,r.lookahead=pu-1,FG(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=pu-1,r.match_available=0,s.next_in=l,s.input=o,s.avail_in=i,r.wrap=a,iv};var w$n=y$n,j$n=jJt,N$n=wJt,k$n=_Jt,S$n=g$n,C$n=v$n,A$n=b$n,E$n=_$n,T$n="pako deflate (from Nodeca project)",xee={deflateInit:w$n,deflateInit2:j$n,deflateReset:N$n,deflateResetKeep:k$n,deflateSetHeader:S$n,deflate:C$n,deflateEnd:A$n,deflateSetDictionary:E$n,deflateInfo:T$n};const M$n=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var P$n=function(s){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(const r in n)M$n(n,r)&&(s[r]=n[r])}}return s},L$n=s=>{let t=0;for(let r=0,a=s.length;r=252?6:s>=248?5:s>=240?4:s>=224?3:s>=192?2:1;Lse[254]=Lse[254]=1;var I$n=s=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(s);let t,n,r,a,i,l=s.length,o=0;for(a=0;a>>6,t[i++]=128|n&63):n<65536?(t[i++]=224|n>>>12,t[i++]=128|n>>>6&63,t[i++]=128|n&63):(t[i++]=240|n>>>18,t[i++]=128|n>>>12&63,t[i++]=128|n>>>6&63,t[i++]=128|n&63);return t};const D$n=(s,t)=>{if(t<65534&&s.subarray&&NJt)return String.fromCharCode.apply(null,s.length===t?s:s.subarray(0,t));let n="";for(let r=0;r{const n=t||s.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(s.subarray(0,t));let r,a;const i=new Array(n*2);for(a=0,r=0;r4){i[a++]=65533,r+=o-1;continue}for(l&=o===2?31:o===3?15:7;o>1&&r1){i[a++]=65533;continue}l<65536?i[a++]=l:(l-=65536,i[a++]=55296|l>>10&1023,i[a++]=56320|l&1023)}return D$n(i,a)},F$n=(s,t)=>{t=t||s.length,t>s.length&&(t=s.length);let n=t-1;for(;n>=0&&(s[n]&192)===128;)n--;return n<0||n===0?t:n+Lse[s[n]]>t?n:t},Ise={string2buf:I$n,buf2string:R$n,utf8border:F$n};function O$n(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var kJt=O$n;const SJt=Object.prototype.toString,{Z_NO_FLUSH:z$n,Z_SYNC_FLUSH:B$n,Z_FULL_FLUSH:$$n,Z_FINISH:U$n,Z_OK:l6e,Z_STREAM_END:q$n,Z_DEFAULT_COMPRESSION:V$n,Z_DEFAULT_STRATEGY:H$n,Z_DEFLATED:G$n}=eie;function lat(s){this.options=F8e.assign({level:V$n,method:G$n,chunkSize:16384,windowBits:15,memLevel:8,strategy:H$n},s||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kJt,this.strm.avail_out=0;let n=xee.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==l6e)throw new Error(DG[n]);if(t.header&&xee.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=Ise.string2buf(t.dictionary):SJt.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=xee.deflateSetDictionary(this.strm,r),n!==l6e)throw new Error(DG[n]);this._dict_set=!0}}lat.prototype.push=function(s,t){const n=this.strm,r=this.options.chunkSize;let a,i;if(this.ended)return!1;for(t===~~t?i=t:i=t===!0?U$n:z$n,typeof s=="string"?n.input=Ise.string2buf(s):SJt.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(i===B$n||i===$$n)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(a=xee.deflate(n,i),a===q$n)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),a=xee.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===l6e;if(n.avail_out===0){this.onData(n.output);continue}if(i>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)break}return!0};lat.prototype.onData=function(s){this.chunks.push(s)};lat.prototype.onEnd=function(s){s===l6e&&(this.result=F8e.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};const ude=16209,W$n=16191;var K$n=function(t,n){let r,a,i,l,o,c,d,u,h,m,p,f,g,v,y,b,w,S,C,E,P,M,I,D;const F=t.state;r=t.next_in,I=t.input,a=r+(t.avail_in-5),i=t.next_out,D=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=F.dmax,d=F.wsize,u=F.whave,h=F.wnext,m=F.window,p=F.hold,f=F.bits,g=F.lencode,v=F.distcode,y=(1<>>24,p>>>=S,f-=S,S=w>>>16&255,S===0)D[i++]=w&65535;else if(S&16){C=w&65535,S&=15,S&&(f>>=S,f-=S),f<15&&(p+=I[r++]<>>24,p>>>=S,f-=S,S=w>>>16&255,S&16){if(E=w&65535,S&=15,fc){t.msg="invalid distance too far back",F.mode=ude;break e}if(p>>>=S,f-=S,S=i-l,E>S){if(S=E-S,S>u&&F.sane){t.msg="invalid distance too far back",F.mode=ude;break e}if(P=0,M=m,h===0){if(P+=d-S,S2;)D[i++]=M[P++],D[i++]=M[P++],D[i++]=M[P++],C-=3;C&&(D[i++]=M[P++],C>1&&(D[i++]=M[P++]))}else{P=i-E;do D[i++]=D[P++],D[i++]=D[P++],D[i++]=D[P++],C-=3;while(C>2);C&&(D[i++]=D[P++],C>1&&(D[i++]=D[P++]))}}else if(S&64){t.msg="invalid distance code",F.mode=ude;break e}else{w=v[(w&65535)+(p&(1<>3,r-=C,f-=C<<3,p&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,p=0,f=0,g=0,v=0,y=0,b=0,w,S,C,E,P,M=null,I;const D=new Uint16Array(XB+1),F=new Uint16Array(XB+1);let q=null,G,V,H;for(d=0;d<=XB;d++)D[d]=0;for(u=0;u=1&&D[m]===0;m--);if(p>m&&(p=m),m===0)return a[i++]=1<<24|64<<16|0,a[i++]=1<<24|64<<16|0,o.bits=1,0;for(h=1;h0&&(s===Akt||m!==1))return-1;for(F[1]=0,d=1;dSkt||s===Ekt&&y>Ckt)return 1;for(;;){G=d-g,l[u]+1=I?(V=q[l[u]-I],H=M[l[u]-I]):(V=96,H=0),w=1<>g)+S]=G<<24|V<<16|H|0;while(S!==0);for(w=1<>=1;if(w!==0?(b&=w-1,b+=w):b=0,u++,--D[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>p&&(b&E)!==C){for(g===0&&(g=p),P+=h,f=d-g,v=1<Skt||s===Ekt&&y>Ckt)return 1;C=b&E,a[C]=p<<24|f<<16|P-i|0}}return b!==0&&(a[P+b]=d-g<<24|64<<16|0),o.bits=p,0};var gee=J$n;const eUn=0,CJt=1,AJt=2,{Z_FINISH:Tkt,Z_BLOCK:tUn,Z_TREES:hde,Z_OK:E9,Z_STREAM_END:sUn,Z_NEED_DICT:nUn,Z_STREAM_ERROR:RN,Z_DATA_ERROR:EJt,Z_MEM_ERROR:TJt,Z_BUF_ERROR:rUn,Z_DEFLATED:Mkt}=eie,O8e=16180,Pkt=16181,Lkt=16182,Ikt=16183,Dkt=16184,Rkt=16185,Fkt=16186,Okt=16187,zkt=16188,Bkt=16189,c6e=16190,A3=16191,Hze=16192,$kt=16193,Gze=16194,Ukt=16195,qkt=16196,Vkt=16197,Hkt=16198,mde=16199,pde=16200,Gkt=16201,Wkt=16202,Kkt=16203,Ykt=16204,Zkt=16205,Wze=16206,Xkt=16207,Qkt=16208,Yp=16209,MJt=16210,PJt=16211,aUn=852,iUn=592,oUn=15,lUn=oUn,Jkt=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function cUn(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const yz=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modePJt?1:0},LJt=s=>{if(yz(s))return RN;const t=s.state;return s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=O8e,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(aUn),t.distcode=t.distdyn=new Int32Array(iUn),t.sane=1,t.back=-1,E9},IJt=s=>{if(yz(s))return RN;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,LJt(s)},DJt=(s,t)=>{let n;if(yz(s))return RN;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?RN:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,IJt(s))},RJt=(s,t)=>{if(!s)return RN;const n=new cUn;s.state=n,n.strm=s,n.window=null,n.mode=O8e;const r=DJt(s,t);return r!==E9&&(s.state=null),r},dUn=s=>RJt(s,lUn);let eSt=!0,Kze,Yze;const uUn=s=>{if(eSt){Kze=new Int32Array(512),Yze=new Int32Array(32);let t=0;for(;t<144;)s.lens[t++]=8;for(;t<256;)s.lens[t++]=9;for(;t<280;)s.lens[t++]=7;for(;t<288;)s.lens[t++]=8;for(gee(CJt,s.lens,0,288,Kze,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;gee(AJt,s.lens,0,32,Yze,0,s.work,{bits:5}),eSt=!1}s.lencode=Kze,s.lenbits=9,s.distcode=Yze,s.distbits=5},FJt=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(i.window.set(t.subarray(n-i.wsize,n),0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),i.window.set(t.subarray(n-r,n-r+a),i.wnext),r-=a,r?(i.window.set(t.subarray(n-r,n),0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave{let n,r,a,i,l,o,c,d,u,h,m,p,f,g,v=0,y,b,w,S,C,E,P,M;const I=new Uint8Array(4);let D,F;const q=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(yz(s)||!s.output||!s.input&&s.avail_in!==0)return RN;n=s.state,n.mode===A3&&(n.mode=Hze),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,h=o,m=c,M=E9;e:for(;;)switch(n.mode){case O8e:if(n.wrap===0){n.mode=Hze;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=d0(n.check,I,2,0),d=0,u=0,n.mode=Pkt;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Yp;break}if((d&15)!==Mkt){s.msg="unknown compression method",n.mode=Yp;break}if(d>>>=4,u-=4,P=(d&15)+8,n.wbits===0&&(n.wbits=P),P>15||P>n.wbits){s.msg="invalid window size",n.mode=Yp;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=d0(n.check,I,2,0)),d=0,u=0,n.mode=Lkt;case Lkt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,I[2]=d>>>16&255,I[3]=d>>>24&255,n.check=d0(n.check,I,4,0)),d=0,u=0,n.mode=Ikt;case Ikt:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=d0(n.check,I,2,0)),d=0,u=0,n.mode=Dkt;case Dkt:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=d0(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=Rkt;case Rkt:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(i,i+p),P)),n.flags&512&&n.wrap&4&&(n.check=d0(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=Fkt;case Fkt:if(n.flags&2048){if(o===0)break e;p=0;do P=r[i+p++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P));while(P&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=A3;break;case Bkt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=Wze;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=$kt;break;case 1:if(uUn(n),n.mode=mde,t===hde){d>>>=2,u-=2;break e}break;case 2:n.mode=qkt;break;case 3:s.msg="invalid block type",n.mode=Yp}d>>>=2,u-=2;break;case $kt:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Yp;break}if(n.length=d&65535,d=0,u=0,n.mode=Gze,t===hde)break e;case Gze:n.mode=Ukt;case Ukt:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;a.set(r.subarray(i,i+p),l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=A3;break;case qkt:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Yp;break}n.have=0,n.mode=Vkt;case Vkt:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[q[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},M=gee(eUn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid code lengths set",n.mode=Yp;break}n.have=0,n.mode=Hkt;case Hkt:for(;n.have>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=y,u-=y,n.lens[n.have++]=w;else{if(w===16){for(F=y+2;u>>=y,u-=y,n.have===0){s.msg="invalid bit length repeat",n.mode=Yp;break}P=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(w===17){for(F=y+3;u>>=y,u-=y,P=0,p=3+(d&7),d>>>=3,u-=3}else{for(F=y+7;u>>=y,u-=y,P=0,p=11+(d&127),d>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Yp;break}for(;p--;)n.lens[n.have++]=P}}if(n.mode===Yp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Yp;break}if(n.lenbits=9,D={bits:n.lenbits},M=gee(CJt,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid literal/lengths set",n.mode=Yp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},M=gee(AJt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,M){s.msg="invalid distances set",n.mode=Yp;break}if(n.mode=mde,t===hde)break e;case mde:n.mode=pde;case pde:if(o>=6&&c>=258){s.next_out=l,s.avail_out=c,s.next_in=i,s.avail_in=o,n.hold=d,n.bits=u,K$n(s,m),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,n.mode===A3&&(n.back=-1);break}for(n.back=0;v=n.lencode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,n.length=w,b===0){n.mode=Zkt;break}if(b&32){n.back=-1,n.mode=A3;break}if(b&64){s.msg="invalid literal/length code",n.mode=Yp;break}n.extra=b&15,n.mode=Gkt;case Gkt:if(n.extra){for(F=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=Wkt;case Wkt:for(;v=n.distcode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,b&64){s.msg="invalid distance code",n.mode=Yp;break}n.offset=w,n.extra=b&15,n.mode=Kkt;case Kkt:if(n.extra){for(F=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Yp;break}n.mode=Ykt;case Ykt:if(c===0)break e;if(p=m-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Yp;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),g=n.window}else g=a,f=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=g[f++];while(--p);n.length===0&&(n.mode=pde);break;case Zkt:if(c===0)break e;a[l++]=n.length,c--,n.mode=pde;break;case Wze:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(yz(s))return RN;let t=s.state;return t.window&&(t.window=null),s.state=null,E9},pUn=(s,t)=>{if(yz(s))return RN;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,E9):RN},fUn=(s,t)=>{const n=t.length;let r,a,i;return yz(s)||(r=s.state,r.wrap!==0&&r.mode!==c6e)?RN:r.mode===c6e&&(a=1,a=Pse(a,t,n,0),a!==r.check)?EJt:(i=FJt(s,t,n,n),i?(r.mode=MJt,TJt):(r.havedict=1,E9))};var xUn=IJt,gUn=DJt,yUn=LJt,vUn=dUn,bUn=RJt,_Un=hUn,wUn=mUn,jUn=pUn,NUn=fUn,kUn="pako inflate (from Nodeca project)",nA={inflateReset:xUn,inflateReset2:gUn,inflateResetKeep:yUn,inflateInit:vUn,inflateInit2:bUn,inflate:_Un,inflateEnd:wUn,inflateGetHeader:jUn,inflateSetDictionary:NUn,inflateInfo:kUn};function SUn(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var CUn=SUn;const OJt=Object.prototype.toString,{Z_NO_FLUSH:AUn,Z_FINISH:EUn,Z_OK:Dse,Z_STREAM_END:Zze,Z_NEED_DICT:Xze,Z_STREAM_ERROR:TUn,Z_DATA_ERROR:tSt,Z_MEM_ERROR:MUn}=eie;function sie(s){this.options=F8e.assign({chunkSize:1024*64,windowBits:15,to:""},s||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(s&&s.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new kJt,this.strm.avail_out=0;let n=nA.inflateInit2(this.strm,t.windowBits);if(n!==Dse)throw new Error(DG[n]);if(this.header=new CUn,nA.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Ise.string2buf(t.dictionary):OJt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=nA.inflateSetDictionary(this.strm,t.dictionary),n!==Dse)))throw new Error(DG[n])}sie.prototype.push=function(s,t){const n=this.strm,r=this.options.chunkSize,a=this.options.dictionary;let i,l,o;if(this.ended)return!1;for(t===~~t?l=t:l=t===!0?EUn:AUn,OJt.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),i=nA.inflate(n,l),i===Xze&&a&&(i=nA.inflateSetDictionary(n,a),i===Dse?i=nA.inflate(n,l):i===tSt&&(i=Xze));n.avail_in>0&&i===Zze&&n.state.wrap>0&&s[n.next_in]!==0;)nA.inflateReset(n),i=nA.inflate(n,l);switch(i){case TUn:case tSt:case Xze:case MUn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===Zze))if(this.options.to==="string"){let c=Ise.utf8border(n.output,n.next_out),d=n.next_out-c,u=Ise.buf2string(n.output,c);n.next_out=d,n.avail_out=r-d,d&&n.output.set(n.output.subarray(c,c+d),0),this.onData(u)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(!(i===Dse&&o===0)){if(i===Zze)return i=nA.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};sie.prototype.onData=function(s){this.chunks.push(s)};sie.prototype.onEnd=function(s){s===Dse&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=F8e.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function cat(s,t){const n=new sie(t);if(n.push(s),n.err)throw n.msg||DG[n.err];return n.result}function PUn(s,t){return t=t||{},t.raw=!0,cat(s,t)}var LUn=sie,IUn=cat,DUn=PUn,RUn=cat,FUn=eie,OUn={Inflate:LUn,inflate:IUn,inflateRaw:DUn,ungzip:RUn,constants:FUn};const{Inflate:zUn,inflate:BUn,inflateRaw:Mjr,ungzip:Pjr}=OUn;var sSt=zUn,$Un=BUn;const zJt=[];for(let s=0;s<256;s++){let t=s;for(let n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;zJt[s]=t}const nSt=4294967295;function UUn(s,t,n){let r=s;for(let a=0;a>>8;return r}function qUn(s,t){return(UUn(nSt,s,t)^nSt)>>>0}function rSt(s,t,n){const r=s.readUint32(),a=qUn(new Uint8Array(s.buffer,s.byteOffset+s.offset-t-4,t),t);if(a!==r)throw new Error(`CRC mismatch for chunk ${n}. Expected ${r}, found ${a}`)}function BJt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function VJt(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||E>=r))for(let P=0;P>8&255}const XUn=new Uint16Array([255]),QUn=new Uint8Array(XUn.buffer),JUn=QUn[0]===255,eqn=new Uint8Array(0);function aSt(s){const{data:t,width:n,height:r,channels:a,depth:i}=s,l=Math.ceil(i/8)*a,o=Math.ceil(i/8*a*n),c=new Uint8Array(r*o);let d=eqn,u=0,h,m;for(let p=0;p>8&255}const hCe=Uint8Array.of(137,80,78,71,13,10,26,10);function iSt(s){if(!sqn(s.readBytes(hCe.length)))throw new Error("wrong PNG signature")}function sqn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const iqn=/^[\u0000-\u00FF]*$/;function oqn(s){if(!iqn.test(s))throw new Error("invalid latin1 text")}function lqn(s,t,n){const r=GJt(t);s[r]=cqn(t,n-r.length-1)}function GJt(s){for(s.mark();s.readByte()!==rqn;);const t=s.offset;s.reset();const n=HJt.decode(s.readBytes(t-s.offset-1));return s.skip(1),aqn(n),n}function cqn(s,t){return HJt.decode(s.readBytes(t))}const Nw={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},Qze={UNKNOWN:-1,DEFLATE:0},oSt={UNKNOWN:-1,ADAPTIVE:0},Jze={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},fde={NONE:0,BACKGROUND:1,PREVIOUS:2},eBe={SOURCE:0,OVER:1};class dqn extends sat{constructor(n,r={}){super(n);zr(this,"_checkCrc");zr(this,"_inflator");zr(this,"_png");zr(this,"_apng");zr(this,"_end");zr(this,"_hasPalette");zr(this,"_palette");zr(this,"_hasTransparency");zr(this,"_transparency");zr(this,"_compressionMethod");zr(this,"_filterMethod");zr(this,"_interlaceMethod");zr(this,"_colorType");zr(this,"_isAnimated");zr(this,"_numberOfFrames");zr(this,"_numberOfPlays");zr(this,"_frames");zr(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new sSt,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=Qze.UNKNOWN,this._filterMethod=oSt.UNKNOWN,this._interlaceMethod=Jze.UNKNOWN,this._colorType=Nw.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(iSt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(iSt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeApngChunk(n,r)}return this.decodeApngImage(),this._apng}decodeChunk(n,r){const a=this.offset;switch(r){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(n);break;case"IDAT":this.decodeIDAT(n);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(n);break;case"iCCP":this.decodeiCCP(n);break;case nqn:lqn(this._png.text,this,n);break;case"pHYs":this.decodepHYs();break;default:this.skip(n);break}if(this.offset-a!==n)throw new Error(`Length mismatch while decoding chunk ${r}`);this._checkCrc?rSt(this,n+4,r):this.skip(4)}decodeApngChunk(n,r){const a=this.offset;switch(r!=="fdAT"&&r!=="IDAT"&&this._writingDataChunks&&this.pushDataToFrame(),r){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(n);break;default:this.decodeChunk(n,r),this.offset=a+n;break}if(this.offset-a!==n)throw new Error(`Length mismatch while decoding chunk ${r}`);this._checkCrc?rSt(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=uqn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case Nw.GREYSCALE:a=1;break;case Nw.TRUECOLOUR:a=3;break;case Nw.INDEXED_COLOUR:a=1;break;case Nw.GREYSCALE_ALPHA:a=2;break;case Nw.TRUECOLOUR_ALPHA:a=4;break;case Nw.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==Qze.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32(),this._numberOfPlays=this.readUint32(),this._isAnimated=!0}decodeFCTL(){const n={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(n)}decodePLTE(n){if(n%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${n}`);const r=n/3;this._hasPalette=!0;const a=[];this._palette=a;for(let i=0;ithis._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${n/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(n/2);for(let r=0;rthis._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${n} vs ${this._palette.length})`);let r=0;for(;r{const c=((l+r.yOffset)*this._png.width+r.xOffset+o)*this._png.channels,d=(l*r.width+o)*this._png.channels;return{index:c,frameIndex:d}};switch(r.blendOp){case eBe.SOURCE:for(let l=0;l=200&&t.status<=299}function xde(s){try{s.dispatchEvent(new MouseEvent("click"))}catch{var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),s.dispatchEvent(t)}}var eF=cc.saveAs||((typeof window>"u"?"undefined":Vh(window))!=="object"||window!==cc?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=cc.URL||cc.webkitURL,a=document.createElement("a");t=t||s.name||"download",a.download=t,a.rel="noopener",typeof s=="string"?(a.href=s,a.origin!==location.origin?cSt(a.href)?sBe(s,t,n):xde(a,a.target="_blank"):xde(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){xde(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(cSt(s))sBe(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){xde(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Vh(i)!=="object"&&(Am.warn("Deprecated: Expected third argument to be a object"),i={autoBom:!i}),i.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}(s,n),t)}:function(s,t,n,r){if((r=r||open("","_blank"))&&(r.document.title=r.document.body.innerText="downloading..."),typeof s=="string")return sBe(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(cc.HTMLElement)||cc.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Vh(FileReader))==="object"){var o=new FileReader;o.onloadend=function(){var u=o.result;u=l?u:u.replace(/^data:[^;]*;/,"data:attachment/file;"),r?r.location.href=u:location=u,r=null},o.readAsDataURL(s)}else{var c=cc.URL||cc.webkitURL,d=c.createObjectURL(s);r?r.location=d:location.href=d,r=null,setTimeout(function(){c.revokeObjectURL(d)},4e4)}});/** * A class to parse color values * @author Stoyan Stefanov * {@link http://www.phpied.com/rgb-color-parser-in-javascript/} * @license Use it if you like it */function WJt(s){var t;s=s||"",this.ok=!1,s.charAt(0)=="#"&&(s=s.substr(1,6)),s={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"}[s=(s=s.replace(/ /g,"")).toLowerCase()]||s;for(var n=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(o){return[parseInt(o[1]),parseInt(o[2]),parseInt(o[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(o){return[parseInt(o[1],16),parseInt(o[2],16),parseInt(o[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(o){return[parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16),parseInt(o[3]+o[3],16)]}}],r=0;r255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var o=this.r.toString(16),c=this.g.toString(16),d=this.b.toString(16);return o.length==1&&(o="0"+o),c.length==1&&(c="0"+c),d.length==1&&(d="0"+d),"#"+o+c+d}}var mCe=cc.atob.bind(cc),dSt=cc.btoa.bind(cc);/** * @license * Joseph Myers does not specify a particular license for his work. * * Author: Joseph Myers * Accessed from: http://www.myersdaily.org/joseph/javascript/md5.js * * Modified by: Owen Leong */function nBe(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Wv(n,r,a,i,t[0],7,-680876936),i=Wv(i,n,r,a,t[1],12,-389564586),a=Wv(a,i,n,r,t[2],17,606105819),r=Wv(r,a,i,n,t[3],22,-1044525330),n=Wv(n,r,a,i,t[4],7,-176418897),i=Wv(i,n,r,a,t[5],12,1200080426),a=Wv(a,i,n,r,t[6],17,-1473231341),r=Wv(r,a,i,n,t[7],22,-45705983),n=Wv(n,r,a,i,t[8],7,1770035416),i=Wv(i,n,r,a,t[9],12,-1958414417),a=Wv(a,i,n,r,t[10],17,-42063),r=Wv(r,a,i,n,t[11],22,-1990404162),n=Wv(n,r,a,i,t[12],7,1804603682),i=Wv(i,n,r,a,t[13],12,-40341101),a=Wv(a,i,n,r,t[14],17,-1502002290),n=Kv(n,r=Wv(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=Kv(i,n,r,a,t[6],9,-1069501632),a=Kv(a,i,n,r,t[11],14,643717713),r=Kv(r,a,i,n,t[0],20,-373897302),n=Kv(n,r,a,i,t[5],5,-701558691),i=Kv(i,n,r,a,t[10],9,38016083),a=Kv(a,i,n,r,t[15],14,-660478335),r=Kv(r,a,i,n,t[4],20,-405537848),n=Kv(n,r,a,i,t[9],5,568446438),i=Kv(i,n,r,a,t[14],9,-1019803690),a=Kv(a,i,n,r,t[3],14,-187363961),r=Kv(r,a,i,n,t[8],20,1163531501),n=Kv(n,r,a,i,t[13],5,-1444681467),i=Kv(i,n,r,a,t[2],9,-51403784),a=Kv(a,i,n,r,t[7],14,1735328473),n=Yv(n,r=Kv(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Yv(i,n,r,a,t[8],11,-2022574463),a=Yv(a,i,n,r,t[11],16,1839030562),r=Yv(r,a,i,n,t[14],23,-35309556),n=Yv(n,r,a,i,t[1],4,-1530992060),i=Yv(i,n,r,a,t[4],11,1272893353),a=Yv(a,i,n,r,t[7],16,-155497632),r=Yv(r,a,i,n,t[10],23,-1094730640),n=Yv(n,r,a,i,t[13],4,681279174),i=Yv(i,n,r,a,t[0],11,-358537222),a=Yv(a,i,n,r,t[3],16,-722521979),r=Yv(r,a,i,n,t[6],23,76029189),n=Yv(n,r,a,i,t[9],4,-640364487),i=Yv(i,n,r,a,t[12],11,-421815835),a=Yv(a,i,n,r,t[15],16,530742520),n=Zv(n,r=Yv(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Zv(i,n,r,a,t[7],10,1126891415),a=Zv(a,i,n,r,t[14],15,-1416354905),r=Zv(r,a,i,n,t[5],21,-57434055),n=Zv(n,r,a,i,t[12],6,1700485571),i=Zv(i,n,r,a,t[3],10,-1894986606),a=Zv(a,i,n,r,t[10],15,-1051523),r=Zv(r,a,i,n,t[1],21,-2054922799),n=Zv(n,r,a,i,t[8],6,1873313359),i=Zv(i,n,r,a,t[15],10,-30611744),a=Zv(a,i,n,r,t[6],15,-1560198380),r=Zv(r,a,i,n,t[13],21,1309151649),n=Zv(n,r,a,i,t[4],6,-145523070),i=Zv(i,n,r,a,t[11],10,-1120210379),a=Zv(a,i,n,r,t[2],15,718787259),r=Zv(r,a,i,n,t[9],21,-343485551),s[0]=OM(n,s[0]),s[1]=OM(r,s[1]),s[2]=OM(a,s[2]),s[3]=OM(i,s[3])}function z8e(s,t,n,r,a,i){return t=OM(OM(t,s),OM(r,i)),OM(t<>>32-a,n)}function Wv(s,t,n,r,a,i,l){return z8e(t&n|~t&r,s,t,a,i,l)}function Kv(s,t,n,r,a,i,l){return z8e(t&r|n&~r,s,t,a,i,l)}function Yv(s,t,n,r,a,i,l){return z8e(t^n^r,s,t,a,i,l)}function Zv(s,t,n,r,a,i,l){return z8e(n^(t|~r),s,t,a,i,l)}function KJt(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)nBe(r,mqn(s.substring(t-64,t)));s=s.substring(t-64);var a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=s.charCodeAt(t)<<(t%4<<3);if(a[t>>2]|=128<<(t%4<<3),t>55)for(nBe(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,nBe(r,a),r}function mqn(s){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=s.charCodeAt(t)+(s.charCodeAt(t+1)<<8)+(s.charCodeAt(t+2)<<16)+(s.charCodeAt(t+3)<<24);return n}var uSt="0123456789abcdef".split("");function pqn(s){for(var t="",n=0;n<4;n++)t+=uSt[s>>8*n+4&15]+uSt[s>>8*n&15];return t}function fqn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function NKe(s){return KJt(s).map(fqn).join("")}var xqn=function(s){for(var t=0;t>16)+(t>>16)+(n>>16)<<16|65535&n}return s+t&4294967295}/** * @license * FPDF is released under a permissive license: there is no usage restriction. * You may embed it freely in your application (commercial or not), with or * without modifications. * * Reference: http://www.fpdf.org/en/script/script37.php */function kKe(s,t){var n,r,a,i;if(s!==n){for(var l=(a=s,i=1+(256/s.length|0),new Array(i+1).join(a)),o=[],c=0;c<256;c++)o[c]=c;var d=0;for(c=0;c<256;c++){var u=o[c];d=(d+u+l.charCodeAt(c))%256,o[c]=o[d],o[d]=u}n=s,r=o}else o=r;var h=t.length,m=0,p=0,f="";for(c=0;c€/\f©þdSiz";var i=(t+this.padding).substr(0,32),l=(n+this.padding).substr(0,32);this.O=this.processOwnerPassword(i,l),this.P=-(1+(255^a)),this.encryptionKey=NKe(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=kKe(this.encryptionKey,this.padding)}function P$(s){if(/[^\u0000-\u00ff]/.test(s))throw new Error("Invalid PDF Name Object: "+s+", Only accept ASCII characters.");for(var t="",n=s.length,r=0;r126?"#"+("0"+a.toString(16)).slice(-2):s[r]}return t}function mSt(s){if(Vh(s)!=="object")throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)");var t={};this.subscribe=function(n,r,a){if(a=a||!1,typeof n!="string"||typeof r!="function"||typeof a!="boolean")throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)");t.hasOwnProperty(n)||(t[n]={});var i=Math.random().toString(35);return t[n][i]=[r,!!a],i},this.unsubscribe=function(n){for(var r in t)if(t[r][n])return delete t[r][n],Object.keys(t[r]).length===0&&delete t[r],!0;return!1},this.publish=function(n){if(t.hasOwnProperty(n)){var r=Array.prototype.slice.call(arguments,1),a=[];for(var i in t[n]){var l=t[n][i];try{l[0].apply(s,r)}catch(o){cc.console&&Am.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function d6e(s){if(!(this instanceof d6e))return new d6e(s);var t="opacity,stroke-opacity".split(",");for(var n in s)s.hasOwnProperty(n)&&t.indexOf(n)>=0&&(this[n]=s[n]);this.id="",this.objectNumber=-1}function YJt(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function hF(s,t,n,r,a){if(!(this instanceof hF))return new hF(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,YJt.call(this,r,a)}function bU(s,t,n,r,a){if(!(this instanceof bU))return new bU(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,YJt.call(this,r,a)}function Po(s){var t,n=typeof arguments[0]=="string"?arguments[0]:"p",r=arguments[1],a=arguments[2],i=arguments[3],l=[],o=1,c=16,d="S",u=null;Vh(s=s||{})==="object"&&(n=s.orientation,r=s.unit||r,a=s.format||a,i=s.compress||s.compressPdf||i,(u=s.encryption||null)!==null&&(u.userPassword=u.userPassword||"",u.ownerPassword=u.ownerPassword||"",u.userPermissions=u.userPermissions||[]),o=typeof s.userUnit=="number"?Math.abs(s.userUnit):1,s.precision!==void 0&&(t=s.precision),s.floatPrecision!==void 0&&(c=s.floatPrecision),d=s.defaultPathOperation||"S"),l=s.filters||(i===!0?["FlateEncode"]:l),r=r||"mm",n=(""+(n||"P")).toLowerCase();var h=s.putOnlyUsedFonts||!1,m={},p={internal:{},__private__:{}};p.__private__.PubSub=mSt;var f="1.3",g=p.__private__.getPdfVersion=function(){return f};p.__private__.setPdfVersion=function(ot){f=ot};var v={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};p.__private__.getPageFormats=function(){return v};var y=p.__private__.getPageFormat=function(ot){return v[ot]};a=a||"a4";var b="compat",w="advanced",S=b;function C(){this.saveGraphicsState(),Ae(new As(Zt,0,0,-Zt,0,Um()*Zt).toString()+" cm"),this.setFontSize(this.getFontSize()/Zt),d="n",S=w}function E(){this.restoreGraphicsState(),d="S",S=b}var P=p.__private__.combineFontStyleAndFontWeight=function(ot,ts){if(ot=="bold"&&ts=="normal"||ot=="bold"&&ts==400||ot=="normal"&&ts=="italic"||ot=="bold"&&ts=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return ts&&(ot=ts==400||ts==="normal"?ot==="italic"?"italic":"normal":ts!=700&&ts!=="bold"||ot!=="normal"?(ts==700?"bold":ts)+""+ot:"bold"),ot};p.advancedAPI=function(ot){var ts=S===b;return ts&&C.call(this),typeof ot!="function"||(ot(this),ts&&E.call(this)),this},p.compatAPI=function(ot){var ts=S===w;return ts&&E.call(this),typeof ot!="function"||(ot(this),ts&&C.call(this)),this},p.isAdvancedAPI=function(){return S===w};var M,I=function(ot){if(S!==w)throw new Error(ot+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},D=p.roundToPrecision=p.__private__.roundToPrecision=function(ot,ts){var Ks=t||ts;if(isNaN(ot)||isNaN(Ks))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return ot.toFixed(Ks).replace(/0+$/,"")};M=p.hpf=p.__private__.hpf=typeof c=="number"?function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.hpf");return D(ot,c)}:c==="smart"?function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.hpf");return D(ot,ot>-1&&ot<1?16:5)}:function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.hpf");return D(ot,16)};var F=p.f2=p.__private__.f2=function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.f2");return D(ot,2)},q=p.__private__.f3=function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.f3");return D(ot,3)},G=p.scale=p.__private__.scale=function(ot){if(isNaN(ot))throw new Error("Invalid argument passed to jsPDF.scale");return S===b?ot*Zt:S===w?ot:void 0},V=function(ot){return G(function(ts){return S===b?Um()-ts:S===w?ts:void 0}(ot))};p.__private__.setPrecision=p.setPrecision=function(ot){typeof parseInt(ot,10)=="number"&&(t=parseInt(ot,10))};var H,K="00000000000000000000000000000000",Z=p.__private__.getFileId=function(){return K},oe=p.__private__.setFileId=function(ot){return K=ot!==void 0&&/^[a-fA-F0-9]{32}$/.test(ot)?ot.toUpperCase():K.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(tl=new M$(u.userPermissions,u.userPassword,u.ownerPassword,K)),K};p.setFileId=function(ot){return oe(ot),this},p.getFileId=function(){return Z()};var re=p.__private__.convertDateToPDFDate=function(ot){var ts=ot.getTimezoneOffset(),Ks=ts<0?"+":"-",Js=Math.floor(Math.abs(ts/60)),Mn=Math.abs(ts%60),Ur=[Ks,ve(Js),"'",ve(Mn),"'"].join("");return["D:",ot.getFullYear(),ve(ot.getMonth()+1),ve(ot.getDate()),ve(ot.getHours()),ve(ot.getMinutes()),ve(ot.getSeconds()),Ur].join("")},ae=p.__private__.convertPDFDateToDate=function(ot){var ts=parseInt(ot.substr(2,4),10),Ks=parseInt(ot.substr(6,2),10)-1,Js=parseInt(ot.substr(8,2),10),Mn=parseInt(ot.substr(10,2),10),Ur=parseInt(ot.substr(12,2),10),ea=parseInt(ot.substr(14,2),10);return new Date(ts,Ks,Js,Mn,Ur,ea,0)},J=p.__private__.setCreationDate=function(ot){var ts;if(ot===void 0&&(ot=new Date),ot instanceof Date)ts=re(ot);else{if(!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(ot))throw new Error("Invalid argument passed to jsPDF.setCreationDate");ts=ot}return H=ts},te=p.__private__.getCreationDate=function(ot){var ts=H;return ot==="jsDate"&&(ts=ae(H)),ts};p.setCreationDate=function(ot){return J(ot),this},p.getCreationDate=function(ot){return te(ot)};var ce,ve=p.__private__.padd2=function(ot){return("0"+parseInt(ot)).slice(-2)},me=p.__private__.padd2Hex=function(ot){return("00"+(ot=ot.toString())).substr(ot.length)},he=0,ge=[],Ee=[],Ne=0,Pe=[],Oe=[],ke=!1,Ve=Ee;p.__private__.setCustomOutputDestination=function(ot){ke=!0,Ve=ot};var _e=function(ot){ke||(Ve=ot)};p.__private__.resetCustomOutputDestination=function(){ke=!1,Ve=Ee};var Ae=p.__private__.out=function(ot){return ot=ot.toString(),Ne+=ot.length+1,Ve.push(ot),Ve},Se=p.__private__.write=function(ot){return Ae(arguments.length===1?ot.toString():Array.prototype.join.call(arguments," "))},We=p.__private__.getArrayBuffer=function(ot){for(var ts=ot.length,Ks=new ArrayBuffer(ts),Js=new Uint8Array(Ks);ts--;)Js[ts]=ot.charCodeAt(ts);return Ks},qe=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];p.__private__.getStandardFonts=function(){return qe};var Be=s.fontSize||16;p.__private__.setFontSize=p.setFontSize=function(ot){return Be=S===w?ot/Zt:ot,this};var Ze,$e=p.__private__.getFontSize=p.getFontSize=function(){return S===b?Be:Be*Zt},Xe=s.R2L||!1;p.__private__.setR2L=p.setR2L=function(ot){return Xe=ot,this},p.__private__.getR2L=p.getR2L=function(){return Xe};var nt,Ge=p.__private__.setZoomMode=function(ot){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(ot))Ze=ot;else if(isNaN(ot)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(ot)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+ot+'" is not recognized.');Ze=ot}else Ze=parseInt(ot,10)};p.__private__.getZoomMode=function(){return Ze};var Je,ut=p.__private__.setPageMode=function(ot){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(ot)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+ot+'" is not recognized.');nt=ot};p.__private__.getPageMode=function(){return nt};var lt=p.__private__.setLayoutMode=function(ot){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(ot)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+ot+'" is not recognized.');Je=ot};p.__private__.getLayoutMode=function(){return Je},p.__private__.setDisplayMode=p.setDisplayMode=function(ot,ts,Ks){return Ge(ot),lt(ts),ut(Ks),this};var qt={title:"",subject:"",author:"",keywords:"",creator:""};p.__private__.getDocumentProperty=function(ot){if(Object.keys(qt).indexOf(ot)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return qt[ot]},p.__private__.getDocumentProperties=function(){return qt},p.__private__.setDocumentProperties=p.setProperties=p.setDocumentProperties=function(ot){for(var ts in qt)qt.hasOwnProperty(ts)&&ot[ts]&&(qt[ts]=ot[ts]);return this},p.__private__.setDocumentProperty=function(ot,ts){if(Object.keys(qt).indexOf(ot)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return qt[ot]=ts};var zt,Zt,ms,Dt,It,qs={},wt={},Us=[],Es={},kn={},Sn={},bn={},cr=null,Fs=0,cn=[],lr=new mSt(p),Tn=s.hotfixes||[],Yn={},fs={},wn=[],As=function ot(ts,Ks,Js,Mn,Ur,ea){if(!(this instanceof ot))return new ot(ts,Ks,Js,Mn,Ur,ea);isNaN(ts)&&(ts=1),isNaN(Ks)&&(Ks=0),isNaN(Js)&&(Js=0),isNaN(Mn)&&(Mn=1),isNaN(Ur)&&(Ur=0),isNaN(ea)&&(ea=0),this._matrix=[ts,Ks,Js,Mn,Ur,ea]};Object.defineProperty(As.prototype,"sx",{get:function(){return this._matrix[0]},set:function(ot){this._matrix[0]=ot}}),Object.defineProperty(As.prototype,"shy",{get:function(){return this._matrix[1]},set:function(ot){this._matrix[1]=ot}}),Object.defineProperty(As.prototype,"shx",{get:function(){return this._matrix[2]},set:function(ot){this._matrix[2]=ot}}),Object.defineProperty(As.prototype,"sy",{get:function(){return this._matrix[3]},set:function(ot){this._matrix[3]=ot}}),Object.defineProperty(As.prototype,"tx",{get:function(){return this._matrix[4]},set:function(ot){this._matrix[4]=ot}}),Object.defineProperty(As.prototype,"ty",{get:function(){return this._matrix[5]},set:function(ot){this._matrix[5]=ot}}),Object.defineProperty(As.prototype,"a",{get:function(){return this._matrix[0]},set:function(ot){this._matrix[0]=ot}}),Object.defineProperty(As.prototype,"b",{get:function(){return this._matrix[1]},set:function(ot){this._matrix[1]=ot}}),Object.defineProperty(As.prototype,"c",{get:function(){return this._matrix[2]},set:function(ot){this._matrix[2]=ot}}),Object.defineProperty(As.prototype,"d",{get:function(){return this._matrix[3]},set:function(ot){this._matrix[3]=ot}}),Object.defineProperty(As.prototype,"e",{get:function(){return this._matrix[4]},set:function(ot){this._matrix[4]=ot}}),Object.defineProperty(As.prototype,"f",{get:function(){return this._matrix[5]},set:function(ot){this._matrix[5]=ot}}),Object.defineProperty(As.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(As.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(As.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(As.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),As.prototype.join=function(ot){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(M).join(ot)},As.prototype.multiply=function(ot){var ts=ot.sx*this.sx+ot.shy*this.shx,Ks=ot.sx*this.shy+ot.shy*this.sy,Js=ot.shx*this.sx+ot.sy*this.shx,Mn=ot.shx*this.shy+ot.sy*this.sy,Ur=ot.tx*this.sx+ot.ty*this.shx+this.tx,ea=ot.tx*this.shy+ot.ty*this.sy+this.ty;return new As(ts,Ks,Js,Mn,Ur,ea)},As.prototype.decompose=function(){var ot=this.sx,ts=this.shy,Ks=this.shx,Js=this.sy,Mn=this.tx,Ur=this.ty,ea=Math.sqrt(ot*ot+ts*ts),Pr=(ot/=ea)*Ks+(ts/=ea)*Js;Ks-=ot*Pr,Js-=ts*Pr;var Ni=Math.sqrt(Ks*Ks+Js*Js);return Pr/=Ni,ot*(Js/=Ni)>16&255,Js=Ni>>8&255,Mn=255&Ni}if(Js===void 0||Ur===void 0&&Ks===Js&&Js===Mn)ts=typeof Ks=="string"?Ks+" "+ea[0]:ot.precision===2?F(Ks/255)+" "+ea[0]:q(Ks/255)+" "+ea[0];else if(Ur===void 0||Vh(Ur)==="object"){if(Ur&&!isNaN(Ur.a)&&Ur.a===0)return["1.","1.","1.",ea[1]].join(" ");ts=typeof Ks=="string"?[Ks,Js,Mn,ea[1]].join(" "):ot.precision===2?[F(Ks/255),F(Js/255),F(Mn/255),ea[1]].join(" "):[q(Ks/255),q(Js/255),q(Mn/255),ea[1]].join(" ")}else ts=typeof Ks=="string"?[Ks,Js,Mn,Ur,ea[2]].join(" "):ot.precision===2?[F(Ks),F(Js),F(Mn),F(Ur),ea[2]].join(" "):[q(Ks),q(Js),q(Mn),q(Ur),ea[2]].join(" ");return ts},Lt=p.__private__.getFilters=function(){return l},Mt=p.__private__.putStream=function(ot){var ts=(ot=ot||{}).data||"",Ks=ot.filters||Lt(),Js=ot.alreadyAppliedFilters||[],Mn=ot.addLength1||!1,Ur=ts.length,ea=ot.objectId,Pr=function(Ai){return Ai};if(u!==null&&ea===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Pr=tl.encryptor(ea,0));var Ni={};Ks===!0&&(Ks=["FlateEncode"]);var Lo=ot.additionalKeyValues||[],wo=(Ni=Po.API.processDataByFilters!==void 0?Po.API.processDataByFilters(ts,Ks):{data:ts,reverseChain:[]}).reverseChain+(Array.isArray(Js)?Js.join(" "):Js.toString());if(Ni.data.length!==0&&(Lo.push({key:"Length",value:Ni.data.length}),Mn===!0&&Lo.push({key:"Length1",value:Ur})),wo.length!=0)if(wo.split("/").length-1==1)Lo.push({key:"Filter",value:wo});else{Lo.push({key:"Filter",value:"["+wo+"]"});for(var Wl=0;Wl>"),Ni.data.length!==0&&(Ae("stream"),Ae(Pr(Ni.data)),Ae("endstream"))},Qt=p.__private__.putPage=function(ot){var ts=ot.number,Ks=ot.data,Js=ot.objId,Mn=ot.contentsObjId;tr(Js,!0),Ae("<>"),Ae("endobj");var Ur=Ks.join(` `);return S===w&&(Ur+=` Q`),tr(Mn,!0),Mt({data:Ur,filters:Lt(),objectId:Mn}),Ae("endobj"),Js},ks=p.__private__.putPages=function(){var ot,ts,Ks=[];for(ot=1;ot<=Fs;ot++)cn[ot].objId=an(),cn[ot].contentsObjId=an();for(ot=1;ot<=Fs;ot++)Ks.push(Qt({number:ot,data:Oe[ot],objId:cn[ot].objId,contentsObjId:cn[ot].contentsObjId,mediaBox:cn[ot].mediaBox,cropBox:cn[ot].cropBox,bleedBox:cn[ot].bleedBox,trimBox:cn[ot].trimBox,artBox:cn[ot].artBox,userUnit:cn[ot].userUnit,rootDictionaryObjId:Yt,resourceDictionaryObjId:it}));tr(Yt,!0),Ae("<>"),Ae("endobj"),lr.publish("postPutPages")},gs=function(ot){lr.publish("putFont",{font:ot,out:Ae,newObject:Gs,putStream:Mt}),ot.isAlreadyPutted!==!0&&(ot.objectNumber=Gs(),Ae("<<"),Ae("/Type /Font"),Ae("/BaseFont /"+P$(ot.postScriptName)),Ae("/Subtype /Type1"),typeof ot.encoding=="string"&&Ae("/Encoding /"+ot.encoding),Ae("/FirstChar 32"),Ae("/LastChar 255"),Ae(">>"),Ae("endobj"))},Vt=function(ot){ot.objectNumber=Gs();var ts=[];ts.push({key:"Type",value:"/XObject"}),ts.push({key:"Subtype",value:"/Form"}),ts.push({key:"BBox",value:"["+[M(ot.x),M(ot.y),M(ot.x+ot.width),M(ot.y+ot.height)].join(" ")+"]"}),ts.push({key:"Matrix",value:"["+ot.matrix.toString()+"]"});var Ks=ot.pages[1].join(` `);Mt({data:Ks,additionalKeyValues:ts,objectId:ot.objectNumber}),Ae("endobj")},Vs=function(ot,ts){ts||(ts=21);var Ks=Gs(),Js=function(ea,Pr){var Ni,Lo=[],wo=1/(Pr-1);for(Ni=0;Ni<1;Ni+=wo)Lo.push(Ni);if(Lo.push(1),ea[0].offset!=0){var Wl={offset:0,color:ea[0].color};ea.unshift(Wl)}if(ea[ea.length-1].offset!=1){var xd={offset:1,color:ea[ea.length-1].color};ea.push(xd)}for(var Vr="",gi=0,Ai=0;Aiea[gi+1].offset;)gi++;var rc=ea[gi].offset,Yc=(Ni-rc)/(ea[gi+1].offset-rc),mo=ea[gi].color,em=ea[gi+1].color;Vr+=me(Math.round((1-Yc)*mo[0]+Yc*em[0]).toString(16))+me(Math.round((1-Yc)*mo[1]+Yc*em[1]).toString(16))+me(Math.round((1-Yc)*mo[2]+Yc*em[2]).toString(16))}return Vr.trim()}(ot.colors,ts),Mn=[];Mn.push({key:"FunctionType",value:"0"}),Mn.push({key:"Domain",value:"[0.0 1.0]"}),Mn.push({key:"Size",value:"["+ts+"]"}),Mn.push({key:"BitsPerSample",value:"8"}),Mn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Mn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Mt({data:Js,additionalKeyValues:Mn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:Ks}),Ae("endobj"),ot.objectNumber=Gs(),Ae("<< /ShadingType "+ot.type),Ae("/ColorSpace /DeviceRGB");var Ur="/Coords ["+M(parseFloat(ot.coords[0]))+" "+M(parseFloat(ot.coords[1]))+" ";ot.type===2?Ur+=M(parseFloat(ot.coords[2]))+" "+M(parseFloat(ot.coords[3])):Ur+=M(parseFloat(ot.coords[2]))+" "+M(parseFloat(ot.coords[3]))+" "+M(parseFloat(ot.coords[4]))+" "+M(parseFloat(ot.coords[5])),Ae(Ur+="]"),ot.matrix&&Ae("/Matrix ["+ot.matrix.toString()+"]"),Ae("/Function "+Ks+" 0 R"),Ae("/Extend [true true]"),Ae(">>"),Ae("endobj")},Zs=function(ot,ts){var Ks=an(),Js=Gs();ts.push({resourcesOid:Ks,objectOid:Js}),ot.objectNumber=Js;var Mn=[];Mn.push({key:"Type",value:"/Pattern"}),Mn.push({key:"PatternType",value:"1"}),Mn.push({key:"PaintType",value:"1"}),Mn.push({key:"TilingType",value:"1"}),Mn.push({key:"BBox",value:"["+ot.boundingBox.map(M).join(" ")+"]"}),Mn.push({key:"XStep",value:M(ot.xStep)}),Mn.push({key:"YStep",value:M(ot.yStep)}),Mn.push({key:"Resources",value:Ks+" 0 R"}),ot.matrix&&Mn.push({key:"Matrix",value:"["+ot.matrix.toString()+"]"}),Mt({data:ot.stream,additionalKeyValues:Mn,objectId:ot.objectNumber}),Ae("endobj")},Zn=function(ot){for(var ts in ot.objectNumber=Gs(),Ae("<<"),ot)switch(ts){case"opacity":Ae("/ca "+F(ot[ts]));break;case"stroke-opacity":Ae("/CA "+F(ot[ts]))}Ae(">>"),Ae("endobj")},Or=function(ot){tr(ot.resourcesOid,!0),Ae("<<"),Ae("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var ts in Ae("/Font <<"),qs)qs.hasOwnProperty(ts)&&(h===!1||h===!0&&m.hasOwnProperty(ts))&&Ae("/"+ts+" "+qs[ts].objectNumber+" 0 R");Ae(">>")}(),function(){if(Object.keys(Es).length>0){for(var ts in Ae("/Shading <<"),Es)Es.hasOwnProperty(ts)&&Es[ts]instanceof hF&&Es[ts].objectNumber>=0&&Ae("/"+ts+" "+Es[ts].objectNumber+" 0 R");lr.publish("putShadingPatternDict"),Ae(">>")}}(),function(ts){if(Object.keys(Es).length>0){for(var Ks in Ae("/Pattern <<"),Es)Es.hasOwnProperty(Ks)&&Es[Ks]instanceof p.TilingPattern&&Es[Ks].objectNumber>=0&&Es[Ks].objectNumber>")}}(ot.objectOid),function(){if(Object.keys(Sn).length>0){var ts;for(ts in Ae("/ExtGState <<"),Sn)Sn.hasOwnProperty(ts)&&Sn[ts].objectNumber>=0&&Ae("/"+ts+" "+Sn[ts].objectNumber+" 0 R");lr.publish("putGStateDict"),Ae(">>")}}(),function(){for(var ts in Ae("/XObject <<"),Yn)Yn.hasOwnProperty(ts)&&Yn[ts].objectNumber>=0&&Ae("/"+ts+" "+Yn[ts].objectNumber+" 0 R");lr.publish("putXobjectDict"),Ae(">>")}(),Ae(">>"),Ae("endobj")},oa=function(ot){wt[ot.fontName]=wt[ot.fontName]||{},wt[ot.fontName][ot.fontStyle]=ot.id},aa=function(ot,ts,Ks,Js,Mn){var Ur={id:"F"+(Object.keys(qs).length+1).toString(10),postScriptName:ot,fontName:ts,fontStyle:Ks,encoding:Js,isStandardFont:Mn||!1,metadata:{}};return lr.publish("addFont",{font:Ur,instance:this}),qs[Ur.id]=Ur,oa(Ur),Ur.id},Kr=p.__private__.pdfEscape=p.pdfEscape=function(ot,ts){return function(Ks,Js){var Mn,Ur,ea,Pr,Ni,Lo,wo,Wl,xd;if(ea=(Js=Js||{}).sourceEncoding||"Unicode",Ni=Js.outputEncoding,(Js.autoencode||Ni)&&qs[zt].metadata&&qs[zt].metadata[ea]&&qs[zt].metadata[ea].encoding&&(Pr=qs[zt].metadata[ea].encoding,!Ni&&qs[zt].encoding&&(Ni=qs[zt].encoding),!Ni&&Pr.codePages&&(Ni=Pr.codePages[0]),typeof Ni=="string"&&(Ni=Pr[Ni]),Ni)){for(wo=!1,Lo=[],Mn=0,Ur=Ks.length;Mn>8&&(wo=!0);Ks=Lo.join("")}for(Mn=Ks.length;wo===void 0&&Mn!==0;)Ks.charCodeAt(Mn-1)>>8&&(wo=!0),Mn--;if(!wo)return Ks;for(Lo=Js.noBOM?[]:[254,255],Mn=0,Ur=Ks.length;Mn>8)>>8)throw new Error("Character at position "+Mn+" of string '"+Ks+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Lo.push(xd),Lo.push(Wl-(xd<<8))}return String.fromCharCode.apply(void 0,Lo)}(ot,ts).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Tr=p.__private__.beginPage=function(ot){Oe[++Fs]=[],cn[Fs]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(ot[0]),topRightY:Number(ot[1])}},Ja(Fs),_e(Oe[ce])},Hr=function(ot,ts){var Ks,Js,Mn;switch(n=ts||n,typeof ot=="string"&&(Ks=y(ot.toLowerCase()),Array.isArray(Ks)&&(Js=Ks[0],Mn=Ks[1])),Array.isArray(ot)&&(Js=ot[0]*Zt,Mn=ot[1]*Zt),isNaN(Js)&&(Js=a[0],Mn=a[1]),(Js>14400||Mn>14400)&&(Am.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),Js=Math.min(14400,Js),Mn=Math.min(14400,Mn)),a=[Js,Mn],n.substr(0,1)){case"l":Mn>Js&&(a=[Mn,Js]);break;case"p":Js>Mn&&(a=[Mn,Js])}Tr(a),il(vo),Ae(nx),pd!==0&&Ae(pd+" J"),fd!==0&&Ae(fd+" j"),lr.publish("addPage",{pageNumber:Fs})},Ba=function(ot){ot>0&&ot<=Fs&&(Oe.splice(ot,1),cn.splice(ot,1),Fs--,ce>Fs&&(ce=Fs),this.setPage(ce))},Ja=function(ot){ot>0&&ot<=Fs&&(ce=ot)},Ro=p.__private__.getNumberOfPages=p.getNumberOfPages=function(){return Oe.length-1},ji=function(ot,ts,Ks){var Js,Mn=void 0;return Ks=Ks||{},ot=ot!==void 0?ot:qs[zt].fontName,ts=ts!==void 0?ts:qs[zt].fontStyle,Js=ot.toLowerCase(),wt[Js]!==void 0&&wt[Js][ts]!==void 0?Mn=wt[Js][ts]:wt[ot]!==void 0&&wt[ot][ts]!==void 0?Mn=wt[ot][ts]:Ks.disableWarning===!1&&Am.warn("Unable to look up font label for font '"+ot+"', '"+ts+"'. Refer to getFontList() for available fonts."),Mn||Ks.noFallback||(Mn=wt.times[ts])==null&&(Mn=wt.times.normal),Mn},Oa=p.__private__.putInfo=function(){var ot=Gs(),ts=function(Js){return Js};for(var Ks in u!==null&&(ts=tl.encryptor(ot,0)),Ae("<<"),Ae("/Producer ("+Kr(ts("jsPDF "+Po.version))+")"),qt)qt.hasOwnProperty(Ks)&&qt[Ks]&&Ae("/"+Ks.substr(0,1).toUpperCase()+Ks.substr(1)+" ("+Kr(ts(qt[Ks]))+")");Ae("/CreationDate ("+Kr(ts(H))+")"),Ae(">>"),Ae("endobj")},Ao=p.__private__.putCatalog=function(ot){var ts=(ot=ot||{}).rootDictionaryObjId||Yt;switch(Gs(),Ae("<<"),Ae("/Type /Catalog"),Ae("/Pages "+ts+" 0 R"),Ze||(Ze="fullwidth"),Ze){case"fullwidth":Ae("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Ae("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Ae("/OpenAction [3 0 R /Fit]");break;case"original":Ae("/OpenAction [3 0 R /XYZ null null 1]");break;default:var Ks=""+Ze;Ks.substr(Ks.length-1)==="%"&&(Ze=parseInt(Ze)/100),typeof Ze=="number"&&Ae("/OpenAction [3 0 R /XYZ null null "+F(Ze)+"]")}switch(Je||(Je="continuous"),Je){case"continuous":Ae("/PageLayout /OneColumn");break;case"single":Ae("/PageLayout /SinglePage");break;case"two":case"twoleft":Ae("/PageLayout /TwoColumnLeft");break;case"tworight":Ae("/PageLayout /TwoColumnRight")}nt&&Ae("/PageMode /"+nt),lr.publish("putCatalog"),Ae(">>"),Ae("endobj")},uo=p.__private__.putTrailer=function(){Ae("trailer"),Ae("<<"),Ae("/Size "+(he+1)),Ae("/Root "+he+" 0 R"),Ae("/Info "+(he-1)+" 0 R"),u!==null&&Ae("/Encrypt "+tl.oid+" 0 R"),Ae("/ID [ <"+K+"> <"+K+"> ]"),Ae(">>")},Ua=p.__private__.putHeader=function(){Ae("%PDF-"+f),Ae("%ºß¬à")},Eo=p.__private__.putXRef=function(){var ot="0000000000";Ae("xref"),Ae("0 "+(he+1)),Ae("0000000000 65535 f ");for(var ts=1;ts<=he;ts++)typeof ge[ts]=="function"?Ae((ot+ge[ts]()).slice(-10)+" 00000 n "):ge[ts]!==void 0?Ae((ot+ge[ts]).slice(-10)+" 00000 n "):Ae("0000000000 00000 n ")},Ji=p.__private__.buildDocument=function(){var ot;he=0,Ne=0,Ee=[],ge=[],Pe=[],Yt=an(),it=an(),_e(Ee),lr.publish("buildDocument"),Ua(),ks(),function(){lr.publish("putAdditionalObjects");for(var Ks=0;Ks"),Ae("/O <"+tl.toHexString(tl.O)+">"),Ae("/P "+tl.P),Ae(">>"),Ae("endobj")),Oa(),Ao();var ts=Ne;return Eo(),uo(),Ae("startxref"),Ae(""+ts),Ae("%%EOF"),_e(Oe[ce]),Ee.join(` `)},qa=p.__private__.getBlob=function(ot){return new Blob([We(ot)],{type:"application/pdf"})},ar=function(ot){for(;ot.firstChild;)ot.removeChild(ot.firstChild)},ui=function(ot){var ts,Ks=ot.document,Js=Ks.documentElement,Mn=Ks.head,Ur=Ks.body;return Mn||(Mn=Ks.createElement("head"),Js.appendChild(Mn)),Ur||(Ur=Ks.createElement("body"),Js.appendChild(Ur)),ar(Mn),ar(Ur),(ts=Ks.createElement("style")).appendChild(Ks.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),Mn.appendChild(ts),{document:Ks,body:Ur}},zo=p.output=p.__private__.output=(Pn=function(ot,ts){switch(typeof(ts=ts||{})=="string"?ts={filename:ts}:ts.filename=ts.filename||"generated.pdf",ot){case void 0:return Ji();case"save":p.save(ts.filename);break;case"arraybuffer":return We(Ji());case"blob":return qa(Ji());case"bloburi":case"bloburl":if(cc.URL!==void 0&&typeof cc.URL.createObjectURL=="function")return cc.URL&&cc.URL.createObjectURL(qa(Ji()))||void 0;Am.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var Ks="",Js=Ji();try{Ks=dSt(Js)}catch{Ks=dSt(unescape(encodeURIComponent(Js)))}return"data:application/pdf;filename="+encodeURIComponent(ts.filename)+";base64,"+Ks;case"pdfobjectnewwindow":if(Object.prototype.toString.call(cc)==="[object Window]"){var Mn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Ur=!ts.pdfObjectUrl;Ur||(Mn=ts.pdfObjectUrl);var ea=cc.open();if(ea!==null){var Pr=ui(ea),Ni=Pr.document.createElement("script"),Lo=this;Ni.src=Mn,Ur&&(Ni.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",Ni.crossOrigin="anonymous"),Ni.onload=function(){ea.PDFObject.embed(Lo.output("dataurlstring"),ts)},Pr.body.appendChild(Ni)}return ea}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(cc)==="[object Window]"){var wo=ts.pdfJsUrl||"examples/PDF.js/web/viewer.html",Wl=cc.open();if(Wl!==null){var xd=ui(Wl),Vr=xd.document.createElement("iframe"),gi=wo.indexOf("?")===-1?"?":"&";Lo=this,Vr.id="pdfViewer",Vr.width="500px",Vr.height="400px",Vr.src=wo+gi+"file=&downloadName="+encodeURIComponent(ts.filename),Vr.onload=function(){Wl.document.title=ts.filename,Vr.contentWindow.PDFViewerApplication.open(Lo.output("bloburl"))},xd.body.appendChild(Vr)}return Wl}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(cc)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var Ai=cc.open();if(Ai!==null){var rc=ui(Ai),Yc=rc.document.createElement("iframe");Yc.src=this.output("datauristring",ts),rc.body.appendChild(Yc),Ai.document.title=ts.filename}if(Ai||typeof safari>"u")return Ai;break;case"datauri":case"dataurl":return cc.document.location.href=this.output("datauristring",ts);default:return null}},Pn.foo=function(){try{return Pn.apply(this,arguments)}catch(Ks){var ot=Ks.stack||"";~ot.indexOf(" at ")&&(ot=ot.split(" at ")[1]);var ts="Error in function "+ot.split(` `)[0].split("<")[0]+": "+Ks.message;if(!cc.console)throw new Error(ts);cc.console.error(ts,Ks),cc.alert&&alert(ts)}},Pn.foo.bar=Pn,Pn.foo),gl=function(ot){return Array.isArray(Tn)===!0&&Tn.indexOf(ot)>-1};switch(r){case"pt":Zt=1;break;case"mm":Zt=72/25.4;break;case"cm":Zt=72/2.54;break;case"in":Zt=72;break;case"px":Zt=gl("px_scaling")==1?.75:96/72;break;case"pc":case"em":Zt=12;break;case"ex":Zt=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);Zt=r}var tl=null;J(),oe();var Ll=p.__private__.getPageInfo=p.getPageInfo=function(ot){if(isNaN(ot)||ot%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:cn[ot].objId,pageNumber:ot,pageContext:cn[ot]}},Ku=p.__private__.getPageInfoByObjId=function(ot){if(isNaN(ot)||ot%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var ts in cn)if(cn[ts].objId===ot)break;return Ll(ts)},uh=p.__private__.getCurrentPageInfo=p.getCurrentPageInfo=function(){return{objId:cn[ce].objId,pageNumber:ce,pageContext:cn[ce]}};p.addPage=function(){return Hr.apply(this,arguments),this},p.setPage=function(){return Ja.apply(this,arguments),_e.call(this,Oe[ce]),this},p.insertPage=function(ot){return this.addPage(),this.movePage(ce,ot),this},p.movePage=function(ot,ts){var Ks,Js;if(ot>ts){Ks=Oe[ot],Js=cn[ot];for(var Mn=ot;Mn>ts;Mn--)Oe[Mn]=Oe[Mn-1],cn[Mn]=cn[Mn-1];Oe[ts]=Ks,cn[ts]=Js,this.setPage(ts)}else if(ot0&&(typeof ot=="string"?ot=gi.splitTextToSize(ot,wo):Object.prototype.toString.call(ot)==="[object Array]"&&(ot=ot.reduce(function(Cl,fl){return Cl.concat(gi.splitTextToSize(fl,wo))},[]))),Ur={text:ot,x:ts,y:Ks,options:Js,mutex:{pdfEscape:Kr,activeFontKey:zt,fonts:qs,activeFontSize:Be}},lr.publish("preProcessText",Ur),ot=Ur.text,Pr=(Js=Ur.options).angle,Vr instanceof As==0&&Pr&&typeof Pr=="number"){Pr*=Math.PI/180,Js.rotationDirection===0&&(Pr=-Pr),S===w&&(Pr=-Pr);var pp=Math.cos(Pr),gd=Math.sin(Pr);Vr=new As(pp,gd,-gd,pp,0,0)}else Pr&&Pr instanceof As&&(Vr=Pr);S!==w||Vr||(Vr=pr),(Lo=Js.charSpace||hh)!==void 0&&(Yc+=M(G(Lo))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(xd=Js.horizontalScale)!==void 0&&(Yc+=M(100*xd)+` Tz `),Js.lang;var Hd=-1,Th=Js.renderingMode!==void 0?Js.renderingMode:Js.stroke,Rp=gi.internal.getCurrentPageInfo().pageContext;switch(Th){case 0:case!1:case"fill":Hd=0;break;case 1:case!0:case"stroke":Hd=1;break;case 2:case"fillThenStroke":Hd=2;break;case 3:case"invisible":Hd=3;break;case 4:case"fillAndAddForClipping":Hd=4;break;case 5:case"strokeAndAddPathForClipping":Hd=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":Hd=6;break;case 7:case"addToPathForClipping":Hd=7}var qx=Rp.usedRenderingMode!==void 0?Rp.usedRenderingMode:-1;Hd!==-1?Yc+=Hd+` Tr `:qx!==-1&&(Yc+=`0 Tr `),Hd!==-1&&(Rp.usedRenderingMode=Hd),Ni=Js.align||"left";var ac,$a=Be*mo,Yr=gi.internal.pageSize.getWidth(),Tc=qs[zt];Lo=Js.charSpace||hh,wo=Js.maxWidth||0,Wl=Object.assign({autoencode:!0,noBOM:!0},Js.flags);var Va=[],Fp=function(Cl){return gi.getStringUnitWidth(Cl,{font:Tc,charSpace:Lo,fontSize:Be,doKerning:!1})*Be/em};if(Object.prototype.toString.call(ot)==="[object Array]"){var cu;ea=An(ot),Ni!=="left"&&(ac=ea.map(Fp));var ba,Zg=0;if(Ni==="right"){ts-=ac[0],ot=[],wi=ea.length;for(var qy=0;qy0?(wo-ac[Id])/xf:0;Id":")"),yd=parseFloat(ea[fh][1]),Xg=parseFloat(ea[fh][2]);break;case 0:O0=(rc?"<":"(")+ea[fh]+(rc?">":")"),yd=Dp(ts),Xg=hp(Ks)}Va!==void 0&&Va[fh]!==void 0&&(Hx=Va[fh]+` Tw `),fh===0?ot.push(Hx+Fb(yd,Xg,Vr)+O0):_m===0?ot.push(Hx+O0):_m===1&&ot.push(Hx+Fb(yd,Xg,Vr)+O0)}ot=_m===0?ot.join(` Tj T* `):ot.join(` Tj `),ot+=` Tj `;var Mc=`BT /`;return Mc+=zt+" "+Be+` Tf `,Mc+=M(Be*mo)+` TL `,Mc+=vm+` `,Mc+=Yc,Mc+=ot,Ae(Mc+="ET"),m[zt]=!0,gi};var ym=p.__private__.clip=p.clip=function(ot){return Ae(ot==="evenodd"?"W*":"W"),this};p.clipEvenOdd=function(){return ym("evenodd")},p.__private__.discardPath=p.discardPath=function(){return Ae("n"),this};var Ld=p.__private__.isValidStyle=function(ot){var ts=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(ot)!==-1&&(ts=!0),ts};p.__private__.setDefaultPathOperation=p.setDefaultPathOperation=function(ot){return Ld(ot)&&(d=ot),this};var Bm=p.__private__.getStyle=p.getStyle=function(ot){var ts=d;switch(ot){case"D":case"S":ts="S";break;case"F":ts="f";break;case"FD":case"DF":ts="B";break;case"f":case"f*":case"B":case"B*":ts=ot}return ts},Sl=p.close=function(){return Ae("h"),this};p.stroke=function(){return Ae("S"),this},p.fill=function(ot){return wu("f",ot),this},p.fillEvenOdd=function(ot){return wu("f*",ot),this},p.fillStroke=function(ot){return wu("B",ot),this},p.fillStrokeEvenOdd=function(ot){return wu("B*",ot),this};var wu=function(ot,ts){Vh(ts)==="object"?to(ts,ot):Ae(ot)},js=function(ot){ot===null||S===w&&ot===void 0||(ot=Bm(ot),Ae(ot))};function Ma(ot,ts,Ks,Js,Mn){var Ur=new bU(ts||this.boundingBox,Ks||this.xStep,Js||this.yStep,this.gState,Mn||this.matrix);Ur.stream=this.stream;var ea=ot+"$$"+this.cloneIndex+++"$$";return hn(ea,Ur),Ur}var to=function(ot,ts){var Ks=kn[ot.key],Js=Es[Ks];if(Js instanceof hF)Ae("q"),Ae(Ta(ts)),Js.gState&&p.setGState(Js.gState),Ae(ot.matrix.toString()+" cm"),Ae("/"+Ks+" sh"),Ae("Q");else if(Js instanceof bU){var Mn=new As(1,0,0,-1,0,Um());ot.matrix&&(Mn=Mn.multiply(ot.matrix||pr),Ks=Ma.call(Js,ot.key,ot.boundingBox,ot.xStep,ot.yStep,Mn).id),Ae("q"),Ae("/Pattern cs"),Ae("/"+Ks+" scn"),Js.gState&&p.setGState(Js.gState),Ae(ts),Ae("Q")}},Ta=function(ot){switch(ot){case"f":case"F":case"n":return"W n";case"f*":return"W* n";case"B":case"S":return"W S";case"B*":return"W* S"}},so=p.moveTo=function(ot,ts){return Ae(M(G(ot))+" "+M(V(ts))+" m"),this},ho=p.lineTo=function(ot,ts){return Ae(M(G(ot))+" "+M(V(ts))+" l"),this},pi=p.curveTo=function(ot,ts,Ks,Js,Mn,Ur){return Ae([M(G(ot)),M(V(ts)),M(G(Ks)),M(V(Js)),M(G(Mn)),M(V(Ur)),"c"].join(" ")),this};p.__private__.line=p.line=function(ot,ts,Ks,Js,Mn){if(isNaN(ot)||isNaN(ts)||isNaN(Ks)||isNaN(Js)||!Ld(Mn))throw new Error("Invalid arguments passed to jsPDF.line");return S===b?this.lines([[Ks-ot,Js-ts]],ot,ts,[1,1],Mn||"S"):this.lines([[Ks-ot,Js-ts]],ot,ts,[1,1]).stroke()},p.__private__.lines=p.lines=function(ot,ts,Ks,Js,Mn,Ur){var ea,Pr,Ni,Lo,wo,Wl,xd,Vr,gi,Ai,rc,Yc;if(typeof ot=="number"&&(Yc=Ks,Ks=ts,ts=ot,ot=Yc),Js=Js||[1,1],Ur=Ur||!1,isNaN(ts)||isNaN(Ks)||!Array.isArray(ot)||!Array.isArray(Js)||!Ld(Mn)||typeof Ur!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(so(ts,Ks),ea=Js[0],Pr=Js[1],Lo=ot.length,Ai=ts,rc=Ks,Ni=0;Ni>8&255,s>>16&255,s>>24&255)},M$.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},M$.prototype.hexToBytes=function(s){for(var t=[],n=0;n>8&255,s>>16&255,255&t,t>>8&255)).substr(0,10);return function(r){return kKe(n,r)}},d6e.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Vh(s)!==Vh(this))return!1;var r=0;for(t in this)if(!(n.indexOf(t)>=0)){if(this.hasOwnProperty(t)&&!s.hasOwnProperty(t)||this[t]!==s[t])return!1;r++}for(t in s)s.hasOwnProperty(t)&&n.indexOf(t)<0&&r--;return r===0},Po.API={events:[]},Po.version="4.2.1";var bx=Po.API,dat=1,vz=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},QB=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},T9=function(s){return s.toString().replace(/#/g,"#23").replace(/[\s\n\r()<>[\]{}\/%]/g,function(t){var n=t.charCodeAt(0).toString(16).toUpperCase();return"#"+(n.length===1?"0"+n:n)})},Cc=function(s){return s.toFixed(2)},RT=function(s){return s.toFixed(5)};bx.__acroform__={};var sw=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},pSt=function(s){return s*dat},B5=function(s){var t=new XJt,n=ko.internal.getHeight(s)||0,r=ko.internal.getWidth(s)||0;return t.BBox=[0,0,Number(Cc(r)),Number(Cc(n))],t},gqn=bx.__acroform__.setBit=function(s,t){if(s=s||0,t=t||0,isNaN(s)||isNaN(t))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBit");return s|1<0;){t="",i--;var d,u,h=gde("3",s,i).height,m=s.multiline?l-i:(l-h)/2,p=m+=2,f=0,g=0,v=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+gde(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var y="",b=0,w=0;wl)continue e;y+=a[w][v],S=!0,g=w,w--}else{y=(y+=a[w][v]+" ").substr(y.length-1)==" "?y.substr(0,y.length-1):y;var C=parseInt(w),E=c(C,y,i),P=w>=a.length-1;if(E&&!P){y+=" ",v=0;continue}if(E||P){if(P)g=C;else if(s.multiline&&(h+2)*(b+2)+2>l)continue e}else{if(!s.multiline||(h+2)*(b+2)+2>l)continue e;g=C}}for(var M="",I=f;I<=g;I++){var D=a[I];if(s.multiline){if(I===g){M+=D[v]+" ",v=(v+1)%D.length;continue}if(I===f){M+=D[D.length-1]+" ";continue}}M+=D[0]+" "}switch(M=M.substr(M.length-1)==" "?M.substr(0,M.length-1):M,u=gde(M,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=Cc(d)+" "+Cc(p)+` Td `,t+="("+vz(M)+`) Tj `,t+=-Cc(d)+` 0 Td `,p=-(i+2),u=0,f=S?g:g+1,b++,y=""}break}return r.text=t,r.fontSize=i,r},gde=function(s,t,n){var r=t.scope.internal.getFont(t.fontName,t.fontStyle),a=t.scope.getStringUnitWidth(s,{font:r,fontSize:parseFloat(n),charSpace:0})*parseFloat(n);return{height:t.scope.getStringUnitWidth("3",{font:r,fontSize:parseFloat(n),charSpace:0})*parseFloat(n)*1.5,width:a}},wqn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},jqn=function(s,t){var n={type:"reference",object:s};t.internal.getPageInfo(s.page).pageContext.annotations.find(function(r){return r.type===n.type&&r.object===n.object})===void 0&&t.internal.getPageInfo(s.page).pageContext.annotations.push(n)},Nqn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(WS.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(wqn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");dat=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new QJt,s.internal.acroformPlugin.acroFormDictionaryRoot.scope=s,s.internal.acroformPlugin.acroFormDictionaryRoot._eventID=s.internal.events.subscribe("postPutResources",function(){(function(n){n.internal.events.unsubscribe(n.internal.acroformPlugin.acroFormDictionaryRoot._eventID),delete n.internal.acroformPlugin.acroFormDictionaryRoot._eventID,n.internal.acroformPlugin.printedOut=!0})(s)}),s.internal.events.subscribe("buildDocument",function(){(function(n){n.internal.acroformPlugin.acroFormDictionaryRoot.objId=void 0;var r=n.internal.acroformPlugin.acroFormDictionaryRoot.Fields;for(var a in r)if(r.hasOwnProperty(a)){var i=r[a];i.objId=void 0,i.hasAnnotation&&jqn(i,n)}})(s)}),s.internal.events.subscribe("putCatalog",function(){(function(n){if(n.internal.acroformPlugin.acroFormDictionaryRoot===void 0)throw new Error("putCatalogCallback: Root missing.");n.internal.write("/AcroForm "+n.internal.acroformPlugin.acroFormDictionaryRoot.objId+" 0 R")})(s)}),s.internal.events.subscribe("postPutPages",function(n){(function(r,a){var i=!r;for(var l in r||(a.internal.newObjectDeferredBegin(a.internal.acroformPlugin.acroFormDictionaryRoot.objId,!0),a.internal.acroformPlugin.acroFormDictionaryRoot.putStream()),r=r||a.internal.acroformPlugin.acroFormDictionaryRoot.Kids)if(r.hasOwnProperty(l)){var o=r[l],c=[],d=o.Rect;if(o.Rect&&(o.Rect=bqn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=ko.createDefaultAppearanceStream(o),Vh(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=_qn(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var p=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(p).length>=1||Array.isArray(p)){for(var l in p)if(p.hasOwnProperty(l)){var f=p[l];typeof f=="function"&&(f=f.call(a,o)),h+="/"+l+" "+f+" ",a.internal.acroformPlugin.xForms.indexOf(f)>=0||a.internal.acroformPlugin.xForms.push(f)}}else typeof(f=p)=="function"&&(f=f.call(a,o)),h+="/"+l+" "+f,a.internal.acroformPlugin.xForms.indexOf(f)>=0||a.internal.acroformPlugin.xForms.push(f);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(g,v){for(var y in g)if(g.hasOwnProperty(y)){var b=y,w=g[y];v.internal.newObjectDeferredBegin(w.objId,!0),Vh(w)==="object"&&typeof w.putStream=="function"&&w.putStream(),delete g[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},ZJt=bx.__acroform__.arrayToPdfArray=function(s,t,n){var r=function(l){return l};if(Array.isArray(s)){for(var a="[",i=0;i0?t:void 0}}),Object.defineProperty(this,"Fields",{enumerable:!1,configurable:!1,get:function(){return t}}),Object.defineProperty(this,"DA",{enumerable:!1,configurable:!1,get:function(){if(s){var n=function(r){return r};return this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),"("+vz(n(s))+")"}},set:function(n){s=n}})};sw(QJt,B4);var WS=function s(){B4.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(y){if(isNaN(y))throw new Error('Invalid value "'+y+'" for attribute F supplied.');t=y}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!ag(t,3)},set:function(y){y?this.F=ig(t,3):this.F=og(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(y){if(isNaN(y))throw new Error('Invalid value "'+y+'" for attribute Ff supplied.');n=y}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(y){r=y!==void 0?y:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(y){r[0]=y}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(y){r[1]=y}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(y){r[2]=y}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(y){r[3]=y}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(y){switch(y){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=y;break;default:throw new Error('Invalid value "'+y+'" for attribute FT supplied.')}}});var i=null;Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,get:function(){if(!i||i.length<1){if(this instanceof u6e)return;i="FieldObject"+s.FieldNum++}var y=function(b){return b};return this.scope&&(y=this.scope.internal.getEncryptor(this.objId)),"("+vz(y(i))+")"},set:function(y){i=y.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(y){i=y}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(y){l=y}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(y){o=y}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(y){c=y}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/dat:d},set:function(y){d=y}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(y){u=y}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof u6e||this instanceof q7))return rBe(h,this.objId,this.scope)},set:function(y){y=y.toString(),h=y}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof f0==0?rBe(m,this.objId,this.scope):m},set:function(y){y=y.toString(),m=this instanceof f0==0?y.substr(0,1)==="("?QB(y.substr(1,y.length-2)):QB(y):y}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof f0==1?QB(m.substr(1,m.length-1)):m},set:function(y){y=y.toString(),m=this instanceof f0==1?"/"+T9(y):y}});var p=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(p)return p},set:function(y){this.V=y}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof f0==0?rBe(p,this.objId,this.scope):p},set:function(y){y=y.toString(),p=this instanceof f0==0?y.substr(0,1)==="("?QB(y.substr(1,y.length-2)):QB(y):y}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof f0==1?QB(p.substr(1,p.length-1)):p},set:function(y){y=y.toString(),p=this instanceof f0==1?"/"+T9(y):y}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var f,g=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return g},set:function(y){y=!!y,g=y}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(f)return f},set:function(y){f=y}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,1)},set:function(y){y?this.Ff=ig(this.Ff,1):this.Ff=og(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,2)},set:function(y){y?this.Ff=ig(this.Ff,2):this.Ff=og(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,3)},set:function(y){y?this.Ff=ig(this.Ff,3):this.Ff=og(this.Ff,3)}});var v=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(v!==null)return v},set:function(y){if([0,1,2].indexOf(y)===-1)throw new Error('Invalid value "'+y+'" for attribute Q supplied.');v=y}}),Object.defineProperty(this,"textAlign",{get:function(){var y;switch(v){case 0:default:y="left";break;case 1:y="center";break;case 2:y="right"}return y},configurable:!0,enumerable:!0,set:function(y){switch(y){case"right":case 2:v=2;break;case"center":case 1:v=1;break;default:v=0}}})};sw(WS,B4);var Kq=function(){WS.call(this),this.FT="/Ch",this.V="()",this.fontName="zapfdingbats";var s=0;Object.defineProperty(this,"TI",{enumerable:!0,configurable:!1,get:function(){return s},set:function(n){s=n}}),Object.defineProperty(this,"topIndex",{enumerable:!0,configurable:!0,get:function(){return s},set:function(n){s=n}});var t=[];Object.defineProperty(this,"Opt",{enumerable:!0,configurable:!1,get:function(){return ZJt(t,this.objId,this.scope)},set:function(n){var r,a;a=[],typeof(r=n)=="string"&&(a=function(i,l,o){o||(o=1);for(var c,d=[];c=l.exec(i);)d.push(c[o]);return d}(r,/\((.*?)\)/g)),t=a}}),this.getOptions=function(){return t},this.setOptions=function(n){t=n,this.sort&&t.sort()},this.addOption=function(n){n=(n=n||"").toString(),t.push(n),this.sort&&t.sort()},this.removeOption=function(n,r){for(r=r||!1,n=(n=n||"").toString();t.indexOf(n)!==-1&&(t.splice(t.indexOf(n),1),r!==!1););},Object.defineProperty(this,"combo",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,18)},set:function(n){n?this.Ff=ig(this.Ff,18):this.Ff=og(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=ig(this.Ff,19):this.Ff=og(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,20)},set:function(n){n?(this.Ff=ig(this.Ff,20),t.sort()):this.Ff=og(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,22)},set:function(n){n?this.Ff=ig(this.Ff,22):this.Ff=og(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,23)},set:function(n){n?this.Ff=ig(this.Ff,23):this.Ff=og(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,27)},set:function(n){n?this.Ff=ig(this.Ff,27):this.Ff=og(this.Ff,27)}}),this.hasAppearanceStream=!1};sw(Kq,WS);var Yq=function(){Kq.call(this),this.fontName="helvetica",this.combo=!1};sw(Yq,Kq);var Zq=function(){Yq.call(this),this.combo=!0};sw(Zq,Yq);var pCe=function(){Zq.call(this),this.edit=!0};sw(pCe,Zq);var f0=function(){WS.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,15)},set:function(n){n?this.Ff=ig(this.Ff,15):this.Ff=og(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,16)},set:function(n){n?this.Ff=ig(this.Ff,16):this.Ff=og(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,17)},set:function(n){n?this.Ff=ig(this.Ff,17):this.Ff=og(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,26)},set:function(n){n?this.Ff=ig(this.Ff,26):this.Ff=og(this.Ff,26)}});var s,t={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var n=function(i){return i};if(this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),Object.keys(t).length!==0){var r,a=[];for(r in a.push("<<"),t)a.push("/"+r+" ("+vz(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Vh(n)==="object"&&(t=n)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return t.CA||""},set:function(n){typeof n=="string"&&(t.CA=n)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return s},set:function(n){var r=n==null?"":n.toString();r.substr(0,1)==="/"&&(r=r.substr(1)),s="/"+T9(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+T9(n)}})};sw(f0,WS);var fCe=function(){f0.call(this),this.pushButton=!0};sw(fCe,f0);var Xq=function(){f0.call(this),this.radio=!0,this.pushButton=!1;var s=[];Object.defineProperty(this,"Kids",{enumerable:!0,configurable:!1,get:function(){return s},set:function(t){s=t!==void 0?t:[]}})};sw(Xq,f0);var u6e=function(){var s,t;WS.call(this),Object.defineProperty(this,"Parent",{enumerable:!1,configurable:!1,get:function(){return s},set:function(a){s=a}}),Object.defineProperty(this,"optionName",{enumerable:!1,configurable:!0,get:function(){return t},set:function(a){t=a}});var n,r={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var a=function(o){return o};this.scope&&(a=this.scope.internal.getEncryptor(this.objId));var i,l=[];for(i in l.push("<<"),r)l.push("/"+i+" ("+vz(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Vh(a)==="object"&&(r=a)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return r.CA||""},set:function(a){typeof a=="string"&&(r.CA=a)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return n},set:function(a){var i=a==null?"":a.toString();i.substr(0,1)==="/"&&(i=i.substr(1)),n="/"+T9(i)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return n.substr(1,n.length-1)},set:function(a){var i=a==null?"":a.toString();i.substr(0,1)==="/"&&(i=i.substr(1)),n="/"+T9(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=ko.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};sw(u6e,WS),Xq.prototype.setAppearance=function(s){if(!("createAppearanceStream"in s)||!("getCA"in s))throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");for(var t in this.Kids)if(this.Kids.hasOwnProperty(t)){var n=this.Kids[t];n.appearanceStreamContent=s.createAppearanceStream(n.optionName),n.caption=s.getCA()}},Xq.prototype.createOption=function(s){var t=new u6e;return t.Parent=this,t.optionName=s,this.Kids.push(t),kqn.call(this.scope,t),t};var xCe=function(){f0.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=ko.CheckBox.createAppearanceStream()};sw(xCe,f0);var q7=function(){WS.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,13)},set:function(t){t?this.Ff=ig(this.Ff,13):this.Ff=og(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,21)},set:function(t){t?this.Ff=ig(this.Ff,21):this.Ff=og(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,23)},set:function(t){t?this.Ff=ig(this.Ff,23):this.Ff=og(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,24)},set:function(t){t?this.Ff=ig(this.Ff,24):this.Ff=og(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,25)},set:function(t){t?this.Ff=ig(this.Ff,25):this.Ff=og(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,26)},set:function(t){t?this.Ff=ig(this.Ff,26):this.Ff=og(this.Ff,26)}});var s=null;Object.defineProperty(this,"MaxLen",{enumerable:!0,configurable:!1,get:function(){return s},set:function(t){s=t}}),Object.defineProperty(this,"maxLength",{enumerable:!0,configurable:!0,get:function(){return s},set:function(t){Number.isInteger(t)&&(s=t)}}),Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return this.V||this.DV}})};sw(q7,WS);var gCe=function(){q7.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!ag(this.Ff,14)},set:function(s){s?this.Ff=ig(this.Ff,14):this.Ff=og(this.Ff,14)}}),this.password=!0};sw(gCe,q7);var ko={CheckBox:{createAppearanceStream:function(){return{N:{On:ko.CheckBox.YesNormal},D:{On:ko.CheckBox.YesPushDown,Off:ko.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=B5(s);t.scope=s.scope;var n=[],r=s.scope.internal.getFont(s.fontName,s.fontStyle).id,a=s.scope.__private__.encodeColorString(s.color),i=SKe(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+Cc(ko.internal.getWidth(s))+" "+Cc(ko.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+Cc(i.fontSize)+" Tf "+a),n.push("BT"),n.push(i.text),n.push("ET"),n.push("Q"),n.push("EMC"),t.stream=n.join(` `),t},YesNormal:function(s){var t=B5(s);t.scope=s.scope;var n=s.scope.internal.getFont(s.fontName,s.fontStyle).id,r=s.scope.__private__.encodeColorString(s.color),a=[],i=ko.internal.getHeight(s),l=ko.internal.getWidth(s),o=SKe(s,s.caption);return a.push("1 g"),a.push("0 0 "+Cc(l)+" "+Cc(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+Cc(l-1)+" "+Cc(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+Cc(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=B5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Cc(ko.internal.getWidth(s))+" "+Cc(ko.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:ko.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=ko.RadioButton.Circle.YesNormal,t.D[s]=ko.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=B5(s);t.scope=s.scope;var n=[],r=ko.internal.getWidth(s)<=ko.internal.getHeight(s)?ko.internal.getWidth(s)/4:ko.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=ko.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+RT(ko.internal.getWidth(s)/2)+" "+RT(ko.internal.getHeight(s)/2)+" cm"),n.push(r+" 0 m"),n.push(r+" "+i+" "+i+" "+r+" 0 "+r+" c"),n.push("-"+i+" "+r+" -"+r+" "+i+" -"+r+" 0 c"),n.push("-"+r+" -"+i+" -"+i+" -"+r+" 0 -"+r+" c"),n.push(i+" -"+r+" "+r+" -"+i+" "+r+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=B5(s);t.scope=s.scope;var n=[],r=ko.internal.getWidth(s)<=ko.internal.getHeight(s)?ko.internal.getWidth(s)/4:ko.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*ko.internal.Bezier_C).toFixed(5)),l=Number((r*ko.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+RT(ko.internal.getWidth(s)/2)+" "+RT(ko.internal.getHeight(s)/2)+" cm"),n.push(a+" 0 m"),n.push(a+" "+i+" "+i+" "+a+" 0 "+a+" c"),n.push("-"+i+" "+a+" -"+a+" "+i+" -"+a+" 0 c"),n.push("-"+a+" -"+i+" -"+i+" -"+a+" 0 -"+a+" c"),n.push(i+" -"+a+" "+a+" -"+i+" "+a+" 0 c"),n.push("f"),n.push("Q"),n.push("0 g"),n.push("q"),n.push("1 0 0 1 "+RT(ko.internal.getWidth(s)/2)+" "+RT(ko.internal.getHeight(s)/2)+" cm"),n.push(r+" 0 m"),n.push(r+" "+l+" "+l+" "+r+" 0 "+r+" c"),n.push("-"+l+" "+r+" -"+r+" "+l+" -"+r+" 0 c"),n.push("-"+r+" -"+l+" -"+l+" -"+r+" 0 -"+r+" c"),n.push(l+" -"+r+" "+r+" -"+l+" "+r+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t},OffPushDown:function(s){var t=B5(s);t.scope=s.scope;var n=[],r=ko.internal.getWidth(s)<=ko.internal.getHeight(s)?ko.internal.getWidth(s)/4:ko.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*ko.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+RT(ko.internal.getWidth(s)/2)+" "+RT(ko.internal.getHeight(s)/2)+" cm"),n.push(a+" 0 m"),n.push(a+" "+i+" "+i+" "+a+" 0 "+a+" c"),n.push("-"+i+" "+a+" -"+a+" "+i+" -"+a+" 0 c"),n.push("-"+a+" -"+i+" -"+i+" -"+a+" 0 -"+a+" c"),n.push(i+" -"+a+" "+a+" -"+i+" "+a+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t}},Cross:{createAppearanceStream:function(s){var t={D:{Off:ko.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=ko.RadioButton.Cross.YesNormal,t.D[s]=ko.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=B5(s);t.scope=s.scope;var n=[],r=ko.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+Cc(ko.internal.getWidth(s)-2)+" "+Cc(ko.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(Cc(r.x1.x)+" "+Cc(r.x1.y)+" m"),n.push(Cc(r.x2.x)+" "+Cc(r.x2.y)+" l"),n.push(Cc(r.x4.x)+" "+Cc(r.x4.y)+" m"),n.push(Cc(r.x3.x)+" "+Cc(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=B5(s);t.scope=s.scope;var n=ko.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+Cc(ko.internal.getWidth(s))+" "+Cc(ko.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+Cc(ko.internal.getWidth(s)-2)+" "+Cc(ko.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(Cc(n.x1.x)+" "+Cc(n.x1.y)+" m"),r.push(Cc(n.x2.x)+" "+Cc(n.x2.y)+" l"),r.push(Cc(n.x4.x)+" "+Cc(n.x4.y)+" m"),r.push(Cc(n.x3.x)+" "+Cc(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=B5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Cc(ko.internal.getWidth(s))+" "+Cc(ko.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}}},createDefaultAppearanceStream:function(s){var t=s.scope.internal.getFont(s.fontName,s.fontStyle).id,n=s.scope.__private__.encodeColorString(s.color);return"/"+t+" "+s.fontSize+" Tf "+n}};ko.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=ko.internal.getWidth(s),n=ko.internal.getHeight(s),r=Math.min(t,n);return{x1:{x:(t-r)/2,y:(n-r)/2+r},x2:{x:(t-r)/2+r,y:(n-r)/2},x3:{x:(t-r)/2,y:(n-r)/2},x4:{x:(t-r)/2+r,y:(n-r)/2+r}}}},ko.internal.getWidth=function(s){var t=0;return Vh(s)==="object"&&(t=pSt(s.Rect[2])),t},ko.internal.getHeight=function(s){var t=0;return Vh(s)==="object"&&(t=pSt(s.Rect[3])),t};var kqn=bx.addField=function(s){if(Nqn(this,s),!(s instanceof WS))throw new Error("Invalid argument passed to jsPDF.addField.");var t;return(t=s).scope.internal.acroformPlugin.printedOut&&(t.scope.internal.acroformPlugin.printedOut=!1,t.scope.internal.acroformPlugin.acroFormDictionaryRoot=null),t.scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(t),s.page=s.scope.internal.getCurrentPageInfo().pageNumber,this};bx.AcroFormChoiceField=Kq,bx.AcroFormListBox=Yq,bx.AcroFormComboBox=Zq,bx.AcroFormEditBox=pCe,bx.AcroFormButton=f0,bx.AcroFormPushButton=fCe,bx.AcroFormRadioButton=Xq,bx.AcroFormCheckBox=xCe,bx.AcroFormTextField=q7,bx.AcroFormPasswordField=gCe,bx.AcroFormAppearance=ko,bx.AcroForm={ChoiceField:Kq,ListBox:Yq,ComboBox:Zq,EditBox:pCe,Button:f0,PushButton:fCe,RadioButton:Xq,CheckBox:xCe,TextField:q7,PasswordField:gCe,Appearance:ko},Po.AcroForm={ChoiceField:Kq,ListBox:Yq,ComboBox:Zq,EditBox:pCe,Button:f0,PushButton:fCe,RadioButton:Xq,CheckBox:xCe,TextField:q7,PasswordField:gCe,Appearance:ko};function JJt(s){return s.reduce(function(t,n,r){return t[n]=r,t},{})}(function(s){var t="addImage_";s.__addimage__={};var n="UNKNOWN",r={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0],[255,216,255,219],[255,216,255,238]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],WEBP:[[82,73,70,70,void 0,void 0,void 0,void 0,87,69,66,80]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]},a=s.__addimage__.getImageFileTypeByImageData=function(F,q){var G,V,H,K,Z,oe=n;if((q=q||n)==="RGBA"||F.data!==void 0&&F.data instanceof Uint8ClampedArray&&"height"in F&&"width"in F)return"RGBA";if(E(F))for(Z in r)for(H=r[Z],G=0;G>"}),"transparency"in q&&Array.isArray(q.transparency)&&q.transparency.length>0){for(var Z="",oe=0,re=q.transparency.length;oe>",g.content=i;var w=g.objId+" 0 R";i="<>";else if(r.options.pageNumber)switch(i="<=0};s.__arabicParser__.arabicLetterHasIsolatedForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length>=1};var d=s.__arabicParser__.arabicLetterHasFinalForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length>=2};s.__arabicParser__.arabicLetterHasInitialForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length>=3};var u=s.__arabicParser__.arabicLetterHasMedialForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length==4},h=s.__arabicParser__.resolveLigatures=function(g){var v=0,y=n,b="",w=0;for(v=0;v>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){this.internal.out("/OpenAction "+t+" 0 R")})),this},function(s){var t=function(){var n=void 0;Object.defineProperty(this,"pdf",{get:function(){return n},set:function(o){n=o}});var r=150;Object.defineProperty(this,"width",{get:function(){return r},set:function(o){r=isNaN(o)||Number.isInteger(o)===!1||o<0?150:o,this.getContext("2d").pageWrapXEnabled&&(this.getContext("2d").pageWrapX=r+1)}});var a=300;Object.defineProperty(this,"height",{get:function(){return a},set:function(o){a=isNaN(o)||Number.isInteger(o)===!1||o<0?300:o,this.getContext("2d").pageWrapYEnabled&&(this.getContext("2d").pageWrapY=a+1)}});var i=[];Object.defineProperty(this,"childNodes",{get:function(){return i},set:function(o){i=o}});var l={};Object.defineProperty(this,"style",{get:function(){return l},set:function(o){l=o}}),Object.defineProperty(this,"parentNode",{})};t.prototype.getContext=function(n,r){var a;if((n=n||"2d")!=="2d")return null;for(a in r)this.pdf.context2d.hasOwnProperty(a)&&(this.pdf.context2d[a]=r[a]);return this.pdf.context2d._canvas=this,this.pdf.context2d},t.prototype.toDataURL=function(){throw new Error("toDataURL is not implemented.")},s.events.push(["initialized",function(){this.canvas=new t,this.canvas.pdf=this}])}(Po.API),function(s){var t={left:0,top:0,bottom:0,right:0},n=!1,r=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},t),this.internal.__cell__.margins.width=this.getPageWidth(),a.call(this))},a=function(){this.internal.__cell__.lastCell=new i,this.internal.__cell__.pages=1},i=function(){var c=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return c},set:function(g){c=g}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(g){d=g}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(g){u=g}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(g){h=g}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(g){m=g}});var p=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return p},set:function(g){p=g}});var f=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return f},set:function(g){f=g}}),this};i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},i.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},s.setHeaderFunction=function(c){return r.call(this),this.internal.__cell__.headerFunction=typeof c=="function"?c:void 0,this},s.getTextDimensions=function(c,d){r.call(this);var u=(d=d||{}).fontSize||this.getFontSize(),h=d.font||this.getFont(),m=d.scaleFactor||this.internal.scaleFactor,p=0,f=0,g=0,v=this;if(!Array.isArray(c)&&typeof c!="string"){if(typeof c!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");c=String(c)}var y=d.maxWidth;y>0?typeof c=="string"?c=this.splitTextToSize(c,y):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(w,S){return w.concat(v.splitTextToSize(S,y))},[])):c=Array.isArray(c)?c:[c];for(var b=0;bthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,p&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var p,f,g,v,y=[],b=[],w=[],S={},C={},E=[],P=[],M=(m=m||{}).autoSize||!1,I=m.printHeaders!==!1,D=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,F=m.margins||Object.assign({width:this.getPageWidth()},t),q=typeof m.padding=="number"?m.padding:3,G=m.headerBackgroundColor||"#c8c8c8",V=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=I,this.internal.__cell__.margins=F,this.internal.__cell__.table_font_size=D,this.internal.__cell__.padding=q,this.internal.__cell__.headerBackgroundColor=G,this.internal.__cell__.headerTextColor=V,this.setFontSize(D),h==null)b=y=Object.keys(u[0]),w=y.map(function(){return"left"});else if(Array.isArray(h)&&Vh(h[0])==="object")for(y=h.map(function(ae){return ae.name}),b=h.map(function(ae){return ae.prompt||ae.name||""}),w=h.map(function(ae){return ae.align||"left"}),p=0;p0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(Po.API);var ees={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},tes=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],CKe=JJt(tes),ses=[100,200,300,400,500,600,700,800,900],Sqn=JJt(ses);function aBe(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return ees[i=i||"normal"]?i:"normal"}(s.style),r=function(i){return i?typeof i=="number"?i>=100&&i<=900&&i%100==0?i:400:/^\d00$/.test(i)?parseInt(i):i==="bold"?700:400:400}(s.weight),a=function(i){return typeof CKe[i=i||"normal"]=="number"?i:"normal"}(s.stretch);return{family:t,style:n,weight:r,stretch:a,src:s.src||[],ref:s.ref||{name:t,style:[a,n,r].join(" ")}}}function fSt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function SSt(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function CSt(s,t,n,r){var a=n*r,i=Math.floor(a/8),l=16-(a-8*i+r),o=(1<>8&255;d.setUint8(u,m)}})(s,i,nes(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,p=0,f=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(F===0)break;t+=F}break;case 249:if(s[t++]!==4||s[t+4]!==0)throw new Error("Invalid graphics extension block.");var g=s[t++];h=s[t++]|s[t++]<<8,m=s[t++],1&g||(m=null),p=g>>2&7,t++;break;case 254:for(;;){if(!((F=s[t++])>=0))throw Error("Invalid block size");if(F===0)break;t+=F}break;default:throw new Error("Unknown graphic control label: 0x"+s[t-1].toString(16))}break;case 44:var v=s[t++]|s[t++]<<8,y=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,w=s[t++]|s[t++]<<8,S=s[t++],C=S>>6&1,E=1<<1+(7&S),P=o,M=c,I=!1;S>>7&&(I=!0,P=t,M=E,t+=3*E);var D=t;for(t++;;){var F;if(!((F=s[t++])>=0))throw Error("Invalid block size");if(F===0)break;t+=F}u.push({x:v,y,width:b,height:w,has_local_palette:I,palette_offset:P,palette_size:M,data_offset:D,data_length:t-D,transparent_index:m,interlaced:!!C,delay:h,disposal:p});break;case 59:d=!1;break;default:throw new Error("Unknown gif block: 0x"+s[t-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return f},this.frameInfo=function(q){if(q<0||q>=u.length)throw new Error("Frame index out of range.");return u[q]},this.decodeAndBlitFrameBGRA=function(q,G){var V=this.frameInfo(q),H=V.width*V.height;if(H>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var K=new Uint8Array(H);ASt(s,V.data_offset,K,H);var Z=V.palette_offset,oe=V.transparent_index;oe===null&&(oe=256);var re=V.width,ae=n-re,J=re,te=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),ve=te,me=4*ae;V.interlaced===!0&&(me+=4*n*7);for(var he=8,ge=0,Ee=K.length;ge=ce&&(me=4*ae+4*n*(he-1),ve=te+(re+ae)*(he<<1),he>>=1)),Ne===oe)ve+=4;else{var Pe=s[Z+3*Ne],Oe=s[Z+3*Ne+1],ke=s[Z+3*Ne+2];G[ve++]=ke,G[ve++]=Oe,G[ve++]=Pe,G[ve++]=255}--J}},this.decodeAndBlitFrameRGBA=function(q,G){var V=this.frameInfo(q),H=V.width*V.height;if(H>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var K=new Uint8Array(H);ASt(s,V.data_offset,K,H);var Z=V.palette_offset,oe=V.transparent_index;oe===null&&(oe=256);var re=V.width,ae=n-re,J=re,te=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),ve=te,me=4*ae;V.interlaced===!0&&(me+=4*n*7);for(var he=8,ge=0,Ee=K.length;ge=ce&&(me=4*ae+4*n*(he-1),ve=te+(re+ae)*(he<<1),he>>=1)),Ne===oe)ve+=4;else{var Pe=s[Z+3*Ne],Oe=s[Z+3*Ne+1],ke=s[Z+3*Ne+2];G[ve++]=Pe,G[ve++]=Oe,G[ve++]=ke,G[ve++]=255}--J}}}function ASt(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,v!==i){if(v===l)break;for(var y=vi;)w=f[w]>>8,++b;var S=w;if(m+b+(y!==v?1:0)>r)return void Am.log("Warning, gif stream longer than expected.");n[m++]=S;var C=m+=b;for(y!==v&&(n[m++]=S),w=y;b--;)w=f[w],n[--C]=255&w,w>>=8;g!==null&&o<4096&&(f[o++]=g<<8|S,o>=d+1&&c<12&&(++c,d=d<<1|1)),g=v}else o=l+1,d=(1<<(c=a+1))-1,g=null}return m!==r&&Am.log("Warning, gif stream shorter than expected."),n}/** * @license Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */function lBe(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),p=new Array(64),f=new Array(64),g=[],v=0,y=7,b=new Array(64),w=new Array(64),S=new Array(64),C=new Array(256),E=new Array(2048),P=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],M=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],I=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],F=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],q=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],G=[0,1,2,3,4,5,6,7,8,9,10,11],V=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],H=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function K(te,ce){for(var ve=0,me=0,he=new Array,ge=1;ge<=16;ge++){for(var Ee=1;Ee<=te[ge];Ee++)he[ce[me]]=[],he[ce[me]][0]=ve,he[ce[me]][1]=ge,me++,ve++;ve*=2}return he}function Z(te){for(var ce=te[0],ve=te[1]-1;ve>=0;)ce&1<>8&255),oe(255&te)}function ae(te,ce,ve,me,he){for(var ge,Ee=he[0],Ne=he[240],Pe=function(Be,Ze){var $e,Xe,nt,Ge,Je,ut,lt,qt,zt,Zt,ms=0;for(zt=0;zt<8;++zt){$e=Be[ms],Xe=Be[ms+1],nt=Be[ms+2],Ge=Be[ms+3],Je=Be[ms+4],ut=Be[ms+5],lt=Be[ms+6];var Dt=$e+(qt=Be[ms+7]),It=$e-qt,qs=Xe+lt,wt=Xe-lt,Us=nt+ut,Es=nt-ut,kn=Ge+Je,Sn=Ge-Je,bn=Dt+kn,cr=Dt-kn,Fs=qs+Us,cn=qs-Us;Be[ms]=bn+Fs,Be[ms+4]=bn-Fs;var lr=.707106781*(cn+cr);Be[ms+2]=cr+lr,Be[ms+6]=cr-lr;var Tn=.382683433*((bn=Sn+Es)-(cn=wt+It)),Yn=.5411961*bn+Tn,fs=1.306562965*cn+Tn,wn=.707106781*(Fs=Es+wt),As=It+wn,Ss=It-wn;Be[ms+5]=Ss+Yn,Be[ms+3]=Ss-Yn,Be[ms+1]=As+fs,Be[ms+7]=As-fs,ms+=8}for(ms=0,zt=0;zt<8;++zt){$e=Be[ms],Xe=Be[ms+8],nt=Be[ms+16],Ge=Be[ms+24],Je=Be[ms+32],ut=Be[ms+40],lt=Be[ms+48];var pr=$e+(qt=Be[ms+56]),hn=$e-qt,Pn=Xe+lt,Gs=Xe-lt,an=nt+ut,tr=nt-ut,Lr=Ge+Je,Yt=Ge-Je,it=pr+Lr,gt=pr-Lr,ft=Pn+an,Lt=Pn-an;Be[ms]=it+ft,Be[ms+32]=it-ft;var Mt=.707106781*(Lt+gt);Be[ms+16]=gt+Mt,Be[ms+48]=gt-Mt;var Qt=.382683433*((it=Yt+tr)-(Lt=Gs+hn)),ks=.5411961*it+Qt,gs=1.306562965*Lt+Qt,Vt=.707106781*(ft=tr+Gs),Vs=hn+Vt,Zs=hn-Vt;Be[ms+40]=Zs+ks,Be[ms+24]=Zs-ks,Be[ms+8]=Vs+gs,Be[ms+56]=Vs-gs,ms++}for(zt=0;zt<64;++zt)Zt=Be[zt]*Ze[zt],p[zt]=Zt>0?Zt+.5|0:Zt-.5|0;return p}(te,ce),Oe=0;Oe<64;++Oe)f[P[Oe]]=Pe[Oe];var ke=f[0]-ve;ve=f[0],ke==0?Z(me[0]):(Z(me[m[ge=32767+ke]]),Z(h[ge]));for(var Ve=63;Ve>0&&f[Ve]==0;)Ve--;if(Ve==0)return Z(Ee),ve;for(var _e,Ae=1;Ae<=Ve;){for(var Se=Ae;f[Ae]==0&&Ae<=Ve;)++Ae;var We=Ae-Se;if(We>=16){_e=We>>4;for(var qe=1;qe<=_e;++qe)Z(Ne);We&=15}ge=32767+f[Ae],Z(he[(We<<4)+m[ge]]),Z(h[ge]),Ae++}return Ve!=63&&Z(Ee),ve}function J(te){te=Math.min(Math.max(te,1),100),i!=te&&(function(ce){for(var ve=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],me=0;me<64;me++){var he=l((ve[me]*ce+50)/100);he=Math.min(Math.max(he,1),255),o[P[me]]=he}for(var ge=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Ee=0;Ee<64;Ee++){var Ne=l((ge[Ee]*ce+50)/100);Ne=Math.min(Math.max(Ne,1),255),c[P[Ee]]=Ne}for(var Pe=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Oe=0,ke=0;ke<8;ke++)for(var Ve=0;Ve<8;Ve++)d[Oe]=1/(o[P[Oe]]*Pe[ke]*Pe[Ve]*8),u[Oe]=1/(c[P[Oe]]*Pe[ke]*Pe[Ve]*8),Oe++}(te<50?Math.floor(5e3/te):Math.floor(200-2*te)),i=te)}this.encode=function(te,ce){ce&&J(ce),g=new Array,v=0,y=7,re(65496),re(65504),re(16),oe(74),oe(70),oe(73),oe(70),oe(0),oe(1),oe(1),oe(0),re(1),re(1),oe(0),oe(0),function(){re(65499),re(132),oe(0);for(var Xe=0;Xe<64;Xe++)oe(o[Xe]);oe(1);for(var nt=0;nt<64;nt++)oe(c[nt])}(),function(Xe,nt){re(65472),re(17),oe(8),re(nt),re(Xe),oe(3),oe(1),oe(17),oe(0),oe(2),oe(17),oe(1),oe(3),oe(17),oe(1)}(te.width,te.height),function(){re(65476),re(418),oe(0);for(var Xe=0;Xe<16;Xe++)oe(M[Xe+1]);for(var nt=0;nt<=11;nt++)oe(I[nt]);oe(16);for(var Ge=0;Ge<16;Ge++)oe(D[Ge+1]);for(var Je=0;Je<=161;Je++)oe(F[Je]);oe(1);for(var ut=0;ut<16;ut++)oe(q[ut+1]);for(var lt=0;lt<=11;lt++)oe(G[lt]);oe(17);for(var qt=0;qt<16;qt++)oe(V[qt+1]);for(var zt=0;zt<=161;zt++)oe(H[zt])}(),re(65498),re(12),oe(3),oe(1),oe(0),oe(2),oe(17),oe(3),oe(17),oe(0),oe(63),oe(0);var ve=0,me=0,he=0;v=0,y=7,this.encode.displayName="_encode_";for(var ge,Ee,Ne,Pe,Oe,ke,Ve,_e,Ae,Se=te.data,We=te.width,qe=te.height,Be=4*We,Ze=0;Ze>3)*Be+(Ve=4*(7&Ae)),Ze+_e>=qe&&(ke-=Be*(Ze+1+_e-qe)),ge+Ve>=Be&&(ke-=ge+Ve-Be+4),Ee=Se[ke++],Ne=Se[ke++],Pe=Se[ke++],b[Ae]=(E[Ee]+E[Ne+256|0]+E[Pe+512|0]>>16)-128,w[Ae]=(E[Ee+768|0]+E[Ne+1024|0]+E[Pe+1280|0]>>16)-128,S[Ae]=(E[Ee+1280|0]+E[Ne+1536|0]+E[Pe+1792|0]>>16)-128;ve=ae(b,d,ve,t,r),me=ae(w,u,me,n,a),he=ae(S,u,he,n,a),ge+=32}Ze+=8}if(y>=0){var $e=[];$e[1]=y+1,$e[0]=(1<q;q++)if(I[D+q]!=F.charCodeAt(q))return!0;return!1}function r(I,D,F,q,G){for(var V=0;VV+1?[]:new D),!(H.length>>0;Me&xt;)xt>>>=1;return xt?(Me&xt-1)+xt:Me}function F(Me,Ue,xt,jt,ns){t(!(jt%xt));do Me[Ue+(jt-=xt)]=ns;while(0=ns),512>=ns)var xs=i(512);else if((xs=i(ns))==null)return 0;return function(bs,Ms,zs,en,Dn,Jn){var tn,Hn,ir=Ms,Dr=1<tn;++tn){if(Nr[tn]>1<(Al-=Nr[tn]))return 0;for(;0=tn;++tn,Dn<<=1){if(Oi+=Al<<=1,0>(Al-=Nr[tn]))return 0;for(;0Ca&&!(0>=(Gr-=Nr[Ca]));)++Ca,Gr<<=1;Dr+=Yi=1<<(Gr=Ca-zs),bs[Ms+(Ca=ro&_a)].g=Gr+zs,bs[Ms+Ca].value=ir-Ms-Ca}en.g=tn-zs,en.value=Jn[Hn++],F(bs,ir+(ro>>zs),Dn,Yi,en),ro=D(ro,tn)}}return Oi!=2*Gn[15]-1?0:Dr}(Me,Ue,xt,jt,ns,xs)}function G(){this.value=this.g=0}function V(){this.value=this.g=0}function H(){this.G=l(5,G),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(Tc,V)}function K(Me,Ue,xt,jt){t(Me!=null),t(Ue!=null),t(2147483648>jt),Me.Ca=254,Me.I=0,Me.b=-8,Me.Ka=0,Me.oa=Ue,Me.pa=xt,Me.Jd=Ue,Me.Yc=xt+jt,Me.Zc=4<=jt?xt+jt-4+1:xt,Ee(Me)}function Z(Me,Ue){for(var xt=0;0jt),Me.Sb=jt,Me.Ra=0,Me.u=0,Me.h=0,4>>=8,Me.Ra+=Me.oa[Me.pa+Me.bb]<>>0,++Me.bb,Me.u-=8;me(Me)&&(Me.h=1,Me.u=0)}function J(Me,Ue){if(t(0<=Ue),!Me.h&&Ue<=Fp){var xt=ve(Me)&Va[Ue];return Me.u+=Ue,ae(Me),xt}return Me.h=1,Me.u=0}function te(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function ce(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function ve(Me){return Me.Ra>>>(Me.u&cu-1)>>>0}function me(Me){return t(Me.bb<=Me.Sb),Me.h||Me.bb==Me.Sb&&Me.u>cu}function he(Me,Ue){Me.u=Ue,Me.h=me(Me)}function ge(Me){Me.u>=ba&&(t(Me.u>=ba),ae(Me))}function Ee(Me){t(Me!=null&&Me.oa!=null),Me.pa>>0,Me.b+=8):(t(Me!=null&&Me.oa!=null),Me.paMe.b&&Ee(Me);var jt=Me.b,ns=xt*Ue>>>8,xs=(Me.I>>>jt>ns)+0;for(xs?(xt-=ns,Me.I-=ns+1<>>0):xt=ns+1,jt=xt,ns=0;256<=jt;)ns+=8,jt>>=8;return jt=7^ns+Zg[jt],Me.b-=jt,Me.Ca=(xt<>24&255,Me[Ue+1]=xt>>16&255,Me[Ue+2]=xt>>8&255,Me[Ue+3]=255&xt}function ke(Me,Ue){return Me[Ue+0]|Me[Ue+1]<<8}function Ve(Me,Ue){return ke(Me,Ue)|Me[Ue+2]<<16}function _e(Me,Ue){return ke(Me,Ue)|ke(Me,Ue+2)<<16}function Ae(Me,Ue){var xt=1<=ns||0>=xs?0:(xt[0]=ns,jt[0]=xs,1)}function Be(Me,Ue){return Me+(1<>>Ue}function Ze(Me,Ue){return((4278255360&Me)+(4278255360&Ue)>>>0&4278255360)+((16711935&Me)+(16711935&Ue)>>>0&16711935)>>>0}function $e(Me,Ue){I[Ue]=function(xt,jt,ns,xs,bs,Ms,zs){var en;for(en=0;en>>1)+(Me&Ue)>>>0}function Ge(Me){return 0<=Me&&256>Me?Me:0>Me?0:255>1))}function ut(Me,Ue,xt){return Math.abs(Ue-xt)-Math.abs(Me-xt)}function lt(Me,Ue,xt,jt,ns,xs,bs){for(jt=xs[bs-1],xt=0;xt>8&255,zs=16711935&(zs=(zs=16711935&bs)+((Ms<<16)+Ms));jt[ns+xs]=(4278255360&bs)+zs>>>0}}function zt(Me,Ue){Ue.jd=255&Me,Ue.hd=Me>>8&255,Ue.ud=Me>>16&255}function Zt(Me,Ue,xt,jt,ns,xs){var bs;for(bs=0;bs>>8,en=Ms,Dn=255&(Dn=(Dn=Ms>>>16)+((Me.jd<<24>>24)*(zs<<24>>24)>>>5));en=255&(en=(en+=(Me.hd<<24>>24)*(zs<<24>>24)>>>5)+((Me.ud<<24>>24)*(Dn<<24>>24)>>>5)),ns[xs+bs]=(4278255360&Ms)+(Dn<<16)+en}}function ms(Me,Ue,xt,jt,ns){I[Ue]=function(xs,bs,Ms,zs,en,Dn,Jn,tn,Hn){for(zs=Jn;zs>xs.b,Hn=xs.Ea,ir=xs.K[0],Dr=xs.w;if(8>tn)for(xs=(1<>=tn}else I["VP8LMapColor"+xt](zs,en,ir,Dr,Dn,Jn,bs,Ms,Hn)}}function Dt(Me,Ue,xt,jt,ns){for(xt=Ue+xt;Ue>16&255,jt[ns++]=xs>>8&255,jt[ns++]=255&xs}}function It(Me,Ue,xt,jt,ns){for(xt=Ue+xt;Ue>16&255,jt[ns++]=xs>>8&255,jt[ns++]=255&xs,jt[ns++]=xs>>24&255}}function qs(Me,Ue,xt,jt,ns){for(xt=Ue+xt;Ue>16&240|bs>>12&15,bs=240&bs|bs>>28&15;jt[ns++]=xs,jt[ns++]=bs}}function wt(Me,Ue,xt,jt,ns){for(xt=Ue+xt;Ue>16&248|bs>>13&7,bs=bs>>5&224|bs>>3&31;jt[ns++]=xs,jt[ns++]=bs}}function Us(Me,Ue,xt,jt,ns){for(xt=Ue+xt;Ue>8&255,jt[ns++]=xs>>16&255}}function Es(Me,Ue,xt,jt,ns,xs){if(xs==0)for(xt=Ue+xt;Ue>24|xs[1]>>8&65280|xs[2]<<8&16711680|xs[3]<<24)>>>0),ns+=32;else r(jt,ns,Me,Ue,xt)}function kn(Me,Ue){I[Ue][0]=I[Me+"0"],I[Ue][1]=I[Me+"1"],I[Ue][2]=I[Me+"2"],I[Ue][3]=I[Me+"3"],I[Ue][4]=I[Me+"4"],I[Ue][5]=I[Me+"5"],I[Ue][6]=I[Me+"6"],I[Ue][7]=I[Me+"7"],I[Ue][8]=I[Me+"8"],I[Ue][9]=I[Me+"9"],I[Ue][10]=I[Me+"10"],I[Ue][11]=I[Me+"11"],I[Ue][12]=I[Me+"12"],I[Ue][13]=I[Me+"13"],I[Ue][14]=I[Me+"0"],I[Ue][15]=I[Me+"0"]}function Sn(Me){return Me==L1||Me==sk||Me==Qj||Me==Vy}function bn(){this.eb=[],this.size=this.A=this.fb=0}function cr(){this.y=[],this.f=[],this.ea=[],this.F=[],this.Tc=this.Ed=this.Cd=this.Fd=this.lb=this.Db=this.Ab=this.fa=this.J=this.W=this.N=this.O=0}function Fs(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new bn,this.f.kb=new cr,this.sd=null}function cn(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function lr(){this.Id=this.fd=this.Md=this.hb=this.ib=this.da=this.bd=this.cd=this.j=this.v=this.Da=this.Sd=this.ob=0}function Tn(Me){return alert("todo:WebPSamplerProcessPlane"),Me.T}function Yn(Me,Ue){var xt=Me.T,jt=Ue.ba.f.RGBA,ns=jt.eb,xs=jt.fb+Me.ka*jt.A,bs=ix[Ue.ba.S],Ms=Me.y,zs=Me.O,en=Me.f,Dn=Me.N,Jn=Me.ea,tn=Me.W,Hn=Ue.cc,ir=Ue.dc,Dr=Ue.Mc,Nr=Ue.Nc,Gn=Me.ka,Gr=Me.ka+Me.T,Ca=Me.U,_a=Ca+1>>1;for(Gn==0?bs(Ms,zs,null,null,en,Dn,Jn,tn,en,Dn,Jn,tn,ns,xs,null,null,Ca):(bs(Ue.ec,Ue.fc,Ms,zs,Hn,ir,Dr,Nr,en,Dn,Jn,tn,ns,xs-jt.A,ns,xs,Ca),++xt);Gn+2xt,ns=xt==$b||xt==ax||xt==Rv||xt==U0||xt==12||Sn(xt);if(Ue.memory=null,Ue.Ib=null,Ue.Jb=null,Ue.Nd=null,!ac(Ue.Oa,Me,ns?11:12))return 0;if(ns&&Sn(xt)&&em(),Me.da)alert("todo:use_scaling");else{if(jt){if(Ue.Ib=Tn,Me.Kb){if(xt=Me.U+1>>1,Ue.memory=i(Me.U+2*xt),Ue.memory==null)return 0;Ue.ec=Ue.memory,Ue.fc=0,Ue.cc=Ue.ec,Ue.dc=Ue.fc+Me.U,Ue.Mc=Ue.cc,Ue.Nc=Ue.dc+xt,Ue.Ib=Yn,em()}}else alert("todo:EmitYUV");ns&&(Ue.Jb=fs,jt&&Yc())}if(jt&&!r2){for(Me=0;256>Me;++Me)a2[Me]=89858*(Me-128)+s2>>Fv,n5[Me]=-22014*(Me-128)+s2,ak[Me]=-45773*(Me-128),dw[Me]=113618*(Me-128)+s2>>Fv;for(Me=n2;Me>Fv,sT[Me-n2]=Oa(Ue,255),uw[Me-n2]=Oa(Ue+8>>4,15);r2=1}return 1}function As(Me){var Ue=Me.ma,xt=Me.U,jt=Me.T;return t(!(1&Me.ka)),0>=xt||0>=jt?0:(xt=Ue.Ib(Me,Ue),Ue.Jb!=null&&Ue.Jb(Me,Ue,xt),Ue.Dc+=xt,1)}function Ss(Me){Me.ma.memory=null}function pr(Me,Ue,xt,jt){return J(Me,8)!=47?0:(Ue[0]=J(Me,14)+1,xt[0]=J(Me,14)+1,jt[0]=J(Me,1),J(Me,3)!=0?0:!Me.h)}function hn(Me,Ue){if(4>Me)return Me+1;var xt=Me-2>>1;return(2+(1&Me)<>4)*Me+(8-(15&xt)))?xt:1;var xt}function Gs(Me,Ue,xt){var jt=ve(xt),ns=Me[Ue+=255&jt].g-8;return 0>>0,t(8>=xt.g),Me.g}function tr(Me,Ue,xt){var jt=Me.xc;return t((Ue=jt==0?0:Me.vc[Me.md*(xt>>jt)+(Ue>>jt)])>Yi.b)*Oi;DrCa&&(eo=Ca),(0,ph[bc[Eu++]>>8&15])(tn,Hn+ +El,Gn,Gr+El-Ca,eo-El,Gn,Gr+El),El=eo}Hn+=Ca,Gr+=Ca,++Dr&ro||(Yi+=Oi)}Jn!=en.nc&&r(zs,Ms-ir,zs,Ms+(Jn-Dn-1)*ir,ir);break;case 1:for(ir=tn,Nr=Hn,Ca=(tn=en.Ea)-(Gr=tn&~(Gn=(Hn=1<>en.b)*Dr;Dn=ns),0xs.o&&(jt=xs.o),xt=jt?xt=0:(ns[0]+=4*xs.v,xs.ka=xt-xs.j,xs.U=xs.va-xs.v,xs.T=jt-xt,xt=1),xt){if(Ms=Ms[0],11>(xt=Me.ca).S){var Dn=xt.f.RGBA,Jn=(jt=xt.S,ns=xs.U,xs=xs.T,en=Dn.eb,Dn.A),tn=xs;for(Dn=Dn.fb+Me.Ma*Dn.A;0jt){var ns=Me.l.width,xs=xt.ca,bs=xt.tb+ns*jt,Ms=Me.V,zs=Me.Ba+Me.c*jt,en=Me.gc;t(Me.ab==1),t(en[0].hc==3),ff(en[0],jt,Ue,Ms,zs,xs,bs),gt(xt,jt,Ue,xs,bs,ns)}Me.C=Me.Ma=Ue}function Lt(Me,Ue,xt,jt,ns,xs,bs){var Ms=Me.$/jt,zs=Me.$%jt,en=Me.m,Dn=Me.s,Jn=xt+Me.$,tn=Jn;ns=xt+jt*ns;var Hn=xt+jt*xs,ir=280+Dn.ua,Dr=Me.Pb?Ms:16777216,Nr=0=Dr){var ro=Jn-xt;t((Dr=Me).Pb),Dr.wd=Dr.m,Dr.xd=ro,0Al.g?(he(_a,_a.u+Al.g),ro[Oi]=Al.value,_a=0):(he(_a,_a.u+Al.g-256),t(256<=Al.value),_a=Al.value),_a==0&&(Ca=!0)}else _a=Gs(Gr.G[0],Gr.H[0],en);if(en.h)break;if(Ca||256>_a){if(!Ca)if(Gr.nd)Ue[Jn]=(Gr.qb|_a<<8)>>>0;else{if(ge(en),Ca=Gs(Gr.G[1],Gr.H[1],en),ge(en),ro=Gs(Gr.G[2],Gr.H[2],en),Oi=Gs(Gr.G[3],Gr.H[3],en),en.h)break;Ue[Jn]=(Oi<<24|Ca<<16|_a<<8|ro)>>>0}if(Ca=!1,++Jn,++zs>=jt&&(zs=0,++Ms,bs!=null&&Ms<=xs&&!(Ms%16)&&bs(Me,Ms),Nr!=null))for(;tn>>Nr.Mb]=_a}else if(280>_a){if(_a=hn(_a-256,en),ro=Gs(Gr.G[4],Gr.H[4],en),ge(en),ro=Pn(jt,ro=hn(ro,en)),en.h)break;if(Jn-xt=jt;)zs-=jt,++Ms,bs!=null&&Ms<=xs&&!(Ms%16)&&bs(Me,Ms);if(t(Jn<=ns),zs&Gn&&(Gr=tr(Dn,zs,Ms)),Nr!=null)for(;tn>>Nr.Mb]=_a}else{if(!(_a>>Nr.Mb]=_a;_a=Jn,t(!(Ca>>>(ro=Nr).Xa)),Ue[_a]=ro.X[Ca],Ca=!0}Ca||t(en.h==me(en))}if(Me.Pb&&en.h&&Jnxs?xs:Ms),Me.a=0,Me.$=Jn-xt}return 1}return Me.a=3,0}function Mt(Me){t(Me!=null),Me.vc=null,Me.yc=null,Me.Ya=null;var Ue=Me.Wa;Ue!=null&&(Ue.X=null),Me.vb=null,t(Me!=null)}function Qt(){var Me=new Pr;return Me==null?null:(Me.a=0,Me.xb=ZC,kn("Predictor","VP8LPredictors"),kn("Predictor","VP8LPredictors_C"),kn("PredictorAdd","VP8LPredictorsAdd"),kn("PredictorAdd","VP8LPredictorsAdd_C"),F0=qt,Gd=Zt,xf=Dt,T1=It,M1=qs,yd=wt,Xg=Us,I.VP8LMapColor32b=Id,I.VP8LMapColor8b=bm,Me)}function ks(Me,Ue,xt,jt,ns){var xs=1,bs=[Me],Ms=[Ue],zs=jt.m,en=jt.s,Dn=null,Jn=0;e:for(;;){if(xt)for(;xs&&J(zs,1);){var tn=bs,Hn=Ms,ir=jt,Dr=1,Nr=ir.m,Gn=ir.gc[ir.ab],Gr=J(Nr,2);if(ir.Oc&1<=ir.ab),Gr){case 0:case 1:Gn.b=J(Nr,3)+2,Dr=ks(Be(Gn.Ea,Gn.b),Be(Gn.nc,Gn.b),0,ir,Gn.K),Gn.K=Gn.K[0];break;case 3:var Ca,_a=J(Nr,8)+1,ro=16<_a?0:4<_a?1:2<_a?2:3;if(tn[0]=Be(Gn.Ea,ro),Gn.b=ro,Ca=Dr=ks(_a,1,0,ir,Gn.K)){var Oi,Al=_a,Yi=Gn,bc=1<<(8>>Yi.b),Eu=i(bc);if(Eu==null)Ca=0;else{var El=Yi.K[0],eo=Yi.w;for(Eu[0]=Yi.K[0][0],Oi=1;Oi<1*Al;++Oi)Eu[Oi]=Ze(El[eo+Oi],Eu[Oi-1]);for(;Oi<4*bc;++Oi)Eu[Oi]=0;Yi.K[0]=null,Yi.K[0]=Eu,Ca=1}}Dr=Ca;break;case 2:break;default:t(0)}xs=Dr}}if(bs=bs[0],Ms=Ms[0],xs&&J(zs,1)&&!(xs=1<=(Jn=J(zs,4))&&11>=Jn)){jt.a=3;break e}var fi;if(fi=xs)t:{var Il,To,vl,ju=jt,Vm=bs,Nu=Ms,Zu=Jn,Vu=xt,lx=ju.m,du=ju.s,ad=[null],Kd=1,gh=0,bd=tT[Zu];s:for(;;){if(Vu&&J(lx,1)){var Mh=J(lx,3)+2,Op=Be(Vm,Mh),Dd=Be(Nu,Mh),tm=Op*Dd;if(!ks(Op,Dd,0,ju,ad))break s;for(ad=ad[0],du.xc=Mh,Il=0;Il>8&65535;ad[Il]=Pc,Pc>=Kd&&(Kd=Pc+1)}}if(lx.h)break s;for(To=0;5>To;++To){var Ph=XS[To];!To&&0=Tu),dx=cx;var Bp=i(gh);if(dx==null||Bp==null||zp==null){ju.a=1;break s}var Nm=zp;for(Il=vl=0;IlTo;++To){Ph=XS[To],kr[To]=Nm,$o[To]=vl,!To&&0Wb)break n}else Bv=Wb;for(kg=0;kgYb)u2[kg++]=Yb,Yb!=0&&(H0=Yb);else{var JC=Yb==16,r5=Yb-16,R1=Mo[r5],F1=J(yh,GC[r5])+R1;if(kg+F1>Wb)break n;for(var e3=JC?H0:0;0=To){var O1,Ky=Bp[0];for(O1=1;O1Ky&&(Ky=Bp[O1]);od+=Ky}}if(id.nd=Zc,id.Qb=0,Zc&&(id.qb=(kr[3][$o[3]+0].value<<24|kr[1][$o[1]+0].value<<16|kr[2][$o[2]+0].value)>>>0,Cd==0&&256>kr[0][$o[0]+0].value&&(id.Qb=1,id.qb+=kr[0][$o[0]+0].value<<8)),id.jc=!id.Qb&&6>od,id.jc){var ik,Lh=id;for(ik=0;ik>=an(mx,8,Mu),gp>>=an(Lh.G[1][Lh.H[1]+gp],16,Mu),gp>>=an(Lh.G[2][Lh.H[2]+gp],0,Mu),an(Lh.G[3][Lh.H[3]+gp],24,Mu))}}}du.vc=ad,du.Wb=Kd,du.Ya=dx,du.yc=zp,fi=1;break t}fi=0}if(!(xs=fi)){jt.a=3;break e}if(0jt+1?[]:0),!(ns.lengthMe?0:Me>Ue?Ue:Me}function Ao(){this.T=this.U=this.ka=this.height=this.width=0,this.y=[],this.f=[],this.ea=[],this.Rc=this.fa=this.W=this.N=this.O=0,this.ma="void",this.put="VP8IoPutHook",this.ac="VP8IoSetupHook",this.bc="VP8IoTeardownHook",this.ha=this.Kb=0,this.data=[],this.hb=this.ib=this.da=this.o=this.j=this.va=this.v=this.Da=this.ob=this.w=0,this.F=[],this.J=0}function uo(){var Me=new ji;return Me!=null&&(Me.a=0,Me.sc="OK",Me.cb=0,Me.Xb=0,Ub||(Ub=qa)),Me}function Ua(Me,Ue,xt){return Me.a==0&&(Me.a=Ue,Me.sc=xt,Me.cb=0),0}function Eo(Me,Ue,xt){return 3<=xt&&Me[Ue+0]==157&&Me[Ue+1]==1&&Me[Ue+2]==42}function Ji(Me,Ue){if(Me==null)return 0;if(Me.a=0,Me.sc="OK",Ue==null)return Ua(Me,2,"null VP8Io passed to VP8GetHeaders()");var xt=Ue.data,jt=Ue.w,ns=Ue.ha;if(4>ns)return Ua(Me,7,"Truncated header.");var xs=xt[jt+0]|xt[jt+1]<<8|xt[jt+2]<<16,bs=Me.Od;if(bs.Rb=!(1&xs),bs.td=xs>>1&7,bs.yd=xs>>4&1,bs.ub=xs>>5,3ns)return Ua(Me,7,"cannot parse picture header");if(!Eo(xt,jt,ns))return Ua(Me,3,"Bad code word");Ms.c=16383&(xt[jt+4]<<8|xt[jt+3]),Ms.Td=xt[jt+4]>>6,Ms.i=16383&(xt[jt+6]<<8|xt[jt+5]),Ms.Ud=xt[jt+6]>>6,jt+=7,ns-=7,Me.za=Ms.c+15>>4,Me.Ub=Ms.i+15>>4,Ue.width=Ms.c,Ue.height=Ms.i,Ue.Da=0,Ue.j=0,Ue.v=0,Ue.va=Ue.width,Ue.o=Ue.height,Ue.da=0,Ue.ib=Ue.width,Ue.hb=Ue.height,Ue.U=Ue.width,Ue.T=Ue.height,a((xs=Me.Pa).jb,0,255,xs.jb.length),t((xs=Me.Qa)!=null),xs.Cb=0,xs.Bb=0,xs.Fb=1,a(xs.Zb,0,0,xs.Zb.length),a(xs.Lb,0,0,xs.Lb)}if(bs.ub>ns)return Ua(Me,7,"bad partition length");K(xs=Me.m,xt,jt,bs.ub),jt+=bs.ub,ns-=bs.ub,bs.Rb&&(Ms.Ld=Ne(xs),Ms.Kd=Ne(xs)),Ms=Me.Qa;var zs,en=Me.Pa;if(t(xs!=null),t(Ms!=null),Ms.Cb=Ne(xs),Ms.Cb){if(Ms.Bb=Ne(xs),Ne(xs)){for(Ms.Fb=Ne(xs),zs=0;4>zs;++zs)Ms.Zb[zs]=Ne(xs)?oe(xs,7):0;for(zs=0;4>zs;++zs)Ms.Lb[zs]=Ne(xs)?oe(xs,6):0}if(Ms.Bb)for(zs=0;3>zs;++zs)en.jb[zs]=Ne(xs)?Z(xs,8):255}else Ms.Bb=0;if(xs.Ka)return Ua(Me,3,"cannot parse segment header");if((Ms=Me.ed).zd=Ne(xs),Ms.Tb=Z(xs,6),Ms.wb=Z(xs,3),Ms.Pc=Ne(xs),Ms.Pc&&Ne(xs)){for(en=0;4>en;++en)Ne(xs)&&(Ms.vd[en]=oe(xs,6));for(en=0;4>en;++en)Ne(xs)&&(Ms.od[en]=oe(xs,6))}if(Me.L=Ms.Tb==0?0:Ms.zd?1:2,xs.Ka)return Ua(Me,3,"cannot parse filter header");var Dn=ns;if(ns=zs=jt,jt=zs+Dn,Ms=Dn,Me.Xb=(1<Ms&&(Jn=Ms),K(Me.Jc[+Dn],xt,zs,Jn),zs+=Jn,Ms-=Jn,ns+=3}K(Me.Jc[+en],xt,zs,Ms),xt=zsJn;++Jn){if(Dn.Cb){var tn=Dn.Zb[Jn];Dn.Fb||(tn+=xt)}else{if(0>16,8>Hn.Eb[1]&&(Hn.Eb[1]=8),Hn.Qc[0]=lw[Oa(tn+en,117)],Hn.Qc[1]=YC[Oa(tn+zs,127)],Hn.lc=tn+zs}if(!bs.Rb)return Ua(Me,4,"Not a key frame.");for(Ne(xs),bs=Me.Pa,xt=0;4>xt;++xt){for(ns=0;8>ns;++ns)for(jt=0;3>jt;++jt)for(Ms=0;11>Ms;++Ms)en=Pe(xs,qb[xt][ns][jt][Ms])?Z(xs,8):cw[xt][ns][jt][Ms],bs.Wc[xt][ns].Yb[jt][Ms]=en;for(ns=0;17>ns;++ns)bs.Xc[xt][ns]=bs.Wc[xt][Vb[ns]]}return Me.kc=Ne(xs),Me.kc&&(Me.Bd=Z(xs,8)),Me.cb=1}function qa(Me,Ue,xt,jt,ns,xs,bs){var Ms=Ue[ns].Yb[xt];for(xt=0;16>ns;++ns){if(!Pe(Me,Ms[xt+0]))return ns;for(;!Pe(Me,Ms[xt+1]);)if(Ms=Ue[++ns].Yb[0],xt=0,ns==16)return 16;var zs=Ue[ns+1].Yb;if(Pe(Me,Ms[xt+2])){var en=Me,Dn=0;if(Pe(en,(tn=Ms)[(Jn=xt)+3]))if(Pe(en,tn[Jn+6])){for(Ms=0,Jn=2*(Dn=Pe(en,tn[Jn+8]))+(tn=Pe(en,tn[Jn+9+Dn])),Dn=0,tn=QL[Jn];tn[Ms];++Ms)Dn+=Dn+Pe(en,tn[Ms]);Dn+=3+(8<(en=Me).b&&Ee(en);var Jn,tn=en.b,Hn=(Jn=en.Ca>>1)-(en.I>>tn)>>31;--en.b,en.Ca+=Hn,en.Ca|=1,en.I-=(Jn+1&Hn)<>3),Me[Ue+xt+32*jt]=-256&ns?0>ns?0:255:ns}function zo(Me,Ue,xt,jt,ns,xs){ui(Me,Ue,0,xt,jt+ns),ui(Me,Ue,1,xt,jt+xs),ui(Me,Ue,2,xt,jt-xs),ui(Me,Ue,3,xt,jt-ns)}function gl(Me){return(20091*Me>>16)+Me}function tl(Me,Ue,xt,jt){var ns,xs=0,bs=i(16);for(ns=0;4>ns;++ns){var Ms=Me[Ue+0]+Me[Ue+8],zs=Me[Ue+0]-Me[Ue+8],en=(35468*Me[Ue+4]>>16)-gl(Me[Ue+12]),Dn=gl(Me[Ue+4])+(35468*Me[Ue+12]>>16);bs[xs+0]=Ms+Dn,bs[xs+1]=zs+en,bs[xs+2]=zs-en,bs[xs+3]=Ms-Dn,xs+=4,Ue++}for(ns=xs=0;4>ns;++ns)Ms=(Me=bs[xs+0]+4)+bs[xs+8],zs=Me-bs[xs+8],en=(35468*bs[xs+4]>>16)-gl(bs[xs+12]),ui(xt,jt,0,0,Ms+(Dn=gl(bs[xs+4])+(35468*bs[xs+12]>>16))),ui(xt,jt,1,0,zs+en),ui(xt,jt,2,0,zs-en),ui(xt,jt,3,0,Ms-Dn),xs++,jt+=32}function Ll(Me,Ue,xt,jt){var ns=Me[Ue+0]+4,xs=35468*Me[Ue+4]>>16,bs=gl(Me[Ue+4]),Ms=35468*Me[Ue+1]>>16;zo(xt,jt,0,ns+bs,Me=gl(Me[Ue+1]),Ms),zo(xt,jt,1,ns+xs,Me,Ms),zo(xt,jt,2,ns-xs,Me,Ms),zo(xt,jt,3,ns-bs,Me,Ms)}function Ku(Me,Ue,xt,jt,ns){tl(Me,Ue,xt,jt),ns&&tl(Me,Ue+16,xt,jt+4)}function uh(Me,Ue,xt,jt){_m(Me,Ue+0,xt,jt,1),_m(Me,Ue+32,xt,jt+128,1)}function ym(Me,Ue,xt,jt){var ns;for(Me=Me[Ue+0]+4,ns=0;4>ns;++ns)for(Ue=0;4>Ue;++Ue)ui(xt,jt,Ue,ns,Me)}function Ld(Me,Ue,xt,jt){Me[Ue+0]&&fh(Me,Ue+0,xt,jt),Me[Ue+16]&&fh(Me,Ue+16,xt,jt+4),Me[Ue+32]&&fh(Me,Ue+32,xt,jt+128),Me[Ue+48]&&fh(Me,Ue+48,xt,jt+128+4)}function Bm(Me,Ue,xt,jt){var ns,xs=i(16);for(ns=0;4>ns;++ns){var bs=Me[Ue+0+ns]+Me[Ue+12+ns],Ms=Me[Ue+4+ns]+Me[Ue+8+ns],zs=Me[Ue+4+ns]-Me[Ue+8+ns],en=Me[Ue+0+ns]-Me[Ue+12+ns];xs[0+ns]=bs+Ms,xs[8+ns]=bs-Ms,xs[4+ns]=en+zs,xs[12+ns]=en-zs}for(ns=0;4>ns;++ns)bs=(Me=xs[0+4*ns]+3)+xs[3+4*ns],Ms=xs[1+4*ns]+xs[2+4*ns],zs=xs[1+4*ns]-xs[2+4*ns],en=Me-xs[3+4*ns],xt[jt+0]=bs+Ms>>3,xt[jt+16]=en+zs>>3,xt[jt+32]=bs-Ms>>3,xt[jt+48]=en-zs>>3,jt+=64}function Sl(Me,Ue,xt){var jt,ns=Ue-32,xs=jm,bs=255-Me[ns-1];for(jt=0;jtxt;++xt)r(Me,Ue+32*xt,Me,Ue-32,16)}function Ta(Me,Ue){var xt;for(xt=16;0jt;++jt)a(Ue,xt+32*jt,Me,16)}function ho(Me,Ue){var xt,jt=16;for(xt=0;16>xt;++xt)jt+=Me[Ue-1+32*xt]+Me[Ue+xt-32];so(jt>>5,Me,Ue)}function pi(Me,Ue){var xt,jt=8;for(xt=0;16>xt;++xt)jt+=Me[Ue-1+32*xt];so(jt>>4,Me,Ue)}function $m(Me,Ue){var xt,jt=8;for(xt=0;16>xt;++xt)jt+=Me[Ue+xt-32];so(jt>>4,Me,Ue)}function al(Me,Ue){so(128,Me,Ue)}function vo(Me,Ue,xt){return Me+2*Ue+xt+2>>2}function $x(Me,Ue){var xt,jt=Ue-32;for(jt=new Uint8Array([vo(Me[jt-1],Me[jt+0],Me[jt+1]),vo(Me[jt+0],Me[jt+1],Me[jt+2]),vo(Me[jt+1],Me[jt+2],Me[jt+3]),vo(Me[jt+2],Me[jt+3],Me[jt+4])]),xt=0;4>xt;++xt)r(Me,Ue+32*xt,jt,0,jt.length)}function il(Me,Ue){var xt=Me[Ue-1],jt=Me[Ue-1+32],ns=Me[Ue-1+64],xs=Me[Ue-1+96];Oe(Me,Ue+0,16843009*vo(Me[Ue-1-32],xt,jt)),Oe(Me,Ue+32,16843009*vo(xt,jt,ns)),Oe(Me,Ue+64,16843009*vo(jt,ns,xs)),Oe(Me,Ue+96,16843009*vo(ns,xs,xs))}function yl(Me,Ue){var xt,jt=4;for(xt=0;4>xt;++xt)jt+=Me[Ue+xt-32]+Me[Ue-1+32*xt];for(jt>>=3,xt=0;4>xt;++xt)a(Me,Ue+32*xt,jt,4)}function E1(Me,Ue){var xt=Me[Ue-1+0],jt=Me[Ue-1+32],ns=Me[Ue-1+64],xs=Me[Ue-1-32],bs=Me[Ue+0-32],Ms=Me[Ue+1-32],zs=Me[Ue+2-32],en=Me[Ue+3-32];Me[Ue+0+96]=vo(jt,ns,Me[Ue-1+96]),Me[Ue+1+96]=Me[Ue+0+64]=vo(xt,jt,ns),Me[Ue+2+96]=Me[Ue+1+64]=Me[Ue+0+32]=vo(xs,xt,jt),Me[Ue+3+96]=Me[Ue+2+64]=Me[Ue+1+32]=Me[Ue+0+0]=vo(bs,xs,xt),Me[Ue+3+64]=Me[Ue+2+32]=Me[Ue+1+0]=vo(Ms,bs,xs),Me[Ue+3+32]=Me[Ue+2+0]=vo(zs,Ms,bs),Me[Ue+3+0]=vo(en,zs,Ms)}function zc(Me,Ue){var xt=Me[Ue+1-32],jt=Me[Ue+2-32],ns=Me[Ue+3-32],xs=Me[Ue+4-32],bs=Me[Ue+5-32],Ms=Me[Ue+6-32],zs=Me[Ue+7-32];Me[Ue+0+0]=vo(Me[Ue+0-32],xt,jt),Me[Ue+1+0]=Me[Ue+0+32]=vo(xt,jt,ns),Me[Ue+2+0]=Me[Ue+1+32]=Me[Ue+0+64]=vo(jt,ns,xs),Me[Ue+3+0]=Me[Ue+2+32]=Me[Ue+1+64]=Me[Ue+0+96]=vo(ns,xs,bs),Me[Ue+3+32]=Me[Ue+2+64]=Me[Ue+1+96]=vo(xs,bs,Ms),Me[Ue+3+64]=Me[Ue+2+96]=vo(bs,Ms,zs),Me[Ue+3+96]=vo(Ms,zs,zs)}function Dp(Me,Ue){var xt=Me[Ue-1+0],jt=Me[Ue-1+32],ns=Me[Ue-1+64],xs=Me[Ue-1-32],bs=Me[Ue+0-32],Ms=Me[Ue+1-32],zs=Me[Ue+2-32],en=Me[Ue+3-32];Me[Ue+0+0]=Me[Ue+1+64]=xs+bs+1>>1,Me[Ue+1+0]=Me[Ue+2+64]=bs+Ms+1>>1,Me[Ue+2+0]=Me[Ue+3+64]=Ms+zs+1>>1,Me[Ue+3+0]=zs+en+1>>1,Me[Ue+0+96]=vo(ns,jt,xt),Me[Ue+0+64]=vo(jt,xt,xs),Me[Ue+0+32]=Me[Ue+1+96]=vo(xt,xs,bs),Me[Ue+1+32]=Me[Ue+2+96]=vo(xs,bs,Ms),Me[Ue+2+32]=Me[Ue+3+96]=vo(bs,Ms,zs),Me[Ue+3+32]=vo(Ms,zs,en)}function hp(Me,Ue){var xt=Me[Ue+0-32],jt=Me[Ue+1-32],ns=Me[Ue+2-32],xs=Me[Ue+3-32],bs=Me[Ue+4-32],Ms=Me[Ue+5-32],zs=Me[Ue+6-32],en=Me[Ue+7-32];Me[Ue+0+0]=xt+jt+1>>1,Me[Ue+1+0]=Me[Ue+0+64]=jt+ns+1>>1,Me[Ue+2+0]=Me[Ue+1+64]=ns+xs+1>>1,Me[Ue+3+0]=Me[Ue+2+64]=xs+bs+1>>1,Me[Ue+0+32]=vo(xt,jt,ns),Me[Ue+1+32]=Me[Ue+0+96]=vo(jt,ns,xs),Me[Ue+2+32]=Me[Ue+1+96]=vo(ns,xs,bs),Me[Ue+3+32]=Me[Ue+2+96]=vo(xs,bs,Ms),Me[Ue+3+64]=vo(bs,Ms,zs),Me[Ue+3+96]=vo(Ms,zs,en)}function _g(Me,Ue){var xt=Me[Ue-1+0],jt=Me[Ue-1+32],ns=Me[Ue-1+64],xs=Me[Ue-1+96];Me[Ue+0+0]=xt+jt+1>>1,Me[Ue+2+0]=Me[Ue+0+32]=jt+ns+1>>1,Me[Ue+2+32]=Me[Ue+0+64]=ns+xs+1>>1,Me[Ue+1+0]=vo(xt,jt,ns),Me[Ue+3+0]=Me[Ue+1+32]=vo(jt,ns,xs),Me[Ue+3+32]=Me[Ue+1+64]=vo(ns,xs,xs),Me[Ue+3+64]=Me[Ue+2+64]=Me[Ue+0+96]=Me[Ue+1+96]=Me[Ue+2+96]=Me[Ue+3+96]=xs}function Dv(Me,Ue){var xt=Me[Ue-1+0],jt=Me[Ue-1+32],ns=Me[Ue-1+64],xs=Me[Ue-1+96],bs=Me[Ue-1-32],Ms=Me[Ue+0-32],zs=Me[Ue+1-32],en=Me[Ue+2-32];Me[Ue+0+0]=Me[Ue+2+32]=xt+bs+1>>1,Me[Ue+0+32]=Me[Ue+2+64]=jt+xt+1>>1,Me[Ue+0+64]=Me[Ue+2+96]=ns+jt+1>>1,Me[Ue+0+96]=xs+ns+1>>1,Me[Ue+3+0]=vo(Ms,zs,en),Me[Ue+2+0]=vo(bs,Ms,zs),Me[Ue+1+0]=Me[Ue+3+32]=vo(xt,bs,Ms),Me[Ue+1+32]=Me[Ue+3+64]=vo(jt,xt,bs),Me[Ue+1+64]=Me[Ue+3+96]=vo(ns,jt,xt),Me[Ue+1+96]=vo(xs,ns,jt)}function nx(Me,Ue){var xt;for(xt=0;8>xt;++xt)r(Me,Ue+32*xt,Me,Ue-32,8)}function Pi(Me,Ue){var xt;for(xt=0;8>xt;++xt)a(Me,Ue,Me[Ue-1],8),Ue+=32}function vm(Me,Ue,xt){var jt;for(jt=0;8>jt;++jt)a(Ue,xt+32*jt,Me,8)}function Yg(Me,Ue){var xt,jt=8;for(xt=0;8>xt;++xt)jt+=Me[Ue+xt-32]+Me[Ue-1+32*xt];vm(jt>>4,Me,Ue)}function hh(Me,Ue){var xt,jt=4;for(xt=0;8>xt;++xt)jt+=Me[Ue+xt-32];vm(jt>>3,Me,Ue)}function mh(Me,Ue){var xt,jt=4;for(xt=0;8>xt;++xt)jt+=Me[Ue-1+32*xt];vm(jt>>3,Me,Ue)}function pd(Me,Ue){vm(128,Me,Ue)}function fd(Me,Ue,xt){var jt=Me[Ue-xt],ns=Me[Ue+0],xs=3*(ns-jt)+iw[1020+Me[Ue-2*xt]-Me[Ue+xt]],bs=gf[112+(xs+4>>3)];Me[Ue-xt]=jm[255+jt+gf[112+(xs+3>>3)]],Me[Ue+0]=jm[255+ns-bs]}function Ux(Me,Ue,xt,jt){var ns=Me[Ue+0],xs=Me[Ue+xt];return fr[255+Me[Ue-2*xt]-Me[Ue-xt]]>jt||fr[255+xs-ns]>jt}function Ah(Me,Ue,xt,jt){return 4*fr[255+Me[Ue-xt]-Me[Ue+0]]+fr[255+Me[Ue-2*xt]-Me[Ue+xt]]<=jt}function Eh(Me,Ue,xt,jt,ns){var xs=Me[Ue-3*xt],bs=Me[Ue-2*xt],Ms=Me[Ue-xt],zs=Me[Ue+0],en=Me[Ue+xt],Dn=Me[Ue+2*xt],Jn=Me[Ue+3*xt];return 4*fr[255+Ms-zs]+fr[255+bs-en]>jt?0:fr[255+Me[Ue-4*xt]-xs]<=ns&&fr[255+xs-bs]<=ns&&fr[255+bs-Ms]<=ns&&fr[255+Jn-Dn]<=ns&&fr[255+Dn-en]<=ns&&fr[255+en-zs]<=ns}function Jh(Me,Ue,xt,jt){var ns=2*jt+1;for(jt=0;16>jt;++jt)Ah(Me,Ue+jt,xt,ns)&&fd(Me,Ue+jt,xt)}function Uu(Me,Ue,xt,jt){var ns=2*jt+1;for(jt=0;16>jt;++jt)Ah(Me,Ue+jt*xt,1,ns)&&fd(Me,Ue+jt*xt,1)}function rx(Me,Ue,xt,jt){var ns;for(ns=3;0>7,Gn=18*Gr+63>>7,Gr=9*Gr+63>>7;zs[en-3*Dn]=jm[255+zs[en-3*Dn]+Gr],zs[en-2*Dn]=jm[255+Jn+Gn],zs[en-Dn]=jm[255+tn+Nr],zs[en+0]=jm[255+Hn-Nr],zs[en+Dn]=jm[255+ir-Gn],zs[en+2*Dn]=jm[255+Dr-Gr]}Ue+=jt}}function Sd(Me,Ue,xt,jt,ns,xs,bs,Ms){for(xs=2*xs+1;0>3)],Dr=gf[112+(Dr+3>>3)],Nr=ir+1>>1;zs[en-2*Dn]=jm[255+zs[en-2*Dn]+Nr],zs[en-Dn]=jm[255+Jn+Dr],zs[en+0]=jm[255+tn-ir],zs[en+Dn]=jm[255+Hn-Nr]}Ue+=jt}}function pf(Me,Ue,xt,jt,ns,xs){mc(Me,Ue,xt,1,16,jt,ns,xs)}function lu(Me,Ue,xt,jt,ns,xs){mc(Me,Ue,1,xt,16,jt,ns,xs)}function mp(Me,Ue,xt,jt,ns,xs){var bs;for(bs=3;0en?0:255:en)&255,en=zs,ns[xs+Ms]=Dn}}function xd(Me,Ue,xt,jt){var ns=Ue.width,xs=Ue.o;if(t(Me!=null&&Ue!=null),0>xt||0>=jt||xt+jt>xs)return null;if(!Me.Cc){if(Me.ga==null){var bs;if(Me.ga=new Ni,(bs=Me.ga==null)||(bs=Ue.width*Ue.o,t(Me.Gb.length==0),Me.Gb=i(bs),Me.Uc=0,Me.Gb==null?bs=0:(Me.mb=Me.Gb,Me.nb=Me.Uc,Me.rc=null,bs=1),bs=!bs),!bs){bs=Me.ga;var Ms=Me.Fa,zs=Me.P,en=Me.qc,Dn=Me.mb,Jn=Me.nb,tn=zs+1,Hn=en-1,ir=bs.l;if(t(Ms!=null&&Dn!=null&&Ue!=null),jg[0]=null,jg[1]=Lo,jg[2]=wo,jg[3]=Wl,bs.ca=Dn,bs.tb=Jn,bs.c=Ue.width,bs.i=Ue.height,t(0=en)Ue=0;else if(bs.$a=3&Ms[zs+0],bs.Z=Ms[zs+0]>>2&3,bs.Lc=Ms[zs+0]>>4&3,zs=Ms[zs+0]>>6&3,0>bs.$a||1=bs.c*bs.i;bs=!Ue}if(bs)return null;Me.ga.Lc!=1?Me.Ga=0:jt=xs-xt}t(Me.ga!=null),t(xt+jt<=xs);e:{if(Ue=(Ms=Me.ga).c,xs=Ms.l.o,Ms.$a==0){if(tn=Me.rc,Hn=Me.Vc,ir=Me.Fa,zs=Me.P+1+xt*Ue,en=Me.mb,Dn=Me.nb+xt*Ue,t(zs<=Me.P+Me.qc),Ms.Z!=0)for(t(jg[Ms.Z]!=null),bs=0;bs=Ue)Ue=1;else if(Ms.ic||Yc(),Ms.ic){Ms=bs.V,tn=bs.Ba,Hn=bs.c;var Dr=bs.i,Nr=(ir=1,zs=bs.$/Hn,en=bs.$%Hn,Dn=bs.m,Jn=bs.s,bs.$),Gn=Hn*Dr,Gr=Hn*Ue,Ca=Jn.wc,_a=Nr(Dr=Gs(_a.G[0],_a.H[0],Dn)))Ms[tn+Nr]=Dr,++Nr,++en>=Hn&&(en=0,++zs<=Ue&&!(zs%16)&&ft(bs,zs));else{if(!(280>Dr)){ir=0;break t}Dr=hn(Dr-256,Dn);var ro,Oi=Gs(_a.G[4],_a.H[4],Dn);if(ge(Dn),!(Nr>=(Oi=Pn(Hn,Oi=hn(Oi,Dn)))&&Gn-Nr>=Dr)){ir=0;break t}for(ro=0;ro=Hn;)en-=Hn,++zs<=Ue&&!(zs%16)&&ft(bs,zs);NrUe?Ue:zs);break t}!ir||Dn.h&&Nr=xs&&(Me.Cc=1),jt=1}if(!jt)return null;if(Me.Cc&&((jt=Me.ga)!=null&&(jt.mc=null),Me.ga=null,0>23,Ms[zs+4*bs+1]=Ms[zs+4*bs+1]*Jn>>23,Ms[zs+4*bs+2]=Ms[zs+4*bs+2]*Jn>>23)}Ue+=xs}}function gi(Me,Ue,xt,jt,ns){for(;0>4)*zs>>16;Me[Ue+2*xs+0]=(240&bs|bs>>4)*zs>>16&240|(15&bs|bs<<4)*zs>>16>>4&15,Me[Ue+2*xs+1]=240&en|Ms}Ue+=ns}}function Ai(Me,Ue,xt,jt,ns,xs,bs,Ms){var zs,en,Dn=255;for(en=0;en>8}function Yc(){B0=Vr,Xj=gi,$0=Ai,aw=rc}function mo(Me,Ue,xt){I[Me]=function(jt,ns,xs,bs,Ms,zs,en,Dn,Jn,tn,Hn,ir,Dr,Nr,Gn,Gr,Ca){var _a,ro=Ca-1>>1,Oi=Ms[zs+0]|en[Dn+0]<<16,Al=Jn[tn+0]|Hn[ir+0]<<16;t(jt!=null);var Yi=3*Oi+Al+131074>>2;for(Ue(jt[ns+0],255&Yi,Yi>>16,Dr,Nr),xs!=null&&(Yi=3*Al+Oi+131074>>2,Ue(xs[bs+0],255&Yi,Yi>>16,Gn,Gr)),_a=1;_a<=ro;++_a){var bc=Ms[zs+_a]|en[Dn+_a]<<16,Eu=Jn[tn+_a]|Hn[ir+_a]<<16,El=Oi+bc+Al+Eu+524296,eo=El+2*(bc+Al)>>3;Yi=eo+Oi>>1,Oi=(El=El+2*(Oi+Eu)>>3)+bc>>1,Ue(jt[ns+2*_a-1],255&Yi,Yi>>16,Dr,Nr+(2*_a-1)*xt),Ue(jt[ns+2*_a-0],255&Oi,Oi>>16,Dr,Nr+(2*_a-0)*xt),xs!=null&&(Yi=El+Al>>1,Oi=eo+Eu>>1,Ue(xs[bs+2*_a-1],255&Yi,Yi>>16,Gn,Gr+(2*_a-1)*xt),Ue(xs[bs+2*_a+0],255&Oi,Oi>>16,Gn,Gr+(2*_a+0)*xt)),Oi=bc,Al=Eu}1&Ca||(Yi=3*Oi+Al+131074>>2,Ue(jt[ns+Ca-1],255&Yi,Yi>>16,Dr,Nr+(Ca-1)*xt),xs!=null&&(Yi=3*Al+Oi+131074>>2,Ue(xs[bs+Ca-1],255&Yi,Yi>>16,Gn,Gr+(Ca-1)*xt)))}}function em(){ix[Bb]=rk,ix[$b]=e2,ix[P1]=JS,ix[ax]=t2,ix[Rv]=ox,ix[U0]=yf,ix[ow]=XC,ix[L1]=e2,ix[sk]=t2,ix[Qj]=ox,ix[Vy]=yf}function Gt(Me){return Me&~s5?0>Me?0:255:Me>>t5}function An(Me,Ue){return Gt((19077*Me>>8)+(26149*Ue>>8)-14234)}function qn(Me,Ue,xt){return Gt((19077*Me>>8)-(6419*Ue>>8)-(13320*xt>>8)+8708)}function qr(Me,Ue){return Gt((19077*Me>>8)+(33050*Ue>>8)-17685)}function Pa(Me,Ue,xt,jt,ns){jt[ns+0]=An(Me,xt),jt[ns+1]=qn(Me,Ue,xt),jt[ns+2]=qr(Me,Ue)}function vi(Me,Ue,xt,jt,ns){jt[ns+0]=qr(Me,Ue),jt[ns+1]=qn(Me,Ue,xt),jt[ns+2]=An(Me,xt)}function Li(Me,Ue,xt,jt,ns){var xs=qn(Me,Ue,xt);Ue=xs<<3&224|qr(Me,Ue)>>3,jt[ns+0]=248&An(Me,xt)|xs>>5,jt[ns+1]=Ue}function wi(Me,Ue,xt,jt,ns){var xs=240&qr(Me,Ue)|15;jt[ns+0]=240&An(Me,xt)|qn(Me,Ue,xt)>>4,jt[ns+1]=xs}function rd(Me,Ue,xt,jt,ns){jt[ns+0]=255,Pa(Me,Ue,xt,jt,ns+1)}function Au(Me,Ue,xt,jt,ns){vi(Me,Ue,xt,jt,ns),jt[ns+3]=255}function pp(Me,Ue,xt,jt,ns){Pa(Me,Ue,xt,jt,ns),jt[ns+3]=255}function gd(Me,Ue,xt){I[Me]=function(jt,ns,xs,bs,Ms,zs,en,Dn,Jn){for(var tn=Dn+(-2&Jn)*xt;Dn!=tn;)Ue(jt[ns+0],xs[bs+0],Ms[zs+0],en,Dn),Ue(jt[ns+1],xs[bs+0],Ms[zs+0],en,Dn+xt),ns+=2,++bs,++zs,Dn+=2*xt;1&Jn&&Ue(jt[ns+0],xs[bs+0],Ms[zs+0],en,Dn)}}function Hd(Me,Ue,xt){return xt==0?Me==0?Ue==0?6:5:Ue==0?4:0:xt}function Th(Me,Ue,xt,jt,ns){switch(Me>>>30){case 3:_m(Ue,xt,jt,ns,0);break;case 2:Hx(Ue,xt,jt,ns);break;case 1:fh(Ue,xt,jt,ns)}}function Rp(Me,Ue){var xt,jt,ns=Ue.M,xs=Ue.Nb,bs=Me.oc,Ms=Me.pc+40,zs=Me.oc,en=Me.pc+584,Dn=Me.oc,Jn=Me.pc+600;for(xt=0;16>xt;++xt)bs[Ms+32*xt-1]=129;for(xt=0;8>xt;++xt)zs[en+32*xt-1]=129,Dn[Jn+32*xt-1]=129;for(0xt;++xt)r(bs,Ms+32*xt-4,bs,Ms+32*xt+12,4);for(xt=-1;8>xt;++xt)r(zs,en+32*xt-4,zs,en+32*xt+4,4),r(Dn,Jn+32*xt-4,Dn,Jn+32*xt+4,4)}var Hn=Me.Gd,ir=Me.Hd+jt,Dr=tn.ad,Nr=tn.Hc;if(0=Me.za-1?a(Gn,Gr,Hn[ir].y[15],4):r(Gn,Gr,Hn[ir+1].y,0,4)),xt=0;4>xt;xt++)Gn[Gr+128+xt]=Gn[Gr+256+xt]=Gn[Gr+384+xt]=Gn[Gr+0+xt];for(xt=0;16>xt;++xt,Nr<<=2)Gn=bs,Gr=Ms+Ov[xt],Yu[tn.Ob[xt]](Gn,Gr),Th(Nr,Dr,16*+xt,Gn,Gr)}else if(Gn=Hd(jt,ns,tn.Ob[0]),Gx[Gn](bs,Ms),Nr!=0)for(xt=0;16>xt;++xt,Nr<<=2)Th(Nr,Dr,16*+xt,bs,Ms+Ov[xt]);for(xt=tn.Gc,Gn=Hd(jt,ns,tn.Dd),Gy[Gn](zs,en),Gy[Gn](Dn,Jn),Nr=Dr,Gn=zs,Gr=en,255&(tn=0|xt)&&(170&tn?Fb(Nr,256,Gn,Gr):Mc(Nr,256,Gn,Gr)),tn=Dn,Nr=Jn,255&(xt>>=8)&&(170&xt?Fb(Dr,320,tn,Nr):Mc(Dr,320,tn,Nr)),nsxt;++xt)r(Hn,ir+xt*Me.R,bs,Ms+32*xt,16);for(xt=0;8>xt;++xt)r(Dr,tn+xt*Me.B,zs,en+32*xt,8),r(Nr,Gn+xt*Me.B,Dn,Jn+32*xt,8)}}function qx(Me,Ue,xt,jt,ns,xs,bs,Ms,zs){var en=[0],Dn=[0],Jn=0,tn=zs!=null?zs.kd:0,Hn=zs??new Mn;if(Me==null||12>xt)return 7;Hn.data=Me,Hn.w=Ue,Hn.ha=xt,Ue=[Ue],xt=[xt],Hn.gb=[Hn.gb];e:{var ir=Ue,Dr=xt,Nr=Hn.gb;if(t(Me!=null),t(Dr!=null),t(Nr!=null),Nr[0]=0,12<=Dr[0]&&!n(Me,ir[0],"RIFF")){if(n(Me,ir[0]+8,"WEBP")){Nr=3;break e}var Gn=_e(Me,ir[0]+4);if(12>Gn||4294967286Dr[0]-8){Nr=7;break e}Nr[0]=Gn,ir[0]+=12,Dr[0]-=12}Nr=0}if(Nr!=0)return Nr;for(Gn=0Nr[0])Nr=7;else{if(!n(Gr,Dr[0],"VP8X")){if(_e(Gr,Dr[0]+4)!=10){Nr=3;break e}if(18>Nr[0]){Nr=7;break e}var Oi=_e(Gr,Dr[0]+8),Al=1+Ve(Gr,Dr[0]+12);if(2147483648<=Al*(Gr=1+Ve(Gr,Dr[0]+15))){Nr=3;break e}ro!=null&&(ro[0]=Oi),Ca!=null&&(Ca[0]=Al),_a!=null&&(_a[0]=Gr),Dr[0]+=18,Nr[0]-=18,Yi[0]=1}Nr=0}}if(Jn=Jn[0],ir=ir[0],Nr!=0)return Nr;if(Dr=!!(2&ir),!Gn&&Jn)return 3;if(xs!=null&&(xs[0]=!!(16&ir)),bs!=null&&(bs[0]=Dr),Ms!=null&&(Ms[0]=0),bs=en[0],ir=Dn[0],Jn&&Dr&&zs==null){Nr=0;break}if(4>xt){Nr=7;break}if(Gn&&Jn||!Gn&&!Jn&&!n(Me,Ue[0],"ALPH")){xt=[xt],Hn.na=[Hn.na],Hn.P=[Hn.P],Hn.Sa=[Hn.Sa];e:{Oi=Me,Nr=Ue,Gn=xt;var Yi=Hn.gb;Ca=Hn.na,_a=Hn.P,ro=Hn.Sa,Al=22,t(Oi!=null),t(Gn!=null),Gr=Nr[0];var bc=Gn[0];for(t(Ca!=null),t(ro!=null),Ca[0]=null,_a[0]=null,ro[0]=0;;){if(Nr[0]=Gr,Gn[0]=bc,8>bc){Nr=7;break e}var Eu=_e(Oi,Gr+4);if(4294967286Yi){Nr=3;break e}if(!n(Oi,Gr,"VP8 ")||!n(Oi,Gr,"VP8L")){Nr=0;break e}if(bc[0]Gn[0])Nr=7;else{if(Gr||Al){if(Yi=_e(Yi,Oi+4),12<=Ca&&Yi>Ca-12){Nr=3;break e}if(tn&&Yi>Gn[0]-8){Nr=7;break e}_a[0]=Yi,Nr[0]+=8,Gn[0]-=8,ro[0]=Al}else ro[0]=5<=Gn[0]&&Yi[Oi+0]==47&&!(Yi[Oi+4]>>5),_a[0]=Gn[0];Nr=0}if(xt=xt[0],Hn.Ja=Hn.Ja[0],Hn.xa=Hn.xa[0],Ue=Ue[0],Nr!=0)break;if(4294967286xt){Nr=7;break}Ms=bs,tn=ir,Dr=xs,Me==null||5>xt?Me=0:5<=xt&&Me[Ue+0]==47&&!(Me[Ue+4]>>5)?(Gn=[0],Yi=[0],Ca=[0],re(_a=new ce,Me,Ue,xt),pr(_a,Gn,Yi,Ca)?(Ms!=null&&(Ms[0]=Gn[0]),tn!=null&&(tn[0]=Yi[0]),Dr!=null&&(Dr[0]=Ca[0]),Me=1):Me=0):Me=0}else{if(10>xt){Nr=7;break}Ms=ir,Me==null||10>xt||!Eo(Me,Ue+3,xt-3)?Me=0:(tn=Me[Ue+0]|Me[Ue+1]<<8|Me[Ue+2]<<16,Dr=16383&(Me[Ue+7]<<8|Me[Ue+6]),Me=16383&(Me[Ue+9]<<8|Me[Ue+8]),1&tn||3<(tn>>1&7)||!(tn>>4&1)||tn>>5>=Hn.Ja||!Dr||!Me?Me=0:(bs&&(bs[0]=Dr),Ms&&(Ms[0]=Me),Me=1))}if(!Me||(bs=bs[0],ir=ir[0],Jn&&(en[0]!=bs||Dn[0]!=ir)))return 3;zs!=null&&(zs[0]=Hn,zs.offset=Ue-zs.w,t(4294967286>Ue-zs.w),t(zs.offset==zs.ha-xt));break}return Nr==0||Nr==7&&Jn&&zs==null?(xs!=null&&(xs[0]|=Hn.na!=null&&0xt||(xs&=-2,bs&=-2),0>xs||0>bs||0>=Ms||0>=zs||xs+Ms>jt||bs+zs>ns))return 0;if(Ue.v=xs,Ue.j=bs,Ue.va=xs+Ms,Ue.o=bs+zs,Ue.U=Ms,Ue.T=zs,Ue.da=Me!=null&&0Me.S){var Ue=Me.f.RGBA;Ue.fb+=(Me.height-1)*Ue.A,Ue.A=-Ue.A}else Ue=Me.f.kb,Me=Me.height,Ue.O+=(Me-1)*Ue.fa,Ue.fa=-Ue.fa,Ue.N+=(Me-1>>1)*Ue.Ab,Ue.Ab=-Ue.Ab,Ue.W+=(Me-1>>1)*Ue.Db,Ue.Db=-Ue.Db,Ue.F!=null&&(Ue.J+=(Me-1)*Ue.lb,Ue.lb=-Ue.lb);return 0}function Yr(Me,Ue,xt,jt){if(jt==null||0>=Me||0>=Ue)return 2;if(xt!=null){if(xt.Da){var ns=xt.cd,xs=xt.bd,bs=-2&xt.v,Ms=-2&xt.j;if(0>bs||0>Ms||0>=ns||0>=xs||bs+ns>Me||Ms+xs>Ue)return 2;Me=ns,Ue=xs}if(xt.da){if(!qe(Me,Ue,ns=[xt.ib],xs=[xt.hb]))return 2;Me=ns[0],Ue=xs[0]}}jt.width=Me,jt.height=Ue;e:{var zs=jt.width,en=jt.height;if(Me=jt.S,0>=zs||0>=en||!(Me>=Bb&&13>Me))Me=2;else{if(0>=jt.Rd&&jt.sd==null){bs=xs=ns=Ue=0;var Dn=(Ms=zs*hw[Me])*en;if(11>Me||(xs=(en+1)/2*(Ue=(zs+1)/2),Me==12&&(bs=(ns=zs)*en)),(en=i(Dn+2*xs+bs))==null){Me=1;break e}jt.sd=en,11>Me?((zs=jt.f.RGBA).eb=en,zs.fb=0,zs.A=Ms,zs.size=Dn):((zs=jt.f.kb).y=en,zs.O=0,zs.fa=Ms,zs.Fd=Dn,zs.f=en,zs.N=0+Dn,zs.Ab=Ue,zs.Cd=xs,zs.ea=en,zs.W=0+Dn+xs,zs.Db=Ue,zs.Ed=xs,Me==12&&(zs.F=en,zs.J=0+Dn+2*xs),zs.Tc=bs,zs.lb=ns)}if(Ue=1,ns=jt.S,xs=jt.width,bs=jt.height,ns>=Bb&&13>ns)if(11>ns)Me=jt.f.RGBA,Ue&=(Ms=Math.abs(Me.A))*(bs-1)+xs<=Me.size,Ue&=Ms>=xs*hw[ns],Ue&=Me.eb!=null;else{Me=jt.f.kb,Ms=(xs+1)/2,Dn=(bs+1)/2,zs=Math.abs(Me.fa),en=Math.abs(Me.Ab);var Jn=Math.abs(Me.Db),tn=Math.abs(Me.lb),Hn=tn*(bs-1)+xs;Ue&=zs*(bs-1)+xs<=Me.Fd,Ue&=en*(Dn-1)+Ms<=Me.Cd,Ue=(Ue&=Jn*(Dn-1)+Ms<=Me.Ed)&zs>=xs&en>=Ms&Jn>=Ms,Ue&=Me.y!=null,Ue&=Me.f!=null,Ue&=Me.ea!=null,ns==12&&(Ue&=tn>=xs,Ue&=Hn<=Me.Tc,Ue&=Me.F!=null)}else Ue=0;Me=Ue?0:2}}return Me!=0||xt!=null&&xt.fd&&(Me=$a(jt)),Me}var Tc=64,Va=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215],Fp=24,cu=32,ba=8,Zg=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];$e("Predictor0","PredictorAdd0"),I.Predictor0=function(){return 4278190080},I.Predictor1=function(Me){return Me},I.Predictor2=function(Me,Ue,xt){return Ue[xt+0]},I.Predictor3=function(Me,Ue,xt){return Ue[xt+1]},I.Predictor4=function(Me,Ue,xt){return Ue[xt-1]},I.Predictor5=function(Me,Ue,xt){return nt(nt(Me,Ue[xt+1]),Ue[xt+0])},I.Predictor6=function(Me,Ue,xt){return nt(Me,Ue[xt-1])},I.Predictor7=function(Me,Ue,xt){return nt(Me,Ue[xt+0])},I.Predictor8=function(Me,Ue,xt){return nt(Ue[xt-1],Ue[xt+0])},I.Predictor9=function(Me,Ue,xt){return nt(Ue[xt+0],Ue[xt+1])},I.Predictor10=function(Me,Ue,xt){return nt(nt(Me,Ue[xt-1]),nt(Ue[xt+0],Ue[xt+1]))},I.Predictor11=function(Me,Ue,xt){var jt=Ue[xt+0];return 0>=ut(jt>>24&255,Me>>24&255,(Ue=Ue[xt-1])>>24&255)+ut(jt>>16&255,Me>>16&255,Ue>>16&255)+ut(jt>>8&255,Me>>8&255,Ue>>8&255)+ut(255&jt,255&Me,255&Ue)?jt:Me},I.Predictor12=function(Me,Ue,xt){var jt=Ue[xt+0];return(Ge((Me>>24&255)+(jt>>24&255)-((Ue=Ue[xt-1])>>24&255))<<24|Ge((Me>>16&255)+(jt>>16&255)-(Ue>>16&255))<<16|Ge((Me>>8&255)+(jt>>8&255)-(Ue>>8&255))<<8|Ge((255&Me)+(255&jt)-(255&Ue)))>>>0},I.Predictor13=function(Me,Ue,xt){var jt=Ue[xt-1];return(Je((Me=nt(Me,Ue[xt+0]))>>24&255,jt>>24&255)<<24|Je(Me>>16&255,jt>>16&255)<<16|Je(Me>>8&255,jt>>8&255)<<8|Je(255&Me,255&jt))>>>0};var qy=I.PredictorAdd0;I.PredictorAdd1=lt,$e("Predictor2","PredictorAdd2"),$e("Predictor3","PredictorAdd3"),$e("Predictor4","PredictorAdd4"),$e("Predictor5","PredictorAdd5"),$e("Predictor6","PredictorAdd6"),$e("Predictor7","PredictorAdd7"),$e("Predictor8","PredictorAdd8"),$e("Predictor9","PredictorAdd9"),$e("Predictor10","PredictorAdd10"),$e("Predictor11","PredictorAdd11"),$e("Predictor12","PredictorAdd12"),$e("Predictor13","PredictorAdd13");var wg=I.PredictorAdd2;ms("ColorIndexInverseTransform","MapARGB","32b",function(Me){return Me>>8&255},function(Me){return Me}),ms("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Me){return Me},function(Me){return Me>>8&255});var F0,Vx=I.ColorIndexInverseTransform,Id=I.MapARGB,ff=I.VP8LColorIndexInverseTransformAlpha,bm=I.MapAlpha,ph=I.VP8LPredictorsAdd=[];ph.length=16,(I.VP8LPredictors=[]).length=16,(I.VP8LPredictorsAdd_C=[]).length=16,(I.VP8LPredictors_C=[]).length=16;var Gd,xf,T1,M1,yd,Xg,O0,_m,Hx,Fb,fh,Mc,Cl,fl,qu,Wd,Qg,z0,wm,nw,Zj,rw,Jg,xh,B0,Xj,$0,aw,JN=i(511),ek=i(2041),Ob=i(225),zb=i(767),tk=0,iw=ek,gf=Ob,jm=zb,fr=JN,Bb=0,$b=1,P1=2,ax=3,Rv=4,U0=5,ow=6,L1=7,sk=8,Qj=9,Vy=10,GC=[2,3,7],Mo=[3,3,11],XS=[280,256,256,256,40],WC=[0,1,1,1,0],XL=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],KC=[24,7,23,25,40,6,39,41,22,26,38,42,56,5,55,57,21,27,54,58,37,43,72,4,71,73,20,28,53,59,70,74,36,44,88,69,75,52,60,3,87,89,19,29,86,90,35,45,68,76,85,91,51,61,104,2,103,105,18,30,102,106,34,46,84,92,67,77,101,107,50,62,120,1,119,121,83,93,17,31,100,108,66,78,118,122,33,47,117,123,49,63,99,109,82,94,0,116,124,65,79,16,32,98,110,48,115,125,81,95,64,114,126,97,111,80,113,127,96,112],tT=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],vd=8,lw=[4,5,6,7,8,9,10,10,11,12,13,14,15,16,17,17,18,19,20,20,21,21,22,22,23,23,24,25,25,26,27,28,29,30,31,32,33,34,35,36,37,37,38,39,40,41,42,43,44,45,46,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91,93,95,96,98,100,101,102,104,106,108,110,112,114,116,118,122,124,126,128,130,132,134,136,138,140,143,145,148,151,154,157],YC=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,119,122,125,128,131,134,137,140,143,146,149,152,155,158,161,164,167,170,173,177,181,185,189,193,197,201,205,209,213,217,221,225,229,234,239,245,249,254,259,264,269,274,279,284],Ub=null,QL=[[173,148,140,0],[176,155,140,135,0],[180,157,141,134,130,0],[254,254,243,230,196,177,153,140,133,130,129,0]],Hy=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],Jj=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],cw=[[[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]],[[253,136,254,255,228,219,128,128,128,128,128],[189,129,242,255,227,213,255,219,128,128,128],[106,126,227,252,214,209,255,255,128,128,128]],[[1,98,248,255,236,226,255,255,128,128,128],[181,133,238,254,221,234,255,154,128,128,128],[78,134,202,247,198,180,255,219,128,128,128]],[[1,185,249,255,243,255,128,128,128,128,128],[184,150,247,255,236,224,128,128,128,128,128],[77,110,216,255,236,230,128,128,128,128,128]],[[1,101,251,255,241,255,128,128,128,128,128],[170,139,241,252,236,209,255,255,128,128,128],[37,116,196,243,228,255,255,255,128,128,128]],[[1,204,254,255,245,255,128,128,128,128,128],[207,160,250,255,238,128,128,128,128,128,128],[102,103,231,255,211,171,128,128,128,128,128]],[[1,152,252,255,240,255,128,128,128,128,128],[177,135,243,255,234,225,128,128,128,128,128],[80,129,211,255,194,224,128,128,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[246,1,255,128,128,128,128,128,128,128,128],[255,128,128,128,128,128,128,128,128,128,128]]],[[[198,35,237,223,193,187,162,160,145,155,62],[131,45,198,221,172,176,220,157,252,221,1],[68,47,146,208,149,167,221,162,255,223,128]],[[1,149,241,255,221,224,255,255,128,128,128],[184,141,234,253,222,220,255,199,128,128,128],[81,99,181,242,176,190,249,202,255,255,128]],[[1,129,232,253,214,197,242,196,255,255,128],[99,121,210,250,201,198,255,202,128,128,128],[23,91,163,242,170,187,247,210,255,255,128]],[[1,200,246,255,234,255,128,128,128,128,128],[109,178,241,255,231,245,255,255,128,128,128],[44,130,201,253,205,192,255,255,128,128,128]],[[1,132,239,251,219,209,255,165,128,128,128],[94,136,225,251,218,190,255,255,128,128,128],[22,100,174,245,186,161,255,199,128,128,128]],[[1,182,249,255,232,235,128,128,128,128,128],[124,143,241,255,227,234,128,128,128,128,128],[35,77,181,251,193,211,255,205,128,128,128]],[[1,157,247,255,236,231,255,255,128,128,128],[121,141,235,255,225,227,255,255,128,128,128],[45,99,188,251,195,217,255,224,128,128,128]],[[1,1,251,255,213,255,128,128,128,128,128],[203,1,248,255,255,128,128,128,128,128,128],[137,1,177,255,224,255,128,128,128,128,128]]],[[[253,9,248,251,207,208,255,192,128,128,128],[175,13,224,243,193,185,249,198,255,255,128],[73,17,171,221,161,179,236,167,255,234,128]],[[1,95,247,253,212,183,255,255,128,128,128],[239,90,244,250,211,209,255,255,128,128,128],[155,77,195,248,188,195,255,255,128,128,128]],[[1,24,239,251,218,219,255,205,128,128,128],[201,51,219,255,196,186,128,128,128,128,128],[69,46,190,239,201,218,255,228,128,128,128]],[[1,191,251,255,255,128,128,128,128,128,128],[223,165,249,255,213,255,128,128,128,128,128],[141,124,248,255,255,128,128,128,128,128,128]],[[1,16,248,255,255,128,128,128,128,128,128],[190,36,230,255,236,255,128,128,128,128,128],[149,1,255,128,128,128,128,128,128,128,128]],[[1,226,255,128,128,128,128,128,128,128,128],[247,192,255,128,128,128,128,128,128,128,128],[240,128,255,128,128,128,128,128,128,128,128]],[[1,134,252,255,255,128,128,128,128,128,128],[213,62,250,255,255,128,128,128,128,128,128],[55,93,255,128,128,128,128,128,128,128,128]],[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]]],[[[202,24,213,235,186,191,220,160,240,175,255],[126,38,182,232,169,184,228,174,255,187,128],[61,46,138,219,151,178,240,170,255,216,128]],[[1,112,230,250,199,191,247,159,255,255,128],[166,109,228,252,211,215,255,174,128,128,128],[39,77,162,232,172,180,245,178,255,255,128]],[[1,52,220,246,198,199,249,220,255,255,128],[124,74,191,243,183,193,250,221,255,255,128],[24,71,130,219,154,170,243,182,255,255,128]],[[1,182,225,249,219,240,255,224,128,128,128],[149,150,226,252,216,205,255,171,128,128,128],[28,108,170,242,183,194,254,223,255,255,128]],[[1,81,230,252,204,203,255,192,128,128,128],[123,102,209,247,188,196,255,233,128,128,128],[20,95,153,243,164,173,255,203,128,128,128]],[[1,222,248,255,216,213,128,128,128,128,128],[168,175,246,252,235,205,255,255,128,128,128],[47,116,215,255,211,212,255,255,128,128,128]],[[1,121,236,253,212,214,255,255,128,128,128],[141,84,213,252,201,202,255,219,128,128,128],[42,80,160,240,162,185,255,205,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[244,1,255,128,128,128,128,128,128,128,128],[238,1,255,128,128,128,128,128,128,128,128]]]],QS=[[[231,120,48,89,115,113,120,152,112],[152,179,64,126,170,118,46,70,95],[175,69,143,80,85,82,72,155,103],[56,58,10,171,218,189,17,13,152],[114,26,17,163,44,195,21,10,173],[121,24,80,195,26,62,44,64,85],[144,71,10,38,171,213,144,34,26],[170,46,55,19,136,160,33,206,71],[63,20,8,114,114,208,12,9,226],[81,40,11,96,182,84,29,16,36]],[[134,183,89,137,98,101,106,165,148],[72,187,100,130,157,111,32,75,80],[66,102,167,99,74,62,40,234,128],[41,53,9,178,241,141,26,8,107],[74,43,26,146,73,166,49,23,157],[65,38,105,160,51,52,31,115,128],[104,79,12,27,217,255,87,17,7],[87,68,71,44,114,51,15,186,23],[47,41,14,110,182,183,21,17,194],[66,45,25,102,197,189,23,18,22]],[[88,88,147,150,42,46,45,196,205],[43,97,183,117,85,38,35,179,61],[39,53,200,87,26,21,43,232,171],[56,34,51,104,114,102,29,93,77],[39,28,85,171,58,165,90,98,64],[34,22,116,206,23,34,43,166,73],[107,54,32,26,51,1,81,43,31],[68,25,106,22,64,171,36,225,114],[34,19,21,102,132,188,16,76,124],[62,18,78,95,85,57,50,48,51]],[[193,101,35,159,215,111,89,46,111],[60,148,31,172,219,228,21,18,111],[112,113,77,85,179,255,38,120,114],[40,42,1,196,245,209,10,25,109],[88,43,29,140,166,213,37,43,154],[61,63,30,155,67,45,68,1,209],[100,80,8,43,154,1,51,26,71],[142,78,78,16,255,128,34,197,171],[41,40,5,102,211,183,4,1,221],[51,50,17,168,209,192,23,25,82]],[[138,31,36,171,27,166,38,44,229],[67,87,58,169,82,115,26,59,179],[63,59,90,180,59,166,93,73,154],[40,40,21,116,143,209,34,39,175],[47,15,16,183,34,223,49,45,183],[46,17,33,183,6,98,15,32,183],[57,46,22,24,128,1,54,17,37],[65,32,73,115,28,128,23,128,205],[40,3,9,115,51,192,18,6,223],[87,37,9,115,59,77,64,21,47]],[[104,55,44,218,9,54,53,130,226],[64,90,70,205,40,41,23,26,57],[54,57,112,184,5,41,38,166,213],[30,34,26,133,152,116,10,32,134],[39,19,53,221,26,114,32,73,255],[31,9,65,234,2,15,1,118,73],[75,32,12,51,192,255,160,43,51],[88,31,35,67,102,85,55,186,85],[56,21,23,111,59,205,45,37,192],[55,38,70,124,73,102,1,34,98]],[[125,98,42,88,104,85,117,175,82],[95,84,53,89,128,100,113,101,45],[75,79,123,47,51,128,81,171,1],[57,17,5,71,102,57,53,41,49],[38,33,13,121,57,73,26,1,85],[41,10,67,138,77,110,90,47,114],[115,21,2,10,102,255,166,23,6],[101,29,16,10,85,128,101,196,26],[57,18,10,102,102,213,34,20,43],[117,20,15,36,163,128,68,1,26]],[[102,61,71,37,34,53,31,243,192],[69,60,71,38,73,119,28,222,37],[68,45,128,34,1,47,11,245,171],[62,17,19,70,146,85,55,62,70],[37,43,37,154,100,163,85,160,1],[63,9,92,136,28,64,32,201,85],[75,15,9,9,64,255,184,119,16],[86,6,28,5,64,255,25,248,1],[56,8,17,132,137,255,55,116,128],[58,15,20,82,135,57,26,121,40]],[[164,50,31,137,154,133,25,35,218],[51,103,44,131,131,123,31,6,158],[86,40,64,135,148,224,45,183,128],[22,26,17,131,240,154,14,1,209],[45,16,21,91,64,222,7,1,197],[56,21,39,155,60,138,23,102,213],[83,12,13,54,192,255,68,47,28],[85,26,85,85,128,128,32,146,171],[18,11,7,63,144,171,4,4,246],[35,27,10,146,174,171,12,26,128]],[[190,80,35,99,180,80,126,54,45],[85,126,47,87,176,51,41,20,32],[101,75,128,139,118,146,116,128,85],[56,41,15,176,236,85,37,9,62],[71,30,17,119,118,255,17,18,138],[101,38,60,138,55,70,43,26,142],[146,36,19,30,171,255,97,27,20],[138,45,61,62,219,1,81,188,64],[32,41,20,117,151,142,20,21,163],[112,19,12,61,195,128,48,4,24]]],qb=[[[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[176,246,255,255,255,255,255,255,255,255,255],[223,241,252,255,255,255,255,255,255,255,255],[249,253,253,255,255,255,255,255,255,255,255]],[[255,244,252,255,255,255,255,255,255,255,255],[234,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255]],[[255,246,254,255,255,255,255,255,255,255,255],[239,253,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[251,255,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[251,254,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,254,253,255,254,255,255,255,255,255,255],[250,255,254,255,254,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[217,255,255,255,255,255,255,255,255,255,255],[225,252,241,253,255,255,254,255,255,255,255],[234,250,241,250,253,255,253,254,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[223,254,254,255,255,255,255,255,255,255,255],[238,253,254,254,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[249,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,255,255,255,255,255,255,255,255,255],[247,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[252,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[186,251,250,255,255,255,255,255,255,255,255],[234,251,244,254,255,255,255,255,255,255,255],[251,251,243,253,254,255,254,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[236,253,254,255,255,255,255,255,255,255,255],[251,253,253,254,254,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[254,254,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[254,254,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[248,255,255,255,255,255,255,255,255,255,255],[250,254,252,254,255,255,255,255,255,255,255],[248,254,249,253,255,255,255,255,255,255,255]],[[255,253,253,255,255,255,255,255,255,255,255],[246,253,253,255,255,255,255,255,255,255,255],[252,254,251,254,254,255,255,255,255,255,255]],[[255,254,252,255,255,255,255,255,255,255,255],[248,254,253,255,255,255,255,255,255,255,255],[253,255,254,254,255,255,255,255,255,255,255]],[[255,251,254,255,255,255,255,255,255,255,255],[245,251,254,255,255,255,255,255,255,255,255],[253,253,254,255,255,255,255,255,255,255,255]],[[255,251,253,255,255,255,255,255,255,255,255],[252,253,254,255,255,255,255,255,255,255,255],[255,254,255,255,255,255,255,255,255,255,255]],[[255,252,255,255,255,255,255,255,255,255,255],[249,255,254,255,255,255,255,255,255,255,255],[255,255,254,255,255,255,255,255,255,255,255]],[[255,255,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]]],Vb=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Gx=[],Yu=[],Gy=[],nk=1,ZC=2,jg=[],ix=[];mo("UpsampleRgbLinePair",Pa,3),mo("UpsampleBgrLinePair",vi,3),mo("UpsampleRgbaLinePair",pp,4),mo("UpsampleBgraLinePair",Au,4),mo("UpsampleArgbLinePair",rd,4),mo("UpsampleRgba4444LinePair",wi,2),mo("UpsampleRgb565LinePair",Li,2);var rk=I.UpsampleRgbLinePair,JS=I.UpsampleBgrLinePair,e2=I.UpsampleRgbaLinePair,t2=I.UpsampleBgraLinePair,ox=I.UpsampleArgbLinePair,yf=I.UpsampleRgba4444LinePair,XC=I.UpsampleRgb565LinePair,Fv=16,s2=1<jt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),jt.ca.f.kb.F!=null&&Yc()),jt.Pb&&0(zs=xt.Md)?0:100en;++en)12>(Jn=ns.pb[en]).lc&&(Jn.ia=zs*fp[0>Jn.lc?0:Jn.lc]>>3),Dn|=Jn.ia;Dn&&(alert("todo:VP8InitRandom"),ns.ia=1)}ns.Ga=xt.Id,100ns.Ga&&(ns.Ga=0)}(function(tn,Hn){if(tn==null)return 0;if(Hn==null)return Ua(tn,2,"NULL VP8Io parameter in VP8Decode().");if(!tn.cb&&!Ji(tn,Hn))return 0;if(t(tn.cb),Hn.ac==null||Hn.ac(Hn)){Hn.ob&&(tn.L=0);var ir=i2[tn.L];if(tn.L==2?(tn.yb=0,tn.zb=0):(tn.yb=Hn.v-ir>>4,tn.zb=Hn.j-ir>>4,0>tn.yb&&(tn.yb=0),0>tn.zb&&(tn.zb=0)),tn.Va=Hn.o+15+ir>>4,tn.Hb=Hn.va+15+ir>>4,tn.Hb>tn.za&&(tn.Hb=tn.za),tn.Va>tn.Ub&&(tn.Va=tn.Ub),0ir;++ir){var Nr;if(tn.Qa.Cb){var Gn=tn.Qa.Lb[ir];tn.Qa.Fb||(Gn+=Dr.Tb)}else Gn=Dr.Tb;for(Nr=0;1>=Nr;++Nr){var Gr=tn.gd[ir][Nr],Ca=Gn;if(Dr.Pc&&(Ca+=Dr.vd[0],Nr&&(Ca+=Dr.od[0])),0<(Ca=0>Ca?0:63>2:_a>>1)>9-Dr.wb&&(_a=9-Dr.wb),1>_a&&(_a=1),Gr.dd=_a,Gr.tc=2*Ca+_a,Gr.ld=40<=Ca?2:15<=Ca?1:0}else Gr.tc=0;Gr.La=Nr}}}ir=0}else Ua(tn,6,"Frame setup failed"),ir=tn.a;if(ir=ir==0){if(ir){tn.$c=0,0tn.Vb){if(tn.Vb=0,tn.Ec=i(Gr),tn.Fc=0,tn.Ec==null){ir=Ua(tn,1,"no memory during frame initialization.");break t}tn.Vb=Gr}Gr=tn.Ec,Ca=tn.Fc,tn.Ac=Gr,tn.Bc=Ca,Ca+=Dr,tn.Gd=l(ro,Ro),tn.Hd=0,tn.rb=l(Oi+1,Tr),tn.sb=1,tn.wa=Al?l(Al,Kr):null,tn.Y=0,tn.D.Nb=0,tn.D.wa=tn.wa,tn.D.Y=tn.Y,0=ir;++ir)JN[255+ir]=0>ir?-ir:ir;for(ir=-1020;1020>=ir;++ir)ek[1020+ir]=-128>ir?-128:127=ir;++ir)Ob[112+ir]=-16>ir?-16:15=ir;++ir)zb[255+ir]=0>ir?0:255vl;++vl){var du,ad=Nu[0+vl];for(du=0;4>du;++du){ad=QS[ju[Vm+du]][ad];for(var Kd=Jj[Pe(To,ad[0])];0>3;for(Kd=0;256>Kd;Kd+=16)vl[Vu+Kd]=tm}Mh=1,Op=Vm[0]}var Pc=15&To.la,Ph=15&lx.la;for(Kd=0;4>Kd;++Kd){var zp=1&Ph;for(tm=bd=0;4>tm;++tm)Pc=Pc>>1|(zp=(Dd=Ub(ju,Op,Dd=zp+(1&Pc),Zu.Sc,Mh,vl,Vu))>Mh)<<7,bd=bd<<2|(3>=4,Ph=Ph>>1|zp<<7,du=(du<<8|bd)>>>0}for(Op=Pc,Mh=Ph>>4,gh=0;4>gh;gh+=2){for(bd=0,Pc=To.la>>4+gh,Ph=lx.la>>4+gh,Kd=0;2>Kd;++Kd){for(zp=1&Ph,tm=0;2>tm;++tm)Dd=zp+(1&Pc),Pc=Pc>>1|(zp=0<(Dd=Ub(ju,Vm[2],Dd,Zu.Qc,0,vl,Vu)))<<3,bd=bd<<2|(3>=2,Ph=Ph>>1|zp<<5}ad|=bd<<4*gh,Op|=Pc<<4<=eo.zb&&eo.M<=eo.Va,eo.Aa==0)t:{if(El.M=eo.M,El.uc=To,Rp(eo,El),Il=1,El=(bd=eo.D).Nb,To=(ad=i2[eo.L])*eo.R,ju=ad/2*eo.B,Kd=16*El*eo.R,tm=8*El*eo.B,Vm=eo.sa,Nu=eo.ta-To+Kd,Zu=eo.qa,vl=eo.ra-ju+tm,Vu=eo.Ha,lx=eo.Ia-ju+tm,Ph=(Pc=bd.M)==0,du=Pc>=eo.Va-1,eo.Aa==2&&Rp(eo,bd),bd.uc)for(zp=(Dd=eo).D.M,t(Dd.D.uc),bd=Dd.yb;bdfi.o&&(Pc=fi.o),fi.F=null,fi.J=null,eo.Fa!=null&&0>1),fi.W+=eo.B*(ad>>1),fi.F!=null&&(fi.J+=fi.width*ad)),bd>1,fi.W+=fi.v>>1,fi.F!=null&&(fi.J+=fi.v),fi.ka=bd-fi.j,fi.U=fi.va-fi.v,fi.T=Pc-bd,Il=fi.put(fi))}El+1!=eo.Ic||du||(r(eo.sa,eo.ta-To,Vm,Nu+16*eo.R,To),r(eo.qa,eo.ra-ju,Zu,vl+8*eo.B,ju),r(eo.Ha,eo.Ia-ju,Vu,lx+8*eo.B,ju))}if(!Il)return Ua(bc,6,"Output aborted.")}return 1}(tn,Hn)),Hn.bc!=null&&Hn.bc(Hn),ir&=1}return ir?(tn.cb=0,ir):0})(Me,jt)||(Ue=Me.a)}}else Ue=Me.a}Ue==0&&bs.Oa!=null&&bs.Oa.fd&&(Ue=$a(bs.ba))}bs=Ue}xs=bs!=0?null:11>xs?Ms.f.RGBA.eb:Ms.f.kb.y}else xs=null;return xs};var hw=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(I,D){for(var F="",q=0;q<4;q++)F+=String.fromCharCode(I[D++]);return F}function u(I,D){return I[D+0]|I[D+1]<<8}function h(I,D){return(I[D+0]|I[D+1]<<8|I[D+2]<<16)>>>0}function m(I,D){return(I[D+0]|I[D+1]<<8|I[D+2]<<16|I[D+3]<<24)>>>0}new c;var p=[0],f=[0],g=[],v=new c,y=s,b=function(I,D){var F={},q=0,G=!1,V=0,H=0;if(F.frames=[],!function(te,ce){for(var ve=0;ve<4;ve++)if(te[ce+ve]!="RIFF".charCodeAt(ve))return!0;return!1}(I,D)){for(m(I,D+=4),D+=8;D>1&1}K!="ANMF"&&(D+=oe)}return F}}(y,0);b.response=y,b.rgbaoutput=!0,b.dataurl=!1;var w=b.header?b.header:null,S=b.frames?b.frames:null;if(w){w.loop_counter=w.loop_count,p=[w.canvas_height],f=[w.canvas_width];for(var C=0;C'+n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")+"",this.internal.__metadata__.metadataObjectNumber=this.internal.newObject(),this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+s.length+" >>"),this.internal.write("stream"),this.internal.write(s),this.internal.write("endstream"),this.internal.write("endobj")}function Dqn(){this.internal.__metadata__.metadataObjectNumber&&this.internal.write("/Metadata "+this.internal.__metadata__.metadataObjectNumber+" 0 R")}(function(s){var t,n,r,a,i,l,o,c,d,u=function(te){return te=te||{},this.isStrokeTransparent=te.isStrokeTransparent||!1,this.strokeOpacity=te.strokeOpacity||1,this.strokeStyle=te.strokeStyle||"#000000",this.fillStyle=te.fillStyle||"#000000",this.isFillTransparent=te.isFillTransparent||!1,this.fillOpacity=te.fillOpacity||1,this.font=te.font||"10px sans-serif",this.textBaseline=te.textBaseline||"alphabetic",this.textAlign=te.textAlign||"left",this.lineWidth=te.lineWidth||1,this.lineJoin=te.lineJoin||"miter",this.lineCap=te.lineCap||"butt",this.path=te.path||[],this.transform=te.transform!==void 0?te.transform.clone():new c,this.globalCompositeOperation=te.globalCompositeOperation||"normal",this.globalAlpha=te.globalAlpha||1,this.clip_path=te.clip_path||[],this.currentPoint=te.currentPoint||new l,this.miterLimit=te.miterLimit||10,this.lastPoint=te.lastPoint||new l,this.lineDashOffset=te.lineDashOffset||0,this.lineDash=te.lineDash||[],this.margin=te.margin||[0,0,0,0],this.prevPageLastElemOffset=te.prevPageLastElemOffset||0,this.ignoreClearRect=typeof te.ignoreClearRect!="boolean"||te.ignoreClearRect,this};s.events.push(["initialized",function(){this.context2d=new h(this),t=this.internal.f2,n=this.internal.getCoordinateString,r=this.internal.getVerticalCoordinateString,a=this.internal.getHorizontalCoordinate,i=this.internal.getVerticalCoordinate,l=this.internal.Point,o=this.internal.Rectangle,c=this.internal.Matrix,d=new u}]);var h=function(te){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var ce=te;Object.defineProperty(this,"pdf",{get:function(){return ce}});var ve=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return ve},set:function(Ae){ve=!!Ae}});var me=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return me},set:function(Ae){me=!!Ae}});var he=0;Object.defineProperty(this,"posX",{get:function(){return he},set:function(Ae){isNaN(Ae)||(he=Ae)}});var ge=0;Object.defineProperty(this,"posY",{get:function(){return ge},set:function(Ae){isNaN(Ae)||(ge=Ae)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Ae){var Se;typeof Ae=="number"?Se=[Ae,Ae,Ae,Ae]:((Se=new Array(4))[0]=Ae[0],Se[1]=Ae.length>=2?Ae[1]:Se[0],Se[2]=Ae.length>=3?Ae[2]:Se[0],Se[3]=Ae.length>=4?Ae[3]:Se[1]),d.margin=Se}});var Ee=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ee},set:function(Ae){Ee=Ae}});var Ne=0;Object.defineProperty(this,"lastBreak",{get:function(){return Ne},set:function(Ae){Ne=Ae}});var Pe=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Pe},set:function(Ae){Pe=Ae}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Ae){Ae instanceof u&&(d=Ae)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Ae){d.path=Ae}});var Oe=[];Object.defineProperty(this,"ctxStack",{get:function(){return Oe},set:function(Ae){Oe=Ae}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Ae){var Se;Se=m(Ae),this.ctx.fillStyle=Se.style,this.ctx.isFillTransparent=Se.a===0,this.ctx.fillOpacity=Se.a,this.pdf.setFillColor(Se.r,Se.g,Se.b,{a:Se.a}),this.pdf.setTextColor(Se.r,Se.g,Se.b,{a:Se.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Ae){var Se=m(Ae);this.ctx.strokeStyle=Se.style,this.ctx.isStrokeTransparent=Se.a===0,this.ctx.strokeOpacity=Se.a,Se.a===0?this.pdf.setDrawColor(255,255,255):(Se.a,this.pdf.setDrawColor(Se.r,Se.g,Se.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Ae){["butt","round","square"].indexOf(Ae)!==-1&&(this.ctx.lineCap=Ae,this.pdf.setLineCap(Ae))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Ae){isNaN(Ae)||(this.ctx.lineWidth=Ae,this.pdf.setLineWidth(Ae))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Ae){["bevel","round","miter"].indexOf(Ae)!==-1&&(this.ctx.lineJoin=Ae,this.pdf.setLineJoin(Ae))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Ae){isNaN(Ae)||(this.ctx.miterLimit=Ae,this.pdf.setMiterLimit(Ae))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Ae){this.ctx.textBaseline=Ae}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Ae){["right","end","center","left","start"].indexOf(Ae)!==-1&&(this.ctx.textAlign=Ae)}});var ke=null,Ve=null,_e=null;Object.defineProperty(this,"fontFaces",{get:function(){return _e},set:function(Ae){ke=null,Ve=null,_e=Ae}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Ae){var Se;if(this.ctx.font=Ae,(Se=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z0-9]+?)\s*$/i.exec(Ae))!==null){var We=Se[1];Se[2];var qe=Se[3],Be=Se[4];Se[5];var Ze=Se[6],$e=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(Be)[2];Be=Math.floor($e==="px"?parseFloat(Be)*this.pdf.internal.scaleFactor:$e==="em"?parseFloat(Be)*this.pdf.getFontSize():parseFloat(Be)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(Be);var Xe=function(ms){var Dt,It,qs=[],wt=ms.trim();if(wt==="")return iBe;if(wt in xSt)return[xSt[wt]];for(;wt!=="";){switch(It=null,Dt=(wt=ySt(wt)).charAt(0)){case'"':case"'":It=Aqn(wt.substring(1),Dt);break;default:It=Eqn(wt)}if(It===null||(qs.push(It[0]),(wt=ySt(It[1]))!==""&&wt.charAt(0)!==","))return iBe;wt=wt.replace(/^,/,"")}return qs}(Ze);if(this.fontFaces){var nt=function(ms,Dt){var It=ms.getFontList(),qs=JSON.stringify(It);if(ke===null||Ve!==qs){var wt=function(Us){var Es=[];return Object.keys(Us).forEach(function(kn){Us[kn].forEach(function(Sn){var bn=null;switch(Sn){case"bold":bn={family:kn,weight:"bold"};break;case"italic":bn={family:kn,style:"italic"};break;case"bolditalic":bn={family:kn,weight:"bold",style:"italic"};break;case"":case"normal":bn={family:kn}}bn!==null&&(bn.ref={name:kn,style:Sn},Es.push(bn))})}),Es}(It);ke=function(Us){for(var Es={},kn=0;kn=700||We==="bold")&&(ut="bold"),We==="italic"&&(ut+="italic"),ut.length===0&&(ut="normal");for(var lt="",qt={arial:"Helvetica",Arial:"Helvetica",verdana:"Helvetica",Verdana:"Helvetica",helvetica:"Helvetica",Helvetica:"Helvetica","sans-serif":"Helvetica",fixed:"Courier",monospace:"Courier",terminal:"Courier",cursive:"Times",fantasy:"Times",serif:"Times"},zt=0;zt=2*Math.PI&&(me=0,he=2*Math.PI),this.path.push({type:"arc",x:te,y:ce,radius:ve,startAngle:me,endAngle:he,counterclockwise:ge})},h.prototype.arcTo=function(te,ce,ve,me,he){throw new Error("arcTo not implemented.")},h.prototype.rect=function(te,ce,ve,me){if(isNaN(te)||isNaN(ce)||isNaN(ve)||isNaN(me))throw Am.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(te,ce),this.lineTo(te+ve,ce),this.lineTo(te+ve,ce+me),this.lineTo(te,ce+me),this.lineTo(te,ce),this.lineTo(te+ve,ce),this.lineTo(te,ce)},h.prototype.fillRect=function(te,ce,ve,me){if(isNaN(te)||isNaN(ce)||isNaN(ve)||isNaN(me))throw Am.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!p.call(this)){var he={};this.lineCap!=="butt"&&(he.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(he.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(te,ce,ve,me),this.fill(),he.hasOwnProperty("lineCap")&&(this.lineCap=he.lineCap),he.hasOwnProperty("lineJoin")&&(this.lineJoin=he.lineJoin)}},h.prototype.strokeRect=function(te,ce,ve,me){if(isNaN(te)||isNaN(ce)||isNaN(ve)||isNaN(me))throw Am.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");f.call(this)||(this.beginPath(),this.rect(te,ce,ve,me),this.stroke())},h.prototype.clearRect=function(te,ce,ve,me){if(isNaN(te)||isNaN(ce)||isNaN(ve)||isNaN(me))throw Am.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(te,ce,ve,me))},h.prototype.save=function(te){te=typeof te!="boolean"||te;for(var ce=this.pdf.internal.getCurrentPageInfo().pageNumber,ve=0;ve0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(te,ce,ve,me,he,ge,Ee,Ne,Pe){var Oe=this.pdf.getImageProperties(te),ke=1,Ve=1,_e=1,Ae=1;me!==void 0&&Ne!==void 0&&(_e=Ne/me,Ae=Pe/he,ke=Oe.width/me*Ne/me,Ve=Oe.height/he*Pe/he),ge===void 0&&(ge=ce,Ee=ve,ce=0,ve=0),me!==void 0&&Ne===void 0&&(Ne=me,Pe=he),me===void 0&&Ne===void 0&&(Ne=Oe.width,Pe=Oe.height);var Se=this.ctx.transform.decompose(),We=oe(Se.rotate.shx),qe=new c,Be=(qe=(qe=(qe=qe.multiply(Se.translate)).multiply(Se.skew)).multiply(Se.scale)).applyToRectangle(new o(ge-ce*_e,Ee-ve*Ae,me*ke,he*Ve));if(this.autoPaging){for(var Ze,$e=v.call(this,Be),Xe=[],nt=0;nt<$e.length;nt+=1)Xe.indexOf($e[nt])===-1&&Xe.push($e[nt]);w(Xe);for(var Ge=Xe[0],Je=Xe[Xe.length-1],ut=Ge;utGe||utBe||$e0)){for(;Pe>=0;Pe--)if(he[Pe-1].close!==!0&&he[Pe-1].begin!==!0){he[Pe-1].deltas.push(ve),he[Pe-1].abs.push(Ne);break}}break;case"bct":ve=[Ne.x1-ge[Ee-1].x,Ne.y1-ge[Ee-1].y,Ne.x2-ge[Ee-1].x,Ne.y2-ge[Ee-1].y,Ne.x-ge[Ee-1].x,Ne.y-ge[Ee-1].y],he[he.length-1].deltas.push(ve);break;case"qct":var Oe=ge[Ee-1].x+2/3*(Ne.x1-ge[Ee-1].x),ke=ge[Ee-1].y+2/3*(Ne.y1-ge[Ee-1].y),Ve=Ne.x+2/3*(Ne.x1-Ne.x),_e=Ne.y+2/3*(Ne.y1-Ne.y),Ae=Ne.x,Se=Ne.y;ve=[Oe-ge[Ee-1].x,ke-ge[Ee-1].y,Ve-ge[Ee-1].x,_e-ge[Ee-1].y,Ae-ge[Ee-1].x,Se-ge[Ee-1].y],he[he.length-1].deltas.push(ve);break;case"arc":he.push({deltas:[],abs:[],arc:!0}),Array.isArray(he[he.length-1].abs)&&he[he.length-1].abs.push(Ne)}}me=ce?null:te==="stroke"?"stroke":"fill";for(var We=!1,qe=0;qe=.01&&(me=this.pdf.internal.getFontSize(),this.pdf.setFontSize(me*te.scale),he=this.lineWidth,this.lineWidth=he*te.scale);var Zt=this.autoPaging!=="text";if(Zt||zt.y+zt.h<=nt){if(Zt||zt.y>=$e&&zt.x<=Je){var ms=Zt?te.text:this.pdf.splitTextToSize(te.text,te.maxWidth||Je-zt.x)[0],Dt=b([JSON.parse(JSON.stringify(Ve))],this.posX+this.margin[3],-lt+$e+this.ctx.prevPageLastElemOffset)[0],It=Zt&&(Ze>qe||Ze=.01&&(this.pdf.setFontSize(me),this.lineWidth=he)}}else te.scale>=.01&&(me=this.pdf.internal.getFontSize(),this.pdf.setFontSize(me*te.scale),he=this.lineWidth,this.lineWidth=he*te.scale),this.pdf.text(te.text,Pe.x+this.posX,Pe.y+this.posY,{angle:te.angle,align:ce,renderingMode:te.renderingMode,maxWidth:te.maxWidth}),te.scale>=.01&&(this.pdf.setFontSize(me),this.lineWidth=he)},G=function(te,ce,ve,me){ve=ve||0,me=me||0,this.pdf.internal.out(n(te+ve)+" "+r(ce+me)+" l")},V=function(te,ce,ve){return this.pdf.lines(te,ce,ve,null,null)},H=function(te,ce,ve,me,he,ge,Ee,Ne){this.pdf.internal.out([t(a(ve+te)),t(i(me+ce)),t(a(he+te)),t(i(ge+ce)),t(a(Ee+te)),t(i(Ne+ce)),"c"].join(" "))},K=function(te,ce,ve,me){for(var he=2*Math.PI,ge=Math.PI/2;ce>ve;)ce-=he;var Ee=Math.abs(ve-ce);Ee1e-5;){var ke=Oe+Pe*Math.min(Ee,ge);Ne.push(Z.call(this,te,Oe,ke)),Ee-=Math.abs(ke-Oe),Oe=ke}return Ne},Z=function(te,ce,ve){var me=(ve-ce)/2,he=te*Math.cos(me),ge=te*Math.sin(me),Ee=he,Ne=-ge,Pe=Ee*Ee+Ne*Ne,Oe=Pe+Ee*he+Ne*ge,ke=4/3*(Math.sqrt(2*Pe*Oe)-Oe)/(Ee*ge-Ne*he),Ve=Ee-ke*Ne,_e=Ne+ke*Ee,Ae=Ve,Se=-_e,We=me+ce,qe=Math.cos(We),Be=Math.sin(We);return{x1:te*Math.cos(ce),y1:te*Math.sin(ce),x2:Ve*qe-_e*Be,y2:Ve*Be+_e*qe,x3:Ae*qe-Se*Be,y3:Ae*Be+Se*qe,x4:te*Math.cos(ve),y4:te*Math.sin(ve)}},oe=function(te){return 180*te/Math.PI},re=function(te,ce,ve,me,he,ge){var Ee=te+.5*(ve-te),Ne=ce+.5*(me-ce),Pe=he+.5*(ve-he),Oe=ge+.5*(me-ge),ke=Math.min(te,he,Ee,Pe),Ve=Math.max(te,he,Ee,Pe),_e=Math.min(ce,ge,Ne,Oe),Ae=Math.max(ce,ge,Ne,Oe);return new o(ke,_e,Ve-ke,Ae-_e)},ae=function(te,ce,ve,me,he,ge,Ee,Ne){var Pe,Oe,ke,Ve,_e,Ae,Se,We,qe,Be,Ze,$e,Xe,nt,Ge=ve-te,Je=me-ce,ut=he-ve,lt=ge-me,qt=Ee-he,zt=Ne-ge;for(Oe=0;Oe<41;Oe++)qe=(Se=(ke=te+(Pe=Oe/40)*Ge)+Pe*((_e=ve+Pe*ut)-ke))+Pe*(_e+Pe*(he+Pe*qt-_e)-Se),Be=(We=(Ve=ce+Pe*Je)+Pe*((Ae=me+Pe*lt)-Ve))+Pe*(Ae+Pe*(ge+Pe*zt-Ae)-We),Oe==0?(Ze=qe,$e=Be,Xe=qe,nt=Be):(Ze=Math.min(Ze,qe),$e=Math.min($e,Be),Xe=Math.max(Xe,qe),nt=Math.max(nt,Be));return new o(Math.round(Ze),Math.round($e),Math.round(Xe-Ze),Math.round(nt-$e))},J=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var te,ce,ve=(te=this.ctx.lineDash,ce=this.ctx.lineDashOffset,JSON.stringify({lineDash:te,lineDashOffset:ce}));this.prevLineDash!==ve&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=ve)}}})(Po.API),function(s){var t=function(l){var o,c,d,u,h,m,p,f,g,v;for(c=[],d=0,u=(l+=o="\0\0\0\0".slice(l.length%4||4)).length;u>d;d+=4)(h=(l.charCodeAt(d)<<24)+(l.charCodeAt(d+1)<<16)+(l.charCodeAt(d+2)<<8)+l.charCodeAt(d+3))!==0?(m=(h=((h=((h=((h=(h-(v=h%85))/85)-(g=h%85))/85)-(f=h%85))/85)-(p=h%85))/85)%85,c.push(m+33,p+33,f+33,g+33,v+33)):c.push(122);return function(y,b){for(var w=b;w>0;w--)y.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,p="length",f=255,g="charCodeAt",v="slice",y="replace";for(l[v](-2),l=l[v](0,-2)[y](/\s/g,"")[y]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[v](l[p]%5||5))[p];h>u;u+=5)c=52200625*(l[g](u)-33)+614125*(l[g](u+1)-33)+7225*(l[g](u+2)-33)+85*(l[g](u+3)-33)+(l[g](u+4)-33),d.push(f&c>>24,f&c>>16,f&c>>8,f&c);return function(b,w){for(var S=w;S>0;S--)b.pop()}(d,o[p]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(cc.DOMPurify?Promise.resolve(cc.DOMPurify):Fa(()=>import("./purify.es-dhnUglUx.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load dompurify: "+o))}).then(function(o){return o.default?o.default:o})}var r=function(o){var c=Vh(o);return c==="undefined"?"undefined":c==="string"||o instanceof String?"string":c==="number"||o instanceof Number?"number":c==="function"||o instanceof Function?"function":o&&o.constructor===Array?"array":o&&o.nodeType===1?"element":c==="object"?"object":"unknown"},a=function(o,c){var d=document.createElement(o);for(var u in c.className&&(d.className=c.className),c.innerHTML&&c.dompurify&&(d.innerHTML=c.dompurify.sanitize(c.innerHTML)),c.style)d.style[u]=c.style[u];return d},i=function o(c,d){for(var u=c.nodeType===3?document.createTextNode(c.nodeValue):c.cloneNode(!1),h=c.firstChild;h;h=h.nextSibling)d!==!0&&h.nodeType===1&&h.nodeName==="SCRIPT"||u.appendChild(o(h,d));return c.nodeType===1&&(c.nodeName==="CANVAS"?(u.width=c.width,u.height=c.height,u.getContext("2d").drawImage(c,0,0)):c.nodeName!=="TEXTAREA"&&c.nodeName!=="SELECT"||(u.value=c.value),u.addEventListener("load",function(){u.scrollTop=c.scrollTop,u.scrollLeft=c.scrollLeft},!0)),u},l=function o(c){var d=Object.assign(o.convert(Promise.resolve()),JSON.parse(JSON.stringify(o.template))),u=o.convert(Promise.resolve(),d);return(u=u.setProgress(1,o,1,[o])).set(c)};(l.prototype=Object.create(Promise.prototype)).constructor=l,l.convert=function(o,c){return o.__proto__=c||l.prototype,o},l.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:!0,x:0,y:0,html2canvas:{},jsPDF:{},backgroundColor:"transparent"}},l.prototype.from=function(o,c){return this.then(function(){switch(c=c||function(d){switch(r(d)){case"string":return"string";case"element":return d.nodeName.toLowerCase()==="canvas"?"canvas":"element";default:return"unknown"}}(o),c){case"string":return this.then(n).then(function(d){return this.set({src:a("div",{innerHTML:o,dompurify:d})})});case"element":return this.set({src:o});case"canvas":return this.set({canvas:o});case"img":return this.set({img:o});default:return this.error("Unknown source type.")}})},l.prototype.to=function(o){switch(o){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();case"pdf":return this.toPdf();default:return this.error("Invalid target.")}},l.prototype.toContainer=function(){return this.thenList([function(){return this.prop.src||this.error("Cannot duplicate - no source HTML.")},function(){return this.prop.pageSize||this.setPageSize()}]).then(function(){var o={position:"relative",display:"inline-block",width:(typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth):this.opt.windowWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:this.opt.backgroundColor},c=i(this.prop.src,this.opt.html2canvas.javascriptEnabled);c.tagName==="BODY"&&(o.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px"),this.prop.overlay=a("div",{className:"html2pdf__overlay",style:{position:"fixed",overflow:"hidden",zIndex:1e3,left:"-100000px",right:0,bottom:0,top:0}}),this.prop.container=a("div",{className:"html2pdf__container",style:o}),this.prop.container.appendChild(c),this.prop.container.firstChild.appendChild(a("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}})),this.prop.container.style.float="none",this.prop.overlay.appendChild(this.prop.container),document.body.appendChild(this.prop.overlay),this.prop.container.firstChild.style.position="relative",this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px"})},l.prototype.toCanvas=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=Object.assign({},this.opt.html2canvas);return delete d.onrendered,c(this.prop.container,d)}).then(function(c){(this.opt.html2canvas.onrendered||function(){})(c),this.prop.canvas=c,document.body.removeChild(this.prop.overlay)})},l.prototype.toContext2d=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=this.opt.jsPDF,u=this.opt.fontFaces,h=typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?1:this.opt.width/this.opt.windowWidth,m=Object.assign({async:!0,allowTaint:!0,scale:h,scrollX:this.opt.scrollX||0,scrollY:this.opt.scrollY||0,backgroundColor:"#ffffff",imageTimeout:15e3,logging:!0,proxy:null,removeContainer:!0,foreignObjectRendering:!1,useCORS:!1},this.opt.html2canvas);if(delete m.onrendered,d.context2d.autoPaging=this.opt.autoPaging===void 0||this.opt.autoPaging,d.context2d.posX=this.opt.x,d.context2d.posY=this.opt.y,d.context2d.margin=this.opt.margin,d.context2d.fontFaces=u,u)for(var p=0;pg&&(f=v,v=g,g=f);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",g>v&&(f=v,v=g,g=f)}return{width:v,height:g,unit:c,k:h,orientation:o}},s.html=function(o,c){(c=c||{}).callback=c.callback||function(){},c.html2canvas=c.html2canvas||{},c.html2canvas.canvas=c.html2canvas.canvas||this.canvas,c.jsPDF=c.jsPDF||this,c.fontFaces=c.fontFaces?c.fontFaces.map(aBe):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(Po.API),Po.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var p=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+p+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){V=!0,K=void 0;var he=I*D;Z=new Uint8Array(he);for(var ge=new DataView(F.buffer),Ee=0;Ee536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){Am.log("bit decode error:"+n)}},jk.prototype.bit1=function(){var s,t=Math.ceil(this.width/8),n=t%4;for(s=this.height-1;s>=0;s--){for(var r=this.bottom_up?s:this.height-1-s,a=0;a>7-o&1];this.data[l+4*o]=c.blue,this.data[l+4*o+1]=c.green,this.data[l+4*o+2]=c.red,this.data[l+4*o+3]=255}n!==0&&(this.pos+=4-n)}},jk.prototype.bit4=function(){for(var s=Math.ceil(this.width/2),t=s%4,n=this.height-1;n>=0;n--){for(var r=this.bottom_up?n:this.height-1-n,a=0;a>4,c=15&i,d=this.palette[o];if(this.data[l]=d.blue,this.data[l+1]=d.green,this.data[l+2]=d.red,this.data[l+3]=255,2*a+1>=this.width)break;d=this.palette[c],this.data[l+4]=d.blue,this.data[l+4+1]=d.green,this.data[l+4+2]=d.red,this.data[l+4+3]=255}t!==0&&(this.pos+=4-t)}},jk.prototype.bit8=function(){for(var s=this.width%4,t=this.height-1;t>=0;t--){for(var n=this.bottom_up?t:this.height-1-t,r=0;r=0;n--){for(var r=this.bottom_up?n:this.height-1-n,a=0;a>5&t)/t*255|0,c=(i>>10&t)/t*255|0,d=i>>15?255:0,u=r*this.width*4+4*a;this.data[u]=c,this.data[u+1]=o,this.data[u+2]=l,this.data[u+3]=d}this.pos+=s}},jk.prototype.bit16=function(){for(var s=this.width%3,t=parseInt("11111",2),n=parseInt("111111",2),r=this.height-1;r>=0;r--){for(var a=this.bottom_up?r:this.height-1-r,i=0;i>5&n)/n*255|0,d=(l>>11)/t*255|0,u=a*this.width*4+4*i;this.data[u]=d,this.data[u+1]=c,this.data[u+2]=o,this.data[u+3]=255}this.pos+=s}},jk.prototype.bit24=function(){for(var s=this.height-1;s>=0;s--){for(var t=this.bottom_up?s:this.height-1-s,n=0;n=0;s--)for(var t=this.bottom_up?s:this.height-1-s,n=0;nr&&(a.push(s.slice(c,i)),o=0,c=i),o+=t[i],i++;return c!==i&&a.push(s.slice(c,i)),a},_St=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,p=0,f=0,g=s.split(" "),v=yde.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?g[0].length+2:n.lineIndent||0){var y=Array(c).join(" "),b=[];g.map(function(S){(S=S.split(/\s*\n/)).length>1?b=b.concat(S.map(function(C,E){return(E&&C.length?` `:"")+C})):b.push(S[0])}),g=b,c=vSt.apply(this,[y,n])}for(i=0,l=g.length;it||w){if(f>t){for(o=bSt.apply(this,[r,a,t-(m+p),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);f=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(S,C){return S+C},0)}else u=[r];h.push(u),m=f+c,p=v}else u.push(r),m+=p+f,p=v}return d=c?function(S,C){return(C?y:"")+S.join(" ")}:function(S){return S.join(" ")},h.map(d)},JB.splitTextToSize=function(s,t,n){var r,a=(n=n||{}).fontSize||this.internal.getFontSize(),i=(function(u){if(u.widths&&u.kerning)return{widths:u.widths,kerning:u.kerning};var h=this.internal.getFont(u.fontName,u.fontStyle),m="Unicode";return h.metadata[m]?{widths:h.metadata[m].widths||{0:1},kerning:h.metadata[m].kerning||{}}:{font:h.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}).call(this,n);r=Array.isArray(s)?s:String(s).split(/\r?\n/);var l=1*this.internal.scaleFactor*t/a;i.textIndent=n.textIndent?1*n.textIndent*this.internal.scaleFactor/a:0,i.lineIndent=n.lineIndent;var o,c,d=[];for(o=0,c=r.length;oimport("./index.es-B6Z02dOJ.js"),[])).catch(function(m){return Promise.reject(new Error("Could not load canvg: "+m))}).then(function(m){return m.default?m.default:m}).then(function(m){return m.fromString(d,s,u)},function(){return Promise.reject(new Error("Could not load canvg."))}).then(function(m){return m.render(u)}).then(function(){h.addImage(c.toDataURL("image/jpeg",1),t,n,r,a,l,o)})},Po.API.putTotalPages=function(s){var t,n=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(t=new RegExp(s,"g"),n=this.internal.getNumberOfPages()):(t=new RegExp(this.pdfEscape16(s,this.internal.getFont()),"g"),n=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var r=1;r<=this.internal.getNumberOfPages();r++)for(var a=0;a1){for(u=0;u>`)}),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this},Po.API.addMetadata=function(s,t){return this.internal.__metadata__===void 0&&(this.internal.__metadata__={metadata:s,namespaceUri:t??"http://jspdf.default.namespaceuri/",rawXml:typeof t=="boolean"&&t},this.internal.events.subscribe("putCatalog",Dqn),this.internal.events.subscribe("postPutResources",Iqn)),this},function(s){var t=s.API,n=t.pdfEscape16=function(i,l){for(var o,c=l.metadata.Unicode.widths,d=["","0","00","000","0000"],u=[""],h=0,m=i.length;h> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange`,c=[],h=0,m=(o=Object.keys(i).sort(function(p,f){return p-f})).length;h=100&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar`,c=[]),i[l]!==void 0&&i[l]!==null&&typeof i[l].toString=="function"&&(d=("0000"+i[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),c.push("<"+l+"><"+d+">"));return c.length&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar `),u+`endcmap CMapName currentdict /CMap defineresource pop end end`};t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="Identity-H"){for(var h=o.metadata.Unicode.widths,m=o.metadata.subset.encode(o.metadata.glyIdsUsed,1),p="",f=0;f>"),c("endobj");var b=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+P$(o.fontName)),c("/FontDescriptor "+y+" 0 R"),c("/W "+s.API.PDFObject.convert(h)),c("/CIDToGIDMap /Identity"),c("/DW 1000"),c("/Subtype /CIDFontType2"),c("/CIDSystemInfo"),c("<<"),c("/Supplement 0"),c("/Registry (Adobe)"),c("/Ordering ("+o.encoding+")"),c(">>"),c(">>"),c("endobj"),o.objectNumber=d(),c("<<"),c("/Type /Font"),c("/Subtype /Type0"),c("/ToUnicode "+v+" 0 R"),c("/BaseFont /"+P$(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+b+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",p=0;p>"),c("endobj"),o.objectNumber=d();for(var y=0;y>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,p=h.activeFontKey,f=h.fonts,g=p,v="",y=0,b="",w=f[g].encoding;if(f[g].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(b=o,g=p,Array.isArray(o)&&(b=o[0]),y=0;y","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],y=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),b=!1,w=0;this.__bidiEngine__={};var S=function(F){var q=F.charCodeAt(),G=q>>8,V=g[G];return V!==void 0?h[256*V+(255&q)]:G===252||G===253?"AL":y.test(G)?"L":G===8?"R":"N"},C=function(F){for(var q,G=0;G=q.length||(H=G[V-1])!=="EN"&&H!=="AN"||(K=q[V+1])!=="EN"&&K!=="AN"?re="N":b&&(K="AN"),re=K===H?K:"N";break;case"ES":re=(H=V>0?G[V-1]:"B")==="EN"&&V+10&&G[V-1]==="EN"){re="EN";break}if(b){re="N";break}for(Z=V+1,oe=q.length;Z=1425&&ae<=2303||ae===64286;if(H=q[Z],J&&(H==="R"||H==="AL")){re="R";break}}}re=V<1||(H=q[V-1])==="B"?"N":G[V-1];break;case"B":b=!1,a=!0,re=w;break;case"S":i=!0,re="N"}return re},P=function(F,q,G){var V=F.split("");return G&&M(V,G,{hiLevel:w}),V.reverse(),q&&q.reverse(),V.join("")},M=function(F,q,G){var V,H,K,Z,oe,re=-1,ae=F.length,J=0,te=[],ce=w?p:m,ve=[];for(b=!1,a=!1,i=!1,H=0;H0)if(V===16){for(H=re;H-1){for(H=re;H=0&&me[Ne]==="WS";Ne--)he[Ne]=w}}(ve,q,ae)},I=function(F,q,G,V,H){if(!(H.hiLevel=F){for(oe=J+1;oe=F;)oe++;for(re=J,Z=oe-1;re=0&&(K[ae]=v[re+1])}(V,G,H),I(2,V,q,G,H),I(1,V,q,G,H),V.join("")};return this.__bidiEngine__.doBidiReorder=function(F,q,G){if(function(H,K){if(K)for(var Z=0;Z>16)&&(n=-(1+(65535^n))),this.italicAngle=+(n+"."+r)):this.italicAngle=0,this.ascender=Math.round(this.ascender*this.scaleFactor),this.decender=Math.round(this.decender*this.scaleFactor),this.lineGap=Math.round(this.lineGap*this.scaleFactor),this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender,this.xHeight=this.os2.exists&&this.os2.xHeight||0,this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8,this.isSerif=(i=this.familyClass)===1||i===2||i===3||i===4||i===5||i===7,this.isScript=this.familyClass===10,this.flags=0,this.post.isFixedPitch&&(this.flags|=1),this.isSerif&&(this.flags|=2),this.isScript&&(this.flags|=8),this.italicAngle!==0&&(this.flags|=64),this.flags|=32,!this.cmap.unicode)throw new Error("No unicode cmap for font")},s.prototype.characterToGlyph=function(t){var n;return((n=this.cmap.unicode)!=null?n.codeMap[t]:void 0)||0},s.prototype.widthOfGlyph=function(t){var n;return n=1e3/this.head.unitsPerEm,this.hmtx.forGlyph(t).advance*n},s.prototype.widthOfString=function(t,n,r){var a,i,l,o;for(l=0,i=0,o=(t=""+t).length;0<=o?io;i=0<=o?++i:--i)a=t.charCodeAt(i),l+=this.widthOfGlyph(this.characterToGlyph(a))+r*(1e3/n)||0;return l*(n/1e3)},s.prototype.lineHeight=function(t,n){var r;return n==null&&(n=!1),r=n?this.lineGap:0,(this.ascender+r-this.decender)/1e3*t},s}();var KS,tL=function(){function s(t){this.data=t??[],this.pos=0,this.length=this.data.length}return s.prototype.readByte=function(){return this.data[this.pos++]},s.prototype.writeByte=function(t){return this.data[this.pos++]=t},s.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},s.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255),this.writeByte(t>>16&255),this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt32=function(){var t;return(t=this.readUInt32())>=2147483648?t-4294967296:t},s.prototype.writeInt32=function(t){return t<0&&(t+=4294967296),this.writeUInt32(t)},s.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},s.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt16=function(){var t;return(t=this.readUInt16())>=32768?t-65536:t},s.prototype.writeInt16=function(t){return t<0&&(t+=65536),this.writeUInt16(t)},s.prototype.readString=function(t){var n,r;for(r=[],n=0;0<=t?nt;n=0<=t?++n:--n)r[n]=String.fromCharCode(this.readByte());return r.join("")},s.prototype.writeString=function(t){var n,r,a;for(a=[],n=0,r=t.length;0<=r?nr;n=0<=r?++n:--n)a.push(this.writeByte(t.charCodeAt(n)));return a},s.prototype.readShort=function(){return this.readInt16()},s.prototype.writeShort=function(t){return this.writeInt16(t)},s.prototype.readLongLong=function(){var t,n,r,a,i,l,o,c;return t=this.readByte(),n=this.readByte(),r=this.readByte(),a=this.readByte(),i=this.readByte(),l=this.readByte(),o=this.readByte(),c=this.readByte(),128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^n)+1099511627776*(255^r)+4294967296*(255^a)+16777216*(255^i)+65536*(255^l)+256*(255^o)+(255^c)+1):72057594037927940*t+281474976710656*n+1099511627776*r+4294967296*a+16777216*i+65536*l+256*o+c},s.prototype.writeLongLong=function(t){var n,r;return n=Math.floor(t/4294967296),r=4294967295&t,this.writeByte(n>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n),this.writeByte(r>>24&255),this.writeByte(r>>16&255),this.writeByte(r>>8&255),this.writeByte(255&r)},s.prototype.readInt=function(){return this.readInt32()},s.prototype.writeInt=function(t){return this.writeInt32(t)},s.prototype.read=function(t){var n,r;for(n=[],r=0;0<=t?rt;r=0<=t?++r:--r)n.push(this.readByte());return n},s.prototype.write=function(t){var n,r,a,i;for(i=[],r=0,a=t.length;ri;a=0<=i?++a:--a)r={tag:n.readString(4),checksum:n.readInt(),offset:n.readInt(),length:n.readInt()},this.tables[r.tag]=r}return t.prototype.encode=function(n){var r,a,i,l,o,c,d,u,h,m,p,f,g;for(g in p=Object.keys(n).length,c=Math.log(2),h=16*Math.floor(Math.log(p)/c),l=Math.floor(h/c),u=16*p-h,(a=new tL).writeInt(this.scalarType),a.writeShort(p),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*p,d=a.pos+i,o=null,f=[],n)for(m=n[g],a.writeString(g),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),f=f.concat(m),g==="head"&&(o=d),d+=m.length;d%4;)f.push(0),d++;return a.write(f),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=aes.call(n);n.length%4;)n.push(0);for(i=new tL(n),a=0,r=0,l=n.length;rm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),t.pos+=2,g=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),d=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),u=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),a=(this.length-t.pos+this.offset)/2,o=function(){var S,C;for(C=[],c=S=0;0<=a?Sa;c=0<=a?++S:--S)C.push(t.readUInt16());return C}(),c=y=0,w=i.length;y=v;r=f<=v?++b:--b)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-f)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,g,v,y,b,w,S,C,E,P,M,I,D,F,q,G,V,H,K,Z,oe,re,ae,J,te,ce,ve,me,he,ge,Ee,Ne,Pe,Oe,ke;switch(V=new tL,l=Object.keys(t).sort(function(Ve,_e){return Ve-_e}),n){case"macroman":for(g=0,v=function(){var Ve=[];for(f=0;f<256;++f)Ve.push(0);return Ve}(),b={0:0},i={},H=0,re=l.length;H=32768)for(c.push(0),E.push(2*(p.length+I-f)),a=oe=F;F<=u?oe<=u:oe>=u;a=F<=u?++oe:--oe)p.push(r[a].new);else c.push(G-F),E.push(0)}for(V.writeUInt16(3),V.writeUInt16(1),V.writeUInt32(12),V.writeUInt16(4),V.writeUInt16(16+8*I+2*p.length),V.writeUInt16(0),V.writeUInt16(D),V.writeUInt16(M),V.writeUInt16(m),V.writeUInt16(P),ge=0,te=h.length;gea;r=0<=a?++r:--r)n=new TSt(t,this.offset),this.tables.push(n),n.isUnicode&&this.unicode==null&&(this.unicode=n);return!0},s.encode=function(t,n){var r,a;return n==null&&(n="macroman"),r=TSt.encode(t,n),(a=new tL).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),zqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return UC(s,KS),s.prototype.tag="hhea",s.prototype.parse=function(t){return t.pos=this.offset,this.version=t.readInt(),this.ascender=t.readShort(),this.decender=t.readShort(),this.lineGap=t.readShort(),this.advanceWidthMax=t.readShort(),this.minLeftSideBearing=t.readShort(),this.minRightSideBearing=t.readShort(),this.xMaxExtent=t.readShort(),this.caretSlopeRise=t.readShort(),this.caretSlopeRun=t.readShort(),this.caretOffset=t.readShort(),t.pos+=8,this.metricDataFormat=t.readShort(),this.numberOfMetrics=t.readUInt16()},s}(),Bqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return UC(s,KS),s.prototype.tag="OS/2",s.prototype.parse=function(t){if(t.pos=this.offset,this.version=t.readUInt16(),this.averageCharWidth=t.readShort(),this.weightClass=t.readUInt16(),this.widthClass=t.readUInt16(),this.type=t.readShort(),this.ySubscriptXSize=t.readShort(),this.ySubscriptYSize=t.readShort(),this.ySubscriptXOffset=t.readShort(),this.ySubscriptYOffset=t.readShort(),this.ySuperscriptXSize=t.readShort(),this.ySuperscriptYSize=t.readShort(),this.ySuperscriptXOffset=t.readShort(),this.ySuperscriptYOffset=t.readShort(),this.yStrikeoutSize=t.readShort(),this.yStrikeoutPosition=t.readShort(),this.familyClass=t.readShort(),this.panose=function(){var n,r;for(r=[],n=0;n<10;++n)r.push(t.readByte());return r}(),this.charRange=function(){var n,r;for(r=[],n=0;n<4;++n)r.push(t.readInt());return r}(),this.vendorID=t.readString(4),this.selection=t.readShort(),this.firstCharIndex=t.readShort(),this.lastCharIndex=t.readShort(),this.version>0&&(this.ascent=t.readShort(),this.descent=t.readShort(),this.lineGap=t.readShort(),this.winAscent=t.readShort(),this.winDescent=t.readShort(),this.codePageRange=function(){var n,r;for(r=[],n=0;n<2;n=++n)r.push(t.readInt());return r}(),this.version>1))return this.xHeight=t.readShort(),this.capHeight=t.readShort(),this.defaultChar=t.readShort(),this.breakChar=t.readShort(),this.maxContext=t.readShort()},s}(),$qn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return UC(s,KS),s.prototype.tag="post",s.prototype.parse=function(t){var n,r,a;switch(t.pos=this.offset,this.format=t.readInt(),this.italicAngle=t.readInt(),this.underlinePosition=t.readShort(),this.underlineThickness=t.readShort(),this.isFixedPitch=t.readInt(),this.minMemType42=t.readInt(),this.maxMemType42=t.readInt(),this.minMemType1=t.readInt(),this.maxMemType1=t.readInt(),this.format){case 65536:case 196608:break;case 131072:var i;for(r=t.readUInt16(),this.glyphNameIndex=[],i=0;0<=r?ir;i=0<=r?++i:--i)this.glyphNameIndex.push(t.readUInt16());for(this.names=[],a=[];t.poso;i=0<=o?++l:--l)c.push(t.readUInt32());return c}).call(this)}},s}(),Uqn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},qqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return UC(s,KS),s.prototype.tag="name",s.prototype.parse=function(t){var n,r,a,i,l,o,c,d,u,h,m;for(t.pos=this.offset,t.readShort(),n=t.readShort(),o=t.readShort(),r=[],i=0;0<=n?in;i=0<=n?++i:--i)r.push({platformID:t.readShort(),encodingID:t.readShort(),languageID:t.readShort(),nameID:t.readShort(),length:t.readShort(),offset:this.offset+o+t.readShort()});for(c={},i=u=0,h=r.length;uo;n=0<=o?++n:--n)this.metrics.push({advance:t.readUInt16(),lsb:t.readInt16()});for(a=this.file.maxp.numGlyphs-this.file.hhea.numberOfMetrics,this.leftSideBearings=function(){var d,u;for(u=[],n=d=0;0<=a?da;n=0<=a?++d:--d)u.push(t.readInt16());return u}(),this.widths=(function(){var d,u,h,m;for(m=[],d=0,u=(h=this.metrics).length;da;n=0<=a?++l:--l)c.push(this.widths.push(r));return c},s.prototype.forGlyph=function(t){return t in this.metrics?this.metrics[t]:{advance:this.metrics[this.metrics.length-1].advance,lsb:this.leftSideBearings[t-this.metrics.length]}},s}(),aes=[].slice,Gqn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return UC(s,KS),s.prototype.tag="glyf",s.prototype.parse=function(){return this.cache={}},s.prototype.glyphFor=function(t){var n,r,a,i,l,o,c,d,u,h;return t in this.cache?this.cache[t]:(i=this.file.loca,n=this.file.contents,r=i.indexOf(t),(a=i.lengthOf(t))===0?this.cache[t]=null:(n.pos=this.offset+r,l=(o=new tL(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new Kqn(o,d,h,c,u):new Wqn(o,l,d,h,c,u),this.cache[t]))},s.prototype.encode=function(t,n,r){var a,i,l,o,c;for(l=[],i=[],o=0,c=n.length;o0&&(a+=c)}for(var d=new Array(4*r.length),u=0;u>8,d[4*u+1]=(16711680&r[u])>>16,d[4*u]=(4278190080&r[u])>>24;return d},s}(),Zqn=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,g,v,y;for(a in r=res.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),p={0:0},y=r.charMap)p[(c=y[a]).old]=c.new;for(f in m=r.maxGlyphID,l)f in p||(p[f]=m++);return u=function(b){var w,S;for(w in S={},b)S[b[w]]=w;return S}(p),h=Object.keys(u).sort(function(b,w){return b-w}),g=function(){var b,w,S;for(S=[],b=0,w=h.length;b>"),i.join(` `)}return""+n},t}();const AKe=[{id:"signature",name:"Signature",description:"The default editorial look, tinted with your own brand and accent colors.",swatch:["#0E1B2C","#2A4C64","#B8965A","#FCFBF8"],brand:"#2A4C64",accent:"#B8965A",paper:"#FCFBF8",paperCool:"#F4F7FA",softLine:"#DFE4EA",bodyInk:"#484E58",headFont:"helvetica",useAgentColors:!0},{id:"land-ranch",name:"Land, Farm & Ranch",description:"Warm olive and saddle leather on a natural paper stock. Built for acreage and estates.",swatch:["#2C3A24","#3E5232","#B07C3A","#F7F4EC"],brand:"#3E5232",accent:"#B07C3A",paper:"#F7F4EC",paperCool:"#F0EDE1",softLine:"#DCD4C2",bodyInk:"#4C4A40",headFont:"times",useAgentColors:!1},{id:"luxury",name:"Luxury",description:"Near-black ink with brushed gold and serif headlines. Quiet, expensive, restrained.",swatch:["#0B0C0F","#16181E","#C9A84C","#FAF8F4"],brand:"#16181E",accent:"#C9A84C",paper:"#FAF8F4",paperCool:"#F2EFE8",softLine:"#E0DACB",bodyInk:"#4A4A50",headFont:"times",useAgentColors:!1},{id:"coastal",name:"Beaches",description:"Deep ocean navy, surf teal, and sea-glass paper. Bright, breezy, coastal.",swatch:["#08293A","#0F3B52","#2FA0A8","#F8FBFC"],brand:"#0F3B52",accent:"#2FA0A8",paper:"#F8FBFC",paperCool:"#EDF6F8",softLine:"#D2E3E9",bodyInk:"#44565E",headFont:"helvetica",useAgentColors:!1}],Xqn="signature";function Qqn(s){return AKe.find(t=>t.id===s)||AKe[0]}const Fc=792,ep=612,ca=52;function e$(s){const t=(s||"").replace("#","").padEnd(6,"0");return[parseInt(t.slice(0,2),16)||0,parseInt(t.slice(2,4),16)||0,parseInt(t.slice(4,6),16)||0]}function Uf(s,t,n){return[Math.round(s[0]+(t[0]-s[0])*n),Math.round(s[1]+(t[1]-s[1])*n),Math.round(s[2]+(t[2]-s[2])*n)]}const qC=[22,24,28],kb=[124,128,136],Do=[255,255,255];function Jqn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const cBe="https://relzejiswnotikjgvjhz.supabase.co";function eVn(s){if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;try{const t=new URL(s,window.location.origin);return t.origin===window.location.origin||t.origin===new URL(cBe).origin?s:`${cBe}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function AZ(s,t=2e3){if(!s)return null;try{const n=await fetch(eVn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((g,v)=>{const y=new Image;y.crossOrigin="anonymous",y.onload=()=>g(y),y.onerror=v,y.src=a}),l=Math.min(1,t/i.naturalWidth),o=Math.max(1,Math.round(i.naturalWidth*l)),c=Math.max(1,Math.round(i.naturalHeight*l)),d=document.createElement("canvas");d.width=o,d.height=c,d.getContext("2d").drawImage(i,0,0,o,c),URL.revokeObjectURL(a);const h=r.type.includes("png"),m=h?"PNG":"JPEG",p=d.toDataURL(h?"image/png":"image/jpeg",.92);return{el:await new Promise(g=>{const v=new Image;v.onload=()=>g(v),v.onerror=()=>g(v),v.src=p}),dataUrl:p,w:o,h:c,format:m}}catch{return null}}let ies={x:.5,y:.5};function tVn(s){ies={x:Math.min(1,Math.max(0,(s==null?void 0:s.x)??.5)),y:Math.min(1,Math.max(0,(s==null?void 0:s.y)??.5))}}function nie(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,p=a/i;let f=0,g=0,v=t.w,y=t.h;const b=l.focal??ies;if(m>p?(v=t.h*p,f=Math.min(Math.max(0,t.w*b.x-v/2),t.w-v)):(y=t.w/p,g=Math.min(Math.max(0,t.h*b.y-y/2),t.h-y)),l.radius&&l.radius>0){const C=Math.min(l.radius*o,c/2,d/2);h.beginPath(),h.moveTo(C,0),h.arcTo(c,0,c,d,C),h.arcTo(c,d,0,d,C),h.arcTo(0,d,0,0,C),h.arcTo(0,0,c,0,C),h.closePath(),h.clip()}const w=[];l.grayscale&&w.push("grayscale(1)"),l.blur&&w.push(`blur(${l.blur*o}px)`),w.length&&(h.filter=w.join(" "));try{h.drawImage(t.el,f,g,v,y,0,0,c,d)}catch{h.fillStyle="#e9e6e0",h.fillRect(0,0,c,d)}if(h.filter="none",l.tint&&l.tint.amount>0){const[C,E,P]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${C},${E},${P},${Math.min(1,l.tint.amount)})`,h.fillRect(0,0,c,d),h.globalCompositeOperation="source-over"}if(l.darken&&l.darken>0&&(h.fillStyle=`rgba(0,0,0,${Math.min(.9,l.darken)})`,h.fillRect(0,0,c,d)),l.gradient==="bottom"){const C=h.createLinearGradient(0,0,0,d);C.addColorStop(0,"rgba(0,0,0,0)"),C.addColorStop(.45,"rgba(0,0,0,0.05)"),C.addColorStop(1,"rgba(0,0,0,0.8)"),h.fillStyle=C,h.fillRect(0,0,c,d)}else if(l.gradient==="full"){const C=h.createLinearGradient(0,0,0,d);C.addColorStop(0,"rgba(0,0,0,0.4)"),C.addColorStop(.5,"rgba(0,0,0,0.18)"),C.addColorStop(1,"rgba(0,0,0,0.85)"),h.fillStyle=C,h.fillRect(0,0,c,d)}else if(l.gradient==="left"){const C=h.createLinearGradient(0,0,c,0);C.addColorStop(0,"rgba(0,0,0,0.75)"),C.addColorStop(.6,"rgba(0,0,0,0.15)"),C.addColorStop(1,"rgba(0,0,0,0)"),h.fillStyle=C,h.fillRect(0,0,c,d)}const S=u.toDataURL("image/jpeg",.92);s.addImage(S,"JPEG",n,r,a,i,void 0,"FAST")}function V7(s,t,n,r,a,i=3){const l=a*2,o=Math.max(1,Math.round(l*i)),c=document.createElement("canvas");c.width=o,c.height=o;const d=c.getContext("2d");d.fillStyle="#ffffff",d.fillRect(0,0,o,o),d.save(),d.beginPath(),d.arc(o/2,o/2,o/2,0,Math.PI*2),d.closePath(),d.clip();const u=t.w/t.h;let h=0,m=0,p=t.w,f=t.h;u>1?(p=t.h,h=(t.w-p)/2):(f=t.w,m=(t.h-f)/2);try{d.drawImage(t.el,h,m,p,f,0,0,o,o)}catch{}d.restore(),s.addImage(c.toDataURL("image/jpeg",.92),"JPEG",n-a,r-a,l,l,void 0,"FAST")}function uat(s,t,n,r,a,i,l="left"){const o=t.w/t.h;let c=i,d=c*o;d>a&&(d=a,c=d/o);const u=l==="right"?n-d:n;return s.addImage(t.dataUrl,t.format,u,r,d,c,void 0,"FAST"),{w:d,h:c}}function v_(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function sVn(s,t,n,r,a,i={font:"helvetica",size:10,color:qC}){s.setFont(i.font,i.style||"normal"),s.setFontSize(i.size),s.setTextColor(...i.color);const l=i.leading??i.size*1.5,o=s.splitTextToSize(t,a);return o.forEach((c,d)=>{s.text(c,n,r+d*l,i.align==="center"?{align:"center"}:void 0)}),r+o.length*l}function pK(s,t,n,r,a,i){let l=r;const o=i.size*1.45;return t.forEach(c=>{s.setFillColor(...i.accent),s.circle(n+2.4,l-i.size*.32,2,"F"),l=sVn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function w1(s,t,n,r,a,i,l,o="F",c,d=.6){s.setFillColor(...l),c&&(s.setDrawColor(...c),s.setLineWidth(d)),s.roundedRect(t,n,r,a,i,i,o)}const bz='',_z='',nVn={title:"Facebook",slug:"facebook",get svg(){return bz+"Facebook"+_z+this.path+wz},path:"M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z",source:"https://about.meta.com/brand/resources/facebook/logo",hex:"0866FF",guidelines:"https://about.meta.com/brand/resources/facebook/logo"},rVn={title:"Instagram",slug:"instagram",get svg(){return bz+"Instagram"+_z+this.path+wz},path:"M7.0301.084c-1.2768.0602-2.1487.264-2.911.5634-.7888.3075-1.4575.72-2.1228 1.3877-.6652.6677-1.075 1.3368-1.3802 2.127-.2954.7638-.4956 1.6365-.552 2.914-.0564 1.2775-.0689 1.6882-.0626 4.947.0062 3.2586.0206 3.6671.0825 4.9473.061 1.2765.264 2.1482.5635 2.9107.308.7889.72 1.4573 1.388 2.1228.6679.6655 1.3365 1.0743 2.1285 1.38.7632.295 1.6361.4961 2.9134.552 1.2773.056 1.6884.069 4.9462.0627 3.2578-.0062 3.668-.0207 4.9478-.0814 1.28-.0607 2.147-.2652 2.9098-.5633.7889-.3086 1.4578-.72 2.1228-1.3881.665-.6682 1.0745-1.3378 1.3795-2.1284.2957-.7632.4966-1.636.552-2.9124.056-1.2809.0692-1.6898.063-4.948-.0063-3.2583-.021-3.6668-.0817-4.9465-.0607-1.2797-.264-2.1487-.5633-2.9117-.3084-.7889-.72-1.4568-1.3876-2.1228C21.2982 1.33 20.628.9208 19.8378.6165 19.074.321 18.2017.1197 16.9244.0645 15.6471.0093 15.236-.005 11.977.0014 8.718.0076 8.31.0215 7.0301.0839m.1402 21.6932c-1.17-.0509-1.8053-.2453-2.2287-.408-.5606-.216-.96-.4771-1.3819-.895-.422-.4178-.6811-.8186-.9-1.378-.1644-.4234-.3624-1.058-.4171-2.228-.0595-1.2645-.072-1.6442-.079-4.848-.007-3.2037.0053-3.583.0607-4.848.05-1.169.2456-1.805.408-2.2282.216-.5613.4762-.96.895-1.3816.4188-.4217.8184-.6814 1.3783-.9003.423-.1651 1.0575-.3614 2.227-.4171 1.2655-.06 1.6447-.072 4.848-.079 3.2033-.007 3.5835.005 4.8495.0608 1.169.0508 1.8053.2445 2.228.408.5608.216.96.4754 1.3816.895.4217.4194.6816.8176.9005 1.3787.1653.4217.3617 1.056.4169 2.2263.0602 1.2655.0739 1.645.0796 4.848.0058 3.203-.0055 3.5834-.061 4.848-.051 1.17-.245 1.8055-.408 2.2294-.216.5604-.4763.96-.8954 1.3814-.419.4215-.8181.6811-1.3783.9-.4224.1649-1.0577.3617-2.2262.4174-1.2656.0595-1.6448.072-4.8493.079-3.2045.007-3.5825-.006-4.848-.0608M16.953 5.5864A1.44 1.44 0 1 0 18.39 4.144a1.44 1.44 0 0 0-1.437 1.4424M5.8385 12.012c.0067 3.4032 2.7706 6.1557 6.173 6.1493 3.4026-.0065 6.157-2.7701 6.1506-6.1733-.0065-3.4032-2.771-6.1565-6.174-6.1498-3.403.0067-6.156 2.771-6.1496 6.1738M8 12.0077a4 4 0 1 1 4.008 3.9921A3.9996 3.9996 0 0 1 8 12.0077",source:"https://about.meta.com/brand/resources/instagram",hex:"FF0069",guidelines:"https://about.meta.com/brand/resources/instagram"},aVn={title:"Pinterest",slug:"pinterest",get svg(){return bz+"Pinterest"+_z+this.path+wz},path:"M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z",source:"https://business.pinterest.com/en/brand-guidelines",hex:"BD081C",guidelines:"https://business.pinterest.com/en/brand-guidelines"},iVn={title:"TikTok",slug:"tiktok",get svg(){return bz+"TikTok"+_z+this.path+wz},path:"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",source:"https://tiktok.com",hex:"000000"},oVn={title:"trulia",slug:"trulia",get svg(){return bz+"trulia"+_z+this.path+wz},path:"M17.6958 8.9368a.6678.6678 0 0 0 .095 1.329.6678.6678 0 0 0 .6678-.668.6678.6678 0 0 0-.7628-.661zm-4.3956.2812v1.121h.7513v3.4726h-.7513v1.121h2.6262v-1.121h-.7513V9.218Zm-12.549.121v1.3814H.0001v1.1281h.7513v1.0852c0 1.1799.9502 2.1362 2.1226 2.1362a2.1126 2.1126 0 0 0 .4608-.0507v-1.115a1.1025 1.1025 0 0 1-.3837.0685c-.5958 0-1.0789-.4689-1.0789-1.047v-1.0772H3.335v-1.1281H1.872V9.339Zm20.92 1.2609c-1.1147-.005-2.0196.9806-2.019 2.1905.0005 1.21.9043 2.1952 2.019 2.1905.0292 0 .0598-.0009.0877-.002.4221-.0111.8757-.2098 1.113-.488v.4218H24v-4.2458h-1.1275l-.0005.4236c-.2385-.2791-.692-.477-1.113-.4879-.0292-.002-.0585-.002-.0878-.002zm-14.8245.0473c-.5173.003-.9275.153-1.2964.654l-.2277-.64h-1.098v1.1271h.5195v3.1444h1.118v-2.1983a.9887.9887 0 0 1 .9851-.9906h.339v-1.0966Zm9.6549.047v1.1172h.7513v3.121h1.8736v-1.117h-.7514l.001-3.1212zm-8.2605.0298v2.2125c0 1.1773.9494 2.1315 2.1195 2.1315s2.1193-.9525 2.1193-2.1298v-2.214h-1.1186v2.2539a1.0018 1.0018 0 1 1-2.001 0v-2.254zm13.5857.9717c.5932 0 1.074.5008 1.0746 1.1191.0005.6184-.4814 1.1192-1.0746 1.1192-.5933 0-1.0742-.5008-1.075-1.1192-.0008-.6183.4817-1.1191 1.075-1.1191z",source:"https://www.trulia.com/newsroom/media/brand-logos",hex:"0A0B09",guidelines:"https://www.trulia.com/newsroom/media/brand-logos"},lVn={title:"YouTube",slug:"youtube",get svg(){return bz+"YouTube"+_z+this.path+wz},path:"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z",source:"https://www.youtube.com/howyoutubeworks/resources/brand-resources/#logos-icons-and-colors",hex:"FF0000",guidelines:"https://www.youtube.com/howyoutubeworks/resources/brand-resources/#logos-icons-and-colors"},cVn={title:"Zillow",slug:"zillow",get svg(){return bz+"Zillow"+_z+this.path+wz},path:"M12.006 0L1.086 8.627v3.868c3.386-2.013 11.219-5.13 14.763-6.015.11-.024.16.005.227.078.372.427 1.586 1.899 1.916 2.301a.128.128 0 0 1-.03.195 43.607 43.607 0 0 0-6.67 6.527c-.03.037-.006.043.012.03 2.642-1.134 8.828-2.94 11.622-3.452V8.627zm-.48 11.177c-2.136.708-8.195 3.307-10.452 4.576V24h21.852v-7.936c-2.99.506-11.902 3.16-15.959 5.246a.183.183 0 0 1-.23-.036l-2.044-2.429c-.055-.061-.062-.098.011-.208 1.574-2.3 4.789-5.899 6.833-7.418.042-.03.031-.06-.012-.042Z",source:"https://www.zillow.com",hex:"006AFF"},dVn={facebook:nVn,instagram:rVn,youtube:lVn,tiktok:iVn,pinterest:aVn,zillow:cVn,trulia:oVn},MSt=new Map;function uVn(s,t,n){return`${s}|${t}|${n}`}function hVn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=dVn[r];if(!a)return null;const i=uVn(r,t,n),l=MSt.get(i);if(l)return l;try{const o=document.createElement("canvas");o.width=n,o.height=n;const c=o.getContext("2d");if(!c)return null;c.clearRect(0,0,n,n),c.scale(n/24,n/24),c.fillStyle=t,c.fill(new Path2D(a.path));const d=o.toDataURL("image/png");return MSt.set(i,d),d}catch{return null}}const nu="helvetica";let OG="helvetica";function oes(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=hVn(t,l,160);if(o){s.addImage(o,"PNG",r-i/2,a-i/2,i,i,void 0,"FAST");return}const c=i/2;s.setFillColor(...n),s.circle(r,a,c,"F"),s.setFont(nu,"bold"),s.setFontSize(c*1.15),s.setTextColor(...Do),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let rie=[252,251,248],M9=[244,247,250],H_=[223,228,234],Lv=[72,78,88];function aie(s,t){return GQt(s.data.pages,t)}function hat(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function les(s){const t=s.property,n=[t.city,[t.state,t.postalCode].filter(Boolean).join(" ")].filter(Boolean).join(", ");return{line1:t.addressLine1||"Your Home",line2:n}}function mVn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function lg(s,t,n,r,a,i,l){const o=l.font||nu,c=l.style||"normal";let d=i;s.setFont(o,c),s.setFontSize(d);const u=l.charSpace??0,h=()=>s.getTextWidth(t)+u*Math.max(0,t.length-1);for(;h()>a&&d>(l.min??6);)d-=.5,s.setFontSize(d);return s.setTextColor(...l.color),s.text(t,n,r,{align:l.align,charSpace:u}),d}function ch(s,t,n,r,a,i){s.setFont(nu,i.style||"normal"),s.setFontSize(i.size),s.setTextColor(...i.color);const l=i.leading??i.size*1.45;let o=s.splitTextToSize(t,a);if(i.maxLines&&o.length>i.maxLines){o=o.slice(0,i.maxLines);const c=o[o.length-1];o[o.length-1]=c.replace(/[\s,;.:]+$/,"")+"…"}return o.forEach((c,d)=>s.text(c,n,r+d*l,i.align==="center"?{align:"center"}:void 0)),r+(o.length-1)*l}function fK(s,t,n,r,a,i){const{doc:l}=s;l.setFont(nu,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function I0(s,t=rie){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,Fc,ep,"F")}function Iv(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??Fc-ca*2-60;fK(s,t,ca,62,s.accent),i.setFont(OG,"bold"),i.setFontSize(OG==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?Do:s.brand),c.forEach((u,h)=>i.text(u,ca,96+h*29));let d=96+(c.length-1)*29;return r&&(d=ch(i,r,ca,d+26,Math.min(o+40,Fc-ca*2),{size:10,color:l?Uf(Do,s.deep,.28):kb,leading:15,maxLines:2})),d+34}function D0(s,t=!1){const{doc:n,data:r}=s,a=t?Uf(Do,s.deep,.7):H_;n.setDrawColor(...a),n.setLineWidth(.6),n.line(ca,ep-46,Fc-ca,ep-46);const i=ep-30;n.setFont(nu,"bold"),n.setFontSize(7),n.setTextColor(...t?Do:s.brand),t&&v_(n,.9),n.text((r.agent.name||"").toUpperCase(),ca,i,{charSpace:1.4});const l=mVn(r);l&&(n.setFont(nu,"normal"),n.setFontSize(7),n.setTextColor(...t?Do:kb),lg(n,l,Fc/2,i,Fc/2-ca-40,7,{color:t?Do:kb,align:"center"})),n.setFont(nu,"normal"),n.setFontSize(7),n.setTextColor(...t?Do:kb),n.text(String(s.pageNo).padStart(2,"0"),Fc-ca,i,{align:"right"}),t&&v_(n,1)}function ces(s,t,n,r,a){const{doc:i}=s;i.setFont(nu,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return w1(i,n,r,a,o,6,Uf(s.accent,Do,.86)),i.setTextColor(...Uf(s.brand,qC,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function mat(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?nie(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):w1(l,t,n,r,a,10,Uf(s.deep,Do,.12))}function pVn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=les(n),i=336;s.hero?nie(t,s.hero,0,0,Fc,ep,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,Fc,ep,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,ep,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,ep,"F");const l=aie(s,"cover");fK(s,l.kicker,ca,66),t.setFont(OG,"bold"),t.setFontSize(OG==="times"?29:26),t.setTextColor(...Do);const o=t.splitTextToSize(r,i-ca*2).slice(0,3);o.forEach((v,y)=>t.text(v,ca,102+y*30));let c=102+(o.length-1)*30;a&&(t.setFont(nu,"normal"),t.setFontSize(9),v_(t,.9),lg(t,a.toUpperCase(),ca,c+22,i-ca*2,9,{color:Do,charSpace:1.4}),v_(t,1),c+=22),c=ch(t,l.body,ca,c+34,i-ca*2,{size:10,color:Uf(Do,s.deep,.22),leading:16});const d=[Jqn(n.property.listPrice),n.property.beds?`${n.property.beds} BD`:null,n.property.baths?`${n.property.baths} BA`:null,n.property.sqft?`${Number(n.property.sqft).toLocaleString()} SF`:null].filter(Boolean);d.length&&(t.setDrawColor(...s.accent),t.setLineWidth(1.5),t.line(ca,c+30,ca+40,c+30),lg(t,d.join(" · "),ca,c+54,i-ca*2,10,{style:"bold",color:Do,charSpace:1}));const u=hat(n),h=ep-(u?152:128);let m=ca;s.headshot&&(V7(t,s.headshot,ca+22,h+18,22),u&&s.coHeadshot?(V7(t,s.coHeadshot,ca+56,h+18,22),m=ca+90):m=ca+56),lg(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:Do}),t.setFont(nu,"normal"),t.setFontSize(8),v_(t,.85);const p=[n.agent.brokerageName].filter(Boolean).join("");p&&lg(t,p,m,h+26,i-m-24,8,{color:Do});const f=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(f&&lg(t,f,m,h+38,i-m-24,8,{color:Do}),u){const v=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");v&&lg(t,v,ca,h+56,i-ca-24,8,{color:Do})}v_(t,1),s.logo&&(v_(t,.95),uat(t,s.logo,ca,ep-74,132,30,"left"),v_(t,1));const g=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(nu,"bold"),t.setFontSize(7.5),t.setTextColor(...Do),v_(t,.9),t.text(g,Fc-ca,ep-34,{align:"right",charSpace:1.6}),v_(t,1)}function fVn(s){I0(s);const{doc:t}=s,n=aie(s,"welcome"),r=Iv(s,n.kicker,n.headline,n.subhead||null),a=[["Make it look irresistible","Professional visuals help buyers stop, click, and imagine themselves at home."],["Put it everywhere buyers search","MLS distribution, property portals, mobile search, and a dedicated online showcase."],["Create demand beyond the portals","Social campaigns, email, database outreach, and local promotion keep momentum moving."]];let i=r+10;a.forEach(([l,o],c)=>{t.setFillColor(...Uf(s.accent,Do,.85)),t.circle(ca+13,i-3,13,"F"),t.setFont(nu,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),ca+13,i,{align:"center"});const d=ca+44,u=Fc-d-ca-40;t.setFont(nu,"bold"),t.setFontSize(11.5),t.setTextColor(...qC),t.text(l,d,i),ch(t,o,d,i+18,u,{size:9.5,color:Lv,leading:14,maxLines:2}),i+=88}),D0(s)}function xVn(s){I0(s,Do);const{doc:t,data:n}=s,r=aie(s,"agent"),a=Iv(s,r.kicker,r.headline,r.subhead||n.agent.tagline||"You are not hiring a website or a billboard — you are hiring a person."),i=hat(n),l=Fc-ca-260,o=a-6,c=262;if(i){const f=(g,v,y,b)=>{w1(t,l,g,260,124,10,M9,"FD",H_),t.setFillColor(...s.accent),t.rect(l,g,260,3,"F");let w=l+18;y&&(V7(t,y,l+48,g+62+2,30),w=l+90);const S=260-(w-l)-18;lg(t,v,w,g+40,S,13,{style:"bold",color:s.brand});let C=g+56;b.filter(Boolean).slice(0,4).forEach(E=>{lg(t,String(E),w,C,S,8,{color:kb}),C+=13})};f(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),f(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{w1(t,l,o,260,c,10,M9,"FD",H_),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&V7(t,s.headshot,l+130,o+72,42),lg(t,n.agent.name,l+130,o+(s.headshot?138:70),216,16,{style:"bold",color:s.brand,align:"center"});let m=o+(s.headshot?158:92);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website].filter(Boolean).slice(0,4).forEach(p=>{lg(t,String(p),l+130,m,220,8.5,{color:kb,align:"center"}),m+=14}),s.logo&&uat(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-ca-44;let u=ch(t,i?i.bio||"You are working with both of us. Here is how to reach us, and the professional details behind the marketing plan in this presentation — every step that follows is something we run personally on your home.":"Here is how to reach me, and the professional details behind the marketing plan in this presentation. Every step that follows is something I run personally on your home.",ca,a+4,d,{size:10,color:Lv,leading:16,maxLines:5});u+=34,[["Phone",n.agent.phone],["Email",n.agent.email],["Website",n.agent.website],["Brokerage",n.agent.brokerageName],["License",n.agent.licenseNumber?`${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null],i?["Co-listing",[i.name,i.licenseNumber].filter(Boolean).join(" · ")]:["",null]].filter(([m,p])=>!!m&&!!p).forEach(([m,p])=>{t.setFont(nu,"bold"),t.setFontSize(7),t.setTextColor(...kb),t.text(m.toUpperCase(),ca,u,{charSpace:1.4}),lg(t,p,ca+86,u,d-86,10.5,{color:qC}),t.setDrawColor(...H_),t.setLineWidth(.5),t.line(ca,u+11,ca+d,u+11),u+=36}),D0(s)}function gVn(s,t){I0(s);const{doc:n}=s,r=aie(s,"overview"),a=Iv(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(Fc-ca*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=ca+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);w1(n,h,m,o,c,8,Do,"FD",H_),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(nu,"bold"),n.setFontSize(15),n.setTextColor(...Uf(s.brand,Do,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),ch(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:qC,leading:13,maxLines:3})}),D0(s)}function GL(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??Gzn[s.key]??[]).slice(0,t)}function PSt(s,t,n){I0(s,n.dark?s.deep:rie);const{doc:r}=s,a=Iv(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?Fc-ca-i:ca,d=o?ca:ca+i+40,u=Fc-ca*2-i-40;mat(s,c,a,i,l,{tint:n.dark?.1:0}),fK(s,t.title,d,a+12);let h=ch(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Uf(Do,s.deep,.2):Lv,leading:15,maxLines:4});const m=GL(t,5);if(m.length&&(h=pK(r,m,d,h+28,u,{font:nu,size:9.5,color:n.dark?Do:qC,accent:s.accent,gap:7})),n.note&&!n.dark){const p=Math.min(h+14,ep-120);ces(s,n.note,d,p,u)}else n.note&&(r.setFont(nu,"bold"),r.setFontSize(9.5),r.setTextColor(...Do),v_(r,.9),ch(r,n.note,ca,ep-78,Fc-ca*2,{size:9.5,style:"bold",color:Do,leading:13,maxLines:1}),v_(r,1));D0(s,n.dark)}function yVn(s,t){I0(s);const{doc:n}=s,r=Iv(s,"Launch day","The MLS is the starting point — not the entire plan.","We prepare the details, media, and messaging before the listing goes live."),a=GL(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(Fc-ca*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=ca+h*(c+o);w1(n,m,r,c,d,8,Do,"FD",H_),n.setFont(nu,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(nu,"bold"),n.setFontSize(7.5),n.setTextColor(...kb),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),ch(n,u,m+16,r+76,c-32,{size:9,color:Lv,leading:13,maxLines:5})}),ch(n,t.body,ca,r+d+34,Fc-ca*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),D0(s)}function vVn(s,t){I0(s);const{doc:n}=s,r=Iv(s,"Maximum visibility","Your listing goes where buyers already search.","MLS syndication helps distribute your property across major real estate destinations."),a=[["Zillow",[0,106,255]],["Realtor.com",[214,40,40]],["Homes.com",[58,61,178]],["Redfin",[200,32,46]],["Trulia",[0,128,116]],["Movoto",[40,44,60]]],i=3,l=16,o=(Fc-ca*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const p=ca+m%i*(o+l),f=r+Math.floor(m/i)*(c+l);w1(n,p,f,o,c,8,Do,"FD",H_),oes(n,u,h,p+28,f+c/2,20),lg(n,u,p+48,f+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;ch(n,t.body,ca,d,Fc-ca*2-140,{size:9.5,color:Lv,leading:14,maxLines:3}),n.setFont(nu,"normal"),n.setFontSize(7.5),n.setTextColor(...kb),n.text("Distribution varies by MLS, market, and portal policies.",ca,ep-62),D0(s)}function bVn(s,t){I0(s,M9);const{doc:n,data:r}=s,{line1:a}=les(r),i=Iv(s,"A home of its own","Your property gets a dedicated online showcase.","One clean destination makes the listing easy to explore, save, and share."),l=404,o=274;w1(n,ca,i,l,o,10,Do,"FD",H_),w1(n,ca,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(ca,i+12,l,10,"F"),n.setFont(nu,"bold"),n.setFontSize(7),n.setTextColor(...Do);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();lg(n,c,ca+14,i+15,l-28,7,{style:"bold",color:Do,charSpace:1}),mat(s,ca+14,i+36,186,142);const d=ca+214,u=l-228;lg(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),ch(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),ch(n,"Photo gallery, property highlights, video tour, showing inquiry, and easy social sharing — all in one place.",d,i+92,u,{size:8.5,color:Lv,leading:12,maxLines:5}),ces(s,"Shareable. Trackable. Memorable.",ca+14,i+o-46,l-28);const h=ca+l+40,m=Fc-h-ca;fK(s,t.title,h,i+12);let p=ch(n,t.body,h,i+32,m,{size:9.5,color:Lv,leading:15,maxLines:5});const f=GL(t,5);f.length&&pK(n,f,h,p+26,m,{font:nu,size:9,color:qC,accent:s.accent,gap:7}),D0(s)}function _Vn(s,t){I0(s,s.deep);const{doc:n}=s,r=Iv(s,"Beyond the search portals","We turn your listing into social content people want to stop and watch.","Creative is tailored for the platforms — not copied and pasted everywhere.",{dark:!0}),a=[["Facebook",[24,119,242]],["Instagram",[214,41,118]],["YouTube",[255,0,0]],["TikTok",[16,16,16]],["Pinterest",[230,0,35]]],i=72,l=16;a.forEach(([d,u],h)=>{const m=ca+h*(i+l);w1(n,m,r,i,i,12,Do),oes(n,d,u,m+i/2,r+i/2-4,30),n.setFont(nu,"bold"),n.setFontSize(6.5),n.setTextColor(...kb),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=ca+5*(i+l)+14,c=Fc-o-ca;fK(s,"The campaign can include",o,r+12),pK(n,GL(t,5),o,r+32,c,{font:nu,size:9,color:Do,accent:s.accent,gap:7}),ch(n,t.body,ca,r+i+44,420,{size:9.5,color:Uf(Do,s.deep,.2),leading:15,maxLines:4}),ch(n,"Every post sends attention back to the property.",ca,ep-84,460,{size:11,style:"bold",color:Do,leading:14,maxLines:1}),D0(s,!0)}function wVn(s,t){I0(s);const{doc:n}=s,r=Iv(s,"Reach buyers directly","Great marketing does not wait for someone to stumble across the listing.","We activate local relationships and existing audiences to create more opportunities."),a=GL(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{w1(n,ca,l-14,34,34,8,Uf(s.accent,Do,.85)),n.setFont(nu,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),ca+17,l+7,{align:"center"});const d=ca+52,u=Fc-d-ca-20;n.setFont(nu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),ch(n,o,d,l+14,u,{size:9.5,color:Lv,leading:14,maxLines:2}),l+=76}),ch(n,t.body,ca,Math.min(l+8,ep-92),Fc-ca*2-120,{size:9.5,color:kb,leading:14,maxLines:2}),D0(s)}function jVn(s,t){I0(s);const{doc:n}=s,r=Iv(s,"Real-world marketing still matters","Digital reach gets attention. Local presence turns attention into action.","Each tactic is selected for the property, timing, neighborhood, and likely buyer."),a=GL(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(Fc-ca*2-o)/l,d=112;a.forEach((u,h)=>{const m=ca+h%l*(c+o),p=r+Math.floor(h/l)*(d+o);w1(n,m,p,c,d,8,M9,"FD",H_),n.setFont(nu,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,p+24,{charSpace:1.2}),ch(n,u,m+16,p+46,c-32,{size:9.5,color:Lv,leading:14,maxLines:3})}),D0(s)}function NVn(s,t){I0(s,M9);const{doc:n}=s,r=Iv(s,"You will always know what is happening","A strong launch needs clear communication and thoughtful adjustments.","You receive useful feedback — not a pile of disconnected activity."),a=GL(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(nu,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),ca,l),n.setFont(nu,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),ca+48,l,{charSpace:1.2}),ch(n,o,ca+250,l-1,Fc-ca-250-ca,{size:9.5,color:Lv,leading:13,maxLines:2}),n.setDrawColor(...H_),n.setLineWidth(.5),n.line(ca,l+22,Fc-ca,l+22),l+=62}),ch(n,"Marketing creates opportunity. Communication helps us act on it.",ca,Math.min(l+18,ep-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),D0(s)}function kVn(s){I0(s,s.deep);const{doc:t,data:n}=s;s.hero&&nie(t,s.hero,0,0,Fc,ep,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=aie(s,"closing"),a=Iv(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=ch(t,r.body,ca,a,i,{size:10.5,color:Uf(Do,s.deep,.18),leading:17});l+=30,pK(t,["Regular written updates for as long as your home is on the market","Showing and online traffic feedback shared as it arrives","Honest pricing conversations backed by current data","Every offer reviewed with you line by line"],ca,l,i,{font:nu,size:9.5,color:Do,accent:s.accent,gap:8});const o=hat(n),c=250,d=Fc-ca-c,u=a-20,h=o?300:258;w1(t,d,u,c,h,10,Do),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(V7(t,s.headshot,d+c/2-34,u+70,32),V7(t,s.coHeadshot,d+c/2+34,u+70,32)):V7(t,s.headshot,d+c/2,u+70,38)),lg(t,o?`${n.agent.name} + ${o.name}`:n.agent.name,d+c/2,u+(s.headshot?132:68),c-30,16,{style:"bold",color:s.brand,align:"center"});let m=u+(s.headshot?152:90);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website,n.agent.licenseNumber?`License ${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null].filter(Boolean).slice(0,5).forEach(p=>{lg(t,String(p),d+c/2,m,c-30,8.5,{color:kb,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...H_),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),lg(t,o.name,d+c/2,m+8,c-30,10,{style:"bold",color:s.brand,align:"center"}),m+=22,[o.title||"Co-listing agent",o.phone,o.email].filter(Boolean).slice(0,3).forEach(p=>{lg(t,String(p),d+c/2,m,c-30,8.5,{color:kb,align:"center"}),m+=13})):s.logo&&uat(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(nu,"bold"),t.setFontSize(9),t.setTextColor(...Do),v_(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",ca,ep-72,{charSpace:1.4}),v_(t,1),D0(s,!0)}function pat(s,t){return s.customImages[t.id]||null}function des(s,t,n,r,a,i){const l=pat(s,t);l?nie(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):mat(s,n,r,a,i)}function SVn(s,t){I0(s,t.dark?s.deep:rie);const{doc:n}=s,r=Iv(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?Fc-ca-a:ca,o=i?ca:ca+a+40,c=Fc-ca*2-a-40;des(s,t,l,r,a,268);const d=(t.body||"").split(/\n{2,}/).filter(Boolean);let u=r+6;d.slice(0,3).forEach(h=>{u=ch(n,h,o,u,c,{size:10,color:t.dark?Uf(Do,s.deep,.2):Lv,leading:16,maxLines:7}),u+=26}),t.bullets.length&&pK(n,t.bullets.slice(0,5),o,Math.min(u,ep-150),c,{font:nu,size:9.5,color:t.dark?Do:qC,accent:s.accent,gap:7}),D0(s,t.dark)}function CVn(s,t){I0(s,t.dark?s.deep:M9);const{doc:n}=s,r=Iv(s,t.kicker||"What others are saying",t.headline,t.subhead||null,{dark:t.dark}),a=t.testimonials.filter(m=>{var p;return(p=m.quote)==null?void 0:p.trim()}).slice(0,6),i=a.length<=2?a.length||1:a.length>4?3:2,l=18,o=(Fc-ca*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=ep-72-r,u=c>1?Math.min(150,(d-l*(c-1))/c):Math.min(200,d),h=c>1?i===3?4:3:7;a.forEach((m,p)=>{const f=ca+p%i*(o+l),g=r+Math.floor(p/i)*(u+l);w1(n,f,g,o,u,10,t.dark?Uf(s.deep,Do,.08):Do,"FD",H_),n.setFillColor(...s.accent),n.rect(f,g,3,u,"F"),n.setFont(OG,"bold"),n.setFontSize(30),n.setTextColor(...Uf(s.accent,t.dark?s.deep:Do,.4)),n.text("“",f+18,g+40),ch(n,m.quote,f+18,g+56,o-40,{size:9.5,color:t.dark?Uf(Do,s.deep,.2):Lv,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(f+18,g+u-32,f+42,g+u-32),n.setFont(nu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const v=[m.name,m.detail].filter(Boolean).join(" · ");v&&lg(n,v.toUpperCase(),f+18,g+u-16,o-36,8,{style:"bold",color:t.dark?Do:s.brand,charSpace:1.1})}),t.body&&ch(n,t.body,ca,Math.min(r+c*(u+l)+14,ep-88),Fc-ca*2-120,{size:9.5,color:t.dark?Uf(Do,s.deep,.2):kb,leading:14,maxLines:2}),D0(s,t.dark)}function AVn(s,t){I0(s,t.dark?s.deep:rie);const{doc:n}=s,r=Iv(s,t.kicker||"Track record",t.headline,t.subhead||null,{dark:t.dark}),a=t.stats.filter(i=>{var l,o;return((l=i.value)==null?void 0:l.trim())||((o=i.label)==null?void 0:o.trim())}).slice(0,4);if(a.length){const l=(Fc-ca*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=ca+d*(l+18);w1(n,u,r,l,o,10,t.dark?Uf(s.deep,Do,.1):Do,"FD",H_),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),lg(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?Do:s.brand,align:"center"}),ch(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Uf(Do,s.deep,.3):kb,leading:12,maxLines:2,align:"center"})}),t.body&&ch(n,t.body,ca,r+o+40,Fc-ca*2-140,{size:10,color:t.dark?Uf(Do,s.deep,.2):Lv,leading:15,maxLines:3})}else t.body&&ch(n,t.body,ca,r,Fc-ca*2-140,{size:10.5,color:t.dark?Do:Lv,leading:16});D0(s,t.dark)}function EVn(s,t){I0(s,t.dark?s.deep:Do);const{doc:n}=s,r=Iv(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!pat(s,t)||!!s.hero,l=i?Fc-ca*2-280:Fc-ca*2-140;let o=r;t.body&&(o=ch(n,t.body,ca,o,l,{size:10,color:t.dark?Uf(Do,s.deep,.2):Lv,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{w1(n,ca,o-9,14,14,4,s.accent),n.setFont(nu,"bold"),n.setFontSize(8),n.setTextColor(...Do),n.text("✓",ca+7,o+1,{align:"center"}),o=ch(n,d,ca+26,o,l-26,{size:10,color:t.dark?Do:qC,leading:14,maxLines:2})+22}),i&&des(s,t,Fc-ca-240,r,240,250),D0(s,t.dark)}function TVn(s,t){I0(s,s.deep);const{doc:n}=s,r=pat(s,t)||s.hero;r&&nie(n,r,0,0,Fc,ep,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),fK(s,t.kicker||"Our approach",ca,ep/2-84),n.setFont(nu,"bold"),n.setFontSize(30),n.setTextColor(...Do);const a=n.splitTextToSize(t.headline||"",Fc-ca*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,ca,ep/2-44+l*38)),t.body&&ch(n,t.body,ca,ep/2+a.length*38-24,480,{size:10.5,color:Uf(Do,s.deep,.2),leading:16,maxLines:4}),D0(s,!0)}function LSt(s,t){switch(t.layout){case"testimonials":return CVn(s,t);case"stats":return AVn(s,t);case"checklist":return EVn(s,t);case"statement":return TVn(s,t);case"story":default:return SVn(s,t)}}async function MVn(s,t,n){var P,M,I,D;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=Qqn((P=t.pages)==null?void 0:P.theme);rie=e$(i.paper),M9=e$(i.paperCool),H_=e$(i.softLine),Lv=e$(i.bodyInk),OG=i.headFont;const l=e$((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=e$((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Uf(l,[0,0,0],i.id==="luxury"?.35:.2),d=(M=t.coAgent)!=null&&M.enabled&&((I=t.coAgent.name)!=null&&I.trim())?t.coAgent:null,u=(t.customPages||[]).filter(F=>F.enabled).sort((F,q)=>F.order-q.order),[h,m,p,f,...g]=await Promise.all([AZ(t.property.photoUrl,a),AZ(t.agent.headshotUrl,700),AZ(t.agent.brokerageLogoUrl,800),AZ((d==null?void 0:d.headshotUrl)||null,700),...u.map(F=>AZ(F.imageUrl||null,a))]),v={};u.forEach((F,q)=>{v[F.id]=g[q]??null}),tVn(t.focal);const y={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:f,logo:p,customImages:v,dpi:r,pageNo:1},b=new Set(((D=t.pages)==null?void 0:D.hidden)||[]),w=[...t.services].filter(F=>F.enabled).sort((F,q)=>F.order-q.order),S=F=>w.find(q=>q.key===F);pVn(y),b.has("welcome")||fVn(y),b.has("agent")||xVn(y),u.filter(F=>F.placement!=="end").forEach(F=>LSt(y,F)),b.has("overview")||gVn(y,w);const C=new Set,E=(F,q)=>{const G=S(F);G&&(C.add(F),q(G))};E("photography",F=>PSt(y,F,{kicker:"First impressions",headline:"Buyers will see your home at its absolute best.",sub:"Strong presentation earns the click before a showing is ever scheduled.",note:"Every image has one job: earn the next click."})),E("video",F=>PSt(y,F,{kicker:"More ways to experience it",headline:"Photos introduce the home. Video helps buyers feel it.",sub:"A cinematic walk-through gives the listing movement, emotion, and shareability.",note:"The right format for every screen.",dark:!0,flip:!0})),E("mls",F=>yVn(y,F)),E("syndication",F=>vVn(y,F)),E("website",F=>bVn(y,F)),E("social",F=>_Vn(y,F)),E("email",F=>wVn(y,F)),E("openhouse",F=>jVn(y,F)),E("communication",F=>NVn(y,F)),w.filter(F=>!C.has(F.key)).forEach(F=>{I0(y);const q=Iv(y,"Marketing",F.title,null),G=GL(F,6),V=ch(s,F.body,ca,q,Fc-ca*2-160,{size:10.5,color:Lv,leading:16});G.length&&pK(s,G,ca,V+30,Fc-ca*2-160,{font:nu,size:9.5,color:qC,accent:y.accent,gap:8}),D0(y)}),u.filter(F=>F.placement==="end").forEach(F=>LSt(y,F)),b.has("closing")||kVn(y)}const ISt=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:MVn}];function PVn(s){return ISt.find(t=>t.id===s)||ISt[0]}async function ues(s,t,n="screen"){const r=new Po({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await PVn(t).render(r,s,n),r.setProperties({title:s.title||`${s.property.addressLine1} — Listing Presentation`,subject:`Listing presentation for ${s.property.addressLine1}`,author:s.agent.name,creator:"LevelUp Hub — Listing Presentation Studio"}),r}function LVn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const IVn={name:"Your Name",headshotUrl:null,brokerageName:null,brokerageLogoUrl:null,licenseNumber:null,licenseState:null,phone:null,email:null,website:null,brandColor:"#2a4c64",accentColor:"#B8965A",tagline:null};async function h6e(s){if(!s)return null;const{data:t}=await U.storage.from(eL).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function m6e(s,t,n){const r=s.agent_snapshot||{},a={...IVn,...t||{},...Object.fromEntries(Object.entries(r).filter(([,i])=>i!=null&&i!==""))};return{title:s.title,property:{addressLine1:s.property_address_line1||"",city:s.city||"",state:s.state||"",postalCode:s.postal_code||"",listPrice:s.list_price!=null?Number(s.list_price):null,beds:s.beds!=null?Number(s.beds):null,baths:s.baths!=null?Number(s.baths):null,sqft:s.sqft!=null?Number(s.sqft):null,photoUrl:n??null},agent:a,coAgent:KQt(s.co_agent),customPages:ZQt(s.custom_pages),services:dKe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:lKe,focal:s.photo_focal||cKe}}async function hes(s,t){if(s.property.photoUrl||!t)return s;const n=await h6e(t);return{...s,property:{...s.property,photoUrl:n}}}async function mes(s,t,n){const r=await hes(s,n);return(await ues(r,t,"screen")).output("blob")}async function pes(s,t,n="print",r){const a=await hes(s,r),l=(await ues(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=LVn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function fes(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await U.storage.from(eL).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await U.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function xes(s,t=2400){const n=URL.createObjectURL(s);try{const r=await new Promise((c,d)=>{const u=new Image;u.onload=()=>c(u),u.onerror=d,u.src=n});if(r.naturalWidth<=t&&s.size<3e6)return s;const a=Math.min(1,t/r.naturalWidth),i=document.createElement("canvas");return i.width=Math.round(r.naturalWidth*a),i.height=Math.round(r.naturalHeight*a),i.getContext("2d").drawImage(r,0,0,i.width,i.height),await new Promise(c=>i.toBlob(c,"image/jpeg",.9))||s}catch{return s}finally{URL.revokeObjectURL(n)}}async function DVn(s,t,n){const r=await xes(n),a=`${s}/${t}/photo.jpg`,{error:i}=await U.storage.from(eL).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function RVn(s,t,n="presentation",r=1800){const a=await xes(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await U.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=U.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function FVn({path:s,alt:t}){const[n,r]=_.useState(null),[a,i]=_.useState(!1);return _.useEffect(()=>{let l=!0;if(r(null),i(!1),!!s)return Vzn(s,3600).then(o=>{l&&r(o)}),()=>{l=!1}},[s]),n&&!a?e.jsx("div",{className:"h-32 w-full overflow-hidden bg-muted",children:e.jsx("img",{src:n,alt:t,loading:"lazy",onError:()=>i(!0),className:"h-32 w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"})}):e.jsx("div",{className:"flex h-32 items-center justify-center bg-gradient-to-br from-primary/15 to-accent/10",children:e.jsx(sa,{className:"h-8 w-8 text-primary/50"})})}const DSt=60*60*24*30;function ges({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=hs(),[l,o]=_.useState([]),[c,d]=_.useState(""),[u,h]=_.useState([]),[m,p]=_.useState(!1),[f,g]=_.useState(""),[v,y]=_.useState(""),[b,w]=_.useState(!1),S=_.useRef(null),C=(n==null?void 0:n.property_address_line1)||(n==null?void 0:n.title)||"your home";_.useEffect(()=>{!s||!n||(o([]),d(""),h([]),g(`Your listing presentation for ${C}`),y(`Hi {{first_name}}, Thank you for the opportunity to talk about selling ${C}. I put together a presentation that walks through my pricing strategy, marketing plan, and what to expect at every step. Take a look and let me know what questions come up — I'm happy to walk through it together.`))},[s,n==null?void 0:n.id]),_.useEffect(()=>{S.current&&clearTimeout(S.current);const D=c.trim();if(!i||D.length<2||/\S+@\S+\.\S+/.test(D)){h([]);return}return S.current=setTimeout(async()=>{p(!0);const F=`%${D}%`,q=U,{data:G}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${F},last_name.ilike.${F},email.ilike.${F}`).order("first_name",{ascending:!0}).limit(6);p(!1),h(G||[])},200),()=>{S.current&&clearTimeout(S.current)}},[c,i==null?void 0:i.id]);const E=D=>{D.email&&(o(F=>F.some(q=>q.email.toLowerCase()===D.email.toLowerCase())?F:[...F,D]),d(""),h([]))},P=()=>{const D=c.trim();if(!/\S+@\S+\.\S+/.test(D)){ne.error("Enter a valid email address");return}E({email:D})},M=_.useMemo(()=>!!n&&l.length>0&&f.trim().length>0&&!b,[n,l,f,b]),I=async()=>{if(!(!n||!i)){if(!n.property_photo_path){ne.error("Add the primary exterior photo before emailing the presentation");return}w(!0);try{const D=await mes(m6e(n,r,a??null),n.template_id,n.property_photo_path),F=await fes(i.id,n.id,D)||n.pdf_path;if(!F)throw new Error("Could not save the presentation PDF");const{data:q,error:G}=await U.storage.from(eL).createSignedUrl(F,DSt);if(G||!(q!=null&&q.signedUrl))throw new Error("Could not create a share link");const V=await h6e(n.property_photo_path).then(oe=>oe).catch(()=>null),{data:H}=await U.storage.from(eL).createSignedUrl(n.property_photo_path,DSt),{data:K,error:Z}=await U.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:f,message:v,pdf_url:q.signedUrl,photo_url:(H==null?void 0:H.signedUrl)||V,recipients:l}});if(Z)throw Z;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Could not send the email");ne.success(K.failed?`Sent to ${K.sent} · ${K.failed} failed`:`Presentation emailed to ${K.sent} ${K.sent===1?"contact":"contacts"}`),t(!1)}catch(D){ne.error((D==null?void 0:D.message)||"Could not send the presentation")}finally{w(!1)}}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(_r,{children:["Sends a branded email with a secure link to the PDF. Use ",e.jsx("code",{children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(D=>e.jsxs(ze,{variant:"secondary",className:"gap-1 py-1",children:[[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email,e.jsx("button",{type:"button",onClick:()=>o(F=>F.filter(q=>q.email!==D.email)),"aria-label":`Remove ${D.email}`,children:e.jsx(er,{className:"h-3 w-3"})})]},D.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:c,onChange:D=>d(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),P())},placeholder:"Search contacts or type an email"}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:P,children:e.jsx(sn,{className:"h-4 w-4"})})]}),(u.length>0||m)&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full overflow-hidden rounded-md border bg-popover shadow-lg",children:[m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(D=>e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent",onClick:()=>E({email:D.email,first_name:D.first_name,last_name:D.last_name,contact_id:D.id}),children:[e.jsx(Oo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:D.email})]},D.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(pe,{id:"pres-subject",value:f,onChange:D=>g(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pres-message",children:"Message"}),e.jsx(Ps,{id:"pres-message",rows:7,value:v,onChange:D=>y(D.target.value)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs(z,{onClick:I,disabled:!M,className:"gap-2",children:[b?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const OVn=()=>{const s=zn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=HQt(),{data:o}=Uzn(),{data:c}=NLe(),{savedTemplates:d,remove:u}=VQt(),[h,m]=_.useState(null),[p,f]=_.useState(""),[g,v]=_.useState(null),[y,b]=_.useState(null),[w,S]=_.useState(null),C=_.useMemo(()=>{var I,D;return(D=(I=o==null?void 0:o[0])==null?void 0:I.default_services)!=null&&D.length?o[0].default_services:a6e},[o]),E=async()=>{var D;if(!c)return;const I=await r.mutateAsync({title:"Untitled Presentation",template_id:((D=o==null?void 0:o[0])==null?void 0:D.slug)||"signature",agent_snapshot:c,services:C});s(`/apps/listing-presentation-studio/${I.id}`)},P=async I=>{var F;const D=await r.mutateAsync({title:`${I.name} — new listing`,template_id:I.template_id||"signature",agent_snapshot:I.agent_snapshot,co_agent:I.co_agent,custom_pages:I.custom_pages,services:(F=I.services)!=null&&F.length?I.services:C,page_settings:I.page_settings});s(`/apps/listing-presentation-studio/${D.id}`)},M=async I=>{try{b(I.id),await pes(m6e(I,c),I.template_id,"print",I.property_photo_path)}catch(D){ne.error((D==null?void 0:D.message)||"Could not build the PDF")}finally{b(null)}};return e.jsxs($s,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," Listing Presentation Studio"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Win the listing before you walk in"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Enter an address, drop in one exterior photo, and get a beautiful 12-page seller presentation branded with your profile — ready to present or print in under two minutes."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{size:"lg",onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(Ty,{className:"h-4 w-4"})," From template",e.jsx(cl,{className:"h-4 w-4"})]})}),e.jsx(qd,{align:"end",className:"w-64",children:d.map(I=>e.jsxs(ua,{onClick:()=>P(I),children:[e.jsx(Ty,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:I.name})]},I.id))})]})]})]})}),d.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Your saved templates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start a new presentation from a saved setup — just add the address and photo."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:d.map(I=>e.jsx(be,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Le,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>P(I),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(Ty,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),I.name]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:I.description||"Branding, theme, page wording, and marketing plan saved."})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>u.mutate(I.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]})},I.id))})]}),n?e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(I=>e.jsx(ln,{className:"h-56 rounded-xl"},I))}):t.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-4 py-16 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-muted",children:e.jsx($r,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No presentations yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create your first seller presentation — it takes about two minutes."})]}),e.jsxs(z,{onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," New presentation"]})]})}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(I=>{const D=I.property_address_line1||"No address yet",F=[I.city,I.state].filter(Boolean).join(", ");return e.jsxs(be,{className:"group overflow-hidden transition-shadow hover:shadow-lg",children:[e.jsx("button",{className:"block w-full text-left",onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:e.jsx(FVn,{path:I.property_photo_path,alt:`${D} property photo`})}),e.jsxs(Le,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:I.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[D,F?` · ${F}`:""]})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:[e.jsx(Wa,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(ua,{onClick:()=>{m(I),f(I.title)},children:[e.jsx($r,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(ua,{onClick:()=>a.mutate(I),children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(ua,{onClick:()=>M(I),children:[e.jsx(Ga,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(ua,{onClick:()=>S(I),children:[e.jsx(on,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(Iy,{}),e.jsxs(ua,{className:"text-destructive",onClick:()=>v(I),children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Updated ",Ys(new Date(I.updated_at),"MMM d, yyyy")]}),I.last_generated_at?e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:y===I.id,onClick:()=>M(I),children:[y===I.id?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4"}),"Download PDF"]})]})]},I.id)})})]}),e.jsx(Is,{open:!!h,onOpenChange:I=>!I&&m(null),children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Rename presentation"})}),e.jsx(pe,{value:p,onChange:I=>f(I.target.value),autoFocus:!0}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(z,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:p.trim()||"Untitled Presentation"}),m(null),ne.success("Renamed"))},children:"Save"})]})]})}),e.jsx(Ql,{open:!!g,onOpenChange:I=>!I&&v(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete this presentation?"}),e.jsx(ql,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{g&&i.mutate(g),v(null)},children:"Delete"})]})]})}),e.jsx(ges,{open:!!w,onOpenChange:I=>!I&&S(null),row:w,brand:c})]})};var yee={};yee.d=(s,t)=>{for(var n in t)yee.o(t,n)&&!yee.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};yee.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Ec=globalThis.pdfjsLib={};yee.d(Ec,{AbortException:()=>Nz,AnnotationEditorLayer:()=>zYe,AnnotationEditorParamsType:()=>Nc,AnnotationEditorType:()=>td,AnnotationEditorUIManager:()=>L9,AnnotationLayer:()=>RGn,AnnotationMode:()=>$6,ColorPicker:()=>g6e,DOMSVGFactory:()=>Sat,DrawLayer:()=>qYe,FeatureTest:()=>Sb,GlobalWorkerOptions:()=>IA,ImageKind:()=>yCe,InvalidPDFException:()=>ves,MissingPDFException:()=>jz,OPS:()=>Ik,OutputScale:()=>LKe,PDFDataRangeTransport:()=>fts,PDFDateString:()=>vat,PDFWorker:()=>Jq,PasswordResponses:()=>UVn,PermissionFlag:()=>$Vn,PixelsPerInch:()=>sL,RenderingCancelledException:()=>gat,TextLayer:()=>Rse,UnexpectedResponseException:()=>q8e,Util:()=>Vo,VerbosityLevel:()=>B8e,XfaLayer:()=>gts,build:()=>xGn,createValidAbsoluteUrl:()=>GVn,fetchData:()=>H8e,getDocument:()=>oGn,getFilenameFromUrl:()=>tHn,getPdfFilenameFromUrl:()=>sHn,getXfaPageViewport:()=>nHn,isDataScheme:()=>G8e,isPdfFile:()=>yat,noContextMenu:()=>FN,normalizeUnicode:()=>QVn,setLayerDimensions:()=>P9,shadow:()=>gu,version:()=>fGn});const u1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),yes=[1,0,0,1,0,0],EKe=[.001,0,0,.001,0,0],zVn=1e7,dBe=1.35,Hw={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},$6={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},BVn="pdfjs_internal_editor_",td={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},Nc={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},$Vn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Xv={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},yCe={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},ay={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},EZ={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},B8e={ERRORS:0,WARNINGS:1,INFOS:5},Ik={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},UVn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let $8e=B8e.WARNINGS;function qVn(s){Number.isInteger(s)&&($8e=s)}function VVn(){return $8e}function U8e(s){$8e>=B8e.INFOS&&console.log(`Info: ${s}`)}function jd(s){$8e>=B8e.WARNINGS&&console.log(`Warning: ${s}`)}function Mp(s){throw new Error(s)}function jy(s,t){s||Mp(t)}function HVn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function GVn(s,t=null,n=null){if(!s)return null;try{if(n&&typeof s=="string"){if(n.addDefaultProtocol&&s.startsWith("www.")){const a=s.match(/\./g);(a==null?void 0:a.length)>=2&&(s=`http://${s}`)}if(n.tryConvertEncoding)try{s=XVn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(HVn(r))return r}catch{}return null}function gu(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const WL=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class TKe extends WL{constructor(t,n){super(t,"PasswordException"),this.code=n}}class MKe extends WL{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class ves extends WL{constructor(t){super(t,"InvalidPDFException")}}class jz extends WL{constructor(t){super(t,"MissingPDFException")}}class q8e extends WL{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class WVn extends WL{constructor(t){super(t,"FormatError")}}class Nz extends WL{constructor(t){super(t,"AbortException")}}function bes(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&Mp("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function fat(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function YVn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function ZVn(){try{return new Function(""),!0}catch{return!1}}class Sb{static get isLittleEndian(){return gu(this,"isLittleEndian",YVn())}static get isEvalSupported(){return gu(this,"isEvalSupported",ZVn())}static get isOffscreenCanvasSupported(){return gu(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?gu(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):gu(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return gu(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const uBe=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var gE,vCe,PKe;class Vo{static makeHexColor(t,n,r){return`#${uBe[t]}${uBe[n]}${uBe[r]}`}static scaleMinMax(t,n){let r;t[0]?(t[0]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[0],n[2]*=t[0],t[3]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[3],n[3]*=t[3]):(r=n[0],n[0]=n[1],n[1]=r,r=n[2],n[2]=n[3],n[3]=r,t[1]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[1],n[3]*=t[1],t[2]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[2],n[2]*=t[2]),n[0]+=t[4],n[1]+=t[5],n[2]+=t[4],n[3]+=t[5]}static transform(t,n){return[t[0]*n[0]+t[2]*n[1],t[1]*n[0]+t[3]*n[1],t[0]*n[2]+t[2]*n[3],t[1]*n[2]+t[3]*n[3],t[0]*n[4]+t[2]*n[5]+t[4],t[1]*n[4]+t[3]*n[5]+t[5]]}static applyTransform(t,n){const r=t[0]*n[0]+t[1]*n[2]+n[4],a=t[0]*n[1]+t[1]*n[3]+n[5];return[r,a]}static applyInverseTransform(t,n){const r=n[0]*n[3]-n[1]*n[2],a=(t[0]*n[3]-t[1]*n[2]+n[2]*n[5]-n[4]*n[3])/r,i=(-t[0]*n[1]+t[1]*n[0]+n[4]*n[1]-n[5]*n[0])/r;return[a,i]}static getAxialAlignedBoundingBox(t,n){const r=this.applyTransform(t,n),a=this.applyTransform(t.slice(2,4),n),i=this.applyTransform([t[0],t[3]],n),l=this.applyTransform([t[2],t[1]],n);return[Math.min(r[0],a[0],i[0],l[0]),Math.min(r[1],a[1],i[1],l[1]),Math.max(r[0],a[0],i[0],l[0]),Math.max(r[1],a[1],i[1],l[1])]}static inverseTransform(t){const n=t[0]*t[3]-t[1]*t[2];return[t[3]/n,-t[1]/n,-t[2]/n,t[0]/n,(t[2]*t[5]-t[4]*t[3])/n,(t[4]*t[1]-t[5]*t[0])/n]}static singularValueDecompose2dScale(t){const n=[t[0],t[2],t[1],t[3]],r=t[0]*n[0]+t[1]*n[2],a=t[0]*n[1]+t[1]*n[3],i=t[2]*n[0]+t[3]*n[2],l=t[2]*n[1]+t[3]*n[3],o=(r+l)/2,c=Math.sqrt((r+l)**2-4*(r*l-i*a))/2,d=o+c||1,u=o-c||1;return[Math.sqrt(d),Math.sqrt(u)]}static normalizeRect(t){const n=t.slice(0);return t[0]>t[2]&&(n[0]=t[2],n[2]=t[0]),t[1]>t[3]&&(n[1]=t[3],n[3]=t[1]),n}static intersect(t,n){const r=Math.max(Math.min(t[0],t[2]),Math.min(n[0],n[2])),a=Math.min(Math.max(t[0],t[2]),Math.max(n[0],n[2]));if(r>a)return null;const i=Math.max(Math.min(t[1],t[3]),Math.min(n[1],n[3])),l=Math.min(Math.max(t[1],t[3]),Math.max(n[1],n[3]));return i>l?null:[r,i,a,l]}static bezierBoundingBox(t,n,r,a,i,l,o,c,d){return d?(d[0]=Math.min(d[0],t,o),d[1]=Math.min(d[1],n,c),d[2]=Math.max(d[2],t,o),d[3]=Math.max(d[3],n,c)):d=[Math.min(t,o),Math.min(n,c),Math.max(t,o),Math.max(n,c)],ss(this,gE,PKe).call(this,t,r,i,o,n,a,l,c,3*(-t+3*(r-i)+o),6*(t-2*r+i),3*(r-t),d),ss(this,gE,PKe).call(this,t,r,i,o,n,a,l,c,3*(-n+3*(a-l)+c),6*(n-2*a+l),3*(a-n),d),d}}gE=new WeakSet,vCe=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,p=m*d,f=h*(h*(h*t+3*d*n)+3*m*r)+p*a,g=h*(h*(h*i+3*d*l)+3*m*o)+p*c;u[0]=Math.min(u[0],f),u[1]=Math.min(u[1],g),u[2]=Math.max(u[2],f),u[3]=Math.max(u[3],g)},PKe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&ss(this,gE,vCe).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const p=u**2-4*h*d;if(p<0)return;const f=Math.sqrt(p),g=2*d;ss(this,gE,vCe).call(this,t,n,r,a,i,l,o,c,(-u+f)/g,m),ss(this,gE,vCe).call(this,t,n,r,a,i,l,o,c,(-u-f)/g,m)},ps(Vo,gE);function XVn(s){return decodeURIComponent(escape(s))}let hBe=null,RSt=null;function QVn(s){return hBe||(hBe=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,RSt=new Map([["ſt","ſt"]])),s.replaceAll(hBe,(t,n,r)=>n?n.normalize("NFKC"):RSt.get(r))}function JVn(){if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.randomUUID)=="function")return crypto.randomUUID();const s=new Uint8Array(32);if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.getRandomValues)=="function")crypto.getRandomValues(s);else for(let t=0;t<32;t++)s[t]=Math.floor(Math.random()*255);return bes(s)}const xat="pdfjs_internal_id_",E3={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function eHn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(bes(s))}const $3="http://www.w3.org/2000/svg",pF=class pF{};zr(pF,"CSS",96),zr(pF,"PDF",72),zr(pF,"PDF_TO_CSS_UNITS",pF.CSS/pF.PDF);let sL=pF;async function H8e(s,t="text"){if(UX(s,document.baseURI)){const n=await fetch(s);if(!n.ok)throw new Error(n.statusText);switch(t){case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"json":return n.json()}return n.text()}return new Promise((n,r)=>{const a=new XMLHttpRequest;a.open("GET",s,!0),a.responseType=t,a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){if(a.status===200||a.status===0){switch(t){case"arraybuffer":case"blob":case"json":n(a.response);return}n(a.responseText);return}r(new Error(a.statusText))}},a.send(null)})}class iie{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let p,f,g,v;d===0?(p=Math.abs(c-t[1])*n+a,f=Math.abs(o-t[0])*n+i,g=(t[3]-t[1])*n,v=(t[2]-t[0])*n):(p=Math.abs(o-t[0])*n+a,f=Math.abs(c-t[1])*n+i,g=(t[2]-t[0])*n,v=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,p-d*n*o-h*n*c,f-u*n*o-m*n*c],this.width=g,this.height=v}get rawDims(){const{viewBox:t}=this;return gu(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:a=this.offsetY,dontFlip:i=!1}={}){return new iie({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return Vo.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=Vo.applyTransform([t[0],t[1]],this.transform),r=Vo.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return Vo.applyInverseTransform([t,n],this.transform)}}class gat extends WL{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function G8e(s){const t=s.length;let n=0;for(;n=1&&a<=12?a-1:0;let i=parseInt(n[3],10);i=i>=1&&i<=31?i:1;let l=parseInt(n[4],10);l=l>=0&&l<=23?l:0;let o=parseInt(n[5],10);o=o>=0&&o<=59?o:0;let c=parseInt(n[6],10);c=c>=0&&c<=59?c:0;const d=n[7]||"Z";let u=parseInt(n[8],10);u=u>=0&&u<=23?u:0;let h=parseInt(n[9],10)||0;return h=h>=0&&h<=59?h:0,d==="-"?(l+=u,o+=h):d==="+"&&(l-=u,o-=h),new Date(Date.UTC(r,a,i,l,o,c))}}cne=new WeakMap,ps(vat,cne);function nHn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new iie({viewBox:i,scale:t,rotation:n})}function bat(s){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return s.startsWith("rgb(")?s.slice(4,-1).split(",").map(t=>parseInt(t)):s.startsWith("rgba(")?s.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(jd(`Not a valid color format: "${s}"`),[0,0,0])}function rHn(s){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const n of s.keys()){t.style.color=n;const r=window.getComputedStyle(t).color;s.set(n,bat(r))}t.remove()}function Ef(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function T3(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform().invertSelf();return[t,n,r,a,i,l]}function P9(s,t,n=!1,r=!0){if(t instanceof iie){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=Sb.isCSSRoundSupported,c=`var(--scale-factor) * ${a}px`,d=`var(--scale-factor) * ${i}px`,u=o?`round(down, ${c}, var(--scale-round-x, 1px))`:`calc(${c})`,h=o?`round(down, ${d}, var(--scale-round-y, 1px))`:`calc(${d})`;!n||t.rotation%180===0?(l.width=u,l.height=h):(l.width=h,l.height=u)}r&&s.setAttribute("data-main-rotation",t.rotation)}class LKe{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}var J6,eO,Fk,tO,dne,une,sMe,_es,Eb,wes,jes,bCe,Nes,DKe;const X3=class X3{constructor(t){ps(this,Eb);ps(this,J6,null);ps(this,eO,null);ps(this,Fk);ps(this,tO,null);ps(this,dne,null);Ht(this,Fk,t),ye(X3,une)||Ht(X3,une,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=Ht(this,J6,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=ye(this,Fk)._uiManager._signal;t.addEventListener("contextmenu",FN,{signal:n}),t.addEventListener("pointerdown",ss(X3,sMe,_es),{signal:n});const r=Ht(this,tO,document.createElement("div"));r.className="buttons",t.append(r);const a=ye(this,Fk).toolbarPosition;if(a){const{style:i}=t,l=ye(this,Fk)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return ss(this,Eb,Nes).call(this),t}get div(){return ye(this,J6)}hide(){var t;ye(this,J6).classList.add("hidden"),(t=ye(this,eO))==null||t.hideDropdown()}show(){var t;ye(this,J6).classList.remove("hidden"),(t=ye(this,dne))==null||t.shown()}async addAltText(t){const n=await t.render();ss(this,Eb,bCe).call(this,n),ye(this,tO).prepend(n,ye(this,Eb,DKe)),Ht(this,dne,t)}addColorPicker(t){Ht(this,eO,t);const n=t.renderButton();ss(this,Eb,bCe).call(this,n),ye(this,tO).prepend(n,ye(this,Eb,DKe))}remove(){var t;ye(this,J6).remove(),(t=ye(this,eO))==null||t.destroy(),Ht(this,eO,null)}};J6=new WeakMap,eO=new WeakMap,Fk=new WeakMap,tO=new WeakMap,dne=new WeakMap,une=new WeakMap,sMe=new WeakSet,_es=function(t){t.stopPropagation()},Eb=new WeakSet,wes=function(t){ye(this,Fk)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},jes=function(t){ye(this,Fk)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},bCe=function(t){const n=ye(this,Fk)._uiManager._signal;t.addEventListener("focusin",ss(this,Eb,wes).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",ss(this,Eb,jes).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",FN,{signal:n})},Nes=function(){const{editorType:t,_uiManager:n}=ye(this,Fk),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",ye(X3,une)[t]),ss(this,Eb,bCe).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),ye(this,tO).append(r)},DKe=function(){const t=document.createElement("div");return t.className="divider",t},ps(X3,sMe),ps(X3,une,null);let IKe=X3;var hne,sO,nO,cL,kes,Ses,Ces;class aHn{constructor(t){ps(this,cL);ps(this,hne,null);ps(this,sO,null);ps(this,nO);Ht(this,nO,t)}show(t,n,r){const[a,i]=ss(this,cL,Ses).call(this,n,r),{style:l}=ye(this,sO)||Ht(this,sO,ss(this,cL,kes).call(this));t.append(ye(this,sO)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){ye(this,sO).remove()}}hne=new WeakMap,sO=new WeakMap,nO=new WeakMap,cL=new WeakSet,kes=function(){const t=Ht(this,sO,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",FN,{signal:ye(this,nO)._signal});const n=Ht(this,hne,document.createElement("div"));return n.className="buttons",t.append(n),ss(this,cL,Ces).call(this),t},Ses=function(t,n){let r=0,a=0;for(const i of t){const l=i.y+i.height;if(lr){a=o,r=l;continue}n?o>a&&(a=o):o{ye(this,nO).highlightSelection("floating_button")},{signal:r}),ye(this,hne).append(t)};function p6e(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function iHn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var nMe;class oHn{constructor(){ps(this,nMe,0)}get id(){return`${BVn}${Jy(this,nMe)._++}`}}nMe=new WeakMap;var _V,mne,e1,wV,_Ce;const Dot=class Dot{constructor(){ps(this,wV);ps(this,_V,JVn());ps(this,mne,0);ps(this,e1,null)}static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,',r=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),a=new Image;a.src=t;const i=a.decode().then(()=>(r.drawImage(a,0,0,1,1,0,0,1,3),new Uint32Array(r.getImageData(0,0,1,1).data.buffer)[0]===0));return gu(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return ss(this,wV,_Ce).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return ss(this,wV,_Ce).call(this,t,t)}async getFromBlob(t,n){const r=await n;return ss(this,wV,_Ce).call(this,t,r)}async getFromId(t){ye(this,e1)||Ht(this,e1,new Map);const n=ye(this,e1).get(t);if(!n)return null;if(n.bitmap)return n.refCounter+=1,n;if(n.file)return this.getFromFile(n.file);if(n.blobPromise){const{blobPromise:r}=n;return delete n.blobPromise,this.getFromBlob(n.id,r)}return this.getFromUrl(n.url)}getFromCanvas(t,n){ye(this,e1)||Ht(this,e1,new Map);let r=ye(this,e1).get(t);if(r!=null&&r.bitmap)return r.refCounter+=1,r;const a=new OffscreenCanvas(n.width,n.height);return a.getContext("2d").drawImage(n,0,0),r={bitmap:a.transferToImageBitmap(),id:`image_${ye(this,_V)}_${Jy(this,mne)._++}`,refCounter:1,isSvg:!1},ye(this,e1).set(t,r),ye(this,e1).set(r.id,r),r}getSvgUrl(t){const n=ye(this,e1).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;ye(this,e1)||Ht(this,e1,new Map);const n=ye(this,e1).get(t);if(!n||(n.refCounter-=1,n.refCounter!==0))return;const{bitmap:r}=n;if(!n.url&&!n.file){const i=new OffscreenCanvas(r.width,r.height);i.getContext("bitmaprenderer").transferFromImageBitmap(r),n.blobPromise=i.convertToBlob()}(a=r.close)==null||a.call(r),n.bitmap=null}isValidId(t){return t.startsWith(`image_${ye(this,_V)}_`)}};_V=new WeakMap,mne=new WeakMap,e1=new WeakMap,wV=new WeakSet,_Ce=async function(t,n){ye(this,e1)||Ht(this,e1,new Map);let r=ye(this,e1).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${ye(this,_V)}_${Jy(this,mne)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await H8e(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=Dot._isSVGFittingCanvas,l=new FileReader,o=new Image,c=new Promise((d,u)=>{o.onload=()=>{r.bitmap=o,r.isSvg=!0,d()},l.onload=async()=>{const h=r.svgUrl=l.result;o.src=await i?`${h}#svgView(preserveAspectRatio(none))`:h},o.onerror=l.onerror=u});l.readAsDataURL(a),await c}else r.bitmap=await createImageBitmap(a);r.refCounter=1}catch(a){console.error(a),r=null}return ye(this,e1).set(t,r),r&&ye(this,e1).set(r.id,r),r};let RKe=Dot;var r0,eM,pne,a0;class lHn{constructor(t=128){ps(this,r0,[]);ps(this,eM,!1);ps(this,pne);ps(this,a0,-1);Ht(this,pne,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),ye(this,eM))return;const c={cmd:t,undo:n,post:r,type:i};if(ye(this,a0)===-1){ye(this,r0).length>0&&(ye(this,r0).length=0),Ht(this,a0,0),ye(this,r0).push(c);return}if(l&&ye(this,r0)[ye(this,a0)].type===i){o&&(c.undo=ye(this,r0)[ye(this,a0)].undo),ye(this,r0)[ye(this,a0)]=c;return}const d=ye(this,a0)+1;d===ye(this,pne)?ye(this,r0).splice(0,1):(Ht(this,a0,d),di===n[l]))return aMe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?Vo.makeHexColor(...n):t}};zr(aMe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let FKe=aMe;var jV,Rw,ly,ev,NV,oA,kV,Ok,tM,SV,rO,t4,zk,aO,fne,xne,CV,gne,s4,sM,AV,nM,n4,iMe,rM,yne,aM,iO,vne,bne,i0,Rh,lA,oO,_ne,wne,iM,r4,cA,jne,O2,Ui,wCe,OKe,Ees,Tes,jCe,Mes,Pes,Les,zKe,Ies,BKe,$Ke,Des,J1,i6,Res,Fes,UKe,Oes,qX,qKe;const EU=class EU{constructor(t,n,r,a,i,l,o,c,d,u,h){ps(this,Ui);ps(this,jV,new AbortController);ps(this,Rw,null);ps(this,ly,new Map);ps(this,ev,new Map);ps(this,NV,null);ps(this,oA,null);ps(this,kV,null);ps(this,Ok,new lHn);ps(this,tM,null);ps(this,SV,0);ps(this,rO,new Set);ps(this,t4,null);ps(this,zk,null);ps(this,aO,new Set);ps(this,fne,!1);ps(this,xne,!1);ps(this,CV,!1);ps(this,gne,null);ps(this,s4,null);ps(this,sM,null);ps(this,AV,null);ps(this,nM,!1);ps(this,n4,null);ps(this,iMe,new oHn);ps(this,rM,!1);ps(this,yne,!1);ps(this,aM,null);ps(this,iO,null);ps(this,vne,null);ps(this,bne,null);ps(this,i0,td.NONE);ps(this,Rh,new Set);ps(this,lA,null);ps(this,oO,null);ps(this,_ne,null);ps(this,wne,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});ps(this,iM,[0,0]);ps(this,r4,null);ps(this,cA,null);ps(this,jne,null);ps(this,O2,null);const m=this._signal=ye(this,jV).signal;Ht(this,cA,t),Ht(this,jne,n),Ht(this,NV,r),this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:m}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:m}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:m}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:m}),a._on("setpreference",this.onSetPreference.bind(this),{signal:m}),a._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:m}),ss(this,Ui,Mes).call(this),ss(this,Ui,Des).call(this),ss(this,Ui,zKe).call(this),Ht(this,oA,i.annotationStorage),Ht(this,gne,i.filterFactory),Ht(this,oO,l),Ht(this,AV,o||null),Ht(this,fne,c),Ht(this,xne,d),Ht(this,CV,u),Ht(this,bne,h||null),this.viewParameters={realScale:sL.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=EU.prototype,n=l=>ye(l,cA).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&l.hasSomethingToControl(),r=(l,{target:o})=>{if(o instanceof HTMLInputElement){const{type:c}=o;return c!=="text"&&c!=="number"}return!0},a=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return gu(this,"_keyboardManager",new oie([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],t.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:r}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,cA).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,cA).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-a,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:n}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[a,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:n}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-a],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:n}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,a],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:n}]]))}destroy(){var t,n,r,a;(t=ye(this,O2))==null||t.resolve(),Ht(this,O2,null),(n=ye(this,jV))==null||n.abort(),Ht(this,jV,null),this._signal=null;for(const i of ye(this,ev).values())i.destroy();ye(this,ev).clear(),ye(this,ly).clear(),ye(this,aO).clear(),Ht(this,Rw,null),ye(this,Rh).clear(),ye(this,Ok).destroy(),(r=ye(this,NV))==null||r.destroy(),(a=ye(this,n4))==null||a.hide(),Ht(this,n4,null),ye(this,s4)&&(clearTimeout(ye(this,s4)),Ht(this,s4,null)),ye(this,r4)&&(clearTimeout(ye(this,r4)),Ht(this,r4,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return ye(this,bne)}get useNewAltTextFlow(){return ye(this,xne)}get useNewAltTextWhenAddingImage(){return ye(this,CV)}get hcmFilter(){return gu(this,"hcmFilter",ye(this,oO)?ye(this,gne).addHCMFilter(ye(this,oO).foreground,ye(this,oO).background):"none")}get direction(){return gu(this,"direction",getComputedStyle(ye(this,cA)).direction)}get highlightColors(){return gu(this,"highlightColors",ye(this,AV)?new Map(ye(this,AV).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return gu(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){Ht(this,vne,t)}editAltText(t,n=!1){var r;(r=ye(this,NV))==null||r.editAltText(this,t,n)}switchToMode(t,n){this._eventBus.on("annotationeditormodechanged",n,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,n){this._eventBus.dispatch("setpreference",{source:this,name:t,value:n})}onSetPreference({name:t,value:n}){switch(t){case"enableNewAltTextWhenAddingImage":Ht(this,CV,n);break}}onPageChanging({pageNumber:t}){Ht(this,SV,t-1)}focusMainContainer(){ye(this,cA).focus()}findParent(t,n){for(const r of ye(this,ev).values()){const{x:a,y:i,width:l,height:o}=r.div.getBoundingClientRect();if(t>=a&&t<=a+l&&n>=i&&n<=i+o)return r}return null}disableUserSelect(t=!1){ye(this,jne).classList.toggle("noUserSelect",t)}addShouldRescale(t){ye(this,aO).add(t)}removeShouldRescale(t){ye(this,aO).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*sL.PDF_TO_CSS_UNITS;for(const n of ye(this,aO))n.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}highlightSelection(t=""){const n=document.getSelection();if(!n||n.isCollapsed)return;const{anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l}=n,o=n.toString(),d=ss(this,Ui,wCe).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=ss(this,Ui,OKe).call(this,d),m=ye(this,i0)===td.NONE,p=()=>{h==null||h.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l,text:o}),m&&this.showAllEditors("highlight",!0,!0)};if(m){this.switchToMode(td.HIGHLIGHT,p);return}p()}addToAnnotationStorage(t){!t.isEmpty()&&ye(this,oA)&&!ye(this,oA).has(t.id)&&ye(this,oA).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,ye(this,nM)&&(Ht(this,nM,!1),ss(this,Ui,jCe).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of ye(this,Rh))if(n.div.contains(t)){Ht(this,iO,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!ye(this,iO))return;const[t,n]=ye(this,iO);Ht(this,iO,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){ss(this,Ui,zKe).call(this),ss(this,Ui,BKe).call(this)}removeEditListeners(){ss(this,Ui,Ies).call(this),ss(this,Ui,$Ke).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of ye(this,zk))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of ye(this,zk))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=ye(this,Rw))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of ye(this,Rh)){const i=a.serialize(!0);i&&n.push(i)}n.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(n))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:n}=t;for(const i of n.items)for(const l of ye(this,zk))if(l.isHandlingMimeForPasting(i.type)){l.paste(i,this.currentLayer);return}let r=n.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(i){jd(`paste: "${i.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();const a=this.currentLayer;try{const i=[];for(const c of r){const d=await a.deserialize(c);if(!d)return;i.push(d)}const l=()=>{for(const c of i)ss(this,Ui,UKe).call(this,c);ss(this,Ui,qKe).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){jd(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),ye(this,i0)!==td.NONE&&!this.isEditorHandlingKeyboard&&EU._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,ye(this,nM)&&(Ht(this,nM,!1),ss(this,Ui,jCe).call(this,"main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(t){t?(ss(this,Ui,Pes).call(this),ss(this,Ui,BKe).call(this),ss(this,Ui,J1).call(this,{isEditing:ye(this,i0)!==td.NONE,isEmpty:ss(this,Ui,qX).call(this),hasSomethingToUndo:ye(this,Ok).hasSomethingToUndo(),hasSomethingToRedo:ye(this,Ok).hasSomethingToRedo(),hasSelectedEditor:!1})):(ss(this,Ui,Les).call(this),ss(this,Ui,$Ke).call(this),ss(this,Ui,J1).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!ye(this,zk)){Ht(this,zk,t);for(const n of ye(this,zk))ss(this,Ui,i6).call(this,n.defaultPropertiesToUpdate)}}getId(){return ye(this,iMe).id}get currentLayer(){return ye(this,ev).get(ye(this,SV))}getLayer(t){return ye(this,ev).get(t)}get currentPageIndex(){return ye(this,SV)}addLayer(t){ye(this,ev).set(t.pageIndex,t),ye(this,rM)?t.enable():t.disable()}removeLayer(t){ye(this,ev).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(ye(this,i0)!==t&&!(ye(this,O2)&&(await ye(this,O2).promise,!ye(this,O2)))){if(Ht(this,O2,Promise.withResolvers()),Ht(this,i0,t),t===td.NONE){this.setEditingState(!1),ss(this,Ui,Fes).call(this),ye(this,O2).resolve();return}this.setEditingState(!0),await ss(this,Ui,Res).call(this),this.unselectAll();for(const a of ye(this,ev).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),ye(this,O2).resolve();return}for(const a of ye(this,ly).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();ye(this,O2).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==ye(this,i0)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(ye(this,zk)){switch(t){case Nc.CREATE:this.currentLayer.addNewEditor();return;case Nc.HIGHLIGHT_DEFAULT_COLOR:(r=ye(this,vne))==null||r.updateColor(n);break;case Nc.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(ye(this,_ne)||Ht(this,_ne,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of ye(this,Rh))a.updateParams(t,n);for(const a of ye(this,zk))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of ye(this,ly).values())l.editorType===t&&l.show(n);(((i=ye(this,_ne))==null?void 0:i.get(Nc.HIGHLIGHT_SHOW_ALL))??!0)!==n&&ss(this,Ui,i6).call(this,[[Nc.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(ye(this,yne)!==t){Ht(this,yne,t);for(const n of ye(this,ev).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of ye(this,ly).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return ye(this,ly).get(t)}addEditor(t){ye(this,ly).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(ye(this,s4)&&clearTimeout(ye(this,s4)),Ht(this,s4,setTimeout(()=>{this.focusMainContainer(),Ht(this,s4,null)},0))),ye(this,ly).delete(t.id),this.unselect(t),(!t.annotationElementId||!ye(this,rO).has(t.annotationElementId))&&((n=ye(this,oA))==null||n.remove(t.id))}addDeletedAnnotationElement(t){ye(this,rO).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return ye(this,rO).has(t)}removeDeletedAnnotationElement(t){ye(this,rO).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){ye(this,Rw)!==t&&(Ht(this,Rw,t),t&&ss(this,Ui,i6).call(this,t.propertiesToUpdate))}updateUI(t){ye(this,Ui,Oes)===t&&ss(this,Ui,i6).call(this,t.propertiesToUpdate)}toggleSelected(t){if(ye(this,Rh).has(t)){ye(this,Rh).delete(t),t.unselect(),ss(this,Ui,J1).call(this,{hasSelectedEditor:this.hasSelection});return}ye(this,Rh).add(t),t.select(),ss(this,Ui,i6).call(this,t.propertiesToUpdate),ss(this,Ui,J1).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of ye(this,Rh))n!==t&&n.unselect();ye(this,Rh).clear(),ye(this,Rh).add(t),t.select(),ss(this,Ui,i6).call(this,t.propertiesToUpdate),ss(this,Ui,J1).call(this,{hasSelectedEditor:!0})}isSelected(t){return ye(this,Rh).has(t)}get firstSelectedEditor(){return ye(this,Rh).values().next().value}unselect(t){t.unselect(),ye(this,Rh).delete(t),ss(this,Ui,J1).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return ye(this,Rh).size!==0}get isEnterHandled(){return ye(this,Rh).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){ye(this,Ok).undo(),ss(this,Ui,J1).call(this,{hasSomethingToUndo:ye(this,Ok).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:ss(this,Ui,qX).call(this)})}redo(){ye(this,Ok).redo(),ss(this,Ui,J1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:ye(this,Ok).hasSomethingToRedo(),isEmpty:ss(this,Ui,qX).call(this)})}addCommands(t){ye(this,Ok).add(t),ss(this,Ui,J1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:ss(this,Ui,qX).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...ye(this,Rh)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)ss(this,Ui,UKe).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=ye(this,Rw))==null||t.commitOrRemove()}hasSomethingToControl(){return ye(this,Rw)||this.hasSelection}selectAll(){for(const t of ye(this,Rh))t.commit();ss(this,Ui,qKe).call(this,ye(this,ly).values())}unselectAll(){if(!(ye(this,Rw)&&(ye(this,Rw).commitOrRemove(),ye(this,i0)!==td.NONE))&&this.hasSelection){for(const t of ye(this,Rh))t.unselect();ye(this,Rh).clear(),ss(this,Ui,J1).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;ye(this,iM)[0]+=t,ye(this,iM)[1]+=n;const[a,i]=ye(this,iM),l=[...ye(this,Rh)],o=1e3;ye(this,r4)&&clearTimeout(ye(this,r4)),Ht(this,r4,setTimeout(()=>{Ht(this,r4,null),ye(this,iM)[0]=ye(this,iM)[1]=0,this.addCommands({cmd:()=>{for(const c of l)ye(this,ly).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)ye(this,ly).has(c.id)&&c.translateInPage(-a,-i)},mustExec:!1})},o));for(const c of l)c.translateInPage(t,n)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),Ht(this,t4,new Map);for(const t of ye(this,Rh))ye(this,t4).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!ye(this,t4))return!1;this.disableUserSelect(!1);const t=ye(this,t4);Ht(this,t4,null);let n=!1;for(const[{x:a,y:i,pageIndex:l},o]of t)o.newX=a,o.newY=i,o.newPageIndex=l,n||(n=a!==o.savedX||i!==o.savedY||l!==o.savedPageIndex);if(!n)return!1;const r=(a,i,l,o)=>{if(ye(this,ly).has(a.id)){const c=ye(this,ev).get(o);c?a._setParentAndPosition(c,i,l):(a.pageIndex=o,a.x=i,a.y=l)}};return this.addCommands({cmd:()=>{for(const[a,{newX:i,newY:l,newPageIndex:o}]of t)r(a,i,l,o)},undo:()=>{for(const[a,{savedX:i,savedY:l,savedPageIndex:o}]of t)r(a,i,l,o)},mustExec:!0}),!0}dragSelectedEditors(t,n){if(ye(this,t4))for(const r of ye(this,t4).keys())r.drag(t,n)}rebuild(t){if(t.parent===null){const n=this.getLayer(t.pageIndex);n?(n.changeParent(t),n.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){var t;return((t=this.getActive())==null?void 0:t.shouldGetKeyboardEvents())||ye(this,Rh).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return ye(this,Rw)===t}getActive(){return ye(this,Rw)}getMode(){return ye(this,i0)}get imageManager(){return gu(this,"imageManager",new RKe)}getSelectionBoxes(t){if(!t)return null;const n=document.getSelection();for(let d=0,u=n.rangeCount;d({x:(u-a)/l,y:1-(d+h-r)/i,width:m/l,height:h/i});break;case"180":o=(d,u,h,m)=>({x:1-(d+h-r)/i,y:1-(u+m-a)/l,width:h/i,height:m/l});break;case"270":o=(d,u,h,m)=>({x:1-(u+m-a)/l,y:(d-r)/i,width:m/l,height:h/i});break;default:o=(d,u,h,m)=>({x:(d-r)/i,y:(u-a)/l,width:h/i,height:m/l});break}const c=[];for(let d=0,u=n.rangeCount;d{m.type==="pointerup"&&m.button!==0||(d.abort(),c==null||c.toggleDrawing(!0),m.type==="pointerup"&&ss(this,Ui,jCe).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},jCe=function(t=""){ye(this,i0)===td.HIGHLIGHT?this.highlightSelection(t):ye(this,fne)&&ss(this,Ui,Ees).call(this)},Mes=function(){document.addEventListener("selectionchange",ss(this,Ui,Tes).bind(this),{signal:this._signal})},Pes=function(){if(ye(this,sM))return;Ht(this,sM,new AbortController);const t=this.combinedSignal(ye(this,sM));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},Les=function(){var t;(t=ye(this,sM))==null||t.abort(),Ht(this,sM,null)},zKe=function(){if(ye(this,aM))return;Ht(this,aM,new AbortController);const t=this.combinedSignal(ye(this,aM));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},Ies=function(){var t;(t=ye(this,aM))==null||t.abort(),Ht(this,aM,null)},BKe=function(){if(ye(this,tM))return;Ht(this,tM,new AbortController);const t=this.combinedSignal(ye(this,tM));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},$Ke=function(){var t;(t=ye(this,tM))==null||t.abort(),Ht(this,tM,null)},Des=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},J1=function(t){Object.entries(t).some(([r,a])=>ye(this,wne)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(ye(this,wne),t)}),ye(this,i0)===td.HIGHLIGHT&&t.hasSelectedEditor===!1&&ss(this,Ui,i6).call(this,[[Nc.HIGHLIGHT_FREE,!0]]))},i6=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},Res=async function(){if(!ye(this,rM)){Ht(this,rM,!0);const t=[];for(const n of ye(this,ev).values())t.push(n.enable());await Promise.all(t);for(const n of ye(this,ly).values())n.enable()}},Fes=function(){if(this.unselectAll(),ye(this,rM)){Ht(this,rM,!1);for(const t of ye(this,ev).values())t.disable();for(const t of ye(this,ly).values())t.disable()}},UKe=function(t){const n=ye(this,ev).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Oes=function(){let t=null;for(t of ye(this,Rh));return t},qX=function(){if(ye(this,ly).size===0)return!0;if(ye(this,ly).size===1)for(const t of ye(this,ly).values())return t.isEmpty();return!1},qKe=function(t){for(const n of ye(this,Rh))n.unselect();ye(this,Rh).clear();for(const n of t)n.isEmpty()||(ye(this,Rh).add(n),n.select());ss(this,Ui,J1).call(this,{hasSelectedEditor:this.hasSelection})},zr(EU,"TRANSLATE_SMALL",1),zr(EU,"TRANSLATE_BIG",10);let L9=EU;var o0,a4,Bk,EV,i4,Fw,TV,o4,m_,dA,lO,l4,oM,uS,VX,NCe;const tb=class tb{constructor(t){ps(this,uS);ps(this,o0,null);ps(this,a4,!1);ps(this,Bk,null);ps(this,EV,null);ps(this,i4,null);ps(this,Fw,null);ps(this,TV,!1);ps(this,o4,null);ps(this,m_,null);ps(this,dA,null);ps(this,lO,null);ps(this,l4,!1);Ht(this,m_,t),Ht(this,l4,t._uiManager.useNewAltTextFlow),ye(tb,oM)||Ht(tb,oM,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){tb._l10n??(tb._l10n=t)}async render(){const t=Ht(this,Bk,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Ht(this,EV,document.createElement("span"));t.append(n),ye(this,l4)?(t.classList.add("new"),t.setAttribute("data-l10n-id",ye(tb,oM).missing),n.setAttribute("data-l10n-id",ye(tb,oM)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const r=ye(this,m_)._uiManager._signal;t.addEventListener("contextmenu",FN,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),ye(this,m_)._uiManager.editAltText(ye(this,m_)),ye(this,l4)&&ye(this,m_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:ye(this,uS,VX)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Ht(this,TV,!0),a(i))},{signal:r}),await ss(this,uS,NCe).call(this),t}finish(){ye(this,Bk)&&(ye(this,Bk).focus({focusVisible:ye(this,TV)}),Ht(this,TV,!1))}isEmpty(){return ye(this,l4)?ye(this,o0)===null:!ye(this,o0)&&!ye(this,a4)}hasData(){return ye(this,l4)?ye(this,o0)!==null||!!ye(this,dA):this.isEmpty()}get guessedText(){return ye(this,dA)}async setGuessedText(t){ye(this,o0)===null&&(Ht(this,dA,t),Ht(this,lO,await tb._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),ss(this,uS,NCe).call(this))}toggleAltTextBadge(t=!1){var n;if(!ye(this,l4)||ye(this,o0)){(n=ye(this,o4))==null||n.remove(),Ht(this,o4,null);return}if(!ye(this,o4)){const r=Ht(this,o4,document.createElement("div"));r.className="noAltTextBadge",ye(this,m_).div.append(r)}ye(this,o4).classList.toggle("hidden",!t)}serialize(t){let n=ye(this,o0);return!t&&ye(this,dA)===n&&(n=ye(this,lO)),{altText:n,decorative:ye(this,a4),guessedText:ye(this,dA),textWithDisclaimer:ye(this,lO)}}get data(){return{altText:ye(this,o0),decorative:ye(this,a4)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Ht(this,dA,r),Ht(this,lO,a)),!(ye(this,o0)===t&&ye(this,a4)===n)&&(i||(Ht(this,o0,t),Ht(this,a4,n)),ss(this,uS,NCe).call(this))}toggle(t=!1){ye(this,Bk)&&(!t&&ye(this,Fw)&&(clearTimeout(ye(this,Fw)),Ht(this,Fw,null)),ye(this,Bk).disabled=!t)}shown(){ye(this,m_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:ye(this,uS,VX)}})}destroy(){var t,n;(t=ye(this,Bk))==null||t.remove(),Ht(this,Bk,null),Ht(this,EV,null),Ht(this,i4,null),(n=ye(this,o4))==null||n.remove(),Ht(this,o4,null)}};o0=new WeakMap,a4=new WeakMap,Bk=new WeakMap,EV=new WeakMap,i4=new WeakMap,Fw=new WeakMap,TV=new WeakMap,o4=new WeakMap,m_=new WeakMap,dA=new WeakMap,lO=new WeakMap,l4=new WeakMap,oM=new WeakMap,uS=new WeakSet,VX=function(){return ye(this,o0)&&"added"||ye(this,o0)===null&&this.guessedText&&"review"||"missing"},NCe=async function(){var a,i,l;const t=ye(this,Bk);if(!t)return;if(ye(this,l4)){if(t.classList.toggle("done",!!ye(this,o0)),t.setAttribute("data-l10n-id",ye(tb,oM)[ye(this,uS,VX)]),(a=ye(this,EV))==null||a.setAttribute("data-l10n-id",ye(tb,oM)[`${ye(this,uS,VX)}-label`]),!ye(this,o0)){(i=ye(this,i4))==null||i.remove();return}}else{if(!ye(this,o0)&&!ye(this,a4)){t.classList.remove("done"),(l=ye(this,i4))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=ye(this,i4);if(!n){Ht(this,i4,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${ye(this,m_).id}`;const o=100,c=ye(this,m_)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(ye(this,Fw)),Ht(this,Fw,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Ht(this,Fw,setTimeout(()=>{Ht(this,Fw,null),ye(this,i4).classList.add("show"),ye(this,m_)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;ye(this,Fw)&&(clearTimeout(ye(this,Fw)),Ht(this,Fw,null)),(d=ye(this,i4))==null||d.classList.remove("show")},{signal:c})}ye(this,a4)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=ye(this,o0)),n.parentNode||t.append(n);const r=ye(this,m_).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},ps(tb,oM,null),zr(tb,"_l10n",null);let f6e=tb;var cO,$k,Cf,MV,dO,tv,uO,lM,Nne,hO,cM,kne,mO,uA,c4,PV,LV,z2,Sne,oMe,ud,VKe,Cne,HKe,GKe,zes,Bes,WKe,KKe,YKe,$es,ZKe,Ues,qes,Ves,XKe,HX;const jh=class jh{constructor(t){ps(this,ud);ps(this,cO,null);ps(this,$k,null);ps(this,Cf,null);ps(this,MV,!1);ps(this,dO,!1);ps(this,tv,null);ps(this,uO,null);ps(this,lM,null);ps(this,Nne,"");ps(this,hO,!1);ps(this,cM,null);ps(this,kne,!1);ps(this,mO,!1);ps(this,uA,!1);ps(this,c4,null);ps(this,PV,0);ps(this,LV,0);ps(this,z2,null);zr(this,"_editToolbar",null);zr(this,"_initialOptions",Object.create(null));zr(this,"_initialData",null);zr(this,"_isVisible",!0);zr(this,"_uiManager",null);zr(this,"_focusEventsAllowed",!0);ps(this,Sne,!1);ps(this,oMe,jh._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:n,rawDims:{pageWidth:r,pageHeight:a,pageX:i,pageY:l}}=this.parent.viewport;this.rotation=n,this.pageRotation=(360+n-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[r,a],this.pageTranslation=[i,l];const[o,c]=this.parentDimensions;this.x=t.x/o,this.y=t.y/c,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=jh.prototype._resizeWithKeyboard,n=L9.TRANSLATE_SMALL,r=L9.TRANSLATE_BIG;return gu(this,"_resizerKeyboardManager",new oie([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-n,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-r,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[n,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[r,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-n]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-r]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,n]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,r]}],[["Escape","mac+Escape"],jh.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return gu(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new cHn({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});n.annotationElementId=t.annotationElementId,n.deleted=!0,n._uiManager.addToAnnotationStorage(n)}static initialize(t,n){if(jh._l10n??(jh._l10n=t),jh._l10nResizer||(jh._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),jh._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);jh._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){Mp("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return ye(this,Sne)}set _isDraggable(t){var n;Ht(this,Sne,t),(n=this.div)==null||n.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,n]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*n/(t*2),this.y+=this.width*t/(n*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*n/(t*2),this.y-=this.width*t/(n*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=ye(this,oMe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):ss(this,ud,HX).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(ye(this,hO)?Ht(this,hO,!1):this.parent.setSelected(this))}focusout(t){var r;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const n=t.relatedTarget;n!=null&&n.closest(`#${this.id}`)||(t.preventDefault(),(r=this.parent)!=null&&r.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,n,r,a){const[i,l]=this.parentDimensions;[r,a]=this.screenToPageTranslation(r,a),this.x=(t+r)/i,this.y=(n+a)/l,this.fixAndSetPosition()}translate(t,n){ss(this,ud,VKe).call(this,this.parentDimensions,t,n)}translateInPage(t,n){ye(this,cM)||Ht(this,cM,[this.x,this.y]),ss(this,ud,VKe).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){ye(this,cM)||Ht(this,cM,[this.x,this.y]);const[r,a]=this.parentDimensions;if(this.x+=t/r,this.y+=n/a,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:u}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,u)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:i,y:l}=this;const[o,c]=this.getBaseTranslation();i+=o,l+=c,this.div.style.left=`${(100*i).toFixed(2)}%`,this.div.style.top=`${(100*l).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!ye(this,cM)&&(ye(this,cM)[0]!==this.x||ye(this,cM)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=jh,a=r/t,i=r/n;switch(this.rotation){case 90:return[-a,i];case 180:return[a,i];case 270:return[a,-i];default:return[-a,-i]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[n,r]=this.pageDimensions;let{x:a,y:i,width:l,height:o}=this;if(l*=n,o*=r,a*=n,i*=r,this._mustFixPosition)switch(t){case 0:a=Math.max(0,Math.min(n-l,a)),i=Math.max(0,Math.min(r-o,i));break;case 90:a=Math.max(0,Math.min(n-o,a)),i=Math.min(r,Math.max(l,i));break;case 180:a=Math.min(n,Math.max(l,a)),i=Math.min(r,Math.max(o,i));break;case 270:a=Math.min(n,Math.max(o,a)),i=Math.max(0,Math.min(r-l,i));break}this.x=a/=n,this.y=i/=r;const[c,d]=this.getBaseTranslation();a+=c,i+=d;const{style:u}=this.div;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*i).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,n){var r;return ss(r=jh,Cne,HKe).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return ss(r=jh,Cne,HKe).call(r,t,n,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[n,r]}=this;return[n*t,r*t]}setDims(t,n){const[r,a]=this.parentDimensions;this.div.style.width=`${(100*t/r).toFixed(2)}%`,ye(this,dO)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!ye(this,dO)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!ye(this,dO)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=ye(this,Cf))==null||t.finish()}async addEditToolbar(){return this._editToolbar||ye(this,mO)?this._editToolbar:(this._editToolbar=new IKe(this),this.div.append(this._editToolbar.render()),ye(this,Cf)&&await this._editToolbar.addAltText(ye(this,Cf)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=ye(this,Cf))==null||t.destroy())}addContainer(t){var r;const n=(r=this._editToolbar)==null?void 0:r.div;n?n.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){ye(this,Cf)||(f6e.initialize(jh._l10n),Ht(this,Cf,new f6e(this)),ye(this,cO)&&(ye(this,Cf).data=ye(this,cO),Ht(this,cO,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=ye(this,Cf))==null?void 0:t.data}set altTextData(t){ye(this,Cf)&&(ye(this,Cf).data=t)}get guessedAltText(){var t;return(t=ye(this,Cf))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=ye(this,Cf))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=ye(this,Cf))==null?void 0:n.serialize(t)}hasAltText(){return!!ye(this,Cf)&&!ye(this,Cf).isEmpty()}hasAltTextData(){var t;return((t=ye(this,Cf))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=ye(this,MV)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),ss(this,ud,ZKe).call(this);const[t,n]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*n/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/n).toFixed(2)}%`);const[r,a]=this.getInitialTranslation();return this.translate(r,a),p6e(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=Sb.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Ht(this,hO,!0),this._isDraggable){ss(this,ud,$es).call(this,t);return}ss(this,ud,YKe).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){ye(this,c4)&&clearTimeout(ye(this,c4)),Ht(this,c4,setTimeout(()=>{var t;Ht(this,c4,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,p=this.width*i,f=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-f+c,h+d+p+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+f+o,l-m+d+p+c];case 180:return[h-d-p+o,l-m+u+c,h-d+o,l-m+u+f+c];case 270:return[h-u-f+o,l-m-d-p+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){Ht(this,mO,!0)}disableEditMode(){Ht(this,mO,!1)}isInEditMode(){return ye(this,mO)}shouldGetKeyboardEvents(){return ye(this,uA)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){ss(this,ud,ZKe).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,n=null){Mp("An editor must be serializable")}static async deserialize(t,n,r){const a=new this.prototype.constructor({parent:n,id:n.getNextId(),uiManager:r});a.rotation=t.rotation,Ht(a,cO,t.accessibilityData);const[i,l]=a.pageDimensions,[o,c,d,u]=a.getRectInCurrentCoords(t.rect,l);return a.x=o/i,a.y=c/l,a.width=d/i,a.height=u/l,a}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=ye(this,lM))==null||t.abort(),Ht(this,lM,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),ye(this,c4)&&(clearTimeout(ye(this,c4)),Ht(this,c4,null)),ss(this,ud,HX).call(this),this.removeEditToolbar(),ye(this,z2)){for(const n of ye(this,z2).values())clearTimeout(n);Ht(this,z2,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(ss(this,ud,zes).call(this),ye(this,tv).classList.remove("hidden"),p6e(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),Ht(this,uO,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=ye(this,tv).children;if(!ye(this,$k)){Ht(this,$k,Array.from(n));const l=ss(this,ud,Ues).bind(this),o=ss(this,ud,qes).bind(this),c=this._uiManager._signal;for(const d of ye(this,$k)){const u=d.getAttribute("data-resizer-name");d.setAttribute("role","spinbutton"),d.addEventListener("keydown",l,{signal:c}),d.addEventListener("blur",o,{signal:c}),d.addEventListener("focus",ss(this,ud,Ves).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",jh._l10nResizer[u])}}const r=ye(this,$k)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(ye(this,$k).length/4);if(i!==a){if(ia)for(let o=0;o{var a,i;(a=this.div)!=null&&a.classList.contains("selectedEditor")&&((i=this._editToolbar)==null||i.show())});return}(n=this._editToolbar)==null||n.show(),(r=ye(this,Cf))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=ye(this,tv))==null||t.classList.add("hidden"),(n=this.div)==null||n.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(a=this._editToolbar)==null||a.hide(),(i=ye(this,Cf))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return ye(this,kne)}set isEditing(t){Ht(this,kne,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Ht(this,dO,!0);const r=t/n,{style:a}=this.div;a.aspectRatio=r,a.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){ye(this,z2)||Ht(this,z2,new Map);const{action:r}=t;let a=ye(this,z2).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),ye(this,z2).delete(r),ye(this,z2).size===0&&Ht(this,z2,null)},jh._telemetryTimeout),ye(this,z2).set(r,a);return}t.type||(t.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),Ht(this,MV,!1)}disable(){this.div&&(this.div.tabIndex=-1),Ht(this,MV,!0)}renderAnnotationElement(t){let n=t.container.querySelector(".annotationContent");if(!n)n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),t.container.prepend(n);else if(n.nodeName==="CANVAS"){const r=n;n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),r.before(n)}return n}resetAnnotationElement(t){const{firstChild:n}=t.container;(n==null?void 0:n.nodeName)==="DIV"&&n.classList.contains("annotationContent")&&n.remove()}};cO=new WeakMap,$k=new WeakMap,Cf=new WeakMap,MV=new WeakMap,dO=new WeakMap,tv=new WeakMap,uO=new WeakMap,lM=new WeakMap,Nne=new WeakMap,hO=new WeakMap,cM=new WeakMap,kne=new WeakMap,mO=new WeakMap,uA=new WeakMap,c4=new WeakMap,PV=new WeakMap,LV=new WeakMap,z2=new WeakMap,Sne=new WeakMap,oMe=new WeakMap,ud=new WeakSet,VKe=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},Cne=new WeakSet,HKe=function(t,n,r){switch(r){case 90:return[n,-t];case 180:return[-t,-n];case 270:return[-n,t];default:return[t,n]}},GKe=function(t){switch(t){case 90:{const[n,r]=this.pageDimensions;return[0,-n/r,r/n,0]}case 180:return[-1,0,0,-1];case 270:{const[n,r]=this.pageDimensions;return[0,n/r,-r/n,0]}default:return[1,0,0,1]}},zes=function(){if(ye(this,tv))return;Ht(this,tv,document.createElement("div")),ye(this,tv).classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],n=this._uiManager._signal;for(const r of t){const a=document.createElement("div");ye(this,tv).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",ss(this,ud,Bes).bind(this,r),{signal:n}),a.addEventListener("contextmenu",FN,{signal:n}),a.tabIndex=-1}this.div.prepend(ye(this,tv))},Bes=function(t,n){var f;n.preventDefault();const{isMac:r}=Sb.platform;if(n.button!==0||n.ctrlKey&&r)return;(f=ye(this,Cf))==null||f.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",ss(this,ud,KKe).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",FN,{signal:l});const o=this.x,c=this.y,d=this.width,u=this.height,h=this.parent.div.style.cursor,m=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;const p=()=>{var g;i.abort(),this.parent.togglePointerEvents(!0),(g=ye(this,Cf))==null||g.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,ss(this,ud,WKe).call(this,o,c,d,u)};window.addEventListener("pointerup",p,{signal:l}),window.addEventListener("blur",p,{signal:l})},WKe=function(t,n,r,a){const i=this.x,l=this.y,o=this.width,c=this.height;i===t&&l===n&&o===r&&c===a||this.addCommands({cmd:()=>{this.width=o,this.height=c,this.x=i,this.y=l;const[d,u]=this.parentDimensions;this.setDims(d*o,u*c),this.fixAndSetPosition()},undo:()=>{this.width=r,this.height=a,this.x=t,this.y=n;const[d,u]=this.parentDimensions;this.setDims(d*r,u*a),this.fixAndSetPosition()},mustExec:!0})},KKe=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=jh.MIN_SIZE/r,u=jh.MIN_SIZE/a,h=Z=>Math.round(Z*1e4)/1e4,m=ss(this,ud,GKe).call(this,this.rotation),p=(Z,oe)=>[m[0]*Z+m[2]*oe,m[1]*Z+m[3]*oe],f=ss(this,ud,GKe).call(this,360-this.rotation),g=(Z,oe)=>[f[0]*Z+f[2]*oe,f[1]*Z+f[3]*oe];let v,y,b=!1,w=!1;switch(t){case"topLeft":b=!0,v=(Z,oe)=>[0,0],y=(Z,oe)=>[Z,oe];break;case"topMiddle":v=(Z,oe)=>[Z/2,0],y=(Z,oe)=>[Z/2,oe];break;case"topRight":b=!0,v=(Z,oe)=>[Z,0],y=(Z,oe)=>[0,oe];break;case"middleRight":w=!0,v=(Z,oe)=>[Z,oe/2],y=(Z,oe)=>[0,oe/2];break;case"bottomRight":b=!0,v=(Z,oe)=>[Z,oe],y=(Z,oe)=>[0,0];break;case"bottomMiddle":v=(Z,oe)=>[Z/2,oe],y=(Z,oe)=>[Z/2,0];break;case"bottomLeft":b=!0,v=(Z,oe)=>[0,oe],y=(Z,oe)=>[Z,0];break;case"middleLeft":w=!0,v=(Z,oe)=>[0,oe/2],y=(Z,oe)=>[Z,oe/2];break}const S=v(o,c),C=y(o,c);let E=p(...C);const P=h(i+E[0]),M=h(l+E[1]);let I=1,D=1,[F,q]=this.screenToPageTranslation(n.movementX,n.movementY);if([F,q]=g(F/r,q/a),b){const Z=Math.hypot(o,c);I=D=Math.max(Math.min(Math.hypot(C[0]-S[0]-F,C[1]-S[1]-q)/Z,1/o,1/c),d/o,u/c)}else w?I=Math.max(d,Math.min(1,Math.abs(C[0]-S[0]-F)))/o:D=Math.max(u,Math.min(1,Math.abs(C[1]-S[1]-q)))/c;const G=h(o*I),V=h(c*D);E=p(...y(G,V));const H=P-E[0],K=M-E[1];this.width=G,this.height=V,this.x=H,this.y=K,this.setDims(r*G,a*V),this.fixAndSetPosition()},YKe=function(t){const{isMac:n}=Sb.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},$es=function(t){const{isSelected:n}=this;this._uiManager.setUpDragSession();const r=new AbortController,a=this._uiManager.combinedSignal(r);if(n){this.div.classList.add("moving"),Ht(this,PV,t.clientX),Ht(this,LV,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-ye(this,PV),d-ye(this,LV));Ht(this,PV,c),Ht(this,LV,d),this._uiManager.dragSelectedEditors(u,h)};window.addEventListener("pointermove",l,{passive:!0,capture:!0,signal:a})}const i=()=>{r.abort(),n&&this.div.classList.remove("moving"),Ht(this,hO,!1),this._uiManager.endDragSession()||ss(this,ud,YKe).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},ZKe=function(){if(ye(this,lM)||!this.div)return;Ht(this,lM,new AbortController);const t=this._uiManager.combinedSignal(ye(this,lM));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},Ues=function(t){jh._resizerKeyboardManager.exec(this,t)},qes=function(t){var n;ye(this,uA)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==ye(this,tv)&&ss(this,ud,HX).call(this)},Ves=function(t){Ht(this,Nne,ye(this,uA)?t:"")},XKe=function(t){if(ye(this,$k))for(const n of ye(this,$k))n.tabIndex=t},HX=function(){if(Ht(this,uA,!1),ss(this,ud,XKe).call(this,-1),ye(this,uO)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=ye(this,uO);ss(this,ud,WKe).call(this,t,n,r,a),Ht(this,uO,null)}},ps(jh,Cne),zr(jh,"_l10n",null),zr(jh,"_l10nResizer",null),zr(jh,"_borderLineWidth",-1),zr(jh,"_colorManager",new FKe),zr(jh,"_zIndex",1),zr(jh,"_telemetryTimeout",1e3);let $h=jh;class cHn extends $h{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const zSt=3285377520,A2=4294901760,A5=65535;class Hes{constructor(t){this.h1=t?t&4294967295:zSt,this.h2=t?t&4294967295:zSt}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let g=0,v=t.length;g>>8,n[r++]=y&255)}}else if(ArrayBuffer.isView(t))n=t.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const a=r>>2,i=r-a*4,l=new Uint32Array(n.buffer,0,a);let o=0,c=0,d=this.h1,u=this.h2;const h=3432918353,m=461845907,p=h&A5,f=m&A5;for(let g=0;g>>17,o=o*m&A2|o*f&A5,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[g],c=c*h&A2|c*p&A5,c=c<<15|c>>>17,c=c*m&A2|c*f&A5,u^=c,u=u<<13|u>>>19,u=u*5+3864292196);switch(o=0,i){case 3:o^=n[a*4+2]<<16;case 2:o^=n[a*4+1]<<8;case 1:o^=n[a*4],o=o*h&A2|o*p&A5,o=o<<15|o>>>17,o=o*m&A2|o*f&A5,a&1?d^=o:u^=o}this.h1=d,this.h2=u}hexdigest(){let t=this.h1,n=this.h2;return t^=n>>>1,t=t*3981806797&A2|t*36045&A5,n=n*4283543511&A2|((n<<16|t>>>16)*2950163797&A2)>>>16,t^=n>>>1,t=t*444984403&A2|t*60499&A5,n=n*3301882366&A2|((n<<16|t>>>16)*3120437893&A2)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const QKe=Object.freeze({map:null,hash:"",transfer:void 0});var pO,fO,l0,lMe,Ges;class _at{constructor(){ps(this,lMe);ps(this,pO,!1);ps(this,fO,null);ps(this,l0,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=ye(this,l0).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return ye(this,l0).get(t)}remove(t){if(ye(this,l0).delete(t),ye(this,l0).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of ye(this,l0).values())if(n instanceof $h)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=ye(this,l0).get(t);let a=!1;if(r!==void 0)for(const[i,l]of Object.entries(n))r[i]!==l&&(a=!0,r[i]=l);else a=!0,ye(this,l0).set(t,n);a&&ss(this,lMe,Ges).call(this),n instanceof $h&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return ye(this,l0).has(t)}getAll(){return ye(this,l0).size>0?fat(ye(this,l0)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return ye(this,l0).size}resetModified(){ye(this,pO)&&(Ht(this,pO,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Wes(this)}get serializable(){if(ye(this,l0).size===0)return QKe;const t=new Map,n=new Hes,r=[],a=Object.create(null);let i=!1;for(const[l,o]of ye(this,l0)){const c=o instanceof $h?o.serialize(!1,a):o;c&&(t.set(l,c),n.update(`${l}:${JSON.stringify(c)}`),i||(i=!!c.bitmap))}if(i)for(const l of t.values())l.bitmap&&r.push(l.bitmap);return t.size>0?{map:t,hash:n.hexdigest(),transfer:r}:QKe}get editorStats(){let t=null;const n=new Map;for(const r of ye(this,l0).values()){if(!(r instanceof $h))continue;const a=r.telemetryFinalData;if(!a)continue;const{type:i}=a;n.has(i)||n.set(i,Object.getPrototypeOf(r).constructor),t||(t=Object.create(null));const l=t[i]||(t[i]=new Map);for(const[o,c]of Object.entries(a)){if(o==="type")continue;let d=l.get(o);d||(d=new Map,l.set(o,d));const u=d.get(c)??0;d.set(c,u+1)}}for(const[r,a]of n)t[r]=a.computeTelemetryFinalData(t[r]);return t}resetModifiedIds(){Ht(this,fO,null)}get modifiedIds(){if(ye(this,fO))return ye(this,fO);const t=[];for(const n of ye(this,l0).values())!(n instanceof $h)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Ht(this,fO,{ids:new Set(t),hash:t.join(",")})}}pO=new WeakMap,fO=new WeakMap,l0=new WeakMap,lMe=new WeakSet,Ges=function(){ye(this,pO)||(Ht(this,pO,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var Ane;class Wes extends _at{constructor(n){super();ps(this,Ane);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Ht(this,Ane,{map:l,hash:a,transfer:i})}get print(){Mp("Should not call PrintAnnotationStorage.print")}get serializable(){return ye(this,Ane)}get modifiedIds(){return gu(this,"modifiedIds",{ids:new Set,hash:""})}}Ane=new WeakMap;var IV;class dHn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){ps(this,IV,new Set);this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const n=this.styleElement.sheet;n.insertRule(t,n.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),ye(this,IV).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||ye(this,IV).has(t.loadedName))){if(jy(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:r,src:a,style:i}=t,l=new FontFace(r,a,i);this.addNativeFontFace(l);try{await l.load(),ye(this,IV).add(r),n==null||n(t)}catch{jd(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}Mp("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const r=t.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(a){throw jd(`Failed to load font '${r.family}': '${a}'.`),t.disableFontFace=!0,a}}return}const n=t.createFontFaceRule();if(n){if(this.insertRule(n),this.isSyncFontLoadingSupported)return;await new Promise(r=>{const a=this._queueLoadingCallback(r);this._prepareFontLoadEvent(t,a)})}}get isFontLoadingAPISupported(){var n;const t=!!((n=this._document)!=null&&n.fonts);return gu(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(u1||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),gu(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(jy(!a.done,"completeRequest() cannot be called twice."),a.done=!0;r.length>0&&r[0].done;){const i=r.shift();setTimeout(i.callback,0)}}const{loadingRequests:r}=this,a={done:!1,complete:n,callback:t};return r.push(a),a}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return gu(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(S,C){return S.charCodeAt(C)<<24|S.charCodeAt(C+1)<<16|S.charCodeAt(C+2)<<8|S.charCodeAt(C+3)&255}function a(S,C,E,P){const M=S.substring(0,C),I=S.substring(C+E);return M+P+I}let i,l;const o=this._document.createElement("canvas");o.width=1,o.height=1;const c=o.getContext("2d");let d=0;function u(S,C){if(++d>30){jd("Load test font never loaded."),C();return}if(c.font="30px "+S,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(u.bind(null,S,C))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const f=16,g=1482184792;let v=r(m,f);for(i=0,l=h.length-3;i{w.remove(),n.complete()})}}IV=new WeakMap;class uHn{constructor(t,{disableFontFace:n=!1,inspectFont:r=null}){this.compiledGlyphs=Object.create(null);for(const a in t)this[a]=t[a];this.disableFontFace=n===!0,this._inspectFont=r}createNativeFontFace(){var n;if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const r={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(r.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,r)}return(n=this._inspectFont)==null||n.call(this,this),t}createFontFaceRule(){var r;if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${eHn(this.data)});`;let n;if(!this.cssFontInfo)n=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let a=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(a+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),n=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${a}src:${t}}`}return(r=this._inspectFont)==null||r.call(this,this,t),n}getPathGenerator(t,n){if(this.compiledGlyphs[n]!==void 0)return this.compiledGlyphs[n];let r;try{r=t.get(this.loadedName+"_path_"+n)}catch(i){jd(`getPathGenerator - ignoring character: "${i}".`)}if(!Array.isArray(r)||r.length===0)return this.compiledGlyphs[n]=function(i,l){};const a=[];for(let i=0,l=r.length;ip.bezierCurveTo(o,c,d,u,h,m)),i+=6}break;case E3.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case E3.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case E3.QUADRATIC_CURVE_TO:{const[o,c,d,u]=r.slice(i,i+4);a.push(h=>h.quadraticCurveTo(o,c,d,u)),i+=4}break;case E3.RESTORE:a.push(o=>o.restore());break;case E3.SAVE:a.push(o=>o.save());break;case E3.SCALE:jy(a.length===2,"Scale command is only valid at the third position.");break;case E3.TRANSFORM:{const[o,c,d,u,h,m]=r.slice(i,i+6);a.push(p=>p.transform(o,c,d,u,h,m)),i+=6}break;case E3.TRANSLATE:{const[o,c]=r.slice(i,i+2);a.push(d=>d.translate(o,c)),i+=2}break}return this.compiledGlyphs[n]=function(l,o){a[0](l),a[1](l),l.scale(o,-o);for(let c=2,d=a.length;c({cMapData:r,isCompressed:this.isCompressed})).catch(r=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${n}`)})}async _fetch(t){Mp("Abstract method `_fetch` called.")}}class Zes extends Yes{async _fetch(t){const n=await H8e(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):V8e(n)}}class Xes{addFilter(t){return"none"}addHCMFilter(t,n){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,n,r,a,i){return"none"}destroy(t=!1){}}var xO,gO,d4,hA,t1,cMe,yO,co,Qv,L$,I$,kCe,D$,Qes,JKe,R$,GX,WX,eYe,KX;class mHn extends Xes{constructor({docId:n,ownerDocument:r=globalThis.document}){super();ps(this,co);ps(this,xO);ps(this,gO);ps(this,d4);ps(this,hA);ps(this,t1);ps(this,cMe);ps(this,yO,0);Ht(this,hA,n),Ht(this,t1,r)}addFilter(n){if(!n)return"none";let r=ye(this,co,Qv).get(n);if(r)return r;const[a,i,l]=ss(this,co,kCe).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=ye(this,co,Qv).get(o),r)return ye(this,co,Qv).set(n,r),r;const c=`g_${ye(this,hA)}_transfer_map_${Jy(this,yO)._++}`,d=ss(this,co,D$).call(this,c);ye(this,co,Qv).set(n,d),ye(this,co,Qv).set(o,d);const u=ss(this,co,R$).call(this,c);return ss(this,co,WX).call(this,a,i,l,u),d}addHCMFilter(n,r){var f;const a=`${n}-${r}`,i="base";let l=ye(this,co,L$).get(i);if((l==null?void 0:l.key)===a||(l?((f=l.filter)==null||f.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},ye(this,co,L$).set(i,l)),!n||!r))return l.url;const o=ss(this,co,KX).call(this,n);n=Vo.makeHexColor(...o);const c=ss(this,co,KX).call(this,r);if(r=Vo.makeHexColor(...c),ye(this,co,I$).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let g=0;g<=255;g++){const v=g/255;d[g]=v<=.03928?v/12.92:((v+.055)/1.055)**2.4}const u=d.join(","),h=`g_${ye(this,hA)}_hcm_filter`,m=l.filter=ss(this,co,R$).call(this,h);ss(this,co,WX).call(this,u,u,u,m),ss(this,co,JKe).call(this,m);const p=(g,v)=>{const y=o[g]/255,b=c[g]/255,w=new Array(v+1);for(let S=0;S<=v;S++)w[S]=y+S/v*(b-y);return w.join(",")};return ss(this,co,WX).call(this,p(0,5),p(1,5),p(2,5),m),l.url=ss(this,co,D$).call(this,h),l.url}addAlphaFilter(n){let r=ye(this,co,Qv).get(n);if(r)return r;const[a]=ss(this,co,kCe).call(this,[n]),i=`alpha_${a}`;if(r=ye(this,co,Qv).get(i),r)return ye(this,co,Qv).set(n,r),r;const l=`g_${ye(this,hA)}_alpha_map_${Jy(this,yO)._++}`,o=ss(this,co,D$).call(this,l);ye(this,co,Qv).set(n,o),ye(this,co,Qv).set(i,o);const c=ss(this,co,R$).call(this,l);return ss(this,co,eYe).call(this,a,c),o}addLuminosityFilter(n){let r=ye(this,co,Qv).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=ss(this,co,kCe).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=ye(this,co,Qv).get(i),r)return ye(this,co,Qv).set(n,r),r;const l=`g_${ye(this,hA)}_luminosity_map_${Jy(this,yO)._++}`,o=ss(this,co,D$).call(this,l);ye(this,co,Qv).set(n,o),ye(this,co,Qv).set(i,o);const c=ss(this,co,R$).call(this,l);return ss(this,co,Qes).call(this,c),n&&ss(this,co,eYe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=ye(this,co,L$).get(n);if((c==null?void 0:c.key)===o||(c?((b=c.filter)==null||b.remove(),c.key=o,c.url="none",c.filter=null):(c={key:o,url:"none",filter:null},ye(this,co,L$).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(ss(this,co,KX).bind(this));let h=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),m=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[p,f]=[i,l].map(ss(this,co,KX).bind(this));m{const E=new Array(256),P=(m-h)/C,M=w/255,I=(S-w)/(255*C);let D=0;for(let F=0;F<=C;F++){const q=Math.round(h+F*P),G=M+F*I;for(let V=D;V<=q;V++)E[V]=G;D=q+1}for(let F=D;F<256;F++)E[F]=E[D-1];return E.join(",")},v=`g_${ye(this,hA)}_hcm_${n}_filter`,y=c.filter=ss(this,co,R$).call(this,v);return ss(this,co,JKe).call(this,y),ss(this,co,WX).call(this,g(p[0],f[0],5),g(p[1],f[1],5),g(p[2],f[2],5),y),c.url=ss(this,co,D$).call(this,v),c.url}destroy(n=!1){n&&ye(this,co,L$).size!==0||(ye(this,d4)&&(ye(this,d4).parentNode.parentNode.remove(),Ht(this,d4,null)),ye(this,gO)&&(ye(this,gO).clear(),Ht(this,gO,null)),Ht(this,yO,0))}}xO=new WeakMap,gO=new WeakMap,d4=new WeakMap,hA=new WeakMap,t1=new WeakMap,cMe=new WeakMap,yO=new WeakMap,co=new WeakSet,Qv=function(){return ye(this,gO)||Ht(this,gO,new Map)},L$=function(){return ye(this,cMe)||Ht(this,cMe,new Map)},I$=function(){if(!ye(this,d4)){const n=ye(this,t1).createElement("div"),{style:r}=n;r.visibility="hidden",r.contain="strict",r.width=r.height=0,r.position="absolute",r.top=r.left=0,r.zIndex=-1;const a=ye(this,t1).createElementNS($3,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Ht(this,d4,ye(this,t1).createElementNS($3,"defs")),n.append(a),a.append(ye(this,d4)),ye(this,t1).body.append(n)}return ye(this,d4)},kCe=function(n){if(n.length===1){const d=n[0],u=new Array(256);for(let m=0;m<256;m++)u[m]=d[m]/255;const h=u.join(",");return[h,h,h]}const[r,a,i]=n,l=new Array(256),o=new Array(256),c=new Array(256);for(let d=0;d<256;d++)l[d]=r[d]/255,o[d]=a[d]/255,c[d]=i[d]/255;return[l.join(","),o.join(","),c.join(",")]},D$=function(n){if(ye(this,xO)===void 0){Ht(this,xO,"");const r=ye(this,t1).URL;r!==ye(this,t1).baseURI&&(G8e(r)?jd('#createUrl: ignore "data:"-URL for performance reasons.'):Ht(this,xO,r.split("#",1)[0]))}return`url(${ye(this,xO)}#${n})`},Qes=function(n){const r=ye(this,t1).createElementNS($3,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),n.append(r)},JKe=function(n){const r=ye(this,t1).createElementNS($3,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),n.append(r)},R$=function(n){const r=ye(this,t1).createElementNS($3,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),ye(this,co,I$).append(r),r},GX=function(n,r,a){const i=ye(this,t1).createElementNS($3,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},WX=function(n,r,a,i){const l=ye(this,t1).createElementNS($3,"feComponentTransfer");i.append(l),ss(this,co,GX).call(this,l,"feFuncR",n),ss(this,co,GX).call(this,l,"feFuncG",r),ss(this,co,GX).call(this,l,"feFuncB",a)},eYe=function(n,r){const a=ye(this,t1).createElementNS($3,"feComponentTransfer");r.append(a),ss(this,co,GX).call(this,a,"feFuncA",n)},KX=function(n){return ye(this,co,I$).style.color=n,bat(getComputedStyle(ye(this,co,I$)).getPropertyValue("color"))};class Jes{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const n=`${this.baseUrl}${t}`;return this._fetch(n).catch(r=>{throw new Error(`Unable to load font data at: ${n}`)})}async _fetch(t){Mp("Abstract method `_fetch` called.")}}class ets extends Jes{async _fetch(t){const n=await H8e(t,"arraybuffer");return new Uint8Array(n)}}if(u1){var tYe=Promise.withResolvers(),vee=null;(async()=>{const t=await Fa(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await Fa(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await Fa(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await Fa(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let i,l;return new Map(Object.entries({fs:t,http:n,https:r,url:a,canvas:i,path2d:l}))})().then(t=>{vee=t,tYe.resolve()},t=>{jd(`loadPackages: ${t}`),vee=new Map,tYe.resolve()})}class nL{static get promise(){return tYe.promise}static get(t){return vee==null?void 0:vee.get(t)}}async function tts(s){const n=await nL.get("fs").promises.readFile(s);return new Uint8Array(n)}class pHn extends Xes{}class fHn extends Kes{_createCanvas(t,n){return nL.get("canvas").createCanvas(t,n)}}class xHn extends Yes{async _fetch(t){return tts(t)}}class gHn extends Jes{async _fetch(t){return tts(t)}}const db={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function sYe(s,t){if(!t)return;const n=t[2]-t[0],r=t[3]-t[1],a=new Path2D;a.rect(t[0],t[1],n,r),s.clip(a)}class wat{getPattern(){Mp("Abstract method `getPattern` called.")}}class yHn extends wat{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let n;this._type==="axial"?n=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(n=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const r of this._colorStops)n.addColorStop(r[0],r[1]);return n}getPattern(t,n,r,a){let i;if(a===db.STROKE||a===db.FILL){const l=n.current.getClippedPathBoundingBox(a,Ef(t))||[0,0,0,0],o=Math.ceil(l[2]-l[0])||1,c=Math.ceil(l[3]-l[1])||1,d=n.cachedCanvases.getCanvas("pattern",o,c),u=d.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-l[0],-l[1]),r=Vo.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),sYe(u,this._bbox),u.fillStyle=this._createGradient(u),u.fill(),i=t.createPattern(d.canvas,"no-repeat");const h=new DOMMatrix(r);i.setTransform(h)}else sYe(t,this._bbox),i=this._createGradient(t);return i}}function mBe(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const p=(c[n]+t.offsetX)*t.scaleX,f=(c[n+1]+t.offsetY)*t.scaleY,g=(c[r]+t.offsetX)*t.scaleX,v=(c[r+1]+t.offsetY)*t.scaleY,y=(c[a]+t.offsetX)*t.scaleX,b=(c[a+1]+t.offsetY)*t.scaleY;if(f>=b)return;const w=d[i],S=d[i+1],C=d[i+2],E=d[l],P=d[l+1],M=d[l+2],I=d[o],D=d[o+1],F=d[o+2],q=Math.round(f),G=Math.round(b);let V,H,K,Z,oe,re,ae,J;for(let te=q;te<=G;te++){if(teb?ge=1:v===b?ge=0:ge=(v-te)/(v-b),V=g-(g-y)*ge,H=E-(E-I)*ge,K=P-(P-D)*ge,Z=M-(M-F)*ge}let ce;teb?ce=1:ce=(f-te)/(f-b),oe=p-(p-y)*ce,re=w-(w-I)*ce,ae=S-(S-D)*ce,J=C-(C-F)*ce;const ve=Math.round(Math.min(V,oe)),me=Math.round(Math.max(V,oe));let he=h*te+ve*4;for(let ge=ve;ge<=me;ge++)ce=(V-ge)/(V-oe),ce<0?ce=0:ce>1&&(ce=1),u[he++]=H-(H-re)*ce|0,u[he++]=K-(K-ae)*ce|0,u[he++]=Z-(Z-J)*ce|0,u[he++]=255}}function vHn(s,t,n){const r=t.coords,a=t.colors;let i,l;switch(t.type){case"lattice":const o=t.verticesPerRow,c=Math.floor(r.length/o)-1,d=o-1;for(i=0;i=D?S=c:E=!0,I>=F?C=d:P=!0;const q=this.getSizeAndScale(S,this.ctx.canvas.width,b),G=this.getSizeAndScale(C,this.ctx.canvas.height,w),V=t.cachedCanvases.getCanvas("pattern",q.size,G.size),H=V.context,K=o.createCanvasGraphics(H);if(K.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(K,a,l),H.translate(-q.scale*u,-G.scale*h),K.transform(q.scale,0,0,G.scale,0,0),H.save(),this.clipBbox(K,u,h,m,p),K.baseTransform=Ef(K.ctx),K.executeOperatorList(r),K.endDrawing(),H.restore(),E||P){const Z=V.canvas;E&&(S=c),P&&(C=d);const oe=this.getSizeAndScale(S,this.ctx.canvas.width,b),re=this.getSizeAndScale(C,this.ctx.canvas.height,w),ae=oe.size,J=re.size,te=t.cachedCanvases.getCanvas("pattern-workaround",ae,J),ce=te.context,ve=E?Math.floor(f/c):0,me=P?Math.floor(g/d):0;for(let he=0;he<=ve;he++)for(let ge=0;ge<=me;ge++)ce.drawImage(Z,ae*he,J*ge,ae,J,0,0,ae,J);return{canvas:te.canvas,scaleX:oe.scale,scaleY:re.scale,offsetX:u,offsetY:h}}return{canvas:V.canvas,scaleX:q.scale,scaleY:G.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(dMe.MAX_PATTERN_SIZE,n);let i=Math.ceil(t*r);return i>=a?i=a:r=i/t,{scale:r,size:i}}clipBbox(t,n,r,a,i){const l=a-n,o=i-r;t.ctx.rect(n,r,l,o),t.current.updateRectMinMax(Ef(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case BSt.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case BSt.UNCOLORED:const o=Vo.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new WVn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==db.SHADING&&(i=Vo.transform(i,n.baseTransform),this.matrix&&(i=Vo.transform(i,this.matrix)));const l=this.createPatternCanvas(n);let o=new DOMMatrix(i);o=o.translate(l.offsetX,l.offsetY),o=o.scale(1/l.scaleX,1/l.scaleY);const c=t.createPattern(l.canvas,"repeat");return c.setTransform(o),c}};zr(dMe,"MAX_PATTERN_SIZE",3e3);let nYe=dMe;function jHn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=Sb.isLittleEndian?4278190080:255,[c,d]=l?[i,o]:[o,i],u=r>>3,h=r&7,m=s.length;n=new Uint32Array(n.buffer);let p=0;for(let f=0;f{s.save=s.__originalSave,s.restore=s.__originalRestore,s.rotate=s.__originalRotate,s.scale=s.__originalScale,s.translate=s.__originalTranslate,s.transform=s.__originalTransform,s.setTransform=s.__originalSetTransform,s.resetTransform=s.__originalResetTransform,s.clip=s.__originalClip,s.moveTo=s.__originalMoveTo,s.lineTo=s.__originalLineTo,s.bezierCurveTo=s.__originalBezierCurveTo,s.rect=s.__originalRect,s.closePath=s.__originalClosePath,s.beginPath=s.__originalBeginPath,delete s._removeMirroring},s.save=function(){t.save(),this.__originalSave()},s.restore=function(){t.restore(),this.__originalRestore()},s.translate=function(r,a){t.translate(r,a),this.__originalTranslate(r,a)},s.scale=function(r,a){t.scale(r,a),this.__originalScale(r,a)},s.transform=function(r,a,i,l,o,c){t.transform(r,a,i,l,o,c),this.__originalTransform(r,a,i,l,o,c)},s.setTransform=function(r,a,i,l,o,c){t.setTransform(r,a,i,l,o,c),this.__originalSetTransform(r,a,i,l,o,c)},s.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},s.rotate=function(r){t.rotate(r),this.__originalRotate(r)},s.clip=function(r){t.clip(r),this.__originalClip(r)},s.moveTo=function(n,r){t.moveTo(n,r),this.__originalMoveTo(n,r)},s.lineTo=function(n,r){t.lineTo(n,r),this.__originalLineTo(n,r)},s.bezierCurveTo=function(n,r,a,i,l,o){t.bezierCurveTo(n,r,a,i,l,o),this.__originalBezierCurveTo(n,r,a,i,l,o)},s.rect=function(n,r,a,i){t.rect(n,r,a,i),this.__originalRect(n,r,a,i)},s.closePath=function(){t.closePath(),this.__originalClosePath()},s.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class SHn{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,n,r){let a;return this.cache[t]!==void 0?(a=this.cache[t],this.canvasFactory.reset(a,n,r)):(a=this.canvasFactory.create(n,r),this.cache[t]=a),a}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const n=this.cache[t];this.canvasFactory.destroy(n),delete this.cache[t]}}}function vde(s,t,n,r,a,i,l,o,c,d){const[u,h,m,p,f,g]=Ef(s);if(h===0&&m===0){const b=l*u+f,w=Math.round(b),S=o*p+g,C=Math.round(S),E=(l+c)*u+f,P=Math.abs(Math.round(E)-w)||1,M=(o+d)*p+g,I=Math.abs(Math.round(M)-C)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),w,C),s.drawImage(t,n,r,a,i,0,0,P,I),s.setTransform(u,h,m,p,f,g),[P,I]}if(u===0&&p===0){const b=o*m+f,w=Math.round(b),S=l*h+g,C=Math.round(S),E=(o+d)*m+f,P=Math.abs(Math.round(E)-w)||1,M=(l+c)*h+g,I=Math.abs(Math.round(M)-C)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,w,C),s.drawImage(t,n,r,a,i,0,0,I,P),s.setTransform(u,h,m,p,f,g),[I,P]}s.drawImage(t,n,r,a,i,l,o,c,d);const v=Math.hypot(u,h),y=Math.hypot(m,p);return[v*c,y*d]}function CHn(s){const{width:t,height:n}=s;if(t>VSt||n>VSt)return null;const r=1e3,a=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1;let l=new Uint8Array(i*(n+1)),o,c,d;const u=t+7&-8;let h=new Uint8Array(u*n),m=0;for(const y of s.data){let b=128;for(;b>0;)h[m++]=y&b?0:255,b>>=1}let p=0;for(m=0,h[m]!==0&&(l[0]=1,++p),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[y]&&(l[d+c]=a[y],++p),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++p),p>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++p),c=1;cr)return null;const f=new Int32Array([0,i,-1,0,-i,0,0,0,1]),g=new Path2D;for(o=0;p&&o<=n;o++){let y=o*i;const b=y+t;for(;y>4,l[y]&=S>>2|S<<2),g.lineTo(y%i,y/i|0),l[y]||--p}while(w!==y);--o}return h=null,l=null,function(y){y.save(),y.scale(1/t,-1/n),y.translate(0,-n),y.fill(g),y.beginPath(),y.restore()}}class HSt{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=yes,this.textMatrixScale=1,this.fontMatrix=EKe,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Xv.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,n])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,n){this.x=t,this.y=n}updatePathMinMax(t,n,r){[n,r]=Vo.applyTransform([n,r],t),this.minX=Math.min(this.minX,n),this.minY=Math.min(this.minY,r),this.maxX=Math.max(this.maxX,n),this.maxY=Math.max(this.maxY,r)}updateRectMinMax(t,n){const r=Vo.applyTransform(n,t),a=Vo.applyTransform(n.slice(2),t),i=Vo.applyTransform([n[0],n[3]],t),l=Vo.applyTransform([n[2],n[1]],t);this.minX=Math.min(this.minX,r[0],a[0],i[0],l[0]),this.minY=Math.min(this.minY,r[1],a[1],i[1],l[1]),this.maxX=Math.max(this.maxX,r[0],a[0],i[0],l[0]),this.maxY=Math.max(this.maxY,r[1],a[1],i[1],l[1])}updateScalingPathMinMax(t,n){Vo.scaleMinMax(t,n),this.minX=Math.min(this.minX,n[0]),this.minY=Math.min(this.minY,n[1]),this.maxX=Math.max(this.maxX,n[2]),this.maxY=Math.max(this.maxY,n[3])}updateCurvePathMinMax(t,n,r,a,i,l,o,c,d,u){const h=Vo.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=db.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===db.STROKE){n||Mp("Stroke bounding box must include transform.");const a=Vo.singularValueDecompose2dScale(n),i=a[0]*this.lineWidth/2,l=a[1]*this.lineWidth/2;r[0]-=i,r[1]-=l,r[2]+=i,r[3]+=l}return r}updateClipFromPath(){const t=Vo.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=db.FILL,n=null){return Vo.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function GSt(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%y_,i=(n-a)/y_,l=a===0?i:i+1,o=s.createImageData(r,y_);let c=0,d;const u=t.data,h=o.data;let m,p,f,g;if(t.kind===yCe.GRAYSCALE_1BPP){const v=u.byteLength,y=new Uint32Array(h.buffer,0,h.byteLength>>2),b=y.length,w=r+7>>3,S=4294967295,C=Sb.isLittleEndian?4278190080:255;for(m=0;mw?r:E*8-7,I=M&-8;let D=0,F=0;for(;P>=1}for(;d=i&&(f=a,g=r*f),d=0,p=g;p--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*y_)}else throw new Error(`bad image kind: ${t.kind}`)}function WSt(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%y_,i=(n-a)/y_,l=a===0?i:i+1,o=s.createImageData(r,y_);let c=0;const d=t.data,u=o.data;for(let h=0;hqSt&&typeof r=="function",u=d?Date.now()+NHn:0;let h=0;const m=this.commonObjs,p=this.objs;let f;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(f=l[o],f!==Ik.dependency)this[f].apply(this,i[o]);else for(const g of i[o]){const v=g.startsWith("g_")?m:p;if(!v.has(g))return v.get(g,r),o}if(o++,o===c)return o;if(d&&++h>qSt){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){ss(this,dL,rYe).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const n of t.values())typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&(n.width=n.height=0);t.clear()}this._cachedBitmapsMap.clear(),ss(this,dL,aYe).call(this)}_scaleImage(t,n){const r=t.width??t.displayWidth,a=t.height??t.displayHeight;let i=Math.max(Math.hypot(n[0],n[1]),1),l=Math.max(Math.hypot(n[2],n[3]),1),o=r,c=a,d="prescale1",u,h;for(;i>2&&o>1||l>2&&c>1;){let m=o,p=c;i>2&&o>1&&(m=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/m),l>2&&c>1&&(p=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/p),u=this.cachedCanvases.getCanvas(d,m,p),h=u.context,h.clearRect(0,0,m,p),h.drawImage(t,0,0,o,c,0,0,m,p),t=u.canvas,o=m,c=p,d=d==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:c}}_createMaskCanvas(t){const n=this.ctx,{width:r,height:a}=t,i=this.current.fillColor,l=this.current.patternFill,o=Ef(n);let c,d,u,h;if((t.bitmap||t.data)&&t.count>1){const M=t.bitmap||t.data.buffer;d=JSON.stringify(l?o:[o.slice(0,4),i]),c=this._cachedBitmapsMap.get(M),c||(c=new Map,this._cachedBitmapsMap.set(M,c));const I=c.get(d);if(I&&!l){const D=Math.round(Math.min(o[0],o[2])+o[4]),F=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:I,offsetX:D,offsetY:F}}u=I}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),WSt(h.context,t));let m=Vo.transform(o,[1/r,0,0,-1/a,0,0]);m=Vo.transform(m,[1,0,0,1,0,-a]);const[p,f,g,v]=Vo.getAxialAlignedBoundingBox([0,0,r,a],m),y=Math.round(g-p)||1,b=Math.round(v-f)||1,w=this.cachedCanvases.getCanvas("fillCanvas",y,b),S=w.context,C=p,E=f;S.translate(-C,-E),S.transform(...m),u||(u=this._scaleImage(h.canvas,T3(S)),u=u.img,c&&l&&c.set(d,u)),S.imageSmoothingEnabled=KSt(Ef(S),t.interpolate),vde(S,u,0,0,u.width,u.height,0,0,r,a),S.globalCompositeOperation="source-in";const P=Vo.transform(T3(S),[1,0,0,1,-C,-E]);return S.fillStyle=l?i.getPattern(n,this,P,db.FILL):i,S.fillRect(0,0,r,a),c&&!l&&(this.cachedCanvases.delete("fillCanvas"),c.set(d,w.canvas)),{canvas:w.canvas,offsetX:Math.round(C),offsetY:Math.round(E)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=AHn[t]}setLineJoin(t){this.ctx.lineJoin=EHn[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,n){const r=this.ctx;r.setLineDash!==void 0&&(r.setLineDash(t),r.lineDashOffset=n)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[n,r]of t)switch(n){case"LW":this.setLineWidth(r);break;case"LC":this.setLineCap(r);break;case"LJ":this.setLineJoin(r);break;case"ML":this.setMiterLimit(r);break;case"D":this.setDash(r[0],r[1]);break;case"RI":this.setRenderingIntent(r);break;case"FL":this.setFlatness(r);break;case"Font":this.setFont(r[0],r[1]);break;case"CA":this.current.strokeAlpha=r;break;case"ca":this.current.fillAlpha=r,this.ctx.globalAlpha=r;break;case"BM":this.ctx.globalCompositeOperation=r;break;case"SMask":this.current.activeSMask=r?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(r);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,n=this.ctx.canvas.height,r="smaskGroupAt"+this.groupLevel,a=this.cachedCanvases.getCanvas(r,t,n);this.suspendedCtx=this.ctx,this.ctx=a.context;const i=this.ctx;i.setTransform(...Ef(this.suspendedCtx)),TZ(this.suspendedCtx,i),kHn(i,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),TZ(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,p=c-u,f=d-h;if(l){const v=Vo.makeHexColor(...l);if(p<0||f<0||p+r>m.width||f+a>m.height){const y=this.cachedCanvases.getCanvas("maskExtension",r,a),b=y.context;b.drawImage(m,-p,-f),b.globalCompositeOperation="destination-atop",b.fillStyle=v,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=y.canvas,p=f=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const y=new Path2D;y.rect(p,f,r,a),t.clip(y),t.globalCompositeOperation="destination-atop",t.fillStyle=v,t.fillRect(p,f,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const g=new Path2D;g.rect(c,d,r,a),n.clip(g),n.globalCompositeOperation="destination-in",n.drawImage(m,p,f,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(TZ(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),TZ(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,n,r,a,i,l){this.ctx.transform(t,n,r,a,i,l),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,n,r){const a=this.ctx,i=this.current;let l=i.x,o=i.y,c,d;const u=Ef(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let p=0,f=0,g=t.length;pUSt&&(d=USt),this.current.fontSizeScale=n/d,this.ctx.font=`${c} ${o} ${d}px ${l}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,n){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n}setLeadingMoveText(t,n){this.setLeading(-n),this.moveText(t,n)}setTextMatrix(t,n,r,a,i,l){this.current.textMatrix=[t,n,r,a,i,l],this.current.textMatrixScale=Math.hypot(t,n),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,n,r,a){const i=this.ctx,l=this.current,o=l.font,c=l.textRenderingMode,d=l.fontSize/l.fontSizeScale,u=c&Xv.FILL_STROKE_MASK,h=!!(c&Xv.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let p;(o.disableFontFace||h||m)&&(p=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),p(i,d),a&&i.setTransform(...a),(u===Xv.FILL||u===Xv.FILL_STROKE)&&i.fill(),(u===Xv.STROKE||u===Xv.FILL_STROKE)&&i.stroke(),i.restore()):((u===Xv.FILL||u===Xv.FILL_STROKE)&&i.fillText(t,n,r),(u===Xv.STROKE||u===Xv.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:Ef(i),x:n,y:r,fontSize:d,addToPath:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=3;a0&&n[a]<255){r=!0;break}return gu(this,"isFontSubpixelAAEnabled",r)}showText(t){const n=this.current,r=n.font;if(r.isType3Font)return this.showType3Text(t);const a=n.fontSize;if(a===0)return;const i=this.ctx,l=n.fontSizeScale,o=n.charSpacing,c=n.wordSpacing,d=n.fontDirection,u=n.textHScale*d,h=t.length,m=r.vertical,p=m?1:-1,f=r.defaultVMetrics,g=a*n.fontMatrix[0],v=n.textRenderingMode===Xv.FILL&&!r.disableFontFace&&!n.patternFill;i.save(),i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),d>0?i.scale(u,-1):i.scale(u,1);let y;if(n.patternFill){i.save();const E=n.fillColor.getPattern(i,this,T3(i),db.FILL);y=Ef(i),i.restore(),i.fillStyle=E}let b=n.lineWidth;const w=n.textMatrixScale;if(w===0||b===0){const E=n.textRenderingMode&Xv.FILL_STROKE_MASK;(E===Xv.STROKE||E===Xv.FILL_STROKE)&&(b=this.getSinglePixelWidth())}else b/=w;if(l!==1&&(i.scale(l,l),b/=l),i.lineWidth=b,r.isInvalidPDFjsFont){const E=[];let P=0;for(const M of t)E.push(M.unicode),P+=M.width;i.fillText(E.join(""),0,0),n.x+=P*g*u,i.restore(),this.compose();return}let S=0,C;for(C=0;C0){const H=i.measureText(I).width*1e3/a*l;if(Gnew Rot(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new nYe(t,r,this.ctx,i,a)}else n=this._getPattern(t[1],t[2]);return n}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,n,r){this.ctx.strokeStyle=this.current.strokeColor=Vo.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=Vo.makeHexColor(t,n,r),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,n=null){let r;return this.cachedPatterns.has(t)?r=this.cachedPatterns.get(t):(r=wHn(this.getObject(t)),this.cachedPatterns.set(t,r)),n&&(r.matrix=n),r}shadingFill(t){if(!this.contentVisible)return;const n=this.ctx;this.save();const r=this._getPattern(t);n.fillStyle=r.getPattern(n,this,T3(n),db.SHADING);const a=T3(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=Vo.getAxialAlignedBoundingBox([0,0,i,l],a);this.ctx.fillRect(o,c,d-o,u-c)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){Mp("Should not call beginInlineImage")}beginImageData(){Mp("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=Ef(this.ctx),n)){const r=n[2]-n[0],a=n[3]-n[1];this.ctx.rect(n[0],n[1],r,a),this.current.updateRectMinMax(Ef(this.ctx),n),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;t.isolated||U8e("TODO: Support non-isolated groups."),t.knockout&&jd("Knockout groups not supported.");const r=Ef(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=Vo.getAxialAlignedBoundingBox(t.bbox,Ef(n));const i=[0,0,n.canvas.width,n.canvas.height];a=Vo.intersect(a,i)||[0,0,0,0];const l=Math.floor(a[0]),o=Math.floor(a[1]),c=Math.max(Math.ceil(a[2])-l,1),d=Math.max(Math.ceil(a[3])-o,1);this.current.startNewPathAndClipBox([0,0,c,d]);let u="groupAt"+this.groupLevel;t.smask&&(u+="_smask_"+this.smaskCounter++%2);const h=this.cachedCanvases.getCanvas(u,c,d),m=h.context;m.translate(-l,-o),m.transform(...r),t.smask?this.smaskStack.push({canvas:h.canvas,context:m,offsetX:l,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(n.setTransform(1,0,0,1,0,0),n.translate(l,o),n.save()),TZ(n,m),this.ctx=m,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(n),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,r=this.groupStack.pop();if(this.ctx=r,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const a=Ef(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=Vo.getAxialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a);this.ctx.drawImage(n.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,n,r,a,i){if(ss(this,dL,rYe).call(this),bde(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),n){const l=n[2]-n[0],o=n[3]-n[1];if(i&&this.annotationCanvasMap){r=r.slice(),r[4]-=n[0],r[5]-=n[1],n=n.slice(),n[0]=n[1]=0,n[2]=l,n[3]=o;const[c,d]=Vo.singularValueDecompose2dScale(Ef(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:p,context:f}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=f,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),bde(this.ctx)}else bde(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new HSt(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),ss(this,dL,aYe).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const n=t.count;t=this.getObject(t.data,t),t.count=n;const r=this.ctx,a=this.processingType3;if(a&&(a.compiled===void 0&&(a.compiled=CHn(t)),a.compiled)){a.compiled(r);return}const i=this._createMaskCanvas(t),l=i.canvas;r.save(),r.setTransform(1,0,0,1,0,0),r.drawImage(l,i.offsetX,i.offsetY),r.restore(),this.compose()}paintImageMaskXObjectRepeat(t,n,r=0,a=0,i,l){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const c=Ef(o);o.transform(n,r,a,i,0,0);const d=this._createMaskCanvas(t);o.setTransform(1,0,0,1,d.offsetX-c[4],d.offsetY-c[5]);for(let u=0,h=l.length;uh?u/h:1,o=d>h?d/h:1}}this._cachedScaleForStroking[0]=l,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:n}=this,{lineWidth:r}=this.current,[a,i]=this.getScaleForStroking();if(n.lineWidth=r||1,a===1&&i===1){n.stroke();return}const l=n.getLineDash();if(t&&n.save(),n.scale(a,i),l.length>0){const o=Math.max(a,i);n.setLineDash(l.map(c=>c/o)),n.lineDashOffset/=o}n.stroke(),t&&n.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};dL=new WeakSet,rYe=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)},aYe=function(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const n=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=n}}};let Qq=Rot;for(const s in Ik)Qq.prototype[s]!==void 0&&(Qq.prototype[Ik[s]]=Qq.prototype[s]);var Tne,Mne;class IA{static get workerPort(){return ye(this,Tne)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Ht(this,Tne,t)}static get workerSrc(){return ye(this,Mne)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Ht(this,Mne,t)}}Tne=new WeakMap,Mne=new WeakMap,ps(IA,Tne,null),ps(IA,Mne,"");const _de={UNKNOWN:0,DATA:1,ERROR:2},Ag={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function kw(s){switch(s instanceof Error||typeof s=="object"&&s!==null||Mp('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new Nz(s.message);case"MissingPDFException":return new jz(s.message);case"PasswordException":return new TKe(s.message,s.code);case"UnexpectedResponseException":return new q8e(s.message,s.status);case"UnknownErrorException":return new MKe(s.message,s.details);default:return new MKe(s.message,s.toString())}}var DV,EN,sts,nts,rts,SCe;class YX{constructor(t,n,r){ps(this,EN);ps(this,DV,new AbortController);this.sourceName=t,this.targetName=n,this.comObj=r,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),r.addEventListener("message",ss(this,EN,sts).bind(this),{signal:ye(this,DV).signal})}on(t,n){const r=this.actionHandler;if(r[t])throw new Error(`There is already an actionName called "${t}"`);r[t]=n}send(t,n,r){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:n},r)}sendWithPromise(t,n,r){const a=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[a]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:a,data:n},r)}catch(l){i.reject(l)}return i.promise}sendWithStream(t,n,r,a){const i=this.streamId++,l=this.sourceName,o=this.targetName,c=this.comObj;return new ReadableStream({start:d=>{const u=Promise.withResolvers();return this.streamControllers[i]={controller:d,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},c.postMessage({sourceName:l,targetName:o,action:t,streamId:i,data:n,desiredSize:d.desiredSize},a),u.promise},pull:d=>{const u=Promise.withResolvers();return this.streamControllers[i].pullCall=u,c.postMessage({sourceName:l,targetName:o,stream:Ag.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{jy(d instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[i].cancelCall=u,this.streamControllers[i].isClosed=!0,c.postMessage({sourceName:l,targetName:o,stream:Ag.CANCEL,streamId:i,reason:kw(d)}),u.promise}},r)}destroy(){var t;(t=ye(this,DV))==null||t.abort(),Ht(this,DV,null)}}DV=new WeakMap,EN=new WeakSet,sts=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){ss(this,EN,rts).call(this,t);return}if(t.callback){const r=t.callbackId,a=this.callbackCapabilities[r];if(!a)throw new Error(`Cannot resolve callback ${r}`);if(delete this.callbackCapabilities[r],t.callback===_de.DATA)a.resolve(t.data);else if(t.callback===_de.ERROR)a.reject(kw(t.reason));else throw new Error("Unexpected callback case");return}const n=this.actionHandler[t.action];if(!n)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const r=this.sourceName,a=t.sourceName,i=this.comObj;new Promise(function(l){l(n(t.data))}).then(function(l){i.postMessage({sourceName:r,targetName:a,callback:_de.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:_de.ERROR,callbackId:t.callbackId,reason:kw(l)})});return}if(t.streamId){ss(this,EN,nts).call(this,t);return}n(t.data)},nts=function(t){const n=t.streamId,r=this.sourceName,a=t.sourceName,i=this.comObj,l=this,o=this.actionHandler[t.action],c={enqueue(d,u=1,h){if(this.isCancelled)return;const m=this.desiredSize;this.desiredSize-=u,m>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:r,targetName:a,stream:Ag.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:Ag.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){jy(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:Ag.ERROR,streamId:n,reason:kw(d)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};c.sinkCapability.resolve(),c.ready=c.sinkCapability.promise,this.streamSinks[n]=c,new Promise(function(d){d(o(t.data,c))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Ag.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:Ag.START_COMPLETE,streamId:n,reason:kw(d)})})},rts=function(t){const n=t.streamId,r=this.sourceName,a=t.sourceName,i=this.comObj,l=this.streamControllers[n],o=this.streamSinks[n];switch(t.stream){case Ag.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(kw(t.reason));break;case Ag.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(kw(t.reason));break;case Ag.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:Ag.PULL_COMPLETE,streamId:n,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,new Promise(function(c){var d;c((d=o.onPull)==null?void 0:d.call(o))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Ag.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:Ag.PULL_COMPLETE,streamId:n,reason:kw(c)})});break;case Ag.ENQUEUE:if(jy(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case Ag.CLOSE:if(jy(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),ss(this,EN,SCe).call(this,l,n);break;case Ag.ERROR:jy(l,"error should have stream controller"),l.controller.error(kw(t.reason)),ss(this,EN,SCe).call(this,l,n);break;case Ag.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(kw(t.reason)),ss(this,EN,SCe).call(this,l,n);break;case Ag.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,kw(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Ag.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:Ag.CANCEL_COMPLETE,streamId:n,reason:kw(c)})}),o.sinkCapability.reject(kw(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},SCe=async function(t,n){var r,a,i;await Promise.allSettled([(r=t.startCall)==null?void 0:r.promise,(a=t.pullCall)==null?void 0:a.promise,(i=t.cancelCall)==null?void 0:i.promise]),delete this.streamControllers[n]};var vO,Pne;class MHn{constructor({parsedData:t,rawData:n}){ps(this,vO);ps(this,Pne);Ht(this,vO,t),Ht(this,Pne,n)}getRaw(){return ye(this,Pne)}get(t){return ye(this,vO).get(t)??null}getAll(){return fat(ye(this,vO))}has(t){return ye(this,vO).has(t)}}vO=new WeakMap,Pne=new WeakMap;const F$=Symbol("INTERNAL");var Lne,Ine,Dne,RV;class PHn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){ps(this,Lne,!1);ps(this,Ine,!1);ps(this,Dne,!1);ps(this,RV,!0);Ht(this,Lne,!!(t&Hw.DISPLAY)),Ht(this,Ine,!!(t&Hw.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(ye(this,Dne))return ye(this,RV);if(!ye(this,RV))return!1;const{print:t,view:n}=this.usage;return ye(this,Lne)?(n==null?void 0:n.viewState)!=="OFF":ye(this,Ine)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==F$&&Mp("Internal method `_setVisible` called."),Ht(this,Dne,r),Ht(this,RV,n)}}Lne=new WeakMap,Ine=new WeakMap,Dne=new WeakMap,RV=new WeakMap;var dM,Fh,FV,OV,Rne,iYe;class LHn{constructor(t,n=Hw.DISPLAY){ps(this,Rne);ps(this,dM,null);ps(this,Fh,new Map);ps(this,FV,null);ps(this,OV,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Ht(this,OV,t.order);for(const r of t.groups)ye(this,Fh).set(r.id,new PHn(n,r));if(t.baseState==="OFF")for(const r of ye(this,Fh).values())r._setVisible(F$,!1);for(const r of t.on)ye(this,Fh).get(r)._setVisible(F$,!0);for(const r of t.off)ye(this,Fh).get(r)._setVisible(F$,!1);Ht(this,FV,this.getHash())}}isVisible(t){if(ye(this,Fh).size===0)return!0;if(!t)return U8e("Optional content group not defined."),!0;if(t.type==="OCG")return ye(this,Fh).has(t.id)?ye(this,Fh).get(t.id).visible:(jd(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return ss(this,Rne,iYe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!ye(this,Fh).has(n))return jd(`Optional content group not found: ${n}`),!0;if(ye(this,Fh).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!ye(this,Fh).has(n))return jd(`Optional content group not found: ${n}`),!0;if(!ye(this,Fh).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!ye(this,Fh).has(n))return jd(`Optional content group not found: ${n}`),!0;if(!ye(this,Fh).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!ye(this,Fh).has(n))return jd(`Optional content group not found: ${n}`),!0;if(ye(this,Fh).get(n).visible)return!1}return!0}return jd(`Unknown optional content policy ${t.policy}.`),!0}return jd(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=ye(this,Fh).get(t);if(!a){jd(`Optional content group not found: ${t}`);return}if(r&&n&&a.rbGroups.length)for(const l of a.rbGroups)for(const o of l)o!==t&&((i=ye(this,Fh).get(o))==null||i._setVisible(F$,!1,!0));a._setVisible(F$,!!n,!0),Ht(this,dM,null)}setOCGState({state:t,preserveRB:n}){let r;for(const a of t){switch(a){case"ON":case"OFF":case"Toggle":r=a;continue}const i=ye(this,Fh).get(a);if(i)switch(r){case"ON":this.setVisibility(a,!0,n);break;case"OFF":this.setVisibility(a,!1,n);break;case"Toggle":this.setVisibility(a,!i.visible,n);break}}Ht(this,dM,null)}get hasInitialVisibility(){return ye(this,FV)===null||this.getHash()===ye(this,FV)}getOrder(){return ye(this,Fh).size?ye(this,OV)?ye(this,OV).slice():[...ye(this,Fh).keys()]:null}getGroups(){return ye(this,Fh).size>0?fat(ye(this,Fh)):null}getGroup(t){return ye(this,Fh).get(t)||null}getHash(){if(ye(this,dM)!==null)return ye(this,dM);const t=new Hes;for(const[n,r]of ye(this,Fh))t.update(`${n}:${r.visible}`);return Ht(this,dM,t.hexdigest())}}dM=new WeakMap,Fh=new WeakMap,FV=new WeakMap,OV=new WeakMap,Rne=new WeakSet,iYe=function(t){const n=t.length;if(n<2)return!0;const r=t[0];for(let a=1;a0){const c=i instanceof Uint8Array&&i.byteLength===i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer;this._queuedChunks.push(c)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!r,this._isRangeSupported=!n,this._contentLength=a,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((c,d)=>{this._onReceiveData({begin:c,chunk:d})}),t.addProgressListener((c,d)=>{this._onProgress({loaded:c,total:d})}),t.addProgressiveReadListener(c=>{this._onReceiveData({chunk:c})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:n}){const r=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(r):this._queuedChunks.push(r);else{const a=this._rangeReaders.some(function(i){return i._begin!==t?!1:(i._enqueue(r),!0)});jy(a,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}_onProgress(t){var n,r,a,i;t.total===void 0?(r=(n=this._rangeReaders[0])==null?void 0:n.onProgress)==null||r.call(n,{loaded:t.loaded}):(i=(a=this._fullRequestReader)==null?void 0:a.onProgress)==null||i.call(a,{loaded:t.loaded,total:t.total})}_onProgressiveDone(){var t;(t=this._fullRequestReader)==null||t.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const n=this._rangeReaders.indexOf(t);n>=0&&this._rangeReaders.splice(n,1)}getFullReader(){jy(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new DHn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new RHn(this,t,n);return this._pdfDataRangeTransport.requestDataRange(t,n),this._rangeReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeReaders.slice(0))r.cancel(t);this._pdfDataRangeTransport.abort()}}class DHn{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=yat(a)?a:null,this._queuedChunks=n||[],this._loaded=0;for(const i of this._queuedChunks)this._loaded+=i.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class RHn{constructor(t,n,r){this._stream=t,this._begin=n,this._end=r,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function FHn(s){let t=!0,n=r("filename\\*","i").exec(s);if(n){n=n[1];let u=o(n);return u=unescape(u),u=c(u),u=d(u),i(u)}if(n=l(s),n){const u=d(n);return i(u)}if(n=r("filename","i").exec(s),n){n=n[1];let u=o(n);return u=d(u),i(u)}function r(u,h){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function a(u,h){if(u){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const m=new TextDecoder(u,{fatal:!0}),p=V8e(h);h=m.decode(p),t=!1}catch{}}return h}function i(u){return t&&/[\x80-\xff]/.test(u)&&(u=a("utf-8",u),t&&(u=a("iso-8859-1",u))),u}function l(u){const h=[];let m;const p=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=p.exec(u))!==null;){let[,g,v,y]=m;if(g=parseInt(g,10),g in h){if(g===0)break;continue}h[g]=[v,y]}const f=[];for(let g=0;g{if(!ats(i.status))throw W8e(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=Nat({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=kat(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Nz("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;await this._headersCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded,total:this._contentLength}),{value:ots(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class zHn{constructor(t,n,r){this._stream=t,this._reader=null,this._loaded=0;const a=t.source;this._withCredentials=a.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!a.disableStream,this._abortController=new AbortController;const i=new Headers(t.headers);i.append("Range",`bytes=${n}-${r-1}`);const l=a.url;fetch(l,its(i,this._withCredentials,this._abortController)).then(o=>{if(!ats(o.status))throw W8e(o.status,l);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;await this._readCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded}),{value:ots(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const pBe=200,fBe=206;function BHn(s){const t=s.response;return typeof t!="string"?t:V8e(t).buffer}class $Hn{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=jat(this.isHttp,n),this.withCredentials=r||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,n,r){const a={begin:t,end:n};for(const i in r)a[i]=r[i];return this.request(a)}requestFull(t){return this.request(t)}request(t){const n=new XMLHttpRequest,r=this.currXhrId++,a=this.pendingRequests[r]={xhr:n};n.open("GET",this.url),n.withCredentials=this.withCredentials;for(const[i,l]of this.headers)n.setRequestHeader(i,l);return this.isHttp&&"begin"in t&&"end"in t?(n.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),a.expectedStatus=fBe):a.expectedStatus=pBe,n.responseType="arraybuffer",t.onError&&(n.onerror=function(i){t.onError(n.status)}),n.onreadystatechange=this.onStateChange.bind(this,r),n.onprogress=this.onProgress.bind(this,r),a.onHeadersReceived=t.onHeadersReceived,a.onDone=t.onDone,a.onError=t.onError,a.onProgress=t.onProgress,n.send(null),r}onProgress(t,n){var a;const r=this.pendingRequests[t];r&&((a=r.onProgress)==null||a.call(r,n))}onStateChange(t,n){var c,d,u;const r=this.pendingRequests[t];if(!r)return;const a=r.xhr;if(a.readyState>=2&&r.onHeadersReceived&&(r.onHeadersReceived(),delete r.onHeadersReceived),a.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],a.status===0&&this.isHttp){(c=r.onError)==null||c.call(r,a.status);return}const i=a.status||pBe;if(!(i===pBe&&r.expectedStatus===fBe)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=BHn(a);if(i===fBe){const h=a.getResponseHeader("Content-Range"),m=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);r.onDone({begin:parseInt(m[1],10),chunk:o})}else o?r.onDone({begin:0,chunk:o}):(u=r.onError)==null||u.call(r,a.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const n=this.pendingRequests[t].xhr;delete this.pendingRequests[t],n.abort()}}class UHn{constructor(t){this._source=t,this._manager=new $Hn(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const n=this._rangeRequestReaders.indexOf(t);n>=0&&this._rangeRequestReaders.splice(n,1)}getFullReader(){return jy(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new qHn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new VHn(this._manager,t,n);return r.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeRequestReaders.slice(0))r.cancel(t)}}class qHn{constructor(t,n){this._manager=t;const r={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=n.url,this._fullRequestId=t.requestFull(r),this._headersCapability=Promise.withResolvers(),this._disableRange=n.disableRange||!1,this._contentLength=n.length,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,n=this._manager.getRequestXhr(t),r=new Headers(n.getAllResponseHeaders().trim().split(/[\r\n]+/).map(l=>{const[o,...c]=l.split(": ");return[o,c.join(": ")]})),{allowRangeRequests:a,suggestedLength:i}=Nat({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=kat(r),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=W8e(t,this._url),this._headersCapability.reject(this._storedError);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var n;(n=this.onProgress)==null||n.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class VHn{constructor(t,n,r){this._manager=t;const a={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(n,r,a),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var t;(t=this.onClosed)==null||t.call(this,this)}_onDone(t){const n=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:n,done:!1}):this._queuedChunk=n,this._done=!0;for(const r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=W8e(t,this._url);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){var n;this.isStreamingSupported||(n=this.onProgress)==null||n.call(this,{loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const HHn=/^[a-z][a-z0-9\-+.]+:/i;function GHn(s){if(HHn.test(s))return new URL(s);const t=nL.get("url");return new URL(t.pathToFileURL(s))}function lts(s,t,n){return s.protocol==="http:"?nL.get("http").request(s,{headers:t},n):nL.get("https").request(s,{headers:t},n)}class WHn{constructor(t){this.source=t,this.url=GHn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=jat(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return jy(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new ZHn(this):new KHn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new XHn(this,t,n):new YHn(this,t,n);return this._rangeRequestReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeRequestReaders.slice(0))r.cancel(t)}}class cts{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const n=t.source;this._contentLength=n.length,this._loaded=0,this._filename=null,this._disableRange=n.disableRange||!1,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!n.disableStream,this._isRangeSupported=!n.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",n=>{this._error(n)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new Nz("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class dts{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const n=t.source;this._isStreamingSupported=!n.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",n=>{this._error(n)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class KHn extends cts{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new jz(`Missing PDF "${this._url}".`);this._storedError=c,this._headersCapability.reject(c);return}this._headersCapability.resolve(),this._setReadableStream(a);const i=new Headers(this._readableStream.headers),{allowRangeRequests:l,suggestedLength:o}=Nat({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=kat(i)};this._request=lts(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class YHn extends dts{constructor(t,n,r){super(t);const a=Object.fromEntries(t.headers);a.Range=`bytes=${n}-${r-1}`;const i=l=>{if(l.statusCode===404){const o=new jz(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=lts(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class ZHn extends cts{constructor(t){super(t);const n=nL.get("fs");n.promises.lstat(this._url).then(r=>{this._contentLength=r.size,this._setReadableStream(n.createReadStream(this._url)),this._headersCapability.resolve()},r=>{r.code==="ENOENT"&&(r=new jz(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class XHn extends dts{constructor(t,n,r){super(t);const a=nL.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const QHn=1e5,r_=30,JHn=.8;var ZEt,uM,p_,Fne,One,bO,mA,zne,Bne,_O,zV,BV,hM,$V,$ne,UV,wO,Une,qne,jO,NO,Vne,mM,qV,RE,uts,hts,oYe,Pj,CCe,lYe,mts,pts;const oy=class oy{constructor({textContentSource:t,container:n,viewport:r}){ps(this,RE);ps(this,uM,Promise.withResolvers());ps(this,p_,null);ps(this,Fne,!1);ps(this,One,!!((ZEt=globalThis.FontInspector)!=null&&ZEt.enabled));ps(this,bO,null);ps(this,mA,null);ps(this,zne,0);ps(this,Bne,0);ps(this,_O,null);ps(this,zV,null);ps(this,BV,0);ps(this,hM,0);ps(this,$V,Object.create(null));ps(this,$ne,[]);ps(this,UV,null);ps(this,wO,[]);ps(this,Une,new WeakMap);ps(this,qne,null);var c;if(t instanceof ReadableStream)Ht(this,UV,t);else if(typeof t=="object")Ht(this,UV,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Ht(this,p_,Ht(this,zV,n)),Ht(this,hM,r.scale*(globalThis.devicePixelRatio||1)),Ht(this,BV,r.rotation),Ht(this,mA,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Ht(this,qne,[1,0,0,-1,-l,o+i]),Ht(this,Bne,a),Ht(this,zne,i),ss(c=oy,Pj,mts).call(c),P9(n,r),ye(this,uM).promise.finally(()=>{ye(oy,qV).delete(this),Ht(this,mA,null),Ht(this,$V,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=Sb.platform;return gu(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{ye(this,_O).read().then(({value:n,done:r})=>{if(r){ye(this,uM).resolve();return}ye(this,bO)??Ht(this,bO,n.lang),Object.assign(ye(this,$V),n.styles),ss(this,RE,uts).call(this,n.items),t()},ye(this,uM).reject)};return Ht(this,_O,ye(this,UV).getReader()),ye(oy,qV).add(this),t(),ye(this,uM).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==ye(this,BV)&&(n==null||n(),Ht(this,BV,a),P9(ye(this,zV),{rotation:a})),r!==ye(this,hM)){n==null||n(),Ht(this,hM,r);const l={div:null,properties:null,ctx:ss(i=oy,Pj,CCe).call(i,ye(this,bO))};for(const o of ye(this,wO))l.properties=ye(this,Une).get(o),l.div=o,ss(this,RE,oYe).call(this,l)}}cancel(){var n;const t=new Nz("TextLayer task cancelled.");(n=ye(this,_O))==null||n.cancel(t).catch(()=>{}),Ht(this,_O,null),ye(this,uM).reject(t)}get textDivs(){return ye(this,wO)}get textContentItemsStr(){return ye(this,$ne)}static cleanup(){if(!(ye(this,qV).size>0)){ye(this,jO).clear();for(const{canvas:t}of ye(this,NO).values())t.remove();ye(this,NO).clear()}}};uM=new WeakMap,p_=new WeakMap,Fne=new WeakMap,One=new WeakMap,bO=new WeakMap,mA=new WeakMap,zne=new WeakMap,Bne=new WeakMap,_O=new WeakMap,zV=new WeakMap,BV=new WeakMap,hM=new WeakMap,$V=new WeakMap,$ne=new WeakMap,UV=new WeakMap,wO=new WeakMap,Une=new WeakMap,qne=new WeakMap,jO=new WeakMap,NO=new WeakMap,Vne=new WeakMap,mM=new WeakMap,qV=new WeakMap,RE=new WeakSet,uts=function(t){var a,i;if(ye(this,Fne))return;(i=ye(this,mA)).ctx??(i.ctx=ss(a=oy,Pj,CCe).call(a,ye(this,bO)));const n=ye(this,wO),r=ye(this,$ne);for(const l of t){if(n.length>QHn){jd("Ignoring additional textDivs for performance reasons."),Ht(this,Fne,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=ye(this,p_);Ht(this,p_,document.createElement("span")),ye(this,p_).classList.add("markedContent"),l.id!==null&&ye(this,p_).setAttribute("id",`${l.id}`),o.append(ye(this,p_))}else l.type==="endMarkedContent"&&Ht(this,p_,ye(this,p_).parentNode);continue}r.push(l.str),ss(this,RE,hts).call(this,l)}},hts=function(t){var g;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};ye(this,wO).push(n);const a=Vo.transform(ye(this,qne),t.transform);let i=Math.atan2(a[1],a[0]);const l=ye(this,$V)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=ye(this,One)&&l.fontSubstitution||l.fontFamily;o=oy.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*ss(g=oy,Pj,pts).call(g,o,ye(this,bO));let u,h;i===0?(u=a[4],h=a[5]-d):(u=a[4]+d*Math.sin(i),h=a[5]-d*Math.cos(i));const m="calc(var(--scale-factor)*",p=n.style;ye(this,p_)===ye(this,zV)?(p.left=`${(100*u/ye(this,Bne)).toFixed(2)}%`,p.top=`${(100*h/ye(this,zne)).toFixed(2)}%`):(p.left=`${m}${u.toFixed(2)}px)`,p.top=`${m}${h.toFixed(2)}px)`),p.fontSize=`${m}${(ye(oy,mM)*c).toFixed(2)}px)`,p.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,ye(this,One)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let f=!1;if(t.str.length>1)f=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const v=Math.abs(t.transform[0]),y=Math.abs(t.transform[3]);v!==y&&Math.max(v,y)/Math.min(v,y)>1.5&&(f=!0)}if(f&&(r.canvasWidth=l.vertical?t.height:t.width),ye(this,Une).set(n,r),ye(this,mA).div=n,ye(this,mA).properties=r,ss(this,RE,oYe).call(this,ye(this,mA)),r.hasText&&ye(this,p_).append(n),r.hasEOL){const v=document.createElement("br");v.setAttribute("role","presentation"),ye(this,p_).append(v)}},oYe=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(ye(oy,mM)>1&&(l=`scale(${1/ye(oy,mM)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;ss(o=oy,Pj,lYe).call(o,a,u*ye(this,hM),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*ye(this,hM)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},Pj=new WeakSet,CCe=function(t=null){let n=ye(this,NO).get(t||(t=""));if(!n){const r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=t,document.body.append(r),n=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),ye(this,NO).set(t,n),ye(this,Vne).set(n,{size:0,family:""})}return n},lYe=function(t,n,r){const a=ye(this,Vne).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},mts=function(){if(ye(this,mM)!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),Ht(this,mM,t.getBoundingClientRect().height),t.remove()},pts=function(t,n){const r=ye(this,jO).get(t);if(r)return r;const a=ss(this,Pj,CCe).call(this,n);a.canvas.width=a.canvas.height=r_,ss(this,Pj,lYe).call(this,a,r_,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return ye(this,jO).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,r_,r_),a.strokeText("g",0,0);let c=a.getImageData(0,0,r_,r_).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/r_);break}a.clearRect(0,0,r_,r_),a.strokeText("A",0,r_),c=a.getImageData(0,0,r_,r_).data,l=0;for(let u=0,h=c.length;u0){l=r_-Math.floor(u/4/r_);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):JHn;return ye(this,jO).set(t,d),d},ps(oy,Pj),ps(oy,jO,new Map),ps(oy,NO,new Map),ps(oy,Vne,new WeakMap),ps(oy,mM,null),ps(oy,qV,new Set);let Rse=oy;class Fse{static textContent(t){const n=[],r={items:n,styles:Object.create(null)};function a(i){var c;if(!i)return;let l=null;const o=i.name;if(o==="#text")l=i.value;else if(Fse.shouldBuildText(o))(c=i==null?void 0:i.attributes)!=null&&c.textContent?l=i.attributes.textContent:i.value&&(l=i.value);else return;if(l!==null&&n.push({str:l}),!!i.children)for(const d of i.children)a(d)}return a(t),r}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const eGn=65536,tGn=100,sGn=5e3,nGn=u1?fHn:hHn,rGn=u1?xHn:Zes,aGn=u1?pHn:mHn,iGn=u1?gHn:ets;function oGn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new cYe,{docId:n}=t,r=s.url?lGn(s.url):null,a=s.data?cGn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof fts?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:eGn;let u=s.worker instanceof Jq?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!G8e(s.docBaseUrl)?s.docBaseUrl:null,p=typeof s.cMapUrl=="string"?s.cMapUrl:null,f=s.cMapPacked!==!1,g=s.CMapReaderFactory||rGn,v=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,y=s.StandardFontDataFactory||iGn,b=s.stopAtErrors!==!0,w=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,S=s.isEvalSupported!==!1,C=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!u1,E=typeof s.isChrome=="boolean"?s.isChrome:!Sb.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),P=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,M=typeof s.disableFontFace=="boolean"?s.disableFontFace:u1,I=s.fontExtraProperties===!0,D=s.enableXfa===!0,F=s.ownerDocument||globalThis.document,q=s.disableRange===!0,G=s.disableStream===!0,V=s.disableAutoFetch===!0,H=s.pdfBug===!0,K=s.CanvasFactory||nGn,Z=s.FilterFactory||aGn,oe=s.enableHWA===!0,re=c?c.length:s.length??NaN,ae=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!u1&&!M,J=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:g===Zes&&y===ets&&p&&v&&UX(p,document.baseURI)&&UX(v,document.baseURI);s.canvasFactory&&OSt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&OSt("`filterFactory`-instance option, please use `FilterFactory` instead.");const te=null;qVn(h);const ce={canvasFactory:new K({ownerDocument:F,enableHWA:oe}),filterFactory:new Z({docId:n,ownerDocument:F}),cMapReaderFactory:J?null:new g({baseUrl:p,isCompressed:f}),standardFontDataFactory:J?null:new y({baseUrl:v})};if(!u){const he={verbosity:h,port:IA.workerPort};u=he.port?Jq.fromPort(he):new Jq(he),t._worker=u}const ve={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:V,rangeChunkSize:d,length:re,docBaseUrl:m,enableXfa:D,evaluatorOptions:{maxImageSize:w,disableFontFace:M,ignoreErrors:b,isEvalSupported:S,isOffscreenCanvasSupported:C,isChrome:E,canvasMaxAreaInBytes:P,fontExtraProperties:I,useSystemFonts:ae,cMapUrl:J?p:null,standardFontDataUrl:J?v:null}},me={disableFontFace:M,fontExtraProperties:I,ownerDocument:F,pdfBug:H,styleElement:te,loadingParams:{disableAutoFetch:V,enableXfa:D}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const he=u.messageHandler.sendWithPromise("GetDocRequest",ve,a?[a.buffer]:null);let ge;if(c)ge=new IHn(c,{disableRange:q,disableStream:G});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ee;u1?Ee=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&UX(r)?ZSt:WHn:Ee=UX(r)?ZSt:UHn,ge=new Ee({url:r,length:re,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:q,disableStream:G})}return he.then(Ee=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Ne=new YX(n,Ee,u.port),Pe=new mGn(Ne,t,ge,me,ce);t._transport=Pe,Ne.send("Ready",null)})}).catch(t._capability.reject),t}function lGn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(u1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function cGn(s){if(u1&&typeof Buffer<"u"&&s instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength)return s;if(typeof s=="string")return V8e(s);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof s=="object"&&!isNaN(s==null?void 0:s.length))return new Uint8Array(s);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function XSt(s){return typeof s=="object"&&Number.isInteger(s==null?void 0:s.num)&&s.num>=0&&Number.isInteger(s==null?void 0:s.gen)&&s.gen>=0}var uMe;const hMe=class hMe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Jy(hMe,uMe)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var t,n,r;this.destroyed=!0;try{(t=this._worker)!=null&&t.port&&(this._worker._pendingDestroy=!0),await((n=this._transport)==null?void 0:n.destroy())}catch(a){throw(r=this._worker)!=null&&r.port&&delete this._worker._pendingDestroy,a}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}};uMe=new WeakMap,ps(hMe,uMe,0);let cYe=hMe;class fts{constructor(t,n,r=!1,a=null){this.length=t,this.initialData=n,this.progressiveDone=r,this.contentDispositionFilename=a,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,n){for(const r of this._rangeListeners)r(t,n)}onDataProgress(t,n){this._readyCapability.promise.then(()=>{for(const r of this._progressListeners)r(t,n)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const n of this._progressiveReadListeners)n(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,n){Mp("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class dGn{constructor(t,n){this._pdfInfo=t,this._transport=n}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return gu(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:n}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(n)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}var pM,pA,iN,O$,ACe;class uGn{constructor(t,n,r,a=!1){ps(this,iN);ps(this,pM,null);ps(this,pA,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new FSt:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new xts,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:n=this.rotate,offsetX:r=0,offsetY:a=0,dontFlip:i=!1}={}){return new iie({viewBox:this.view,scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}getAnnotations({intent:t="display"}={}){const{renderingIntent:n}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,n)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return gu(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var t;return((t=this._transport._htmlForXfa)==null?void 0:t.children[this._pageIndex])||null}render({canvasContext:t,viewport:n,intent:r="display",annotationMode:a=$6.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var S,C;(S=this._stats)==null||S.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:p,cacheKey:f}=m;Ht(this,pA,!1),ss(this,iN,ACe).call(this),o||(o=this._transport.getOptionalContentConfig(p));let g=this._intentStates.get(f);g||(g=Object.create(null),this._intentStates.set(f,g)),g.streamReaderCancelTimeout&&(clearTimeout(g.streamReaderCancelTimeout),g.streamReaderCancelTimeout=null);const v=!!(p&Hw.PRINT);g.displayReadyCapability||(g.displayReadyCapability=Promise.withResolvers(),g.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(C=this._stats)==null||C.time("Page Request"),this._pumpOperatorList(m));const y=E=>{var P;g.renderTasks.delete(b),(this._maybeCleanupAfterRender||v)&&Ht(this,pA,!0),ss(this,iN,O$).call(this,!v),E?(b.capability.reject(E),this._abortOperatorList({intentState:g,reason:E instanceof Error?E:new Error(E)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(P=globalThis.Stats)!=null&&P.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new uYe({callback:y,params:{canvasContext:t,viewport:n,transform:i,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:g.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:d});(g.renderTasks||(g.renderTasks=new Set)).add(b);const w=b.task;return Promise.all([g.displayReadyCapability.promise,o]).then(([E,P])=>{var M;if(this.destroyed){y();return}if((M=this._stats)==null||M.time("Rendering"),!(P.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:E,optionalContentConfig:P}),b.operatorListChanged()}).catch(y),w}getOperatorList({intent:t="display",annotationMode:n=$6.ENABLE,printAnnotationStorage:r=null,isEditing:a=!1}={}){var d;function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(c))}const l=this._transport.getRenderingIntent(t,n,r,a,!0);let o=this._intentStates.get(l.cacheKey);o||(o=Object.create(null),this._intentStates.set(l.cacheKey,o));let c;return o.opListReadCapability||(c=Object.create(null),c.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||(o.renderTasks=new Set)).add(c),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(d=this._stats)==null||d.time("Page Request"),this._pumpOperatorList(l)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:n=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:n===!0},{highWaterMark:100,size(a){return a.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(r=>Fse.textContent(r));const n=this.streamTextContent(t);return new Promise(function(r,a){function i(){l.read().then(function({value:c,done:d}){if(d){r(o);return}o.lang??(o.lang=c.lang),Object.assign(o.styles,c.styles),o.items.push(...c.items),i()},a)}const l=n.getReader(),o={items:[],styles:Object.create(null),lang:null};i()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const n of this._intentStates.values())if(this._abortOperatorList({intentState:n,reason:new Error("Page was destroyed."),force:!0}),!n.opListReadCapability)for(const r of n.renderTasks)t.push(r.completed),r.cancel();return this.objs.clear(),Ht(this,pA,!1),ss(this,iN,ACe).call(this),Promise.all(t)}cleanup(t=!1){Ht(this,pA,!0);const n=ss(this,iN,O$).call(this,!1);return t&&n&&this._stats&&(this._stats=new FSt),n}_startRenderPage(t,n){var a,i;const r=this._intentStates.get(n);r&&((a=this._stats)==null||a.timeEnd("Page Request"),(i=r.displayReadyCapability)==null||i.resolve(t))}_renderPageChunk(t,n){for(let r=0,a=t.length;r{c.read().then(({value:h,done:m})=>{if(m){d.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(h,d),u())},h=>{if(d.streamReader=null,!this._transport.destroyed){if(d.operatorList){d.operatorList.lastChunk=!0;for(const m of d.renderTasks)m.operatorListChanged();ss(this,iN,O$).call(this,!0)}if(d.displayReadyCapability)d.displayReadyCapability.reject(h);else if(d.opListReadCapability)d.opListReadCapability.reject(h);else throw h}})};u()}_abortOperatorList({intentState:t,reason:n,force:r=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!r){if(t.renderTasks.size>0)return;if(n instanceof gat){let a=tGn;n.extraDelay>0&&n.extraDelay<1e3&&(a+=n.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:n,force:!0})},a);return}}if(t.streamReader.cancel(new Nz(n.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[a,i]of this._intentStates)if(i===t){this._intentStates.delete(a);break}this.cleanup()}}}get stats(){return this._stats}}pM=new WeakMap,pA=new WeakMap,iN=new WeakSet,O$=function(t=!1){if(ss(this,iN,ACe).call(this),!ye(this,pA)||this.destroyed)return!1;if(t)return Ht(this,pM,setTimeout(()=>{Ht(this,pM,null),ss(this,iN,O$).call(this,!1)},sGn)),!1;for(const{renderTasks:n,operatorList:r}of this._intentStates.values())if(n.size>0||!r.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),Ht(this,pA,!1),!0},ACe=function(){ye(this,pM)&&(clearTimeout(ye(this,pM)),Ht(this,pM,null))};var fA,mMe;class hGn{constructor(){ps(this,fA,new Map);ps(this,mMe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};ye(this,mMe).then(()=>{for(const[a]of ye(this,fA))a.call(this,r)})}addEventListener(t,n,r=null){let a=null;if((r==null?void 0:r.signal)instanceof AbortSignal){const{signal:i}=r;if(i.aborted){jd("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}ye(this,fA).set(n,a)}removeEventListener(t,n){const r=ye(this,fA).get(n);r==null||r(),ye(this,fA).delete(n)}terminate(){for(const[,t]of ye(this,fA))t==null||t();ye(this,fA).clear()}}fA=new WeakMap,mMe=new WeakMap;var pMe,kO,SO,VV,ECe,HV,TCe;const Qp=class Qp{constructor({name:t=null,port:n=null,verbosity:r=VVn()}={}){ps(this,VV);var a;if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if((a=ye(Qp,SO))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(ye(Qp,SO)||Ht(Qp,SO,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return u1?Promise.all([nL.promise,this._readyCapability.promise]):this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new YX("main","worker",t),this._messageHandler.on("ready",function(){}),ss(this,VV,ECe).call(this)}_initialize(){if(ye(Qp,kO)||ye(Qp,HV,TCe)){this._setupFakeWorker();return}let{workerSrc:t}=Qp;try{Qp._isSameOrigin(window.location.href,t)||(t=Qp._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new YX("main","worker",n),a=()=>{i.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},i=new AbortController;n.addEventListener("error",()=>{this._webWorker||a()},{signal:i.signal}),r.on("test",o=>{if(i.abort(),this.destroyed||!o){a();return}this._messageHandler=r,this._port=n,this._webWorker=n,ss(this,VV,ECe).call(this)}),r.on("ready",o=>{if(i.abort(),this.destroyed){a();return}try{l()}catch{this._setupFakeWorker()}});const l=()=>{const o=new Uint8Array;r.send("test",o,[o.buffer])};l();return}catch{U8e("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(Qp,kO)||(jd("Setting up fake worker."),Ht(Qp,kO,!0)),Qp._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new hGn;this._port=n;const r=`fake${Jy(Qp,pMe)._++}`,a=new YX(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new YX(r,r+"_worker",n),ss(this,VV,ECe).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(t=ye(Qp,SO))==null||t.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){var r;if(!(t!=null&&t.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const n=(r=ye(this,SO))==null?void 0:r.get(t.port);if(n){if(n._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new Qp(t)}static get workerSrc(){if(IA.workerSrc)return IA.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return gu(this,"_setupFakeWorkerGlobal",(async()=>ye(this,HV,TCe)?ye(this,HV,TCe):(await import(this.workerSrc)).WorkerMessageHandler)())}};pMe=new WeakMap,kO=new WeakMap,SO=new WeakMap,VV=new WeakSet,ECe=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},HV=new WeakSet,TCe=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},ps(Qp,HV),ps(Qp,pMe,0),ps(Qp,kO,!1),ps(Qp,SO),u1&&(Ht(Qp,kO,!0),IA.workerSrc||(IA.workerSrc="./pdf.worker.mjs")),Qp._isSameOrigin=(t,n)=>{let r;try{if(r=new URL(t),!r.origin||r.origin==="null")return!1}catch{return!1}const a=new URL(n,r);return r.origin===a.origin},Qp._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let Jq=Qp;var xA,u4,GV,WV,h4,CO,ZX;class mGn{constructor(t,n,r,a,i){ps(this,CO);ps(this,xA,new Map);ps(this,u4,new Map);ps(this,GV,new Map);ps(this,WV,new Map);ps(this,h4,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new xts,this.fontLoader=new dHn({ownerDocument:a.ownerDocument,styleElement:a.styleElement}),this.loadingParams=a.loadingParams,this._params=a,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.cMapReaderFactory=i.cMapReaderFactory,this.standardFontDataFactory=i.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=r,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}get annotationStorage(){return gu(this,"annotationStorage",new _at)}getRenderingIntent(t,n=$6.ENABLE,r=null,a=!1,i=!1){let l=Hw.DISPLAY,o=QKe;switch(t){case"any":l=Hw.ANY;break;case"display":break;case"print":l=Hw.PRINT;break;default:jd(`getRenderingIntent - invalid intent: ${t}`)}const c=l&Hw.PRINT&&r instanceof Wes?r:this.annotationStorage;switch(n){case $6.DISABLE:l+=Hw.ANNOTATIONS_DISABLE;break;case $6.ENABLE:break;case $6.ENABLE_FORMS:l+=Hw.ANNOTATIONS_FORMS;break;case $6.ENABLE_STORAGE:l+=Hw.ANNOTATIONS_STORAGE,o=c.serializable;break;default:jd(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=Hw.IS_EDITING),i&&(l+=Hw.OPLIST);const{ids:d,hash:u}=c.modifiedIds,h=[l,o.hash,u];return{renderingIntent:l,cacheKey:h.join("_"),annotationStorageSerializable:o,modifiedIds:d}}destroy(){var r;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(r=ye(this,h4))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of ye(this,u4).values())t.push(a._destroy());ye(this,u4).clear(),ye(this,GV).clear(),ye(this,WV).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const n=this.messageHandler.sendWithPromise("Terminate",null);return t.push(n),Promise.all(t).then(()=>{var a;this.commonObjs.clear(),this.fontLoader.clear(),ye(this,xA).clear(),this.filterFactory.destroy(),Rse.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new Nz("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:n}=this;t.on("GetReader",(r,a)=>{jy(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=i=>{this._lastProgress={loaded:i.loaded,total:i.total}},a.onPull=()=>{this._fullReader.read().then(function({value:i,done:l}){if(l){a.close();return}jy(i instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),a.enqueue(new Uint8Array(i),1,[i])}).catch(i=>{a.error(i)})},a.onCancel=i=>{this._fullReader.cancel(i),a.ready.catch(l=>{if(!this.destroyed)throw l})}}),t.on("ReaderHeadersReady",async r=>{var o;await this._fullReader.headersReady;const{isStreamingSupported:a,isRangeSupported:i,contentLength:l}=this._fullReader;return(!a||!i)&&(this._lastProgress&&((o=n.onProgress)==null||o.call(n,this._lastProgress)),this._fullReader.onProgress=c=>{var d;(d=n.onProgress)==null||d.call(n,{loaded:c.loaded,total:c.total})}),{isStreamingSupported:a,isRangeSupported:i,contentLength:l}}),t.on("GetRangeReader",(r,a)=>{jy(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(r.begin,r.end);if(!i){a.close();return}a.onPull=()=>{i.read().then(function({value:l,done:o}){if(o){a.close();return}jy(l instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),a.enqueue(new Uint8Array(l),1,[l])}).catch(l=>{a.error(l)})},a.onCancel=l=>{i.cancel(l),a.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:r})=>{this._numPages=r.numPages,this._htmlForXfa=r.htmlForXfa,delete r.htmlForXfa,n._capability.resolve(new dGn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new TKe(r.message,r.code);break;case"InvalidPDFException":a=new ves(r.message);break;case"MissingPDFException":a=new jz(r.message);break;case"UnexpectedResponseException":a=new q8e(r.message,r.status);break;case"UnknownErrorException":a=new MKe(r.message,r.details);break;default:Mp("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Ht(this,h4,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?ye(this,h4).reject(i):ye(this,h4).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){ye(this,h4).reject(i)}}else ye(this,h4).reject(new TKe(r.message,r.code));return ye(this,h4).promise}),t.on("DataLoaded",r=>{var a;(a=n.onProgress)==null||a.call(n,{loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),t.on("StartRenderPage",r=>{if(this.destroyed)return;ye(this,u4).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),t.on("commonobj",([r,a,i])=>{var l;if(this.destroyed||this.commonObjs.has(r))return null;switch(a){case"Font":const{disableFontFace:o,fontExtraProperties:c,pdfBug:d}=this._params;if("error"in i){const p=i.error;jd(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(p,f)=>globalThis.FontInspector.fontAdded(p,f):null,h=new uHn(i,{disableFontFace:o,inspectFont:u});this.fontLoader.bind(h).catch(()=>t.sendWithPromise("FontFallback",{id:r})).finally(()=>{!c&&h.data&&(h.data=null),this.commonObjs.resolve(r,h)});break;case"CopyLocalImage":const{imageRef:m}=i;jy(m,"The imageRef must be defined.");for(const p of ye(this,u4).values())for(const[,f]of p.objs)if((f==null?void 0:f.ref)===m)return f.dataLen?(this.commonObjs.resolve(r,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,i);break;default:throw new Error(`Got unknown common object type ${a}`)}return null}),t.on("obj",([r,a,i,l])=>{var c;if(this.destroyed)return;const o=ye(this,u4).get(a);if(!o.objs.has(r)){if(o._intentStates.size===0){(c=l==null?void 0:l.bitmap)==null||c.close();return}switch(i){case"Image":o.objs.resolve(r,l),(l==null?void 0:l.dataLen)>zVn&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(r,l);break;default:throw new Error(`Got unknown object type ${i}`)}}}),t.on("DocProgress",r=>{var a;this.destroyed||(a=n.onProgress)==null||a.call(n,{loaded:r.loaded,total:r.total})}),t.on("FetchBuiltInCMap",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(r)}),t.on("FetchStandardFontData",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(r)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var r;this.annotationStorage.size<=0&&jd("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:n}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((r=this._fullReader)==null?void 0:r.filename)??null},n).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const n=t-1,r=ye(this,GV).get(n);if(r)return r;const a=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&ye(this,WV).set(i.refStr,t);const l=new uGn(n,i,this,this._params.pdfBug);return ye(this,u4).set(n,l),l});return ye(this,GV).set(n,a),a}getPageIndex(t){return XSt(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,n){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:n})}getFieldObjects(){return ss(this,CO,ZX).call(this,"GetFieldObjects")}hasJSActions(){return ss(this,CO,ZX).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return ss(this,CO,ZX).call(this,"GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return ss(this,CO,ZX).call(this,"GetOptionalContentConfig").then(n=>new LHn(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=ye(this,xA).get(t);if(n)return n;const r=this.messageHandler.sendWithPromise(t,null).then(a=>{var i,l;return{info:a[0],metadata:a[1]?new MHn(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return ye(this,xA).set(t,r),r}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const n of ye(this,u4).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),ye(this,xA).clear(),this.filterFactory.destroy(!0),Rse.cleanup()}}cachedPageNumber(t){if(!XSt(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return ye(this,WV).get(n)??null}}xA=new WeakMap,u4=new WeakMap,GV=new WeakMap,WV=new WeakMap,h4=new WeakMap,CO=new WeakSet,ZX=function(t,n=null){const r=ye(this,xA).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return ye(this,xA).set(t,a),a};const wde=Symbol("INITIAL_DATA");var Uk,Hne,dYe;class xts{constructor(){ps(this,Hne);ps(this,Uk,Object.create(null))}get(t,n=null){if(n){const a=ss(this,Hne,dYe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=ye(this,Uk)[t];if(!r||r.data===wde)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=ye(this,Uk)[t];return!!n&&n.data!==wde}resolve(t,n=null){const r=ss(this,Hne,dYe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in ye(this,Uk)){const{data:r}=ye(this,Uk)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Ht(this,Uk,Object.create(null))}*[Symbol.iterator](){for(const t in ye(this,Uk)){const{data:n}=ye(this,Uk)[t];n!==wde&&(yield[t,n])}}}Uk=new WeakMap,Hne=new WeakSet,dYe=function(t){var n;return(n=ye(this,Uk))[t]||(n[t]={...Promise.withResolvers(),data:wde})};var fM;class pGn{constructor(t){ps(this,fM,null);Ht(this,fM,t),this.onContinue=null}get promise(){return ye(this,fM).capability.promise}cancel(t=0){ye(this,fM).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=ye(this,fM).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=ye(this,fM);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}fM=new WeakMap;var xM,AO;const fF=class fF{constructor({callback:t,params:n,objs:r,commonObjs:a,annotationCanvasMap:i,operatorList:l,pageIndex:o,canvasFactory:c,filterFactory:d,useRequestAnimationFrame:u=!1,pdfBug:h=!1,pageColors:m=null}){ps(this,xM,null);this.callback=t,this.params=n,this.objs=r,this.commonObjs=a,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=l,this._pageIndex=o,this.canvasFactory=c,this.filterFactory=d,this._pdfBug=h,this.pageColors=m,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new pGn(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=n.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){var o,c;if(this.cancelled)return;if(this._canvas){if(ye(fF,AO).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");ye(fF,AO).add(this._canvas)}this._pdfBug&&((o=globalThis.StepperManager)!=null&&o.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:r,viewport:a,transform:i,background:l}=this.params;this.gfx=new Qq(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:i,viewport:a,transparency:t,background:l}),this.operatorListIdx=0,this.graphicsReady=!0,(c=this.graphicsReadyCallback)==null||c.call(this)}cancel(t=null,n=0){var r;this.running=!1,this.cancelled=!0,(r=this.gfx)==null||r.endDrawing(),ye(this,xM)&&(window.cancelAnimationFrame(ye(this,xM)),Ht(this,xM,null)),ye(fF,AO).delete(this._canvas),this.callback(t||new gat(`Rendering cancelled, page ${this._pageIndex+1}`,n))}operatorListChanged(){var t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?Ht(this,xM,window.requestAnimationFrame(()=>{Ht(this,xM,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),ye(fF,AO).delete(this._canvas),this.callback())))}};xM=new WeakMap,AO=new WeakMap,ps(fF,AO,new WeakSet);let uYe=fF;const fGn="4.8.69",xGn="3634dab10";function QSt(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function MZ(s){return Math.max(0,Math.min(255,255*s))}class JSt{static CMYK_G([t,n,r,a]){return["G",1-Math.min(1,.3*t+.59*r+.11*n+a)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=MZ(t),[t,t,t]}static G_HTML([t]){const n=QSt(t);return`#${n}${n}${n}`}static RGB_G([t,n,r]){return["G",.3*t+.59*n+.11*r]}static RGB_rgb(t){return t.map(MZ)}static RGB_HTML(t){return`#${t.map(QSt).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,n,r,a]){return["RGB",1-Math.min(1,t+a),1-Math.min(1,r+a),1-Math.min(1,n+a)]}static CMYK_rgb([t,n,r,a]){return[MZ(1-Math.min(1,t+a)),MZ(1-Math.min(1,r+a)),MZ(1-Math.min(1,n+a))]}static CMYK_HTML(t){const n=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(n)}static RGB_CMYK([t,n,r]){const a=1-t,i=1-n,l=1-r,o=Math.min(a,i,l);return["CMYK",a,i,l,o]}}class gGn{create(t,n,r=!1){if(t<=0||n<=0)throw new Error("Invalid SVG dimensions");const a=this._createSVG("svg:svg");return a.setAttribute("version","1.1"),r||(a.setAttribute("width",`${t}px`),a.setAttribute("height",`${n}px`)),a.setAttribute("preserveAspectRatio","none"),a.setAttribute("viewBox",`0 0 ${t} ${n}`),a}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){Mp("Abstract method `_createSVG` called.")}}class Sat extends gGn{_createSVG(t){return document.createElementNS($3,t)}}class gts{static setupStorage(t,n,r,a,i){const l=a.getValue(n,{value:null});switch(r.name){case"textarea":if(l.value!==null&&(t.textContent=l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(l.value===r.attributes.xfaOn?t.setAttribute("checked",!0):l.value===r.attributes.xfaOff&&t.removeAttribute("checked"),i==="print")break;t.addEventListener("change",o=>{a.setValue(n,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(l.value!==null&&t.setAttribute("value",l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})})}break;case"select":if(l.value!==null){t.setAttribute("value",l.value);for(const o of r.children)o.attributes.value===l.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const c=o.target.options,d=c.selectedIndex===-1?"":c[c.selectedIndex].value;a.setValue(n,{value:d})});break}}static setAttributes({html:t,element:n,storage:r=null,intent:a,linkService:i}){const{attributes:l}=n,o=t instanceof HTMLAnchorElement;l.type==="radio"&&(l.name=`${l.name}-${a}`);for(const[c,d]of Object.entries(l))if(d!=null)switch(c){case"class":d.length&&t.setAttribute(c,d.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",d);break;case"style":Object.assign(t.style,d);break;case"textContent":t.textContent=d;break;default:(!o||c!=="href"&&c!=="newWindow")&&t.setAttribute(c,d)}o&&i.addLinkAttributes(t,l.href,l.newWindow),r&&l.dataId&&this.setupStorage(t,l.dataId,n,r)}static render(t){var h,m;const n=t.annotationStorage,r=t.linkService,a=t.xfaHtml,i=t.intent||"display",l=document.createElement(a.name);a.attributes&&this.setAttributes({html:l,element:a,intent:i,linkService:r});const o=i!=="richText",c=t.div;if(c.append(l),t.viewport){const p=`matrix(${t.viewport.transform.join(",")})`;c.style.transform=p}o&&c.setAttribute("class","xfaLayer xfaFont");const d=[];if(a.children.length===0){if(a.value){const p=document.createTextNode(a.value);l.append(p),o&&Fse.shouldBuildText(a.name)&&d.push(p)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[p,f,g]=u.at(-1);if(f+1===p.children.length){u.pop();continue}const v=p.children[++u.at(-1)[1]];if(v===null)continue;const{name:y}=v;if(y==="#text"){const w=document.createTextNode(v.value);d.push(w),g.append(w);continue}const b=(h=v==null?void 0:v.attributes)!=null&&h.xmlns?document.createElementNS(v.attributes.xmlns,y):document.createElement(y);if(g.append(b),v.attributes&&this.setAttributes({html:b,element:v,storage:n,intent:i,linkService:r}),((m=v.children)==null?void 0:m.length)>0)u.push([v,-1,b]);else if(v.value){const w=document.createTextNode(v.value);o&&Fse.shouldBuildText(y)&&d.push(w),b.append(w)}}for(const p of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))p.setAttribute("readOnly",!0);return{textDivs:d}}static update(t){const n=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=n,t.div.hidden=!1}}const lie=1e3,yGn=9,I9=new WeakSet;function lE(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class vGn{static create(t){switch(t.data.annotationType){case ay.LINK:return new yts(t);case ay.TEXT:return new bGn(t);case ay.WIDGET:switch(t.data.fieldType){case"Tx":return new _Gn(t);case"Btn":return t.data.radioButton?new _ts(t):t.data.checkBox?new jGn(t):new NGn(t);case"Ch":return new kGn(t);case"Sig":return new wGn(t)}return new kz(t);case ay.POPUP:return new mYe(t);case ay.FREETEXT:return new Sts(t);case ay.LINE:return new CGn(t);case ay.SQUARE:return new AGn(t);case ay.CIRCLE:return new EGn(t);case ay.POLYLINE:return new Cts(t);case ay.CARET:return new MGn(t);case ay.INK:return new Cat(t);case ay.POLYGON:return new TGn(t);case ay.HIGHLIGHT:return new Ats(t);case ay.UNDERLINE:return new PGn(t);case ay.SQUIGGLY:return new LGn(t);case ay.STRIKEOUT:return new IGn(t);case ay.STAMP:return new Ets(t);case ay.FILEATTACHMENT:return new DGn(t);default:return new yg(t)}}}var EO,KV,YV,Gne,hYe;const Fot=class Fot{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){ps(this,Gne);ps(this,EO,null);ps(this,KV,!1);ps(this,YV,null);this.isRenderable=n,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,n&&(this.container=this._createContainer(r)),a&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:n,richText:r}){return!!(t!=null&&t.str||n!=null&&n.str||r!=null&&r.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Fot._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;ye(this,EO)||Ht(this,EO,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&ss(this,Gne,hYe).call(this,n),(r=ye(this,YV))==null||r.popup.updateEdited(t)}resetEdited(){var t;ye(this,EO)&&(ss(this,Gne,hYe).call(this,ye(this,EO).rect),(t=ye(this,YV))==null||t.popup.resetEdited(),Ht(this,EO,null))}_createContainer(t){const{data:n,parent:{page:r,viewport:a}}=this,i=document.createElement("section");i.setAttribute("data-annotation-id",n.id),this instanceof kz||(i.tabIndex=lie);const{style:l}=i;if(l.zIndex=this.parent.zIndex++,n.alternativeText&&(i.title=n.alternativeText),n.noRotate&&i.classList.add("norotate"),!n.rect||this instanceof mYe){const{rotation:g}=n;return!n.hasOwnCanvas&&g!==0&&this.setRotation(g,i),i}const{width:o,height:c}=lE(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const g=n.borderStyle.horizontalCornerRadius,v=n.borderStyle.verticalCornerRadius;if(g>0||v>0){const b=`calc(${g}px * var(--scale-factor)) / calc(${v}px * var(--scale-factor))`;l.borderRadius=b}else if(this instanceof _ts){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case EZ.SOLID:l.borderStyle="solid";break;case EZ.DASHED:l.borderStyle="dashed";break;case EZ.BEVELED:jd("Unimplemented border style: beveled");break;case EZ.INSET:jd("Unimplemented border style: inset");break;case EZ.UNDERLINE:l.borderBottomStyle="solid";break}const y=n.borderColor||null;y?(Ht(this,KV,!0),l.borderColor=Vo.makeHexColor(y[0]|0,y[1]|0,y[2]|0)):l.borderWidth=0}const d=Vo.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:p}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-p)/h}%`;const{rotation:f}=n;return n.hasOwnCanvas||f===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(f,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=lE(this.data.rect);let o,c;t%180===0?(o=100*i/r,c=100*l/a):(o=100*l/r,c=100*i/a),n.style.width=`${o}%`,n.style.height=`${c}%`,n.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(n,r,a)=>{const i=a.detail[n],l=i[0],o=i.slice(1);a.target.style[r]=JSt[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:JSt[`${l}_rgb`](o)})};return gu(this,"_commonActions",{display:n=>{const{display:r}=n.detail,a=r%2===1;this.container.style.visibility=a?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:a,noPrint:r===1||r===2})},print:n=>{this.annotationStorage.setValue(this.data.id,{noPrint:!n.detail.print})},hidden:n=>{const{hidden:r}=n.detail;this.container.style.visibility=r?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:r,noView:r})},focus:n=>{setTimeout(()=>n.target.focus({preventScroll:!1}),0)},userName:n=>{n.target.title=n.detail.userName},readonly:n=>{n.target.disabled=n.detail.readonly},required:n=>{this._setRequired(n.target,n.detail.required)},bgColor:n=>{t("bgColor","backgroundColor",n)},fillColor:n=>{t("fillColor","backgroundColor",n)},fgColor:n=>{t("fgColor","color",n)},textColor:n=>{t("textColor","color",n)},borderColor:n=>{t("borderColor","borderColor",n)},strokeColor:n=>{t("strokeColor","borderColor",n)},rotation:n=>{const r=n.detail.rotation;this.setRotation(r),this.annotationStorage.setValue(this.data.id,{rotation:r})}})}_dispatchEventFromSandbox(t,n){const r=this._commonActions;for(const a of Object.keys(n.detail)){const i=t[a]||r[a];i==null||i(n)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const n=this.annotationStorage.getRawValue(this.data.id);if(!n)return;const r=this._commonActions;for(const[a,i]of Object.entries(n)){const l=r[a];if(l){const o={detail:{[a]:i},target:t};l(o),delete n[a]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[n,r,a,i]=this.data.rect.map(g=>Math.fround(g));if(t.length===8){const[g,v,y,b]=t.subarray(2,6);if(a===g&&i===v&&n===y&&r===b)return}const{style:l}=this.container;let o;if(ye(this,KV)){const{borderColor:g,borderWidth:v}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const p=u.createElement("clipPath"),f=`clippath_${this.data.id}`;p.setAttribute("id",f),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let g=2,v=t.length;g`)}ye(this,KV)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${f})`}_createPopup(){const{data:t}=this,n=Ht(this,YV,new mYe({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(n.render())}render(){Mp("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,n=null){const r=[];if(this._fieldObjects){const a=this._fieldObjects[t];if(a)for(const{page:i,id:l,exportValues:o}of a){if(i===-1||l===n)continue;const c=typeof o=="string"?o:null,d=document.querySelector(`[data-element-id="${l}"]`);if(d&&!I9.has(d)){jd(`_getElementsByName - element not allowed: ${l}`);continue}r.push({id:l,exportValue:c,domElement:d})}return r}for(const a of document.getElementsByName(t)){const{exportValue:i}=a,l=a.getAttribute("data-element-id");l!==n&&I9.has(a)&&r.push({id:l,exportValue:i,domElement:a})}return r}show(){var t;this.container&&(this.container.hidden=!1),(t=this.popup)==null||t.maybeShow()}hide(){var t;this.container&&(this.container.hidden=!0),(t=this.popup)==null||t.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const n of t)n.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:n}}=this;this.container.addEventListener("dblclick",()=>{var r;(r=this.linkService.eventBus)==null||r.dispatch("switchannotationeditormode",{source:this,mode:t,editId:n})})}};EO=new WeakMap,KV=new WeakMap,YV=new WeakMap,Gne=new WeakSet,hYe=function(t){const{container:{style:n},data:{rect:r,rotation:a},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:l,pageX:o,pageY:c}}}}=this;r==null||r.splice(0,4,...t);const{width:d,height:u}=lE(t);n.left=`${100*(t[0]-o)/i}%`,n.top=`${100*(l-t[3]+c)/l}%`,a===0?(n.width=`${100*d/i}%`,n.height=`${100*u/l}%`):this.setRotation(a)};let yg=Fot;var Jw,tF,vts,bts;class yts extends yg{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});ps(this,Jw);this.isTooltipOnly=n.data.isTooltipOnly}render(){const{data:n,linkService:r}=this,a=document.createElement("a");a.setAttribute("data-element-id",n.id);let i=!1;return n.url?(r.addLinkAttributes(a,n.url,n.newWindow),i=!0):n.action?(this._bindNamedAction(a,n.action),i=!0):n.attachment?(ss(this,Jw,vts).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(ss(this,Jw,bts).call(this,a,n.setOCGState),i=!0):n.dest?(this._bindLink(a,n.dest),i=!0):(n.actions&&(n.actions.Action||n.actions["Mouse Up"]||n.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(a,n),i=!0),n.resetForm?(this._bindResetFormAction(a,n.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(a,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(a),this.container}_bindLink(n,r){n.href=this.linkService.getDestinationHash(r),n.onclick=()=>(r&&this.linkService.goToDestination(r),!1),(r||r==="")&&ss(this,Jw,tF).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),ss(this,Jw,tF).call(this)}_bindJSAction(n,r){n.href=this.linkService.getAnchorUrl("");const a=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(r.actions)){const l=a.get(i);l&&(n[l]=()=>{var o;return(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:r.id,name:i}}),!1})}n.onclick||(n.onclick=()=>!1),ss(this,Jw,tF).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),ss(this,Jw,tF).call(this),!this._fieldObjects){jd('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),a||(n.onclick=()=>!1);return}n.onclick=()=>{var h;a==null||a();const{fields:i,refs:l,include:o}=r,c=[];if(i.length!==0||l.length!==0){const m=new Set(l);for(const p of i){const f=this._fieldObjects[p]||[];for(const{id:g}of f)m.add(g)}for(const p of Object.values(this._fieldObjects))for(const f of p)m.has(f.id)===o&&c.push(f)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:p}=m;switch(u.push(p),m.type){case"text":{const g=m.defaultValue||"";d.setValue(p,{value:g});break}case"checkbox":case"radiobutton":{const g=m.defaultValue===m.exportValues;d.setValue(p,{value:g});break}case"combobox":case"listbox":{const g=m.defaultValue||"";d.setValue(p,{value:g});break}default:continue}const f=document.querySelector(`[data-element-id="${p}"]`);if(f){if(!I9.has(f)){jd(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;f.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Jw=new WeakSet,tF=function(){this.container.setAttribute("data-internal-link","")},vts=function(n,r,a=null){n.href=this.linkService.getAnchorUrl(""),r.description&&(n.title=r.description),n.onclick=()=>{var i;return(i=this.downloadManager)==null||i.openOrDownloadData(r.content,r.filename,a),!1},ss(this,Jw,tF).call(this)},bts=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),ss(this,Jw,tF).call(this)};class bGn extends yg{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class kz extends yg{render(){return this.container}showElementAndHideCanvas(t){var n;this.data.hasOwnCanvas&&(((n=t.previousSibling)==null?void 0:n.nodeName)==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Sb.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,n,r,a,i){r.includes("mouse")?t.addEventListener(r,l=>{var o;(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l),shift:l.shiftKey,modifier:this._getKeyModifier(l)}})}):t.addEventListener(r,l=>{var o;if(r==="blur"){if(!n.focused||!l.relatedTarget)return;n.focused=!1}else if(r==="focus"){if(n.focused)return;n.focused=!0}i&&((o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l)}}))})}_setEventListeners(t,n,r,a){var i,l,o;for(const[c,d]of r)(d==="Action"||(i=this.data.actions)!=null&&i[d])&&((d==="Focus"||d==="Blur")&&(n||(n={focused:!1})),this._setEventListener(t,n,c,d,a),d==="Focus"&&!((l=this.data.actions)!=null&&l.Blur)?this._setEventListener(t,n,"blur","Blur",null):d==="Blur"&&!((o=this.data.actions)!=null&&o.Focus)&&this._setEventListener(t,n,"focus","Focus",null))}_setBackgroundColor(t){const n=this.data.backgroundColor||null;t.style.backgroundColor=n===null?"transparent":Vo.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||yGn,i=t.style;let l;const o=2,c=d=>Math.round(10*d)/10;if(this.data.multiLine){const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o),u=Math.round(d/(dBe*a))||1,h=d/u;l=Math.min(a,c(h/dBe))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/dBe))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=Vo.makeHexColor(r[0],r[1],r[2]),this.data.textAlignment!==null&&(i.textAlign=n[this.data.textAlignment])}_setRequired(t,n){n?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",n)}}class _Gn extends kz{constructor(t){const n=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:n})}setPropertyOnSiblings(t,n,r,a){const i=this.annotationStorage;for(const l of this._getElementsByName(t.name,t.id))l.domElement&&(l.domElement[n]=r),i.setValue(l.id,{[a]:r})}render(){var a,i;const t=this.annotationStorage,n=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){const l=t.getValue(n,{value:this.data.fieldValue});let o=l.value||"";const c=t.getValue(n,{charLimit:this.data.maxLen}).charLimit;c&&o.length>c&&(o=o.slice(0,c));let d=l.formattedValue||((a=this.data.textContent)==null?void 0:a.join(` `))||null;d&&this.data.comb&&(d=d.replaceAll(/\s+/g,""));const u={userValue:o,formattedValue:d,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=d??o,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type="text",r.setAttribute("value",d??o),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),I9.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=lie,this._setRequired(r,this.data.required),c&&(r.maxLength=c),r.addEventListener("input",m=>{t.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",m=>{const p=this.data.defaultFieldValue??"";r.value=u.userValue=p,u.formattedValue=null});let h=m=>{const{formattedValue:p}=u;p!=null&&(m.target.value=p),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",p=>{var g;if(u.focused)return;const{target:f}=p;u.userValue&&(f.value=u.userValue),u.lastCommittedValue=f.value,u.commitKey=1,(g=this.data.actions)!=null&&g.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const f={value(g){u.userValue=g.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),g.target.value=u.userValue},formattedValue(g){const{formattedValue:v}=g.detail;u.formattedValue=v,v!=null&&g.target!==document.activeElement&&(g.target.value=v),t.setValue(n,{formattedValue:v})},selRange(g){g.target.setSelectionRange(...g.detail.selRange)},charLimit:g=>{var w;const{charLimit:v}=g.detail,{target:y}=g;if(v===0){y.removeAttribute("maxLength");return}y.setAttribute("maxLength",v);let b=u.userValue;!b||b.length<=v||(b=b.slice(0,v),y.value=u.userValue=b,t.setValue(n,{value:b}),(w=this.linkService.eventBus)==null||w.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:y.selectionStart,selEnd:y.selectionEnd}}))}};this._dispatchEventFromSandbox(f,p)}),r.addEventListener("keydown",p=>{var v;u.commitKey=1;let f=-1;if(p.key==="Escape"?f=0:p.key==="Enter"&&!this.data.multiLine?f=2:p.key==="Tab"&&(u.commitKey=3),f===-1)return;const{value:g}=p.target;u.lastCommittedValue!==g&&(u.lastCommittedValue=g,u.userValue=g,(v=this.linkService.eventBus)==null||v.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:f,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",p=>{var g,v;if(!u.focused||!p.relatedTarget)return;(g=this.data.actions)!=null&&g.Blur||(u.focused=!1);const{value:f}=p.target;u.userValue=f,u.lastCommittedValue!==f&&((v=this.linkService.eventBus)==null||v.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:f,willCommit:!0,commitKey:u.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}})),m(p)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",p=>{var C;u.lastCommittedValue=null;const{data:f,target:g}=p,{value:v,selectionStart:y,selectionEnd:b}=g;let w=y,S=b;switch(p.inputType){case"deleteWordBackward":{const E=v.substring(0,y).match(/\w*[^\w]*$/);E&&(w-=E[0].length);break}case"deleteWordForward":{const E=v.substring(y).match(/^[^\w]*\w*/);E&&(S+=E[0].length);break}case"deleteContentBackward":y===b&&(w-=1);break;case"deleteContentForward":y===b&&(S+=1);break}p.preventDefault(),(C=this.linkService.eventBus)==null||C.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:v,change:f||"",willCommit:!1,selStart:w,selEnd:S}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${p}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class wGn extends kz{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class jGn extends kz{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.exportValue===n.fieldValue}).value;typeof a=="string"&&(a=a!=="Off",t.setValue(r,{value:a})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const i=document.createElement("input");return I9.add(i),i.setAttribute("data-element-id",r),i.disabled=n.readOnly,this._setRequired(i,this.data.required),i.type="checkbox",i.name=n.fieldName,a&&i.setAttribute("checked",!0),i.setAttribute("exportValue",n.exportValue),i.tabIndex=lie,i.addEventListener("change",l=>{const{name:o,checked:c}=l.target;for(const d of this._getElementsByName(o,r)){const u=c&&d.exportValue===n.exportValue;d.domElement&&(d.domElement.checked=u),t.setValue(d.id,{value:u})}t.setValue(r,{value:c})}),i.addEventListener("resetform",l=>{const o=n.defaultFieldValue||"Off";l.target.checked=o===n.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener("updatefromsandbox",l=>{const o={value(c){c.target.checked=c.detail.value!=="Off",t.setValue(r,{value:c.target.checked})}};this._dispatchEventFromSandbox(o,l)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],l=>l.target.checked)),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class _ts extends kz{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.fieldValue===n.buttonValue}).value;if(typeof a=="string"&&(a=a!==n.buttonValue,t.setValue(r,{value:a})),a)for(const l of this._getElementsByName(n.fieldName,r))t.setValue(l.id,{value:!1});const i=document.createElement("input");if(I9.add(i),i.setAttribute("data-element-id",r),i.disabled=n.readOnly,this._setRequired(i,this.data.required),i.type="radio",i.name=n.fieldName,a&&i.setAttribute("checked",!0),i.tabIndex=lie,i.addEventListener("change",l=>{const{name:o,checked:c}=l.target;for(const d of this._getElementsByName(o,r))t.setValue(d.id,{value:!1});t.setValue(r,{value:c})}),i.addEventListener("resetform",l=>{const o=n.defaultFieldValue;l.target.checked=o!=null&&o===n.buttonValue}),this.enableScripting&&this.hasJSActions){const l=n.buttonValue;i.addEventListener("updatefromsandbox",o=>{const c={value:d=>{const u=l===d.detail.value;for(const h of this._getElementsByName(d.target.name)){const m=u&&h.id===r;h.domElement&&(h.domElement.checked=m),t.setValue(h.id,{value:m})}}};this._dispatchEventFromSandbox(c,o)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class NGn extends yts{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const n=t.lastChild;return this.enableScripting&&this.hasJSActions&&n&&(this._setDefaultPropertiesFromJS(n),n.addEventListener("updatefromsandbox",r=>{this._dispatchEventFromSandbox({},r)})),t}}class kGn extends kz{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,n=this.data.id,r=t.getValue(n,{value:this.data.fieldValue}),a=document.createElement("select");I9.add(a),a.setAttribute("data-element-id",n),a.disabled=this.data.readOnly,this._setRequired(a,this.data.required),a.name=this.data.fieldName,a.tabIndex=lie;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:p}=a;return p?Array.prototype.filter.call(m,f=>f.selected).map(f=>f[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const p=m.detail.value,f=new Set(Array.isArray(p)?p:[p]);for(const g of a.options)g.selected=f.has(g.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const p=a.options,f=m.detail.remove;p[f].selected=!1,a.remove(f),p.length>0&&Array.prototype.findIndex.call(p,v=>v.selected)===-1&&(p[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:p,displayValue:f,exportValue:g}=m.detail.insert,v=a.children[p],y=document.createElement("option");y.textContent=f,y.value=g,v?v.before(y):a.append(y),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:p}=m.detail;for(;a.length!==0;)a.remove(0);for(const f of p){const{displayValue:g,exportValue:v}=f,y=document.createElement("option");y.textContent=g,y.value=v,a.append(y)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const p=new Set(m.detail.indices);for(const f of m.target.options)f.selected=p.has(f.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var p;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(p=this.linkService.eventBus)==null||p.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class mYe extends yg{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:yg._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new SGn({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),n=[];for(const r of this.elements)r.popup=t,r.container.ariaHasPopup="dialog",n.push(r.data.id),r.addHighlightArea();return this.container.setAttribute("aria-controls",n.map(r=>`${xat}${r}`).join(",")),this.container}}var ZV,fMe,xMe,XV,TO,vx,gA,QV,Wne,Kne,JV,yA,qk,vA,Yne,bA,Zne,MO,PO,gm,MCe,pYe,wts,jts,Nts,kts,PCe,LCe,fYe;class SGn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){ps(this,gm);ps(this,ZV,ss(this,gm,Nts).bind(this));ps(this,fMe,ss(this,gm,fYe).bind(this));ps(this,xMe,ss(this,gm,LCe).bind(this));ps(this,XV,ss(this,gm,PCe).bind(this));ps(this,TO,null);ps(this,vx,null);ps(this,gA,null);ps(this,QV,null);ps(this,Wne,null);ps(this,Kne,null);ps(this,JV,null);ps(this,yA,!1);ps(this,qk,null);ps(this,vA,null);ps(this,Yne,null);ps(this,bA,null);ps(this,Zne,null);ps(this,MO,null);ps(this,PO,!1);var m;Ht(this,vx,t),Ht(this,Zne,a),Ht(this,gA,l),Ht(this,bA,o),Ht(this,Kne,c),Ht(this,TO,n),Ht(this,Yne,d),Ht(this,JV,u),Ht(this,Wne,r),Ht(this,QV,vat.toDateObject(i)),this.trigger=r.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",ye(this,XV)),p.addEventListener("mouseenter",ye(this,xMe)),p.addEventListener("mouseleave",ye(this,fMe)),p.classList.add("popupTriggerArea");for(const p of r)(m=p.container)==null||m.addEventListener("keydown",ye(this,ZV));ye(this,vx).hidden=!0,h&&ss(this,gm,PCe).call(this)}render(){if(ye(this,qk))return;const t=Ht(this,qk,document.createElement("div"));if(t.className="popup",ye(this,TO)){const i=t.style.outlineColor=Vo.makeHexColor(...ye(this,TO));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=Vo.makeHexColor(...ye(this,TO).map(o=>Math.floor(.7*(255-o)+o)))}const n=document.createElement("span");n.className="header";const r=document.createElement("h1");if(n.append(r),{dir:r.dir,str:r.textContent}=ye(this,Zne),t.append(n),ye(this,QV)){const i=document.createElement("span");i.classList.add("popupDate"),i.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),i.setAttribute("data-l10n-args",JSON.stringify({dateObj:ye(this,QV).valueOf()})),n.append(i)}const a=ye(this,gm,MCe);if(a)gts.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(ye(this,gA));t.append(i)}ye(this,vx).append(t)}_formatContents({str:t,dir:n}){const r=document.createElement("p");r.classList.add("popupContent"),r.dir=n;const a=t.split(/(?:\r\n?|\n)/);for(let i=0,l=a.length;i{l.key==="Enter"&&(i?l.metaKey:l.ctrlKey)&&ss(this,nre,xYe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return ye(this,sre)}addHighlightArea(){this.container.classList.add("highlightArea")}}sre=new WeakMap,nre=new WeakSet,xYe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var rre,LO,IO,are,U9,Tts,gYe;class RGn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){ps(this,U9);ps(this,rre,null);ps(this,LO,null);ps(this,IO,new Map);ps(this,are,null);this.div=t,Ht(this,rre,n),Ht(this,LO,r),Ht(this,are,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return ye(this,IO).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;P9(r,this.viewport);const a=new Map,i={data:null,layer:r,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new Sat,annotationStorage:t.annotationStorage||new _at,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const o of n){if(o.noHTML)continue;const c=o.annotationType===ay.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=lE(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=vGn.create(i);if(!d.isRenderable)continue;if(!c&&o.popupRef){const h=a.get(o.popupRef);h?h.push(d):a.set(o.popupRef,[d])}const u=d.render();o.hidden&&(u.style.visibility="hidden"),await ss(this,U9,Tts).call(this,u,o.id),d._isEditable&&(ye(this,IO).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}ss(this,U9,gYe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,P9(n,{rotation:t.rotation}),ss(this,U9,gYe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(ye(this,IO).values())}getEditableAnnotation(t){return ye(this,IO).get(t)}}rre=new WeakMap,LO=new WeakMap,IO=new WeakMap,are=new WeakMap,U9=new WeakSet,Tts=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${xat}${n}`,i=await((l=ye(this,are))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=ye(this,rre))==null||o.moveElementInDOM(this.div,t,r,!1)},gYe=function(){if(!ye(this,LO))return;const t=this.div;for(const[n,r]of ye(this,LO)){const a=t.querySelector(`[data-annotation-id="${n}"]`);if(!a)continue;r.className="annotationContent";const{firstChild:i}=a;i?i.nodeName==="CANVAS"?i.replaceWith(r):i.classList.contains("annotationContent")?i.after(r):i.before(r):a.append(r)}ye(this,LO).clear()};const jde=/\r\n?|\n/g;var Vk,Ow,ire,DO,zw,Hg,Mts,Pts,Lts,ICe,yE,DCe,RCe,Its,vYe,Dts;const Zm=class Zm extends $h{constructor(n){super({...n,name:"freeTextEditor"});ps(this,Hg);ps(this,Vk);ps(this,Ow,"");ps(this,ire,`${this.id}-editor`);ps(this,DO,null);ps(this,zw);Ht(this,Vk,n.color||Zm._defaultColor||$h._defaultLineColor),Ht(this,zw,n.fontSize||Zm._defaultFontSize)}static get _keyboardManager(){const n=Zm.prototype,r=l=>l.isEmpty(),a=L9.TRANSLATE_SMALL,i=L9.TRANSLATE_BIG;return gu(this,"_keyboardManager",new oie([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],n.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],n.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],n._translateEmpty,{args:[-a,0],checker:r}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],n._translateEmpty,{args:[-i,0],checker:r}],[["ArrowRight","mac+ArrowRight"],n._translateEmpty,{args:[a,0],checker:r}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],n._translateEmpty,{args:[i,0],checker:r}],[["ArrowUp","mac+ArrowUp"],n._translateEmpty,{args:[0,-a],checker:r}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],n._translateEmpty,{args:[0,-i],checker:r}],[["ArrowDown","mac+ArrowDown"],n._translateEmpty,{args:[0,a],checker:r}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],n._translateEmpty,{args:[0,i],checker:r}]]))}static initialize(n,r){$h.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case Nc.FREETEXT_SIZE:Zm._defaultFontSize=r;break;case Nc.FREETEXT_COLOR:Zm._defaultColor=r;break}}updateParams(n,r){switch(n){case Nc.FREETEXT_SIZE:ss(this,Hg,Mts).call(this,r);break;case Nc.FREETEXT_COLOR:ss(this,Hg,Pts).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Nc.FREETEXT_SIZE,Zm._defaultFontSize],[Nc.FREETEXT_COLOR,Zm._defaultColor||$h._defaultLineColor]]}get propertiesToUpdate(){return[[Nc.FREETEXT_SIZE,ye(this,zw)],[Nc.FREETEXT_COLOR,ye(this,Vk)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-Zm._internalPadding*n,-(Zm._internalPadding+ye(this,zw))*n]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(td.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Ht(this,DO,new AbortController);const n=this._uiManager.combinedSignal(ye(this,DO));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:n}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:n}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:n}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:n}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:n})}disableEditMode(){var n;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",ye(this,ire)),this._isDraggable=!0,(n=ye(this,DO))==null||n.abort(),Ht(this,DO,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),n.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var n;this.width||(this.enableEditMode(),this.editorDiv.focus(),(n=this._initialOptions)!=null&&n.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const n=ye(this,Ow),r=Ht(this,Ow,ss(this,Hg,Lts).call(this).trimEnd());if(n===r)return;const a=i=>{if(Ht(this,Ow,i),!i){this.remove();return}ss(this,Hg,RCe).call(this),this._uiManager.rebuild(this),ss(this,Hg,ICe).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),ss(this,Hg,ICe).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(n){this.enterInEditMode()}keydown(n){n.target===this.div&&n.key==="Enter"&&(this.enterInEditMode(),n.preventDefault())}editorDivKeydown(n){Zm._keyboardManager.exec(this,n)}editorDivFocus(n){this.isEditing=!0}editorDivBlur(n){this.isEditing=!1}editorDivInput(n){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",ye(this,ire)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:a}=this.editorDiv;if(a.fontSize=`calc(${ye(this,zw)}px * var(--scale-factor))`,a.color=ye(this,Vk),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),p6e(this,this.div,["dblclick","keydown"]),this.width){const[i,l]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[c,d]=this.getInitialTranslation();[c,d]=this.pageTranslationToScreen(c,d);const[u,h]=this.pageDimensions,[m,p]=this.pageTranslation;let f,g;switch(this.rotation){case 0:f=n+(o[0]-m)/u,g=r+this.height-(o[1]-p)/h;break;case 90:f=n+(o[0]-m)/u,g=r-(o[1]-p)/h,[c,d]=[d,-c];break;case 180:f=n-this.width+(o[0]-m)/u,g=r-(o[1]-p)/h,[c,d]=[-c,-d];break;case 270:f=n+(o[0]-m-this.height*h)/u,g=r+(o[1]-p-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(f*i,g*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);ss(this,Hg,RCe).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var f,g,v;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=ss(f=Zm,yE,vYe).call(f,r.getData("text")||"").replaceAll(jde,` `);if(!i)return;const l=window.getSelection();if(!l.rangeCount)return;this.editorDiv.normalize(),l.deleteFromDocument();const o=l.getRangeAt(0);if(!i.includes(` `)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),l.collapseToStart();return}const{startContainer:c,startOffset:d}=o,u=[],h=[];if(c.nodeType===Node.TEXT_NODE){const y=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(jde,"")),y!==this.editorDiv){let b=u;for(const w of this.editorDiv.childNodes){if(w===y){b=h;continue}b.push(ss(g=Zm,yE,DCe).call(g,w))}}u.push(c.nodeValue.slice(0,d).replaceAll(jde,""))}else if(c===this.editorDiv){let y=u,b=0;for(const w of this.editorDiv.childNodes)b++===d&&(y=h),y.push(ss(v=Zm,yE,DCe).call(v,w))}Ht(this,Ow,`${u.join(` `)}${i}${h.join(` `)}`),ss(this,Hg,RCe).call(this);const m=new Range;let p=u.reduce((y,b)=>y+b.length,0);for(const{firstChild:y}of this.editorDiv.childNodes)if(y.nodeType===Node.TEXT_NODE){const b=y.nodeValue.length;if(p<=b){m.setStart(y,p),m.setEnd(y,p);break}p-=b}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof Sts){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:p},textContent:f,textPosition:g,parent:{page:{pageNumber:v}}}=n;if(!f||f.length===0)return null;i=n={annotationType:td.FREETEXT,color:Array.from(d),fontSize:c,value:f.join(` `),position:g,pageIndex:v-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:p}}const l=await super.deserialize(n,r,a);return Ht(l,zw,n.fontSize),Ht(l,Vk,Vo.makeHexColor(...n.color)),Ht(l,Ow,ss(o=Zm,yE,vYe).call(o,n.value)),l.annotationElementId=n.id||null,l._initialData=i,l}serialize(n=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const r=Zm._internalPadding*this.parentScale,a=this.getRect(r,r),i=$h._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:ye(this,Vk)),l={annotationType:td.FREETEXT,color:i,fontSize:ye(this,zw),value:ss(this,Hg,Its).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!ss(this,Hg,Dts).call(this,l)?null:(l.id=this.annotationElementId,l)}renderAnnotationElement(n){const r=super.renderAnnotationElement(n);if(this.deleted)return r;const{style:a}=r;a.fontSize=`calc(${ye(this,zw)}px * var(--scale-factor))`,a.color=ye(this,Vk),r.replaceChildren();for(const l of ye(this,Ow).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=Zm._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:ye(this,Ow)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};Vk=new WeakMap,Ow=new WeakMap,ire=new WeakMap,DO=new WeakMap,zw=new WeakMap,Hg=new WeakSet,Mts=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-ye(this,zw))*this.parentScale),Ht(this,zw,i),ss(this,Hg,ICe).call(this)},a=ye(this,zw);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Pts=function(n){const r=i=>{Ht(this,Vk,this.editorDiv.style.color=i)},a=ye(this,Vk);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Lts=function(){var a;const n=[];this.editorDiv.normalize();let r=null;for(const i of this.editorDiv.childNodes)(r==null?void 0:r.nodeType)===Node.TEXT_NODE&&i.nodeName==="BR"||(n.push(ss(a=Zm,yE,DCe).call(a,i)),r=i);return n.join(` `)},ICe=function(){const[n,r]=this.parentDimensions;let a;if(this.isAttachedToDOM)a=this.div.getBoundingClientRect();else{const{currentLayer:i,div:l}=this,o=l.style.display,c=l.classList.contains("hidden");l.classList.remove("hidden"),l.style.display="hidden",i.div.append(this.div),a=l.getBoundingClientRect(),l.remove(),l.style.display=o,l.classList.toggle("hidden",c)}this.rotation%180===this.parentRotation%180?(this.width=a.width/n,this.height=a.height/r):(this.width=a.height/n,this.height=a.width/r),this.fixAndSetPosition()},yE=new WeakSet,DCe=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(jde,"")},RCe=function(){if(this.editorDiv.replaceChildren(),!!ye(this,Ow))for(const n of ye(this,Ow).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},Its=function(){return ye(this,Ow).replaceAll(" "," ")},vYe=function(n){return n.replaceAll(" "," ")},Dts=function(n){const{value:r,fontSize:a,color:i,pageIndex:l}=this._initialData;return this._hasBeenMoved||n.value!==r||n.fontSize!==a||n.color.some((o,c)=>o!==i[c])||n.pageIndex!==l},ps(Zm,yE),zr(Zm,"_freeTextDefaultContent",""),zr(Zm,"_internalPadding",0),zr(Zm,"_defaultColor",null),zr(Zm,"_defaultFontSize",10),zr(Zm,"_type","freetext"),zr(Zm,"_editorType",td.FREETEXT);let yYe=Zm;class Rts{toSVGPath(){Mp("Abstract method `toSVGPath` must be implemented.")}get box(){Mp("Abstract getter `box` must be implemented.")}serialize(t,n){Mp("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){Mp("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){Mp("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Bw,Hk,eH,tH,m4,Ed,RO,FO,ore,lre,sH,nH,gM,cre,gMe,yMe,Ay,XX,Fts,Ots,zts,Bts,$ts,Uts;const Q3=class Q3{constructor({x:t,y:n},r,a,i,l,o=0){ps(this,Ay);ps(this,Bw);ps(this,Hk,[]);ps(this,eH);ps(this,tH);ps(this,m4,[]);ps(this,Ed,new Float64Array(18));ps(this,RO);ps(this,FO);ps(this,ore);ps(this,lre);ps(this,sH);ps(this,nH);ps(this,gM,[]);Ht(this,Bw,r),Ht(this,nH,i*a),Ht(this,tH,l),ye(this,Ed).set([NaN,NaN,NaN,NaN,t,n],6),Ht(this,eH,o),Ht(this,lre,ye(Q3,cre)*a),Ht(this,ore,ye(Q3,yMe)*a),Ht(this,sH,a),ye(this,gM).push(t,n)}isEmpty(){return isNaN(ye(this,Ed)[8])}add({x:t,y:n}){var I;Ht(this,RO,t),Ht(this,FO,n);const[r,a,i,l]=ye(this,Bw);let[o,c,d,u]=ye(this,Ed).subarray(8,12);const h=t-d,m=n-u,p=Math.hypot(h,m);if(p=6;a-=6)isNaN(n[a])?r.push(`L${n[a+4]} ${n[a+5]}`):r.push(`C${n[a]} ${n[a+1]} ${n[a+2]} ${n[a+3]} ${n[a+4]} ${n[a+5]}`);return ss(this,Ay,Ots).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new qts(t,n,r,a,i,l)}getOutlines(){var h;const t=ye(this,m4),n=ye(this,Hk),r=ye(this,Ed),[a,i,l,o]=ye(this,Bw),c=new Float64Array((((h=ye(this,gM))==null?void 0:h.length)??0)+2);for(let m=0,p=c.length-2;m=6;m-=6)for(let p=0;p<6;p+=2){if(isNaN(n[m+p])){d[u]=d[u+1]=NaN,u+=2;continue}d[u]=n[m+p],d[u+1]=n[m+p+1],u+=2}return ss(this,Ay,$ts).call(this,d,u),this.newFreeDrawOutline(d,c,ye(this,Bw),ye(this,sH),ye(this,eH),ye(this,tH))}};Bw=new WeakMap,Hk=new WeakMap,eH=new WeakMap,tH=new WeakMap,m4=new WeakMap,Ed=new WeakMap,RO=new WeakMap,FO=new WeakMap,ore=new WeakMap,lre=new WeakMap,sH=new WeakMap,nH=new WeakMap,gM=new WeakMap,cre=new WeakMap,gMe=new WeakMap,yMe=new WeakMap,Ay=new WeakSet,XX=function(){const t=ye(this,Ed).subarray(4,6),n=ye(this,Ed).subarray(16,18),[r,a,i,l]=ye(this,Bw);return[(ye(this,RO)+(t[0]-n[0])/2-r)/i,(ye(this,FO)+(t[1]-n[1])/2-a)/l,(ye(this,RO)+(n[0]-t[0])/2-r)/i,(ye(this,FO)+(n[1]-t[1])/2-a)/l]},Fts=function(){const[t,n,r,a]=ye(this,Bw),[i,l,o,c]=ss(this,Ay,XX).call(this);return`M${(ye(this,Ed)[2]-t)/r} ${(ye(this,Ed)[3]-n)/a} L${(ye(this,Ed)[4]-t)/r} ${(ye(this,Ed)[5]-n)/a} L${i} ${l} L${o} ${c} L${(ye(this,Ed)[16]-t)/r} ${(ye(this,Ed)[17]-n)/a} L${(ye(this,Ed)[14]-t)/r} ${(ye(this,Ed)[15]-n)/a} Z`},Ots=function(t){const n=ye(this,Hk);t.push(`L${n[4]} ${n[5]} Z`)},zts=function(t){const[n,r,a,i]=ye(this,Bw),l=ye(this,Ed).subarray(4,6),o=ye(this,Ed).subarray(16,18),[c,d,u,h]=ss(this,Ay,XX).call(this);t.push(`L${(l[0]-n)/a} ${(l[1]-r)/i} L${c} ${d} L${u} ${h} L${(o[0]-n)/a} ${(o[1]-r)/i}`)},Bts=function(t){const n=ye(this,Ed),[r,a,i,l]=ye(this,Bw),[o,c,d,u]=ss(this,Ay,XX).call(this),h=new Float64Array(36);return h.set([NaN,NaN,NaN,NaN,(n[2]-r)/i,(n[3]-a)/l,NaN,NaN,NaN,NaN,(n[4]-r)/i,(n[5]-a)/l,NaN,NaN,NaN,NaN,o,c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,(n[16]-r)/i,(n[17]-a)/l,NaN,NaN,NaN,NaN,(n[14]-r)/i,(n[15]-a)/l],0),this.newFreeDrawOutline(h,t,ye(this,Bw),ye(this,sH),ye(this,eH),ye(this,tH))},$ts=function(t,n){const r=ye(this,Hk);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},Uts=function(t,n){const r=ye(this,Ed).subarray(4,6),a=ye(this,Ed).subarray(16,18),[i,l,o,c]=ye(this,Bw),[d,u,h,m]=ss(this,Ay,XX).call(this);return t.set([NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-l)/c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,h,m,NaN,NaN,NaN,NaN,(a[0]-i)/o,(a[1]-l)/c],n),n+=24},ps(Q3,cre,8),ps(Q3,gMe,2),ps(Q3,yMe,ye(Q3,cre)+ye(Q3,gMe));let x6e=Q3;var rH,OO,_A,dre,$w,ure,Jx,P_,QX,JX,Vts;class qts extends Rts{constructor(n,r,a,i,l,o){super();ps(this,P_);ps(this,rH);ps(this,OO,null);ps(this,_A);ps(this,dre);ps(this,$w);ps(this,ure);ps(this,Jx);Ht(this,Jx,n),Ht(this,$w,r),Ht(this,rH,a),Ht(this,ure,i),Ht(this,_A,l),Ht(this,dre,o),ss(this,P_,Vts).call(this,o);const{x:c,y:d,width:u,height:h}=ye(this,OO);for(let m=0,p=n.length;mn[0]-r[0]||n[1]-r[1]||n[2]-r[2]);const t=[];for(const n of ye(this,yM))n[3]?(t.push(...ss(this,Tb,bYe).call(this,n)),ss(this,Tb,Gts).call(this,n)):(ss(this,Tb,Wts).call(this,n),t.push(...ss(this,Tb,bYe).call(this,n)));return ss(this,Tb,Hts).call(this,t)}}hre=new WeakMap,yM=new WeakMap,Gk=new WeakMap,Tb=new WeakSet,Hts=function(t){const n=[],r=new Set;for(const l of t){const[o,c,d]=l;n.push([o,c,l],[o,d,l])}n.sort((l,o)=>l[1]-o[1]||l[0]-o[0]);for(let l=0,o=n.length;l0;){const l=r.values().next().value;let[o,c,d,u,h]=l;r.delete(l);let m=o,p=c;for(i=[o,d],a.push(i);;){let f;if(r.has(u))f=u;else if(r.has(h))f=h;else break;r.delete(f),[o,c,d,u,h]=f,m!==o&&(i.push(m,p,o,p===c?c:d),m=o),p=p===c?d:c}i.push(m,p)}return new FGn(a,ye(this,hre))},FCe=function(t){const n=ye(this,Gk);let r=0,a=n.length-1;for(;r<=a;){const i=r+a>>1,l=n[i][0];if(l===t)return i;l=0;a--){const[i,l]=ye(this,Gk)[a];if(i!==t)break;if(i===t&&l===n){ye(this,Gk).splice(a,1);return}}},bYe=function(t){const[n,r,a]=t,i=[[n,r,a]],l=ss(this,Tb,FCe).call(this,a);for(let o=0;o=c){if(p>d)i[u][1]=d;else{if(h===1)return[];i.splice(u,1),u--,h--}continue}i[u][2]=c,p>d&&i.push([n,d,p])}}}return i};var mre,aH;class FGn extends Rts{constructor(n,r){super();ps(this,mre);ps(this,aH);Ht(this,aH,n),Ht(this,mre,r)}toSVGPath(){const n=[];for(const r of ye(this,aH)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Ht(this,f_,!0),ss(this,Hc,OCe).call(this,n),ss(this,Hc,nF).call(this)):ye(this,wA)&&(Ht(this,cH,n.anchorNode),Ht(this,yre,n.anchorOffset),Ht(this,vre,n.focusNode),Ht(this,bre,n.focusOffset),ss(this,Hc,kYe).call(this),ss(this,Hc,nF).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=nh.prototype;return gu(this,"_keyboardManager",new oie([[["ArrowLeft","mac+ArrowLeft"],n._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],n._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],n._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],n._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:ye(this,f_)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:ye(this,$2),methodOfCreation:ye(this,_re)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(n){return{numberOfColors:n.get("color").size}}static initialize(n,r){var a;$h.initialize(n,r),nh._defaultColor||(nh._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case Nc.HIGHLIGHT_DEFAULT_COLOR:nh._defaultColor=r;break;case Nc.HIGHLIGHT_THICKNESS:nh._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return ye(this,uH)}updateParams(n,r){switch(n){case Nc.HIGHLIGHT_COLOR:ss(this,Hc,Yts).call(this,r);break;case Nc.HIGHLIGHT_THICKNESS:ss(this,Hc,Zts).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Nc.HIGHLIGHT_DEFAULT_COLOR,nh._defaultColor],[Nc.HIGHLIGHT_THICKNESS,nh._defaultThickness]]}get propertiesToUpdate(){return[[Nc.HIGHLIGHT_COLOR,this.color||nh._defaultColor],[Nc.HIGHLIGHT_THICKNESS,ye(this,$2)||nh._defaultThickness],[Nc.HIGHLIGHT_FREE,ye(this,f_)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Ht(this,dH,new g6e({editor:this})),n.addColorPicker(ye(this,dH))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(ss(this,Hc,eQ).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,ss(this,Hc,eQ).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){ss(this,Hc,SYe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(ss(this,Hc,nF).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?ss(this,Hc,SYe).call(this):n&&(ss(this,Hc,nF).call(this,n),r=!this.parent&&((a=this.div)==null?void 0:a.classList.contains("selectedEditor"))),super.setParent(n),this.show(this._isVisible),r&&this.select()}rotate(n){var i,l,o;const{drawLayer:r}=this.parent;let a;ye(this,f_)?(n=(n-this.rotation+360)%360,a=ss(i=nh,oN,z$).call(i,ye(this,Yk).box,n)):a=ss(l=nh,oN,z$).call(l,this,n),r.rotate(ye(this,s1),n),r.rotate(ye(this,dy),n),r.updateBox(ye(this,s1),a),r.updateBox(ye(this,dy),ss(o=nh,oN,z$).call(o,ye(this,B2).box,n))}render(){if(this.div)return this.div;const n=super.render();ye(this,hH)&&(n.setAttribute("aria-label",ye(this,hH)),n.setAttribute("role","mark")),ye(this,f_)?n.classList.add("free"):this.div.addEventListener("keydown",ss(this,Hc,Qts).bind(this),{signal:this._uiManager._signal});const r=Ht(this,$O,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=ye(this,BO);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),p6e(this,ye(this,$O),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(ye(this,dy),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(ye(this,dy),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:ss(this,Hc,zCe).call(this,!0);break;case 1:case 3:ss(this,Hc,zCe).call(this,!1);break}}select(){var n,r;super.select(),ye(this,dy)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,dy),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(ye(this,dy),"selected"))}unselect(){var n;super.unselect(),ye(this,dy)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,dy),"selected"),ye(this,f_)||ss(this,Hc,zCe).call(this,!1))}get _mustFixPosition(){return!ye(this,f_)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(ye(this,s1),n),this.parent.drawLayer.show(ye(this,dy),n))}static startHighlighting(n,r,{target:a,x:i,y:l}){const{x:o,y:c,width:d,height:u}=a.getBoundingClientRect(),h=new AbortController,m=n.combinedSignal(h),p=g=>{g.preventDefault(),g.stopPropagation()},f=g=>{h.abort(),ss(this,oN,sss).call(this,n,g)};window.addEventListener("blur",f,{signal:m}),window.addEventListener("pointerup",f,{signal:m}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",FN,{signal:m}),a.addEventListener("pointermove",ss(this,oN,tss).bind(this,n),{signal:m}),this._freeHighlight=new _Ye({x:i,y:l},[o,c,d,u],n.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=n.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(n,r,a){var g,v,y,b;let i=null;if(n instanceof Ats){const{data:{quadPoints:w,rect:S,rotation:C,id:E,color:P,opacity:M,popupRef:I},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:td.HIGHLIGHT,color:Array.from(P),opacity:M,quadPoints:w,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:C,id:E,deleted:!1,popupRef:I}}else if(n instanceof Cat){const{data:{inkLists:w,rect:S,rotation:C,id:E,color:P,borderStyle:{rawWidth:M},popupRef:I},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:td.HIGHLIGHT,color:Array.from(P),thickness:M,inkLists:w,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:C,id:E,deleted:!1,popupRef:I}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=Vo.makeHexColor(...l),Ht(u,jA,d||1),c&&Ht(u,$2,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[p,f]=u.pageTranslation;if(o){const w=Ht(u,wA,[]);for(let S=0;S=0)Ht(this,s1,r),Ht(this,BO,a),this.parent.drawLayer.finalizeLine(r,n),Ht(this,dy,this.parent.drawLayer.drawOutline(ye(this,B2)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(ye(this,s1),n),this.parent.drawLayer.updateBox(ye(this,s1),ss(h=nh,oN,z$).call(h,ye(this,Yk).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(ye(this,dy),ye(this,B2)),this.parent.drawLayer.updateBox(ye(this,dy),ss(m=nh,oN,z$).call(m,ye(this,B2).box,p))}const{x:l,y:o,width:c,height:d}=n.box;switch(this.rotation){case 0:this.x=l,this.y=o,this.width=c,this.height=d;break;case 90:{const[p,f]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*f/p,this.height=d*p/f;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[p,f]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*f/p,this.height=d*p/f;break}}const{lastPoint:u}=ye(this,B2).box;Ht(this,uH,[(u[0]-l)/c,(u[1]-o)/d])},Yts=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(ye(this,s1),l),(d=ye(this,dH))==null||d.updateColor(l),Ht(this,jA,o),(u=this.parent)==null||u.drawLayer.changeOpacity(ye(this,s1),o)},a=this.color,i=ye(this,jA);this.addCommands({cmd:r.bind(this,n,nh._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},Zts=function(n){const r=ye(this,$2),a=i=>{Ht(this,$2,i),ss(this,Hc,Xts).call(this,i)};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},Xts=function(n){if(!ye(this,f_))return;ss(this,Hc,OCe).call(this,{highlightOutlines:ye(this,Yk).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},SYe=function(){ye(this,s1)===null||!this.parent||(this.parent.drawLayer.remove(ye(this,s1)),Ht(this,s1,null),this.parent.drawLayer.remove(ye(this,dy)),Ht(this,dy,null))},nF=function(n=this.parent){ye(this,s1)===null&&({id:Jy(this,s1)._,clipPathId:Jy(this,BO)._}=n.drawLayer.draw(ye(this,Yk),this.color,ye(this,jA)),Ht(this,dy,n.drawLayer.drawOutline(ye(this,B2))),ye(this,$O)&&(ye(this,$O).style.clipPath=ye(this,BO)))},oN=new WeakSet,z$=function({x:n,y:r,width:a,height:i},l){switch(l){case 90:return{x:1-r-i,y:n,width:i,height:a};case 180:return{x:1-n-a,y:1-r-i,width:a,height:i};case 270:return{x:r,y:1-n-a,width:i,height:a}}return{x:n,y:r,width:a,height:i}},Qts=function(n){nh._keyboardManager.exec(this,n)},zCe=function(n){if(!ye(this,cH))return;const r=window.getSelection();n?r.setPosition(ye(this,cH),ye(this,yre)):r.setPosition(ye(this,vre),ye(this,bre))},eQ=function(){return ye(this,f_)?this.rotation:0},Jts=function(){if(ye(this,f_))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=ye(this,wA),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const p=d*n+a,f=(1-u-m)*r+i;o[c]=o[c+4]=p,o[c+1]=o[c+3]=f,o[c+2]=o[c+6]=p+h*n,o[c+5]=o[c+7]=f+m*r,c+=8}return o},ess=function(n){return ye(this,Yk).serialize(n,ss(this,Hc,eQ).call(this))},tss=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},sss=function(n,r){this._freeHighlight.isEmpty()?n.drawLayer.remove(this._freeHighlightId):n.createAndAddNewEditor(r,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},nss=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},ps(nh,oN),zr(nh,"_defaultColor",null),zr(nh,"_defaultOpacity",1),zr(nh,"_defaultThickness",12),zr(nh,"_type","highlight"),zr(nh,"_editorType",td.HIGHLIGHT),zr(nh,"_freeHighlightId",-1),zr(nh,"_freeHighlight",null),zr(nh,"_freeHighlightClipId","");let y6e=nh;var UO,qO,p4,NA,U2,VO,HO,GO,kA,mH,WO,KO,bM,Ti,rss,ass,iss,oss,AYe,lss,EYe,css,dss,uss,hss,mss,rF,TYe,MYe,PYe,BCe,$Ce,B$,LYe,UCe,FE,pss,IYe,fss,xss,DYe,qCe,tQ;const Sf=class Sf extends $h{constructor(n){super({...n,name:"inkEditor"});ps(this,Ti);ps(this,UO,0);ps(this,qO,0);ps(this,p4,null);ps(this,NA,new Path2D);ps(this,U2,!1);ps(this,VO,null);ps(this,HO,!1);ps(this,GO,!1);ps(this,kA,null);ps(this,mH,null);ps(this,WO,0);ps(this,KO,0);ps(this,bM,null);this.color=n.color||null,this.thickness=n.thickness||null,this.opacity=n.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(n,r){$h.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case Nc.INK_THICKNESS:Sf._defaultThickness=r;break;case Nc.INK_COLOR:Sf._defaultColor=r;break;case Nc.INK_OPACITY:Sf._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case Nc.INK_THICKNESS:ss(this,Ti,rss).call(this,r);break;case Nc.INK_COLOR:ss(this,Ti,ass).call(this,r);break;case Nc.INK_OPACITY:ss(this,Ti,iss).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Nc.INK_THICKNESS,Sf._defaultThickness],[Nc.INK_COLOR,Sf._defaultColor||$h._defaultLineColor],[Nc.INK_OPACITY,Math.round(Sf._defaultOpacity*100)]]}get propertiesToUpdate(){return[[Nc.INK_THICKNESS,this.thickness||Sf._defaultThickness],[Nc.INK_COLOR,this.color||Sf._defaultColor||$h._defaultLineColor],[Nc.INK_OPACITY,Math.round(100*(this.opacity??Sf._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(ss(this,Ti,BCe).call(this),ss(this,Ti,$Ce).call(this)),this.isAttachedToDOM||(this.parent.add(this),ss(this,Ti,B$).call(this)),ss(this,Ti,tQ).call(this)))}remove(){var n;this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,ye(this,p4)&&(clearTimeout(ye(this,p4)),Ht(this,p4,null)),(n=ye(this,kA))==null||n.disconnect(),Ht(this,kA,null),super.remove())}setParent(n){!this.parent&&n?this._uiManager.removeShouldRescale(this):this.parent&&n===null&&this._uiManager.addShouldRescale(this),super.setParent(n)}onScaleChanging(){const[n,r]=this.parentDimensions,a=this.width*n,i=this.height*r;this.setDimensions(a,i)}enableEditMode(){ye(this,U2)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,ss(this,Ti,TYe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),ss(this,Ti,MYe).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){ye(this,U2)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Ht(this,U2,!0),this.div.classList.add("disabled"),ss(this,Ti,tQ).call(this,!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),this.enableEditMode())}canvasPointerdown(n){n.button!==0||!this.isInEditMode()||ye(this,U2)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),ss(this,Ti,lss).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),ss(this,Ti,EYe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),ss(this,Ti,PYe).call(this,n)}canvasPointerleave(n){ss(this,Ti,PYe).call(this,n)}get isResizable(){return!this.isEmpty()&&ye(this,U2)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[a,i,l,o]=ss(this,Ti,oss).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),ss(this,Ti,BCe).call(this),this.width){const[c,d]=this.parentDimensions;this.setAspectRatio(this.width*c,this.height*d),this.setAt(n*c,r*d,this.width*c,this.height*d),Ht(this,GO,!0),ss(this,Ti,B$).call(this),this.setDims(this.width*c,this.height*d),ss(this,Ti,rF).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return ss(this,Ti,$Ce).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(ye(this,WO)===a&&ye(this,KO)===i)return;Ht(this,WO,a),Ht(this,KO,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),ye(this,U2)&&ss(this,Ti,LYe).call(this,n,r),ss(this,Ti,B$).call(this),ss(this,Ti,rF).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var v,y,b;if(n instanceof Cat)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=Vo.makeHexColor(...n.color),i.opacity=n.opacity;const[l,o]=i.pageDimensions,c=i.width*l,d=i.height*o,u=i.parentScale,h=n.thickness/2;Ht(i,U2,!0),Ht(i,WO,Math.round(c)),Ht(i,KO,Math.round(d));const{paths:m,rect:p,rotation:f}=n;for(let{bezier:w}of m){w=ss(v=Sf,FE,fss).call(v,w,p,f);const S=[];i.paths.push(S);let C=u*(w[0]-h),E=u*(w[1]-h);for(let M=2,I=w.length;M{this.thickness=i,ss(this,Ti,tQ).call(this)},a=this.thickness;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},ass=function(n){const r=i=>{this.color=i,ss(this,Ti,rF).call(this)},a=this.color;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},iss=function(n){const r=i=>{this.opacity=i,ss(this,Ti,rF).call(this)};n/=100;const a=this.opacity;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Nc.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},oss=function(){const{parentRotation:n,parentDimensions:[r,a]}=this;switch(n){case 90:return[0,a,a,r];case 180:return[r,a,r,a];case 270:return[r,0,a,r];default:return[0,0,r,a]}},AYe=function(){const{ctx:n,color:r,opacity:a,thickness:i,parentScale:l,scaleFactor:o}=this;n.lineWidth=i*l/o,n.lineCap="round",n.lineJoin="round",n.miterLimit=10,n.strokeStyle=`${r}${iHn(a)}`},lss=function(n,r){this.canvas.addEventListener("contextmenu",FN,{signal:this._uiManager._signal}),ss(this,Ti,MYe).call(this),Ht(this,VO,new AbortController);const a=this._uiManager.combinedSignal(ye(this,VO));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:a}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:a}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:a}),this.isEditing=!0,ye(this,GO)||(Ht(this,GO,!0),ss(this,Ti,B$).call(this),this.thickness||(this.thickness=Sf._defaultThickness),this.color||(this.color=Sf._defaultColor||$h._defaultLineColor),this.opacity??(this.opacity=Sf._defaultOpacity)),this.currentPath.push([n,r]),Ht(this,HO,!1),ss(this,Ti,AYe).call(this),Ht(this,bM,()=>{ss(this,Ti,uss).call(this),ye(this,bM)&&window.requestAnimationFrame(ye(this,bM))}),window.requestAnimationFrame(ye(this,bM))},EYe=function(n,r){const[a,i]=this.currentPath.at(-1);if(this.currentPath.length>1&&n===a&&r===i)return;const l=this.currentPath;let o=ye(this,NA);if(l.push([n,r]),Ht(this,HO,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Ht(this,NA,o=new Path2D),o.moveTo(...l[0])),ss(this,Ti,hss).call(this,o,...l.at(-3),...l.at(-2),n,r)},css=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);ye(this,NA).lineTo(...n)},dss=function(n,r){Ht(this,bM,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),ss(this,Ti,EYe).call(this,n,r),ss(this,Ti,css).call(this);let a;if(this.currentPath.length!==1)a=ss(this,Ti,mss).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=ye(this,NA),l=this.currentPath;this.currentPath=[],Ht(this,NA,new Path2D);const o=()=>{this.allRawPaths.push(l),this.paths.push(a),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},c=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(ss(this,Ti,BCe).call(this),ss(this,Ti,$Ce).call(this)),ss(this,Ti,tQ).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},uss=function(){if(!ye(this,HO))return;Ht(this,HO,!1);const n=Math.ceil(this.thickness*this.parentScale),r=this.currentPath.slice(-3),a=r.map(o=>o[0]),i=r.map(o=>o[1]);Math.min(...a)-n,Math.max(...a)+n,Math.min(...i)-n,Math.max(...i)+n;const{ctx:l}=this;l.save(),l.clearRect(0,0,this.canvas.width,this.canvas.height);for(const o of this.bezierPath2D)l.stroke(o);l.stroke(ye(this,NA)),l.restore()},hss=function(n,r,a,i,l,o,c){const d=(r+i)/2,u=(a+l)/2,h=(i+o)/2,m=(l+c)/2;n.bezierCurveTo(d+2*(i-d)/3,u+2*(l-u)/3,h+2*(i-h)/3,m+2*(l-m)/3,h,m)},mss=function(){const n=this.currentPath;if(n.length<=2)return[[n[0],n[0],n.at(-1),n.at(-1)]];const r=[];let a,[i,l]=n[0];for(a=1;a{Ht(this,p4,null),this.canvas.removeEventListener("contextmenu",FN)},10)),ss(this,Ti,dss).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},BCe=function(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")},$Ce=function(){Ht(this,kA,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),ye(this,kA).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,kA))==null||n.disconnect(),Ht(this,kA,null)},{once:!0})},B$=function(){if(!ye(this,GO))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),ss(this,Ti,UCe).call(this)},LYe=function(n,r){const a=ss(this,Ti,qCe).call(this),i=(n-a)/ye(this,qO),l=(r-a)/ye(this,UO);this.scaleFactor=Math.min(i,l)},UCe=function(){const n=ss(this,Ti,qCe).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},FE=new WeakSet,pss=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return gu(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(td.STAMP,{bitmapFile:n.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var n;return{type:"stamp",hasAltText:!!((n=this.altTextData)!=null&&n.altText)}}static computeTelemetryFinalData(n){const r=n.get("hasAltText");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}async mlGuessAltText(n=null,r=!0){if(this.hasAltTextData())return null;const{mlManager:a}=this._uiManager;if(!a)throw new Error("No ML.");if(!await a.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:l,height:o}=n||this.copyCanvas(null,null,!0).imageData,c=await a.guess({name:"altText",request:{data:i,width:l,height:o,channels:i.length/(l*o)}});if(!c)throw new Error("No response from the AI service.");if(c.error)throw new Error("Error from the AI service.");if(c.cancel)return null;if(!c.output)throw new Error("No valid response from the AI service.");const d=c.output;return await this.setGuessedAltText(d),r&&!this.hasAltTextData()&&(this.altTextData={alt:d,decorative:!1}),d}remove(){var n,r;ye(this,sv)&&(Ht(this,Af,null),this._uiManager.imageManager.deleteId(ye(this,sv)),(n=ye(this,f4))==null||n.remove(),Ht(this,f4,null),(r=ye(this,CA))==null||r.disconnect(),Ht(this,CA,null),ye(this,x4)&&(clearTimeout(ye(this,x4)),Ht(this,x4,null))),super.remove()}rebuild(){if(!this.parent){ye(this,sv)&&ss(this,tu,VCe).call(this);return}super.rebuild(),this.div!==null&&(ye(this,sv)&&ye(this,f4)===null&&ss(this,tu,VCe).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(ye(this,_M)||ye(this,Af)||ye(this,SA)||ye(this,wM)||ye(this,sv))}get isResizable(){return!0}render(){if(this.div)return this.div;let n,r;if(this.width&&(n=this.x,r=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),ye(this,Af)?ss(this,tu,FYe).call(this):ss(this,tu,VCe).call(this),this.width&&!this.annotationElementId){const[a,i]=this.parentDimensions;this.setAt(n*a,r*i,this.width*a,this.height*i)}return this.div}copyCanvas(n,r,a=!1){var p;n||(n=224);const{width:i,height:l}=ye(this,Af),o=new LKe;let c=ye(this,Af),d=i,u=l,h=null;if(r){if(i>r||l>r){const M=Math.min(r/i,r/l);d=Math.floor(i*M),u=Math.floor(l*M)}h=document.createElement("canvas");const f=h.width=Math.ceil(d*o.sx),g=h.height=Math.ceil(u*o.sy);ye(this,Uw)||(c=ss(this,tu,HCe).call(this,f,g));const v=h.getContext("2d");v.filter=this._uiManager.hcmFilter;let y="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(y="#8f8f9d",b="#42414d");const w=15,S=w*o.sx,C=w*o.sy,E=new OffscreenCanvas(S*2,C*2),P=E.getContext("2d");P.fillStyle=y,P.fillRect(0,0,S*2,C*2),P.fillStyle=b,P.fillRect(0,0,S,C),P.fillRect(S,C,S,C),v.fillStyle=v.createPattern(E,"repeat"),v.fillRect(0,0,f,g),v.drawImage(c,0,0,c.width,c.height,0,0,f,g)}let m=null;if(a){let f,g;if(o.symmetric&&c.widthn||l>n){const b=Math.min(n/i,n/l);f=Math.floor(i*b),g=Math.floor(l*b),ye(this,Uw)||(c=ss(this,tu,HCe).call(this,f,g))}const y=new OffscreenCanvas(f,g).getContext("2d",{willReadFrequently:!0});y.drawImage(c,0,0,c.width,c.height,0,0,f,g),m={width:f,height:g,data:y.getImageData(0,0,f,g).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return ye(this,f4)}static async deserialize(n,r,a){var g;let i=null;if(n instanceof Ets){const{data:{rect:v,rotation:y,id:b,structParent:w,popupRef:S},container:C,parent:{page:{pageNumber:E}}}=n,P=C.querySelector("canvas"),M=a.imageManager.getFromCanvas(C.id,P);P.remove();const I=((g=await r._structTree.getAriaAttributes(`${xat}${b}`))==null?void 0:g.get("aria-label"))||"";i=n={annotationType:td.STAMP,bitmapId:M.id,bitmap:M.bitmap,pageIndex:E-1,rect:v.slice(0),rotation:y,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:I},isSvg:!1,structParent:w,popupRef:S}}const l=await super.deserialize(n,r,a),{rect:o,bitmap:c,bitmapUrl:d,bitmapId:u,isSvg:h,accessibilityData:m}=n;u&&a.imageManager.isValidId(u)?(Ht(l,sv,u),c&&Ht(l,Af,c)):Ht(l,SA,d),Ht(l,Uw,h);const[p,f]=l.pageDimensions;return l.width=(o[2]-o[0])/p,l.height=(o[3]-o[1])/f,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,Ht(l,fH,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:td.STAMP,bitmapId:ye(this,sv),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:ye(this,Uw),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=ss(this,tu,GCe).call(this,!0),a.accessibilityData=this.serializeAltText(!0),a;const{decorative:i,altText:l}=this.serializeAltText(!1);if(!i&&l&&(a.accessibilityData={type:"Figure",alt:l}),this.annotationElementId){const c=ss(this,tu,vss).call(this,a);if(c.isSame)return null;c.isSameAltText?delete a.accessibilityData:a.accessibilityData.structParent=this._initialData.structParent??-1}if(a.id=this.annotationElementId,r===null)return a;r.stamps||(r.stamps=new Map);const o=ye(this,Uw)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(ye(this,sv)))r.stamps.set(ye(this,sv),{area:o,serialized:a}),a.bitmap=ss(this,tu,GCe).call(this,!1);else if(ye(this,Uw)){const c=r.stamps.get(ye(this,sv));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=ss(this,tu,GCe).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};Af=new WeakMap,sv=new WeakMap,_M=new WeakMap,SA=new WeakMap,wM=new WeakMap,pH=new WeakMap,f4=new WeakMap,CA=new WeakMap,x4=new WeakMap,Uw=new WeakMap,fH=new WeakMap,tu=new WeakSet,sQ=function(n,r=!1){if(!n){this.remove();return}Ht(this,Af,n.bitmap),r||(Ht(this,sv,n.id),Ht(this,Uw,n.isSvg)),n.file&&Ht(this,pH,n.file.name),ss(this,tu,FYe).call(this)},nQ=function(){if(Ht(this,_M,null),this._uiManager.enableWaiting(!1),!!ye(this,f4)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,Af)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,Af)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},VCe=function(){if(ye(this,sv)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(ye(this,sv)).then(a=>ss(this,tu,sQ).call(this,a,!0)).finally(()=>ss(this,tu,nQ).call(this));return}if(ye(this,SA)){const a=ye(this,SA);Ht(this,SA,null),this._uiManager.enableWaiting(!0),Ht(this,_M,this._uiManager.imageManager.getFromUrl(a).then(i=>ss(this,tu,sQ).call(this,i)).finally(()=>ss(this,tu,nQ).call(this)));return}if(ye(this,wM)){const a=ye(this,wM);Ht(this,wM,null),this._uiManager.enableWaiting(!0),Ht(this,_M,this._uiManager.imageManager.getFromFile(a).then(i=>ss(this,tu,sQ).call(this,i)).finally(()=>ss(this,tu,nQ).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=Ree.supportedTypesStr;const r=this._uiManager._signal;Ht(this,_M,new Promise(a=>{n.addEventListener("change",async()=>{if(!n.files||n.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(n.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),ss(this,tu,sQ).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>ss(this,tu,nQ).call(this))),n.click()},FYe=function(){const{div:n}=this;let{width:r,height:a}=ye(this,Af);const[i,l]=this.pageDimensions,o=.75;if(this.width)r=this.width*i,a=this.height*l;else if(r>o*i||a>o*l){const h=Math.min(o*i/r,o*l/a);r*=h,a*=h}const[c,d]=this.parentDimensions;this.setDims(r*c/i,a*d/l),this._uiManager.enableWaiting(!1);const u=Ht(this,f4,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),ss(this,tu,OYe).call(this,r,a),ss(this,tu,yss).call(this),ye(this,fH)||(this.parent.addUndoableEditor(this),Ht(this,fH,!0)),this._reportTelemetry({action:"inserted_image"}),ye(this,pH)&&u.setAttribute("aria-label",ye(this,pH))},gss=function(n,r){var o;const[a,i]=this.parentDimensions;this.width=n/a,this.height=r/i,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,ye(this,x4)!==null&&clearTimeout(ye(this,x4)),Ht(this,x4,setTimeout(()=>{Ht(this,x4,null),ss(this,tu,OYe).call(this,n,r)},200))},HCe=function(n,r){const{width:a,height:i}=ye(this,Af);let l=a,o=i,c=ye(this,Af);for(;l>2*n||o>2*r;){const d=l,u=o;l>2*n&&(l=l>=16384?Math.floor(l/2)-1:Math.ceil(l/2)),o>2*r&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const h=new OffscreenCanvas(l,o);h.getContext("2d").drawImage(c,0,0,d,u,0,0,l,o),c=h.transferToImageBitmap()}return c},OYe=function(n,r){const a=new LKe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=ye(this,f4);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=ye(this,Uw)?ye(this,Af):ss(this,tu,HCe).call(this,i,l),d=o.getContext("2d");d.filter=this._uiManager.hcmFilter,d.drawImage(c,0,0,c.width,c.height,0,0,i,l)},GCe=function(n){if(n){if(ye(this,Uw)){const i=this._uiManager.imageManager.getSvgUrl(ye(this,sv));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=ye(this,Af),r.getContext("2d").drawImage(ye(this,Af),0,0),r.toDataURL()}if(ye(this,Uw)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*sL.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*sL.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(ye(this,Af),0,0,ye(this,Af).width,ye(this,Af).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(ye(this,Af))},yss=function(){this._uiManager._signal&&(Ht(this,CA,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&ss(this,tu,gss).call(this,r.width,r.height)})),ye(this,CA).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,CA))==null||n.disconnect(),Ht(this,CA,null)},{once:!0}))},vss=function(n){var d;const{rect:r,pageIndex:a,accessibilityData:{altText:i}}=this._initialData,l=n.rect.every((u,h)=>Math.abs(u-r[h])<1),o=n.pageIndex===a,c=(((d=n.accessibilityData)==null?void 0:d.alt)||"")===i;return{isSame:l&&o&&c,isSameAltText:c}},zr(Ree,"_type","stamp"),zr(Ree,"_editorType",td.STAMP);let RYe=Ree;var YO,xH,g4,jM,AA,qw,NM,gH,yH,n1,EA,ml,kM,Cv,bss,BYe,$Ye,UYe,WCe;const Pk=class Pk{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){ps(this,Cv);ps(this,YO);ps(this,xH,!1);ps(this,g4,null);ps(this,jM,null);ps(this,AA,null);ps(this,qw,new Map);ps(this,NM,!1);ps(this,gH,!1);ps(this,yH,!1);ps(this,n1,null);ps(this,EA,null);ps(this,ml);const h=[...ye(Pk,kM).values()];if(!Pk._initialized){Pk._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Ht(this,ml,t),this.pageIndex=n,this.div=r,Ht(this,YO,i),Ht(this,g4,l),this.viewport=d,Ht(this,n1,c),this.drawLayer=o,this._structTree=a,ye(this,ml).addLayer(this)}get isEmpty(){return ye(this,qw).size===0}get isInvisible(){return this.isEmpty&&ye(this,ml).getMode()===td.NONE}updateToolbar(t){ye(this,ml).updateToolbar(t)}updateMode(t=ye(this,ml).getMode()){switch(ss(this,Cv,WCe).call(this),t){case td.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case td.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case td.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:n}=this.div;for(const r of ye(Pk,kM).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=ye(this,n1))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(ye(this,ml).getMode()!==td.INK)return;if(!t){for(const r of ye(this,qw).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){ye(this,ml).setEditingState(t)}addCommands(t){ye(this,ml).addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){var n;(n=ye(this,g4))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of ye(this,qw).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(ye(this,ml).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!ye(this,g4))return;const n=ye(this,g4).getEditableAnnotations();for(const r of n){if(r.hide(),ye(this,ml).isDeletedAnnotationElement(r.data.id)||t.has(r.data.id))continue;const a=await this.deserialize(r);a&&(this.addOrRebuild(a),a.enableEditing())}}disable(){var a;Ht(this,yH,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of ye(this,qw).values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else n.set(i.annotationElementId,i);(a=this.getEditableAnnotation(i.annotationElementId))==null||a.show(),i.remove()}if(ye(this,g4)){const i=ye(this,g4).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(ye(this,ml).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(ye(this,ml).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}ss(this,Cv,WCe).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of ye(Pk,kM).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Ht(this,yH,!1)}getEditableAnnotation(t){var n;return((n=ye(this,g4))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){ye(this,ml).getActive()!==t&&ye(this,ml).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=ye(this,n1))!=null&&t.div&&!ye(this,EA)){Ht(this,EA,new AbortController);const n=ye(this,ml).combinedSignal(ye(this,EA));ye(this,n1).div.addEventListener("pointerdown",ss(this,Cv,bss).bind(this),{signal:n}),ye(this,n1).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=ye(this,n1))!=null&&t.div&&ye(this,EA)&&(ye(this,EA).abort(),Ht(this,EA,null),ye(this,n1).div.classList.remove("highlighting"))}enableClick(){if(ye(this,jM))return;Ht(this,jM,new AbortController);const t=ye(this,ml).combinedSignal(ye(this,jM));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=ye(this,jM))==null||t.abort(),Ht(this,jM,null)}attach(t){ye(this,qw).set(t.id,t);const{annotationElementId:n}=t;n&&ye(this,ml).isDeletedAnnotationElement(n)&&ye(this,ml).removeDeletedAnnotationElement(t)}detach(t){var n;ye(this,qw).delete(t.id),(n=ye(this,YO))==null||n.removePointerInTextLayer(t.contentDiv),!ye(this,yH)&&t.annotationElementId&&ye(this,ml).addDeletedAnnotationElement(t)}remove(t){this.detach(t),ye(this,ml).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,ye(this,gH)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(ye(this,ml).addDeletedAnnotationElement(t.annotationElementId),$h.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(n=t.parent)==null||n.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),ye(this,ml).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),ye(this,ml).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!ye(this,AA)&&(t._focusEventsAllowed=!1,Ht(this,AA,setTimeout(()=>{Ht(this,AA,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:ye(this,ml)._signal}),n.focus())},0))),t._structTreeParentId=(r=ye(this,YO))==null?void 0:r.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const n=()=>t._uiManager.rebuild(t),r=()=>{t.remove()};this.addCommands({cmd:n,undo:r,mustExec:!1})}getNextId(){return ye(this,ml).getId()}combinedSignal(t){return ye(this,ml).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=ye(this,Cv,BYe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){ye(this,ml).updateToolbar(t),ye(this,ml).updateMode(t);const{offsetX:r,offsetY:a}=ss(this,Cv,UYe).call(this),i=this.getNextId(),l=ss(this,Cv,$Ye).call(this,{parent:this,id:i,x:r,y:a,uiManager:ye(this,ml),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=ye(Pk,kM).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,ye(this,ml)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=ss(this,Cv,$Ye).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:ye(this,ml),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(ss(this,Cv,UYe).call(this),!0)}setSelected(t){ye(this,ml).setSelected(t)}toggleSelected(t){ye(this,ml).toggleSelected(t)}unselect(t){ye(this,ml).unselect(t)}pointerup(t){const{isMac:n}=Sb.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&ye(this,NM)){if(Ht(this,NM,!1),!ye(this,xH)){Ht(this,xH,!0);return}if(ye(this,ml).getMode()===td.STAMP){ye(this,ml).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(ye(this,ml).getMode()===td.HIGHLIGHT&&this.enableTextSelection(),ye(this,NM)){Ht(this,NM,!1);return}const{isMac:n}=Sb.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Ht(this,NM,!0);const r=ye(this,ml).getActive();Ht(this,xH,!r||r.isEmpty())}findNewParent(t,n,r){const a=ye(this,ml).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=ye(this,ml).getActive())==null?void 0:t.parent)===this&&(ye(this,ml).commitOrRemove(),ye(this,ml).setActiveEditor(null)),ye(this,AA)&&(clearTimeout(ye(this,AA)),Ht(this,AA,null));for(const r of ye(this,qw).values())(n=ye(this,YO))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,ye(this,qw).clear(),ye(this,ml).removeLayer(this)}render({viewport:t}){this.viewport=t,P9(this.div,t);for(const n of ye(this,ml).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){ye(this,ml).commitOrRemove(),ss(this,Cv,WCe).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,P9(this.div,{rotation:r}),n!==r)for(const a of ye(this,qw).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return ye(this,ml).viewParameters.realScale}};YO=new WeakMap,xH=new WeakMap,g4=new WeakMap,jM=new WeakMap,AA=new WeakMap,qw=new WeakMap,NM=new WeakMap,gH=new WeakMap,yH=new WeakMap,n1=new WeakMap,EA=new WeakMap,ml=new WeakMap,kM=new WeakMap,Cv=new WeakSet,bss=function(t){ye(this,ml).unselectAll();const{target:n}=t;if(n===ye(this,n1).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&ye(this,n1).div.contains(n)){const{isMac:r}=Sb.platform;if(t.button!==0||t.ctrlKey&&r)return;ye(this,ml).showAllEditors("highlight",!0,!0),ye(this,n1).div.classList.add("free"),this.toggleDrawing(),y6e.startHighlighting(this,ye(this,ml).direction==="ltr",{target:ye(this,n1).div,x:t.x,y:t.y}),ye(this,n1).div.addEventListener("pointerup",()=>{ye(this,n1).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:ye(this,ml)._signal}),t.preventDefault()}},BYe=function(){return ye(Pk,kM).get(ye(this,ml).getMode())},$Ye=function(t){const n=ye(this,Cv,BYe);return n?new n.prototype.constructor(t):null},UYe=function(){const{x:t,y:n,width:r,height:a}=this.div.getBoundingClientRect(),i=Math.max(0,t),l=Math.max(0,n),o=Math.min(window.innerWidth,t+r),c=Math.min(window.innerHeight,n+a),d=(i+o)/2-t,u=(l+c)/2-n,[h,m]=this.viewport.rotation%180===0?[d,u]:[u,d];return{offsetX:h,offsetY:m}},WCe=function(){Ht(this,gH,!0);for(const t of ye(this,qw).values())t.isEmpty()&&t.remove();Ht(this,gH,!1)},zr(Pk,"_initialized",!1),ps(Pk,kM,new Map([yYe,CYe,RYe,y6e].map(t=>[t._editorType,t])));let zYe=Pk;var y4,wre,Tg,TA,jre,VYe,q9,HYe,_ss;const J0=class J0{constructor({pageIndex:t}){ps(this,q9);ps(this,y4,null);ps(this,wre,0);ps(this,Tg,new Map);ps(this,TA,new Map);this.pageIndex=t}setParent(t){if(!ye(this,y4)){Ht(this,y4,t);return}if(ye(this,y4)!==t){if(ye(this,Tg).size>0)for(const n of ye(this,Tg).values())n.remove(),t.append(n);Ht(this,y4,t)}}static get _svgFactory(){return gu(this,"_svgFactory",new Sat)}draw(t,n,r,a=!1){const i=Jy(this,wre)._++,l=ss(this,q9,HYe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=J0._svgFactory.createElement("defs");l.append(o);const c=J0._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&ye(this,TA).set(i,c);const u=ss(this,q9,_ss).call(this,o,d),h=J0._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),ye(this,Tg).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=Jy(this,wre)._++,r=ss(this,q9,HYe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=J0._svgFactory.createElement("defs");r.append(a);const i=J0._svgFactory.createElement("path");a.append(i);const l=`path_p${this.pageIndex}_${n}`;i.setAttribute("id",l),i.setAttribute("d",t.toSVGPath()),i.setAttribute("vector-effect","non-scaling-stroke");let o;if(t.mustRemoveSelfIntersections){const u=J0._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=J0._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=J0._svgFactory.createElement("use");u.append(m),m.setAttribute("href",`#${l}`),m.setAttribute("stroke","none"),m.setAttribute("fill","black"),m.setAttribute("fill-rule","nonzero"),m.classList.add("mask")}const c=J0._svgFactory.createElement("use");r.append(c),c.setAttribute("href",`#${l}`),o&&c.setAttribute("mask",`url(#${o})`);const d=c.cloneNode();return r.append(d),c.classList.add("mainOutline"),d.classList.add("secondaryOutline"),ye(this,Tg).set(n,r),n}finalizeLine(t,n){const r=ye(this,TA).get(t);ye(this,TA).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){ye(this,Tg).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){ye(this,TA).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;ss(r=J0,jre,VYe).call(r,ye(this,Tg).get(t),n)}show(t,n){ye(this,Tg).get(t).classList.toggle("hidden",!n)}rotate(t,n){ye(this,Tg).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){ye(this,Tg).get(t).setAttribute("fill",n)}changeOpacity(t,n){ye(this,Tg).get(t).setAttribute("fill-opacity",n)}addClass(t,n){ye(this,Tg).get(t).classList.add(n)}removeClass(t,n){ye(this,Tg).get(t).classList.remove(n)}getSVGRoot(t){return ye(this,Tg).get(t)}remove(t){ye(this,TA).delete(t),ye(this,y4)!==null&&(ye(this,Tg).get(t).remove(),ye(this,Tg).delete(t))}destroy(){Ht(this,y4,null);for(const t of ye(this,Tg).values())t.remove();ye(this,Tg).clear(),ye(this,TA).clear()}};y4=new WeakMap,wre=new WeakMap,Tg=new WeakMap,TA=new WeakMap,jre=new WeakSet,VYe=function(t,{x:n=0,y:r=0,width:a=1,height:i=1}={}){const{style:l}=t;l.top=`${100*r}%`,l.left=`${100*n}%`,l.width=`${100*a}%`,l.height=`${100*i}%`},q9=new WeakSet,HYe=function(t){var r;const n=J0._svgFactory.create(1,1,!0);return ye(this,y4).append(n),n.setAttribute("aria-hidden",!0),ss(r=J0,jre,VYe).call(r,n,t),n},_ss=function(t,n){const r=J0._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=J0._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},ps(J0,jre);let qYe=J0;Ec.AbortException;Ec.AnnotationEditorLayer;Ec.AnnotationEditorParamsType;Ec.AnnotationEditorType;Ec.AnnotationEditorUIManager;Ec.AnnotationLayer;Ec.AnnotationMode;Ec.ColorPicker;Ec.DOMSVGFactory;Ec.DrawLayer;Ec.FeatureTest;var Aat=Ec.GlobalWorkerOptions;Ec.ImageKind;Ec.InvalidPDFException;Ec.MissingPDFException;Ec.OPS;Ec.OutputScale;Ec.PDFDataRangeTransport;Ec.PDFDateString;Ec.PDFWorker;Ec.PasswordResponses;Ec.PermissionFlag;Ec.PixelsPerInch;Ec.RenderingCancelledException;Ec.TextLayer;Ec.UnexpectedResponseException;Ec.Util;Ec.VerbosityLevel;Ec.XfaLayer;Ec.build;Ec.createValidAbsoluteUrl;Ec.fetchData;var v6e=Ec.getDocument;Ec.getFilenameFromUrl;Ec.getPdfFilenameFromUrl;Ec.getXfaPageViewport;Ec.isDataScheme;Ec.isPdfFile;Ec.noContextMenu;Ec.normalizeUnicode;Ec.setLayerDimensions;Ec.shadow;Ec.version;const Eat="/assets/pdf.worker.min-GB3t0DcA.mjs";Aat.workerSrc=Eat;const zGn=({blob:s,scale:t=1.5})=>{const n=_.useRef(null),[r,a]=_.useState(!1),[i,l]=_.useState(null);return _.useEffect(()=>{let o=!1;const c=n.current;return!s||!c?void 0:((async()=>{a(!0),l(null);try{const u=await s.arrayBuffer(),h=await v6e({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const p=await h.getPage(m);if(o)return;const f=p.getViewport({scale:t}),g=document.createElement("canvas");g.width=Math.floor(f.width),g.height=Math.floor(f.height),g.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const v=g.getContext("2d");v&&(c.appendChild(g),await p.render({canvasContext:v,viewport:f}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),i&&e.jsx("p",{className:"p-4 text-sm text-destructive",children:i}),e.jsx("div",{ref:n,className:"space-y-4"})]})};function Sz({label:s,value:t,onChange:n,prefix:r="presentation",hint:a,urlPlaceholder:i="…or paste an image URL",round:l=!1,className:o}){const{user:c}=hs(),d=_.useRef(null),[u,h]=_.useState(!1),m=async p=>{if(!(!p||!c)){if(!p.type.startsWith("image/")){ne.error("Please choose an image file");return}if(p.size>20*1024*1024){ne.error("That photo is larger than 20 MB");return}h(!0);try{const f=await RVn(c.id,p,r);n(f),ne.success("Photo uploaded")}catch(f){ne.error((f==null?void 0:f.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Ct("space-y-2",o),children:[e.jsx(ee,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ct("relative shrink-0 overflow-hidden border bg-muted",l?"h-16 w-16 rounded-full":"h-16 w-24 rounded-md"),children:t?e.jsx("img",{src:t,alt:s,className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:e.jsx(nc,{className:"h-5 w-5"})})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:p=>{var f;return m((f=p.target.files)==null?void 0:f[0])}}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:u,onClick:()=>{var p;return(p=d.current)==null?void 0:p.click()},children:[u?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(N0,{className:"h-4 w-4"}),t?"Replace photo":"Upload photo"]}),t&&e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",onClick:()=>n(null),children:[e.jsx(er,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(pe,{value:t||"",onChange:p=>n(p.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function BGn({value:s,onChange:t}){return e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Nt,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(mn,{checked:s.enabled,onCheckedChange:n=>t({enabled:n})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds a second agent to the cover, the About page, and the closing contact card."})]}),s.enabled&&e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:s.title||"",onChange:n=>t({title:n.target.value}),placeholder:"Co-listing agent"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:s.email||"",onChange:n=>t({email:n.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(Sz,{label:"Headshot",value:s.headshotUrl,onChange:n=>t({headshotUrl:n||""}),prefix:"co-agent",round:!0}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Shared bio (optional)"}),e.jsx(Ps,{rows:4,value:s.bio||"",onChange:n=>t({bio:n.target.value}),placeholder:"Replaces the intro paragraph on the About page when both agents are shown."})]})]})]})}function $Gn({value:s,onChange:t}){return e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx(Nt,{className:"text-base",children:"Presentation theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Themes restyle every page — paper, headline type, and palette. Signature follows your own brand colors."})]}),e.jsx(Le,{className:"grid gap-2 sm:grid-cols-2",children:AKe.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Ct("group relative overflow-hidden rounded-xl border p-3 text-left transition-all hover:shadow-sm",r?"border-primary ring-1 ring-primary":"border-border"),children:[e.jsx("div",{className:"flex h-10 w-full overflow-hidden rounded-md",children:n.swatch.map(a=>e.jsx("div",{className:"flex-1",style:{backgroundColor:a}},a))}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:n.name}),r&&e.jsx(Wr,{className:"h-4 w-4 text-primary"})]}),e.jsx("p",{className:"mt-1 text-xs leading-snug text-muted-foreground",children:n.description})]},n.id)})})]})}const UGn={cover:[{key:"kicker",label:"Cover eyebrow"},{key:"body",label:"Cover paragraph",long:!0}],welcome:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead",long:!0}],agent:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead (defaults to your tagline)",long:!0}],overview:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead",long:!0}],closing:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"body",label:"Closing paragraph",long:!0}]},qGn=["cover","welcome","agent","overview","closing"];function VGn({pages:s,onChange:t}){const n=new Set(s.hidden||[]),r=(i,l,o)=>{t({...s,copy:{...s.copy||{},[i]:{...(s.copy||{})[i]||{},[l]:o}}})},a=i=>{const l={...s.copy||{}};delete l[i],t({...s,copy:l})};return e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx(Nt,{className:"text-base",children:"Edit page wording"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Rewrite the headlines on the built-in pages. The preview updates as you type."})]}),e.jsx(Le,{children:e.jsx(ez,{type:"multiple",className:"w-full",children:qGn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=GQt(s,i);return e.jsxs(AL,{value:i,children:[e.jsx(EL,{className:"text-sm",children:Hzn[i]}),e.jsxs(TL,{className:"space-y-3 pt-1",children:[UGn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:o.label}),o.long?e.jsx(Ps,{rows:2,value:l[o.key]||"",placeholder:oKe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(pe,{value:l[o.key]||"",placeholder:oKe[i][o.key],onChange:c=>r(i,o.key,c.target.value)})]},o.key)),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-2",onClick:()=>a(i),children:[e.jsx(Dx,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function HGn({pages:s,onChange:t}){const n=[...s].sort((o,c)=>o.order-c.order),r=(o,c)=>t(n.map(d=>d.id===o?{...d,...c}:d)),a=o=>t([...n,Qrt(o,n.length)]),i=o=>t(n.filter(c=>c.id!==o).map((c,d)=>({...c,order:d}))),l=(o,c)=>{const d=n.findIndex(m=>m.id===o),u=d+c;if(d<0||u<0||u>=n.length)return;const h=[...n];[h[d],h[u]]=[h[u],h[d]],t(h.map((m,p)=>({...m,order:p})))};return e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yj,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Nt,{className:"text-base",children:"Your own pages"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add About Us, testimonials, track record, or a statement page. Each one is styled to match the rest of the presentation and can be toggled on or off."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Dze.map(o=>e.jsxs("button",{type:"button",onClick:()=>a(o.layout),className:"rounded-lg border p-3 text-left transition-colors hover:border-primary hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx(sn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:o.description})]},o.layout))}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(fc,{}),e.jsx(ez,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(AL,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(EL,{className:"flex-1 text-left text-sm",children:e.jsxs("span",{className:"flex items-center gap-2",children:[((d=o.headline)==null?void 0:d.trim())||((u=Dze.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:(h=Dze.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===0,onClick:()=>l(o.id,-1),children:e.jsx(ap,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(Vf,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(TL,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Placement"}),e.jsxs(ls,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"after-agent",children:'After "About your agent"'}),e.jsx(He,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(mn,{checked:o.dark,onCheckedChange:m=>r(o.id,{dark:m})}),e.jsx("span",{className:"text-sm",children:"Dark background"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Eyebrow"}),e.jsx(pe,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Headline"}),e.jsx(pe,{value:o.headline,onChange:m=>r(o.id,{headline:m.target.value})})]}),o.layout!=="statement"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Subhead"}),e.jsx(pe,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Body copy"}),e.jsx(Ps,{rows:5,value:o.body,onChange:m=>r(o.id,{body:m.target.value}),placeholder:"Leave a blank line between paragraphs."})]}),(o.layout==="story"||o.layout==="checklist"||o.layout==="statement")&&e.jsx(Sz,{label:"Photo (optional)",value:o.imageUrl,onChange:m=>r(o.id,{imageUrl:m}),prefix:"custom-page",urlPlaceholder:"…or paste an image URL",hint:"Defaults to the property photo when left empty."}),o.layout==="story"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Photo side"}),e.jsxs(ls,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"right",children:"Right"}),e.jsx(He,{value:"left",children:"Left"})]})]})]}),(o.layout==="story"||o.layout==="checklist")&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:m,onChange:f=>{const g=[...o.bullets];g[p]=f.target.value,r(o.id,{bullets:g})}}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{bullets:o.bullets.filter((f,g)=>g!==p)}),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Add item"]})]}),o.layout==="testimonials"&&e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,p)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Ps,{rows:3,value:m.quote,placeholder:"Client quote",onChange:f=>{const g=[...o.testimonials];g[p]={...m,quote:f.target.value},r(o.id,{testimonials:g})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{value:m.name,placeholder:"Name",onChange:f=>{const g=[...o.testimonials];g[p]={...m,name:f.target.value},r(o.id,{testimonials:g})}}),e.jsx(pe,{value:m.detail,placeholder:"Neighborhood or year",onChange:f=>{const g=[...o.testimonials];g[p]={...m,detail:f.target.value},r(o.id,{testimonials:g})}})]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-2 text-destructive",onClick:()=>r(o.id,{testimonials:o.testimonials.filter((f,g)=>g!==p)}),children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Remove"]})]},p)),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",disabled:o.testimonials.length>=4,onClick:()=>r(o.id,{testimonials:[...o.testimonials,{quote:"",name:"",detail:""}]}),children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Add testimonial"]})]}),o.layout==="stats"&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"w-28",value:m.value,placeholder:"27",onChange:f=>{const g=[...o.stats];g[p]={...m,value:f.target.value},r(o.id,{stats:g})}}),e.jsx(pe,{value:m.label,placeholder:"Homes sold",onChange:f=>{const g=[...o.stats];g[p]={...m,label:f.target.value},r(o.id,{stats:g})}}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((f,g)=>g!==p)}),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Add stat"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only use numbers you can back up — leave a stat blank to hide it."})]})]})]},o.id)})})]})]})]})}function GGn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=_.useState(""),[o,c]=_.useState("");return _.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Save as a reusable template"}),e.jsx(_r,{children:"Saves your branding, co-listing agent, theme, page wording, custom pages, and marketing plan. The property address and photo are not saved — you add those each time."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Template name"}),e.jsx(pe,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Ps,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{disabled:!i.trim()||r,onClick:async()=>{await a(i.trim(),o.trim()),t(!1)},className:"gap-2",children:[r&&e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const t5t=["welcome","agent","overview","closing"],WGn=()=>{const{id:s}=Mi(),t=zn(),{user:n}=hs(),{data:r}=NLe(),{data:a,isLoading:i,refetch:l}=qzn(s),{update:o}=HQt(),{save:c}=VQt(),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(dKe(null)),[g,v]=_.useState(WQt),[y,b]=_.useState([]),[w,S]=_.useState(lKe),[C,E]=_.useState(cKe),[P,M]=_.useState(null),[I,D]=_.useState(null),[F,q]=_.useState(!1),[G,V]=_.useState(!1),[H,K]=_.useState(null),[Z,oe]=_.useState(!1),[re,ae]=_.useState(!1),[J,te]=_.useState(!1),[ce,ve]=_.useState(!1),[me,he]=_.useState(!0),[ge,Ee]=_.useState(!1),Ne=_.useRef(null);_.useEffect(()=>{if(!a||d)return;u({title:a.title||"",addressLine1:a.property_address_line1||"",city:a.city||"",state:a.state||"",postalCode:a.postal_code||"",listPrice:a.list_price!=null?String(a.list_price):"",beds:a.beds!=null?String(a.beds):"",baths:a.baths!=null?String(a.baths):"",sqft:a.sqft!=null?String(a.sqft):""});const $e=a.agent_snapshot;m({...r,...$e||{}}),f(dKe(a.services)),v(KQt(a.co_agent)),b(ZQt(a.custom_pages)),S(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:lKe),E(a.photo_focal||cKe),M(a.property_photo_path)},[a,r,d]),_.useEffect(()=>{let $e=!1;return P?h6e(P).then(Xe=>{$e||D(Xe)}):D(null),()=>{$e=!0}},[P]);const Pe=_.useMemo(()=>!a||!d?null:{...a,title:d.title,property_address_line1:d.addressLine1,city:d.city,state:d.state,postal_code:d.postalCode,list_price:d.listPrice?Number(d.listPrice):null,beds:d.beds?Number(d.beds):null,baths:d.baths?Number(d.baths):null,sqft:d.sqft?Number(d.sqft):null,agent_snapshot:h||{},co_agent:g,custom_pages:y,services:p,page_settings:w,photo_focal:C,property_photo_path:P},[a,d,h,g,y,p,w,C,P]),Oe=$e=>u(Xe=>Xe&&{...Xe,...$e}),ke=$e=>m(Xe=>Xe&&{...Xe,...$e}),Ve=$e=>(w.hidden||[]).includes($e),_e=($e,Xe)=>S(nt=>{const Ge=new Set(nt.hidden||[]);return Xe?Ge.delete($e):Ge.add($e),{...nt,hidden:Array.from(Ge)}}),Ae=p.filter($e=>$e.enabled),Se=1+t5t.filter($e=>!Ve($e)&&$e!=="overview").length+(Ve("overview")?0:1)+Ae.filter($e=>$e.key!=="communication").length+y.filter($e=>$e.enabled).length,We=async($e=!1)=>{if(Pe){ve(!0);try{await o.mutateAsync({id:Pe.id,title:Pe.title||"Untitled Presentation",property_address_line1:Pe.property_address_line1,city:Pe.city,state:Pe.state,postal_code:Pe.postal_code,list_price:Pe.list_price,beds:Pe.beds,baths:Pe.baths,sqft:Pe.sqft,agent_snapshot:Pe.agent_snapshot,co_agent:Pe.co_agent,custom_pages:Pe.custom_pages,services:Pe.services,page_settings:Pe.page_settings,photo_focal:Pe.photo_focal,property_photo_path:Pe.property_photo_path}),$e||ne.success("Presentation saved")}finally{ve(!1)}}},qe=async $e=>{if(!(!n||!s)){if(!$e.type.startsWith("image/")){ne.error("Please choose a JPG or PNG photo");return}if($e.size>25*1024*1024){ne.error("That photo is larger than 25 MB");return}q(!0);try{const Xe=await DVn(n.id,s,$e);M(Xe);const nt=await h6e(Xe);D(nt?`${nt}${nt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:Xe}),ne.success("Photo uploaded")}catch(Xe){ne.error((Xe==null?void 0:Xe.message)||"Upload failed")}finally{q(!1)}}},Be=async()=>{if(Pe){oe(!0);try{const $e=await mes(m6e(Pe,r,I),Pe.template_id,P);K($e)}catch($e){ne.error(($e==null?void 0:$e.message)||"Could not build the preview")}finally{oe(!1)}}};_.useEffect(()=>{if(!me||!Pe)return;const $e=setTimeout(()=>{Be()},900);return()=>clearTimeout($e)},[me,Pe]);const Ze=async()=>{if(!(!Pe||!n)){if(!Pe.property_photo_path){ne.error("Add the primary exterior photo before generating the PDF");return}ae(!0);try{await We(!0);const $e=await pes(m6e(Pe,r,I),Pe.template_id,"print",P);await fes(n.id,Pe.id,$e),await l(),ne.success("Presentation downloaded")}catch($e){ne.error(($e==null?void 0:$e.message)||"Could not build the PDF")}finally{ae(!1)}}};return i||!d||!a?e.jsx($s,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ln,{className:"h-10 w-64"}),e.jsx(ln,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs($s,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>t("/apps/listing-presentation-studio"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(pe,{value:d.title,onChange:$e=>Oe({title:$e.target.value}),className:"h-9 border-none bg-transparent px-0 text-xl font-semibold shadow-none focus-visible:ring-0",placeholder:"Untitled Presentation"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ae.length," services selected · ",Se," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>We(),disabled:ce,className:"gap-2",children:[ce?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4"})," Save"]}),e.jsxs(z,{variant:"outline",onClick:()=>Ee(!0),className:"gap-2",children:[e.jsx(tP,{className:"h-4 w-4"})," Save as template"]}),e.jsxs(z,{variant:"outline",onClick:Be,disabled:Z,className:"gap-2",children:[Z?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(xa,{className:"h-4 w-4"})," Preview"]}),e.jsxs(z,{variant:"outline",onClick:async()=>{await We(!0),te(!0)},className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Email"]}),e.jsxs(z,{onClick:Ze,disabled:re,className:"gap-2",children:[re?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ga,{className:"h-4 w-4"}),"Generate PDF"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,440px)_minmax(0,1fr)]",children:[e.jsxs(Qr,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-4",children:[e.jsx(Wt,{value:"property",children:"Property"}),e.jsx(Wt,{value:"branding",children:"Branding"}),e.jsx(Wt,{value:"plan",children:"Plan"}),e.jsx(Wt,{value:"pages",children:"Pages"})]}),e.jsxs(Kt,{value:"property",className:"space-y-4",children:[e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"Property address"})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Street address"}),e.jsx(pe,{value:d.addressLine1,onChange:$e=>Oe({addressLine1:$e.target.value}),placeholder:"1408 Elmwood Drive"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2 space-y-1.5",children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:d.city,onChange:$e=>Oe({city:$e.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:d.state,onChange:$e=>Oe({state:$e.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:d.postalCode,onChange:$e=>Oe({postalCode:$e.target.value})})]}),e.jsx(fc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"List price (optional)"}),e.jsx(pe,{inputMode:"numeric",value:d.listPrice,onChange:$e=>Oe({listPrice:$e.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Square feet"}),e.jsx(pe,{inputMode:"numeric",value:d.sqft,onChange:$e=>Oe({sqft:$e.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Beds"}),e.jsx(pe,{inputMode:"numeric",value:d.beds,onChange:$e=>Oe({beds:$e.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Baths"}),e.jsx(pe,{inputMode:"numeric",value:d.baths,onChange:$e=>Oe({baths:$e.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var $e;return($e=Ne.current)==null?void 0:$e.click()},onKeyDown:$e=>{var Xe;return $e.key==="Enter"&&((Xe=Ne.current)==null?void 0:Xe.click())},onDragOver:$e=>{$e.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:$e=>{var nt;$e.preventDefault(),V(!1);const Xe=(nt=$e.dataTransfer.files)==null?void 0:nt[0];Xe&&qe(Xe)},className:Ct("relative flex h-48 w-full cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-dashed bg-muted/40 transition-colors hover:bg-muted",G&&"border-primary bg-primary/10"),children:I?e.jsx("img",{src:I,alt:"Property exterior",className:"h-full w-full object-cover",style:{objectPosition:`${C.x*100}% ${C.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[F?e.jsx(bt,{className:"h-6 w-6 animate-spin"}):e.jsx(N0,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Drag & drop the front exterior photo"}),e.jsx("span",{className:"text-xs",children:"or click to browse · JPG or PNG · landscape works best"})]})}),e.jsx("input",{ref:Ne,type:"file",accept:"image/*",className:"hidden",onChange:$e=>{var nt;const Xe=(nt=$e.target.files)==null?void 0:nt[0];Xe&&qe(Xe),$e.target.value=""}}),I&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx(aJ,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Horizontal"}),e.jsx(Mx,{value:[C.x*100],min:0,max:100,step:1,onValueChange:([$e])=>E(Xe=>({...Xe,x:$e/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Vertical"}),e.jsx(Mx,{value:[C.y*100],min:0,max:100,step:1,onValueChange:([$e])=>E(Xe=>({...Xe,y:$e/100}))})]})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var $e;return($e=Ne.current)==null?void 0:$e.click()},disabled:F,children:[e.jsx(Gi,{className:"h-4 w-4"})," Replace photo"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo anchors the cover and appears on a few key pages — photography, video, the property website, and the closing page."})]})]})]}),e.jsxs(Kt,{value:"branding",className:"space-y-4",children:[e.jsx($Gn,{value:w.theme||Xqn,onChange:$e=>S(Xe=>({...Xe,theme:$e}))}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Nt,{className:"text-base",children:"Your details"}),e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Le,{className:"space-y-3",children:h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edits here apply to this presentation only — your LevelUp profile stays unchanged."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:h.name,onChange:$e=>ke({name:$e.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline||"",onChange:$e=>ke({tagline:$e.target.value}),placeholder:"Helping families move with confidence"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:h.phone||"",onChange:$e=>ke({phone:$e.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email||"",onChange:$e=>ke({email:$e.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:h.website||"",onChange:$e=>ke({website:$e.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:h.brokerageName||"",onChange:$e=>ke({brokerageName:$e.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:h.licenseNumber||"",onChange:$e=>ke({licenseNumber:$e.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{value:h.licenseState||"",onChange:$e=>ke({licenseState:$e.target.value})})]})]}),e.jsx(fc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:$e=>ke({brandColor:$e.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.brandColor,onChange:$e=>ke({brandColor:$e.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:$e=>ke({accentColor:$e.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.accentColor,onChange:$e=>ke({accentColor:$e.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headshot URL"}),e.jsx(pe,{value:h.headshotUrl||"",onChange:$e=>ke({headshotUrl:$e.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage logo URL"}),e.jsx(pe,{value:h.brokerageLogoUrl||"",onChange:$e=>ke({brokerageLogoUrl:$e.target.value})})]}),r&&e.jsxs(z,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(Gi,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(BGn,{value:g,onChange:$e=>v(Xe=>({...Xe,...$e}))})]}),e.jsx(Kt,{value:"plan",className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx(Nt,{className:"text-base",children:"Marketing plan"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the services you turn on appear in the PDF. Uncheck any line item you do not offer."})]}),e.jsx(Le,{children:e.jsx(ez,{type:"multiple",className:"w-full",children:p.slice().sort(($e,Xe)=>$e.order-Xe.order).map($e=>{var Xe;return e.jsxs(AL,{value:$e.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(mn,{checked:$e.enabled,onCheckedChange:nt=>f(Ge=>Ge.map(Je=>Je.key===$e.key?{...Je,enabled:nt}:Je))}),e.jsx(EL,{className:"flex-1 text-left text-sm",children:$e.title})]}),e.jsxs(TL,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:$e.title,onChange:nt=>f(Ge=>Ge.map(Je=>Je.key===$e.key?{...Je,title:nt.target.value}:Je))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{rows:4,value:$e.body,onChange:nt=>f(Ge=>Ge.map(Je=>Je.key===$e.key?{...Je,body:nt.target.value}:Je))})]}),!!((Xe=$e.options)!=null&&Xe.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),$e.options.map(nt=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(za,{className:"mt-0.5",checked:nt.enabled,onCheckedChange:Ge=>f(Je=>Je.map(ut=>{var lt;return ut.key===$e.key?{...ut,options:(lt=ut.options)==null?void 0:lt.map(qt=>qt.key===nt.key?{...qt,enabled:!!Ge}:qt)}:ut}))}),e.jsx("span",{className:"leading-snug",children:nt.label})]},nt.key))]})]})]},$e.key)})})})]})}),e.jsxs(Kt,{value:"pages",className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx(Nt,{className:"text-base",children:"Page visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The cover and every enabled service page always print. These supporting pages are optional."})]}),e.jsxs(Le,{className:"space-y-3",children:[t5t.map($e=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:Wzn[$e]}),e.jsx(mn,{checked:!Ve($e),onCheckedChange:Xe=>_e($e,Xe)})]},$e)),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Page order"}),e.jsxs("ol",{className:"mt-2 space-y-1 text-xs text-muted-foreground",children:[e.jsx("li",{children:"01 · Cover"}),!Ve("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Ve("agent")&&e.jsx("li",{children:"About your agent"}),y.filter($e=>$e.enabled&&$e.placement!=="end").sort(($e,Xe)=>$e.order-Xe.order).map($e=>e.jsx("li",{children:$e.headline||"Custom page"},$e.id)),!Ve("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Ae.filter($e=>$e.key!=="communication").map($e=>e.jsx("li",{children:$e.title},$e.key)),y.filter($e=>$e.enabled&&$e.placement==="end").sort(($e,Xe)=>$e.order-Xe.order).map($e=>e.jsx("li",{children:$e.headline||"Custom page"},$e.id)),!Ve("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(VGn,{pages:w,onChange:S}),e.jsxs(be,{children:[e.jsxs(_t,{className:"pb-3",children:[e.jsx(Nt,{className:"text-base",children:"What they're saying"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a testimonial page and drop in up to six client quotes. It styles itself to your theme."})]}),e.jsx(Le,{children:e.jsx(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b($e=>[...$e,{...Qrt("testimonials",$e.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(HGn,{pages:y,onChange:b})]})]}),e.jsxs(be,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Nt,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(mn,{checked:me,onCheckedChange:he}),"Auto-update"]})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:Be,disabled:Z,className:"gap-2",children:[Z?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Le,{className:"h-[calc(70vh-60px)] p-0",children:H?e.jsx(zGn,{blob:H}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(xa,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fill in the address, upload the photo, then generate the preview."}),e.jsxs(z,{onClick:Be,disabled:Z,className:"gap-2",children:[Z?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(xa,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(GGn,{open:ge,onOpenChange:Ee,defaultName:d.title,saving:c.isPending,onSave:async($e,Xe)=>{await c.mutateAsync({name:$e,description:Xe||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:g,custom_pages:y,services:p,page_settings:w})}}),e.jsx(ges,{open:J,onOpenChange:te,row:Pe,brand:r,photoUrl:I})]})};function KGn(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 wss="popby_geocode_cache_v1";function YGn(){try{return JSON.parse(localStorage.getItem(wss)||"{}")}catch{return{}}}function ZGn(s){try{localStorage.setItem(wss,JSON.stringify(s))}catch{}}function XGn({contacts:s,onLogPopby:t}){const[n,r]=_.useState(null),[a,i]=_.useState("idle"),[l,o]=_.useState(5),[c,d]=_.useState(""),[u,h]=_.useState(new Map),[m,p]=_.useState(!1);_.useEffect(()=>{(async()=>{const{data:b}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&d(b.value)})()},[]);const f=_.useMemo(()=>s.filter(b=>b.isDue&&(b.address||b.city&&b.state||b.zip)),[s]),g=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(b=>{r({lat:b.coords.latitude,lng:b.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};_.useEffect(()=>{if(!c||!n||f.length===0)return;let b=!1;const w=YGn(),S=new Map;f.forEach(E=>{const P=[E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase();w[P]&&S.set(E.id,w[P])}),h(new Map(S));const C=f.filter(E=>!([E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase()in w));if(C.length!==0)return p(!0),(async()=>{const E=[...C],P=async()=>{var M,I;for(;E.length&&!b;){const D=E.shift(),F=[D.address,D.city,D.state,D.zip].filter(Boolean),q=F.join("|").toLowerCase(),G=F.join(", ");try{const H=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?limit=1&access_token=${c}`)).json();if((I=(M=H==null?void 0:H.features)==null?void 0:M[0])!=null&&I.center){const[K,Z]=H.features[0].center;w[q]={lat:Z,lng:K},S.set(D.id,{lat:Z,lng:K})}else w[q]=null}catch{}}};await Promise.all([P(),P(),P(),P()]),b||(ZGn(w),h(new Map(S)),p(!1))})(),()=>{b=!0}},[c,n,f]);const v=_.useMemo(()=>{if(!n)return[];const b=[];return f.forEach(w=>{const S=u.get(w.id);if(!S)return;const C=KGn(n.lat,n.lng,S.lat,S.lng);C<=l&&b.push({...w,distanceMiles:C,lat:S.lat,lng:S.lng})}),b.sort((w,S)=>w.distanceMiles-S.distanceMiles)},[n,f,u,l]),y=b=>{const S=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${b.lat},${b.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`;window.open(S,"_blank","noopener")};return e.jsxs(be,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(XU,{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(ls,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(rs,{className:"w-[110px] h-9",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"2",children:"2 miles"}),e.jsx(He,{value:"5",children:"5 miles"}),e.jsx(He,{value:"10",children:"10 miles"}),e.jsx(He,{value:"25",children:"25 miles"})]})]}),e.jsxs(z,{size:"sm",variant:a==="ok"?"outline":"default",onClick:g,disabled:a==="loading",children:[a==="loading"?e.jsx(Gi,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(XU,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Le,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Ha,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"Tap ",e.jsx("span",{className:"font-medium text-foreground",children:'"Use my location"'})," to see who's close by right now."]}),a==="denied"&&e.jsxs("div",{className:"text-center py-6 text-sm text-destructive flex flex-col items-center gap-2",children:[e.jsx(Ho,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&f.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&&f.length>0&&m&&v.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ln,{className:"h-14 w-full"}),e.jsx(ln,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&v.length===0&&f.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"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:v.map(b=>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:[b.first_name," ",b.last_name]}),e.jsx(ze,{variant:"outline",className:"text-xs",children:b.distanceMiles<1?`${(b.distanceMiles*5280).toFixed(0)} ft`:`${b.distanceMiles.toFixed(1)} mi`}),b.daysOverdue>0&&e.jsxs(ze,{variant:"destructive",className:"text-xs",children:[b.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[b.address,b.city,b.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.phone&&e.jsx(z,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${b.phone}`,children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>y(b),className:"h-9 w-9",title:"Directions",children:e.jsx(iJ,{className:"h-4 w-4"})}),e.jsxs(z,{size:"sm",onClick:()=>t(b),children:[e.jsx(Ko,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const QGn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",JGn=[{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 eWn(){const s=zn(),t=lZt(),{data:n}=ARn(),{data:r}=Q_(),{data:a}=Znt(),{data:i}=c8e(90),{data:l}=Rb(),o=LRn(),c=MRn(),d=TRn(),u=PRn(),{data:h=[],isLoading:m}=rt({queryKey:["popby-templates"],queryFn:async()=>{const{data:H,error:K}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",QGn).order("publish_date",{ascending:!1});if(K)throw K;const{data:Z}=await U.from("template_likes").select("template_id"),{data:oe}=await U.from("template_comments").select("template_id"),re=new Map;Z==null||Z.forEach(J=>{re.set(J.template_id,(re.get(J.template_id)||0)+1)});const ae=new Map;return oe==null||oe.forEach(J=>{ae.set(J.template_id,(ae.get(J.template_id)||0)+1)}),(H||[]).map(J=>({...J,likesCount:re.get(J.id)||0,commentsCount:ae.get(J.id)||0}))}}),p=H=>{const K=l==null?void 0:l.find(Z=>Z.id===H);return K?`${K.first_name} ${K.last_name||""}`.trim():"Unknown"},f=H=>{if(!H)return null;const K=n==null?void 0:n.find(Z=>Z.id===H);return(K==null?void 0:K.name)||null},[g,v]=_.useState(null),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState({popby_item_id:"",notes:""}),[I,D]=_.useState({name:"",description:""}),F=async()=>{g&&(await c.mutateAsync({contact_id:g.id,popby_item_id:P.popby_item_id||void 0,notes:P.notes||void 0}),b(!1),v(null),M({popby_item_id:"",notes:""}))},q=async()=>{I.name.trim()&&(await d.mutateAsync({name:I.name.trim(),description:I.description.trim()||void 0}),E(!1),D({name:"",description:""}))},G=async(H,K)=>{await u.mutateAsync({relationship_type_id:H,frequency_days:parseInt(K)})},V=H=>{var Z;const K=a==null?void 0:a.find(oe=>oe.relationship_type_id===H);return((Z=K==null?void 0:K.frequency_days)==null?void 0:Z.toString())||"90"};return e.jsx($s,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(z,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(z,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(Gc,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(z,{variant:"outline",onClick:()=>E(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(Qr,{defaultValue:"due",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"due",children:"Due for Popby"}),e.jsx(Wt,{value:"activity",children:"Recent Activity"}),e.jsx(Wt,{value:"library",children:"Popby Library"}),e.jsx(Wt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Kt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(XGn,{contacts:t||[],onLogPopby:H=>{v(H),b(!0)}}),!t||t.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Ko,{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(H=>e.jsx(be,{className:"hover:shadow-md transition-shadow",children:e.jsx(Le,{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:[H.first_name," ",H.last_name]}),H.daysOverdue>0&&e.jsxs(ze,{variant:"destructive",className:"text-xs",children:[H.daysOverdue,"+ days overdue"]}),H.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:[wZ(H).hasAddress&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ha,{className:"h-3 w-3"}),wZ(H).city||wZ(H).line,wZ(H).isSecondary&&e.jsxs("span",{className:"text-xs",children:["(",wZ(H).label,")"]})]}),H.tags&&H.tags.length>0&&e.jsx("span",{children:H.tags.map(K=>{var Z;return(Z=K.relationship_type)==null?void 0:Z.name}).join(", ")})]}),H.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Ys(new Date(H.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H.phone&&e.jsx(z,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${H.phone}`,children:e.jsx(va,{className:"h-4 w-4"})})}),e.jsxs(z,{size:"sm",onClick:()=>{v(H),b(!0)},children:[e.jsx(Xl,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},H.id))})]}),e.jsx(Kt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Zr,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Le,{className:"space-y-3",children:i.map(H=>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(Ko,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:p(H.contact_id)}),f(H.popby_item_id)&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:f(H.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ys(new Date(H.completed_at),"MMM d, yyyy h:mm a")}),H.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:H.notes})]})]},H.id))})]})}),e.jsx(Kt,{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(H=>e.jsx(be,{children:e.jsx(Le,{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(Ko,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:H.name}),H.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:H.description}),!H.owner_user_id&&e.jsx(ze,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},H.id)),e.jsx(be,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>E(!0),children:e.jsx(Le,{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(sn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Kt,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),m&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((H,K)=>e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(ln,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(ln,{className:"h-5 w-3/4 mb-2"}),e.jsx(ln,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ln,{className:"h-5 w-16"}),e.jsx(ln,{className:"h-5 w-20"})]})]})},K))}),!m&&h.length===0&&e.jsx(be,{children:e.jsxs(Le,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Sh,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby templates available yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Check back soon for new templates."})]})}),!m&&h.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.map(H=>e.jsxs(be,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${H.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:H.preview_image_url?e.jsx("img",{src:H.preview_image_url,alt:H.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(Le,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:H.name}),H.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:ete(H.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(Ug,{className:"h-3.5 w-3.5"}),H.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3.5 w-3.5"}),H.commentsCount]})]}),e.jsxs(z,{size:"sm",className:"w-full gap-2",onClick:K=>{K.stopPropagation(),s(`/templates/${H.id}`)},children:[e.jsx(mr,{className:"h-4 w-4"}),"View Template"]})]})]},H.id))})]})]}),e.jsx(Is,{open:y,onOpenChange:b,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Log Popby for ",g==null?void 0:g.first_name," ",g==null?void 0:g.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Popby Item (optional)"}),e.jsxs(ls,{value:P.popby_item_id,onValueChange:H=>M(K=>({...K,popby_item_id:H})),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a popby item..."})}),e.jsx(as,{children:n==null?void 0:n.map(H=>e.jsx(He,{value:H.id,children:H.name},H.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Ps,{placeholder:"Any notes about this popby...",value:P.notes,onChange:H=>M(K=>({...K,notes:H.target.value}))})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(z,{onClick:F,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(Is,{open:w,onOpenChange:S,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{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(H=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(ee,{className:"font-medium",children:H.name}),e.jsxs(ls,{value:V(H.id),onValueChange:K=>G(H.id,K),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{})}),e.jsx(as,{children:JGn.map(K=>e.jsx(He,{value:K.value,children:K.label},K.value))})]})]},H.id))]}),e.jsx(hr,{children:e.jsx(z,{onClick:()=>S(!1),children:"Done"})})]})}),e.jsx(Is,{open:C,onOpenChange:E,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name *"}),e.jsx(pe,{placeholder:"e.g., Homemade cookies",value:I.name,onChange:H=>D(K=>({...K,name:H.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{placeholder:"Optional description...",value:I.description,onChange:H=>D(K=>({...K,description:H.target.value}))})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(z,{onClick:q,disabled:!I.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const tWn=Gj({property_address:Jo().min(1,"Property address is required"),city:Jo().optional(),state:Jo().optional(),zip:Jo().optional(),transaction_type:uJe(["buyer","seller"]),close_date:Jo().min(1,"Close date is required"),sale_price:TJ().min(0,"Sale price must be positive"),commission_amount:TJ().optional(),lead_source_id:Jo().optional(),client_type_id:Jo().optional(),contact_id:Jo().optional(),notes:Jo().optional(),is_win:bCs()});function jss({open:s,onOpenChange:t,transaction:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(""),h=SLe(),m=HUs(),{data:p}=Q9(),{data:f}=Q_(),{data:g}=Rb(),v=vLe(),y=Wet(),{data:b}=CLe(),w=(b==null?void 0:b.show_commission)??!0,S=gPe({resolver:yPe(tWn),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}});_.useEffect(()=>{n?S.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}):S.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,S]);const C=async I=>{const D={property_address:I.property_address,transaction_type:I.transaction_type,close_date:I.close_date,sale_price:I.sale_price,is_win:I.is_win,commission_amount:I.commission_amount||null,lead_source_id:I.lead_source_id||null,client_type_id:I.client_type_id||null,contact_id:I.contact_id||null,city:I.city||null,state:I.state||null,zip:I.zip||null,notes:I.notes||null};n?await m.mutateAsync({id:n.id,...D}):await h.mutateAsync(D),t(!1)},E=async()=>{if(!i.trim())return;const[I,...D]=i.trim().split(" "),F=D.join(" ")||null,q=await v.mutateAsync({first_name:I,last_name:F,tagIds:[]});q&&(S.setValue("contact_id",q.id),l(""),c(!1),a(!1))},P=async()=>{if(!d.trim())return;const I=await y.mutateAsync(d.trim());I&&(S.setValue("lead_source_id",I.id),u(""))},M=g==null?void 0:g.find(I=>I.id===S.watch("contact_id"));return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Os,{children:e.jsx(Rs,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(Ki,{className:"max-h-[70vh] pr-4",children:e.jsx(wPe,{...S,children:e.jsxs("form",{onSubmit:S.handleSubmit(C),className:"space-y-4",children:[e.jsx(Mf,{control:S.control,name:"property_address",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Property Address *"}),e.jsx(sf,{children:e.jsx(pe,{placeholder:"123 Main St",...I})}),e.jsx(hb,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Mf,{control:S.control,name:"city",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"City"}),e.jsx(sf,{children:e.jsx(pe,{placeholder:"City",...I})})]})}),e.jsx(Mf,{control:S.control,name:"state",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"State"}),e.jsx(sf,{children:e.jsx(pe,{placeholder:"TX",...I})})]})}),e.jsx(Mf,{control:S.control,name:"zip",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Zip"}),e.jsx(sf,{children:e.jsx(pe,{placeholder:"75001",...I})})]})})]}),e.jsx(Mf,{control:S.control,name:"transaction_type",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Transaction Type *"}),e.jsxs(ls,{onValueChange:I.onChange,value:I.value,children:[e.jsx(sf,{children:e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select type"})})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]}),e.jsx(hb,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Mf,{control:S.control,name:"close_date",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Close Date *"}),e.jsx(sf,{children:e.jsx(pe,{type:"date",...I})}),e.jsx(hb,{})]})}),e.jsx(Mf,{control:S.control,name:"sale_price",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Sale Price *"}),e.jsx(sf,{children:e.jsx(pe,{type:"number",placeholder:"0",...I,onChange:D=>I.onChange(Number(D.target.value))})}),e.jsx(hb,{})]})})]}),w&&e.jsx(Mf,{control:S.control,name:"commission_amount",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Commission"}),e.jsx(sf,{children:e.jsx(pe,{type:"number",placeholder:"0",...I,value:I.value??"",onChange:D=>I.onChange(D.target.value?Number(D.target.value):void 0)})})]})}),e.jsx(Mf,{control:S.control,name:"lead_source_id",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Lead Source"}),e.jsxs(ls,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(sf,{children:e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select source"})})}),e.jsx(as,{children:p==null?void 0:p.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add custom source...",value:d,onChange:I=>u(I.target.value),className:"flex-1"}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:P,disabled:!d.trim(),children:e.jsx(sn,{className:"h-4 w-4"})})]}),e.jsx(Mf,{control:S.control,name:"client_type_id",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Client Type"}),e.jsxs(ls,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(sf,{children:e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select client type"})})}),e.jsx(as,{children:f==null?void 0:f.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))})]})]})}),e.jsx(Mf,{control:S.control,name:"contact_id",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Client Contact"}),e.jsxs(hd,{open:r,onOpenChange:a,children:[e.jsx(md,{asChild:!0,children:e.jsx(sf,{children:e.jsxs(z,{variant:"outline",role:"combobox",className:Ct("w-full justify-between",!I.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(R_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(nd,{className:"w-full p-0",align:"start",children:[e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search contacts..."}),e.jsxs(Rj,{children:[e.jsx(Fj,{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(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(G_,{children:g==null?void 0:g.map(D=>e.jsxs(c1,{value:`${D.first_name} ${D.last_name||""}`,onSelect:()=>{I.onChange(D.id),a(!1)},children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",D.id===I.value?"opacity-100":"opacity-0")}),D.first_name," ",D.last_name||""]},D.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(pe,{placeholder:"Enter contact name...",value:i,onChange:D=>l(D.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{size:"sm",onClick:E,disabled:!i.trim()||v.isPending,children:"Add Contact"}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Mf,{control:S.control,name:"notes",render:({field:I})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Notes"}),e.jsx(sf,{children:e.jsx(Ps,{placeholder:"Any notes about this transaction...",...I})})]})}),e.jsx(Mf,{control:S.control,name:"is_win",render:({field:I})=>e.jsxs(ef,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(tf,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(sf,{children:e.jsx(mn,{checked:I.value,onCheckedChange:I.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function Tat({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState("all"),[p,f]=_.useState("all"),[g,v]=_.useState("all"),[y,b]=_.useState(!1),w=GUs(),S=SLe(),{data:C}=Q9();Q_();const E=XW(),P=D=>{const{id:F,created_at:q,updated_at:G,lead_source:V,client_type:H,contact:K,...Z}=D;S.mutate(Z)},M=()=>{o&&(w.mutate(o),c(null))},I=s.filter(D=>{var K,Z,oe,re;const F=d===""||D.property_address.toLowerCase().includes(d.toLowerCase())||((Z=(K=D.contact)==null?void 0:K.first_name)==null?void 0:Z.toLowerCase().includes(d.toLowerCase()))||((re=(oe=D.contact)==null?void 0:oe.last_name)==null?void 0:re.toLowerCase().includes(d.toLowerCase())),q=h==="all"||D.transaction_type===h,G=p==="all"||D.lead_source_id===p,V=g==="all"||D.client_type_id===g,H=!y||D.is_win;return F&&q&&G&&V&&H});return n?e.jsx(be,{children:e.jsx(Le,{className:"p-6 space-y-4",children:[1,2,3].map(D=>e.jsx(ln,{className:"h-16 w-full"},D))})}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(_t,{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(Nt,{children:["Transactions (",I.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search...",value:d,onChange:D=>u(D.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(ls,{value:h,onValueChange:m,children:[e.jsx(rs,{className:"w-[100px]",children:e.jsx(cs,{placeholder:"Type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]}),e.jsxs(ls,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-[130px]",children:e.jsx(cs,{placeholder:"Lead Source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Sources"}),C==null?void 0:C.map(D=>e.jsx(He,{value:D.id,children:D.name},D.id))]})]}),e.jsxs(z,{variant:y?"default":"outline",size:"sm",onClick:()=>b(!y),children:[e.jsx(Kh,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Le,{children:I.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):E?e.jsx("div",{className:"space-y-3",children:I.map(D=>e.jsxs(be,{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:D.property_address}),D.is_win&&e.jsx(Kh,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[D.city,D.state?`, ${D.state}`:""]})]}),e.jsx(ze,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.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: "}),xmt(D.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),lm(D.sale_price)]}),t&&D.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),lm(D.commission_amount)]}),D.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),D.lead_source.name]}),D.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),D.contact.first_name," ",D.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[D.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>l(D),children:e.jsx(Cp,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>P(D),children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>c(D.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})]},D.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[r&&e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Close Date"}),e.jsx(Tt,{children:"Sale Price"}),t&&e.jsx(Tt,{children:"Commission"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Client"}),!a&&e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(Qa,{children:I.map(D=>{var F;return e.jsxs(fn,{children:[r&&e.jsx(yt,{className:"font-medium text-sm",children:r[D.owner_user_id]||"Unknown"}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[D.is_win&&e.jsx(Kh,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:D.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[D.city,D.state?`, ${D.state}`:""]})]})]})}),e.jsx(yt,{children:e.jsx(ze,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.transaction_type})}),e.jsx(yt,{children:xmt(D.close_date)}),e.jsx(yt,{children:lm(D.sale_price)}),t&&e.jsx(yt,{children:D.commission_amount?lm(D.commission_amount):"-"}),e.jsx(yt,{children:((F=D.lead_source)==null?void 0:F.name)||"-"}),e.jsx(yt,{children:D.contact?`${D.contact.first_name} ${D.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(yt,{children:e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onClick:()=>l(D),children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ua,{onClick:()=>P(D),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ua,{onClick:()=>c(D.id),className:"text-destructive",children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},D.id)})})]})})})]}),e.jsx(jss,{open:!!i,onOpenChange:D=>!D&&l(null),transaction:i||void 0}),e.jsx(Ql,{open:!!o,onOpenChange:D=>!D&&c(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Transaction?"}),e.jsx(ql,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Nss({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,p)=>{if(!p||p===0)return null;const f=Math.min(m/p*100,100),g=Math.max(p-m,0),v=l>0?g/l:0,y=i/12*100,b=f>=y?"ahead":f>=y*.8?"on-track":"behind";return{percent:f,remaining:g,pace:v,status:b}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(kl,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(ze,{variant:"secondary",children:[e.jsx(gN,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(ze,{variant:"destructive",children:[e.jsx(_S,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bu,{className:"h-5 w-5 text-primary"}),e.jsxs(Nt,{children:[n," Goals Progress"]})]})}),e.jsx(Le,{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(Di,{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(Di,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[lm(t.totalVolume,!0)," of ",lm(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 ",lm(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(Di,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[lm(t.totalCommission,!0)," of ",lm(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 ",lm(u.pace,!0),"/month"]})]})]})})]})}const sWn={light:"",dark:".dark"},kss=_.createContext(null);function Sss(){const s=_.useContext(kss);if(!s)throw new Error("useChart must be used within a ");return s}const Css=_.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=_.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(kss.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Ct("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(nWn,{id:o,config:r}),e.jsx(Nb,{children:n})]})})});Css.displayName="Chart";const nWn=({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(sWn).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},Ass=_.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:m},p)=>{const{config:f}=Sss(),g=_.useMemo(()=>{var C;if(a||!(t!=null&&t.length))return null;const[y]=t,b=`${m||y.dataKey||y.name||"value"}`,w=GYe(f,y,b),S=!m&&typeof l=="string"?((C=f[l])==null?void 0:C.label)||l:w==null?void 0:w.label;return o?e.jsx("div",{className:Ct("font-medium",c),children:o(S,t)}):S?e.jsx("div",{className:Ct("font-medium",c),children:S}):null},[l,o,t,a,c,f,m]);if(!s||!(t!=null&&t.length))return null;const v=t.length===1&&r!=="dot";return e.jsxs("div",{ref:p,className:Ct("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:g,e.jsx("div",{className:"grid gap-1.5",children:t.map((y,b)=>{const w=`${h||y.name||y.dataKey||"value"}`,S=GYe(f,y,w),C=u||y.payload.fill||y.color;return e.jsx("div",{className:Ct("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&&(y==null?void 0:y.value)!==void 0&&y.name?d(y.value,y.name,y,b,y.payload):e.jsxs(e.Fragment,{children:[S!=null&&S.icon?e.jsx(S.icon,{}):!i&&e.jsx("div",{className:Ct("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":C,"--color-border":C}}),e.jsxs("div",{className:Ct("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[v?g:null,e.jsx("span",{className:"text-muted-foreground",children:(S==null?void 0:S.label)||y.name})]}),y.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:y.value.toLocaleString()})]})]})},y.dataKey)})})]})});Ass.displayName="ChartTooltip";const rWn=_.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=Sss();return n!=null&&n.length?e.jsx("div",{ref:i,className:Ct("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=GYe(l,o,c);return e.jsxs("div",{className:Ct("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});rWn.displayName="ChartLegend";function GYe(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 Nde=["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 Mat({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(be,{children:e.jsx(Le,{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(be,{className:"overflow-hidden",children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Le,{className:"overflow-hidden",children:e.jsx(Css,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(Nb,{width:"100%",height:"100%",children:e.jsxs(KW,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(TE,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Mv,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Pv,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Rf,{content:e.jsx(Ass,{})}),e.jsx(W_,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Le,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(Nb,{width:"100%",height:"100%",children:e.jsxs(cYt,{children:[e.jsx(DC,{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(cz,{fill:Nde[i%Nde.length]},`cell-${i}`))}),e.jsx(Rf,{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:Nde[i%Nde.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function aWn(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=_Je(t,r,new Date);if(rVe(a))return Ys(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(rVe(r))return Ys(r,"yyyy-MM-dd")}catch{}return null}const iWn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function oWn({open:s,onOpenChange:t}){const[n,r]=_.useState([]),[a,i]=_.useState(!1),[l,o]=_.useState(0),{data:c}=Q9(),{data:d}=Q_(),u=SLe(),h=()=>{const y=iWn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),w=`${y} ${b}`,S=new Blob([w],{type:"text/csv"}),C=URL.createObjectURL(S),E=document.createElement("a");E.href=C,E.download="transaction-import-template.csv",E.click(),URL.revokeObjectURL(C)},m=y=>{const b=y.split(` `).filter(S=>S.trim());if(b.length<2)return[];const w=b[0].split(",").map(S=>S.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((S,C)=>{var Z,oe,re,ae;const E=[];let P="",M=!1;for(const J of S)J==='"'?M=!M:J===","&&!M?(E.push(P.trim()),P=""):P+=J;E.push(P.trim());const I=J=>{var ce;const te=w.indexOf(J);return te>=0?(ce=E[te])==null?void 0:ce.replace(/^["']|["']$/g,"").trim():""},D=(Z=I("transaction_type"))==null?void 0:Z.toLowerCase(),F=(oe=I("sale_price"))==null?void 0:oe.replace(/[$,]/g,""),q=(re=I("commission_amount"))==null?void 0:re.replace(/[$,]/g,""),G=(ae=I("is_win"))==null?void 0:ae.toLowerCase(),V=I("close_date"),H=aWn(V);let K;return I("property_address")?["buyer","seller"].includes(D)?H?(!F||isNaN(Number(F)))&&(K="Invalid sale price"):K=`Invalid date format: "${V}" - use MM/DD/YYYY or YYYY-MM-DD`:K='Transaction type must be "buyer" or "seller"':K="Missing property address",{property_address:I("property_address"),city:I("city"),state:I("state"),zip:I("zip"),transaction_type:D==="seller"?"seller":"buyer",close_date:H||"",sale_price:Number(F)||0,commission_amount:q?Number(q):null,lead_source_name:I("lead_source"),client_type_name:I("client_type"),is_win:["yes","true","1"].includes(G),notes:I("notes"),error:K}})},p=y=>{var S;const b=(S=y.target.files)==null?void 0:S[0];if(!b)return;const w=new FileReader;w.onload=C=>{var M;const E=(M=C.target)==null?void 0:M.result,P=m(E);r(P)},w.readAsText(b)},f=async()=>{const y=n.filter(S=>!S.error);if(y.length===0){ne.error("No valid transactions to import");return}i(!0),o(0);let b=0,w=0;for(let S=0;SM.name.toLowerCase()===C.lead_source_name.toLowerCase()),P=d==null?void 0:d.find(M=>M.name.toLowerCase()===C.client_type_name.toLowerCase());await u.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,lead_source_id:(E==null?void 0:E.id)||null,client_type_id:(P==null?void 0:P.id)||null,contact_id:null,notes:C.notes||null,is_win:C.is_win}),b++}catch(E){w++,console.error("Failed to import transaction:",E)}o(Math.round((S+1)/y.length*100))}i(!1),b>0&&ne.success(`Imported ${b} transaction${b>1?"s":""}`),w>0&&ne.error(`Failed to import ${w} transaction${w>1?"s":""}`),r([]),t(!1)},g=n.filter(y=>!y.error).length,v=n.filter(y=>y.error).length;return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Import Transactions"}),e.jsx(_r,{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(z,{variant:"outline",onClick:h,children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(pe,{id:"csv-file",type:"file",accept:".csv",onChange:p})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ze,{variant:"outline",children:[n.length," rows found"]}),g>0&&e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(Wr,{className:"h-3 w-3 mr-1"}),g," valid"]}),v>0&&e.jsxs(ze,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),v," errors"]})]}),e.jsx(Ki,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((y,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${y.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:y.property_address||"(no address)"}),e.jsx(ze,{variant:y.transaction_type==="buyer"?"default":"secondary",children:y.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[y.close_date," • $",y.sale_price.toLocaleString()]}),y.error&&e.jsx(Ote,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(zte,{className:"text-xs",children:y.error})})]},b)),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(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:f,disabled:g===0||a,children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Import ",g," Transaction",g!==1?"s":""]})]})]})]})})}const lWn=Gj({transactions_goal:TJ().min(0).optional(),volume_goal:TJ().min(0).optional(),gci_goal:TJ().min(0).optional()});function cWn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=WUs(),{data:i}=CLe(),l=(i==null?void 0:i.show_commission)??!0,o=gPe({resolver:yPe(lWn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});_.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(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:[n," Goals"]}),e.jsx(_r,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(wPe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Mf,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Transactions Goal"}),e.jsx(sf,{children:e.jsx(pe,{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(M4e,{children:"Total number of deals you want to close"}),e.jsx(hb,{})]})}),e.jsx(Mf,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"Volume Goal ($)"}),e.jsx(sf,{children:e.jsx(pe,{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(M4e,{children:"Total sales volume you want to achieve"}),e.jsx(hb,{})]})}),l&&e.jsx(Mf,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(ef,{children:[e.jsx(tf,{children:"GCI Goal ($)"}),e.jsx(sf,{children:e.jsx(pe,{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(M4e,{children:"Gross commission income target"}),e.jsx(hb,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function Pat({transactions:s,isLoading:t}){const n=_.useRef(null),r=_.useRef(null),a=_.useRef([]),i=_.useRef(null),{isAdmin:l}=hs(),[o,c]=_.useState(""),[d,u]=_.useState(!0),[h,m]=_.useState(0),[p,f]=_.useState(!1),g=s.filter(y=>y.latitude!=null&&y.longitude!=null),v=s.filter(y=>y.latitude==null||y.longitude==null);return _.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}u(!1)})()},[]),_.useEffect(()=>{if(!o||v.length===0||p)return;(async()=>{var w;f(!0);let b=0;for(const S of v){const C=[S.property_address,S.city,S.state,S.zip].filter(Boolean).join(", ");if(C)try{const P=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(C)}.json?access_token=${o}&limit=1`)).json();if((w=P.features)!=null&&w[0]){const[M,I]=P.features[0].center;await U.from("scorecard_transactions").update({latitude:I,longitude:M}).eq("id",S.id),S.latitude=I,S.longitude=M,b++}}catch(E){console.error("Geocode error:",E)}}m(b),f(!1)})()},[o,s]),_.useEffect(()=>{if(!n.current||!o||r.current)return;Od.accessToken=o;const y=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],w=4;if(y.length>0){const S=y.reduce((E,P)=>E+P.longitude,0)/y.length,C=y.reduce((E,P)=>E+P.latitude,0)/y.length;b=[S,C],w=y.length===1?12:10}return r.current=new Od.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:w,center:b}),r.current.addControl(new Od.NavigationControl,"top-right"),()=>{var S;(S=r.current)==null||S.remove(),r.current=null}},[o]),_.useEffect(()=>{var b;if(!r.current||!o)return;a.current.forEach(w=>w.remove()),a.current=[],(b=i.current)==null||b.remove();const y=s.filter(w=>w.latitude!=null&&w.longitude!=null);if(y.forEach(w=>{var I;const S=w.transaction_type==="buyer",C=S?"#3B82F6":"#10B981",E=document.createElement("div");E.className="cursor-pointer",E.innerHTML=`
${S?'':''}
`;const P=new Od.Popup({offset:25,closeButton:!0}).setHTML(`
${w.property_address}
${w.city?`
${w.city}${w.state?", "+w.state:""} ${w.zip||""}
`:""}
${S?"Buyer":"Seller"} $${Number(w.sale_price).toLocaleString()}
Closed: ${Ou(w.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(I=w.lead_source)!=null&&I.name?" · "+w.lead_source.name:""}
${w.contact?`
Client: ${w.contact.first_name} ${w.contact.last_name||""}
`:""}
`),M=new Od.Marker(E).setLngLat([w.longitude,w.latitude]).setPopup(P).addTo(r.current);a.current.push(M)}),y.length>1){const w=new Od.LngLatBounds;y.forEach(S=>w.extend([S.longitude,S.latitude])),r.current.fitBounds(w,{padding:60,maxZoom:13})}else y.length===1&&r.current.flyTo({center:[y[0].longitude,y[0].latitude],zoom:12})},[s,o,p]),d||t?e.jsx(be,{children:e.jsx(Le,{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(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Ha,{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:[g.length," of ",s.length," mapped",p&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Ho,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in the Popby Map to enable maps across the platform.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const Ess=()=>{const{data:s}=K_();return rt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await U.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 U.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"})},dWn=s=>{const{data:t}=K_(),{data:n}=Ess();return rt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",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 uWn(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 hWn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function mWn({year:s}){var m;const{data:t,isLoading:n}=Ess(),{data:r,isLoading:a}=dWn(s),i=zn(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=_.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const p=t.map(D=>uWn(D,r));p.sort((D,F)=>F.totalVolume-D.totalVolume);const f={};t.forEach(D=>{f[D.id]=D.name||D.email});const g=r.length,v=r.reduce((D,F)=>D+Number(F.sale_price),0),y=r.reduce((D,F)=>D+(Number(F.commission_amount)||0),0),b=r.filter(D=>D.transaction_type==="buyer").length,w=r.filter(D=>D.transaction_type==="seller").length,S={};r.forEach(D=>{var q;const F=((q=D.lead_source)==null?void 0:q.name)||"Unknown";S[F]=(S[F]||0)+1});const C=Object.entries(S).sort((D,F)=>F[1]-D[1])[0],E={};r.forEach(D=>{const F=Ou(D.close_date).toLocaleString("default",{month:"short"});E[F]=(E[F]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(D=>({month:D,count:E[D]||0})),I=Object.entries(S).map(([D,F])=>({name:D,count:F})).sort((D,F)=>F.count-D.count);return{aggregate:{totalTxns:g,buyerCount:b,sellerCount:w,totalVolume:v,avgPrice:g>0?v/g:0,totalGCI:y,topSource:C?{name:C[0],count:C[1]}:null,memberCount:t.length},memberStats:p,topPerformer:p[0]||null,agentNameMap:f,teamChartStats:{transactionsByMonth:M,leadSourceBreakdown:I}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(p=>e.jsx(ln,{className:"h-24"},p))}),e.jsx(ln,{className:"h-64"})]}):!o||c.length===0?e.jsx(be,{className:"py-12",children:e.jsxs(Le,{className:"text-center space-y-2",children:[e.jsx(On,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(On,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(sa,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nd,{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:lm(o.totalVolume,!0)})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{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:lm(o.avgPrice,!0)})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nd,{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:lm(o.totalGCI,!0)})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Kh,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((m=o.topSource)==null?void 0:m.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(be,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Le,{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(jl,{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:lm(d.totalVolume,!0)})]})]})}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Member Performance"})}),e.jsx(Le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Transactions"}),e.jsx(Tt,{className:"text-center",children:"B / S"}),e.jsx(Tt,{className:"text-right",children:"Volume"}),e.jsx(Tt,{className:"text-right",children:"Avg Price"}),e.jsx(Tt,{className:"text-right",children:"GCI"}),e.jsx(Tt,{className:"text-right"})]})}),e.jsx(Qa,{children:c.map((p,f)=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[f===0&&p.totalTransactions>0&&e.jsx(jl,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(ja,{className:"h-8 w-8",children:[e.jsx(xi,{src:p.member.avatar_url||void 0}),e.jsx(Na,{className:"text-xs",children:hWn(p.member.name,p.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:p.member.name||p.member.email}),p.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.member.email})]})]})}),e.jsx(yt,{className:"text-center font-semibold",children:p.totalTransactions}),e.jsxs(yt,{className:"text-center text-sm",children:[p.buyerCount," / ",p.sellerCount]}),e.jsx(yt,{className:"text-right font-medium",children:lm(p.totalVolume,!0)}),e.jsx(yt,{className:"text-right text-sm",children:lm(p.averagePrice,!0)}),e.jsx(yt,{className:"text-right font-medium",children:lm(p.totalGCI,!0)}),e.jsx(yt,{className:"text-right",children:e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${p.member.id}`),children:e.jsx(xa,{className:"h-4 w-4"})})})]},p.member.id))})]})})})]}),e.jsxs(Qr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"transactions",children:[e.jsx(My,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Wt,{value:"charts",children:[e.jsx(wl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Wt,{value:"map",children:[e.jsx(Ha,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Kt,{value:"transactions",children:e.jsx(Tat,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Kt,{value:"charts",children:h&&e.jsx(Mat,{stats:h,year:s})}),e.jsx(Kt,{value:"map",children:e.jsx(Pat,{transactions:r||[],isLoading:a})})]})]})}const KCe=new Date().getFullYear(),s5t=Array.from({length:10},(s,t)=>KCe-t),kde="all";function pWn(){var q;const[s,t]=_.useState(KCe),n=s===null?kde:String(s),r=G=>t(G===kde?null:Number(G)),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState("my"),{data:f}=K_(),g=(f==null?void 0:f.role)==="team_leader",{data:v,isLoading:y}=Ket(s??void 0),{yearStats:b,lifetimeStats:w,isLoading:S,showCommission:C}=kBt(s??void 0),{data:E,isLoading:P}=NBt(s??KCe),{data:M}=CLe(),I=KUs(),D=()=>{if(!v||v.length===0)return;const G=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...C?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],V=v.map(re=>{var ae,J;return[re.property_address,re.city||"",re.state||"",re.zip||"",re.transaction_type,re.close_date,re.sale_price,...C?[re.commission_amount||""]:[],((ae=re.lead_source)==null?void 0:ae.name)||"",((J=re.client_type)==null?void 0:J.name)||"",re.contact?`${re.contact.first_name} ${re.contact.last_name||""}`.trim():"",re.is_win?"Yes":"No",re.notes||""]}),H=[G,...V].map(re=>re.map(ae=>`"${String(ae).replace(/"/g,'""')}"`).join(",")).join(` `),K=new Blob([H],{type:"text/csv"}),Z=URL.createObjectURL(K),oe=document.createElement("a");oe.href=Z,oe.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,oe.click(),URL.revokeObjectURL(Z)},F=!v||v.length===0;return e.jsxs($s,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),g&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(z,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>p("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(z,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>p("team"),className:"h-8",children:[e.jsx(On,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),m==="team"&&g?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),e.jsxs(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:kde,children:"All Years"}),s5t.map(G=>e.jsx(He,{value:String(G),children:G},G))]})]})]}),e.jsx(mWn,{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(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-[140px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:kde,children:"All Years"}),s5t.map(G=>e.jsx(He,{value:String(G),children:G},G))]})]}),e.jsx(z,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Gc,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-lg",children:"Settings"})}),e.jsx(Le,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ee,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(mn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:G=>I.mutate({show_commission:G})})]})})]}),F&&!y?e.jsx(be,{className:"py-12",children:e.jsxs(Le,{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(wl,{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(z,{onClick:()=>i(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(z,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Ra,{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(z,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Ga,{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(z,{onClick:()=>i(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(z,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(bu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(z,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(z,{variant:"outline",onClick:D,disabled:F,children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Ga,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(sa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w.totalTransactions," lifetime"]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(On,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[b.buyerCount,"/",b.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lm(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[lm(w.totalVolume,!0)," lifetime"]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{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:lm(b.averagePrice,!0)})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Kh,{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:((q=b.topLeadSource)==null?void 0:q.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),C&&e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lm(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[lm(w.totalCommission,!0)," lifetime"]})]})}),C&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(be,{children:e.jsxs(Le,{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(Nd,{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:lm(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[lm(w.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&E&&e.jsx(Nss,{goals:E,stats:b,year:s,showCommission:C}),e.jsxs(Qr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"transactions",children:"Transactions"}),e.jsx(Wt,{value:"charts",children:"Charts"}),e.jsxs(Wt,{value:"map",children:[e.jsx(Ha,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Kt,{value:"transactions",children:e.jsx(Tat,{transactions:v||[],showCommission:C,isLoading:y})}),e.jsx(Kt,{value:"charts",children:e.jsx(Mat,{stats:b,year:s??void 0})}),e.jsx(Kt,{value:"map",children:e.jsx(Pat,{transactions:v||[],isLoading:y})})]})]})]})]}),e.jsx(jss,{open:a,onOpenChange:i}),e.jsx(oWn,{open:l,onOpenChange:o}),e.jsx(cWn,{open:c,onOpenChange:d,year:s??KCe,existingGoals:E})]})}const fWn=s=>rt({queryKey:["listing-launch-kit",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([U.from("listing_launch_kits").select("*").eq("listing_id",s).maybeSingle(),U.from("listing_community_guides").select("*").eq("listing_id",s).maybeSingle()]);return{kit:t.data??null,guide:n.data??null}}}),xWn=()=>{const s=$t();return mt({mutationFn:async({listingId:t,regenerate:n})=>{var i,l;const{data:r,error:a}=await U.functions.invoke("listing-launch-kit",{body:{listingId:t,regenerate:!!n}});if(a){let o=r==null?void 0:r.error;if(!o)try{const c=await((l=(i=a==null?void 0:a.context)==null?void 0:i.json)==null?void 0:l.call(i));o=c==null?void 0:c.error}catch{}throw new Error(o||a.message||"Could not build the launch kit.")}if(r!=null&&r.error)throw new Error(r.error);return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing-launch-kit",n.listingId]})}})},gWn=()=>{const s=$t();return mt({mutationFn:async({guideId:t,enabled:n})=>{const{error:r}=await U.from("listing_community_guides").update({is_enabled:n}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing-launch-kit",n.listingId]})}})};function FT({label:s,value:t,multiline:n=!0}){const[r,a]=_.useState(!1);if(!t)return null;const i=async()=>{await navigator.clipboard.writeText(t),a(!0),ne.success(`${s} copied`),setTimeout(()=>a(!1),1800)};return e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border bg-muted/40",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:s}),e.jsxs(z,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:i,children:[r?e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1 text-primary"}):e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),r?"Copied":"Copy"]})]}),e.jsx("p",{className:`px-4 py-3 text-sm leading-relaxed text-foreground ${n?"whitespace-pre-wrap":""}`,children:t})]})}function Tss({listingId:s,open:t,onOpenChange:n,listingAddress:r,listingSlug:a,autoGenerate:i}){var S,C,E,P,M,I,D,F,q,G,V,H,K,Z,oe,re;const l=zn(),{data:o,isLoading:c}=fWn(t?s:null),d=xWn(),u=gWn(),[h,m]=_.useState(!1),p=(o==null?void 0:o.kit)??null,f=(o==null?void 0:o.guide)??null,g=d.isPending;_.useEffect(()=>{if(!t){m(!1);return}c||h||p||!s||(i||!p)&&(m(!0),d.mutate({listingId:s},{onError:ae=>ne.error((ae==null?void 0:ae.message)||"Could not build the launch kit.")}))},[t,c,p,s,i,h]);const v=_.useMemo(()=>{const ae=a||s;return ae?`${window.location.origin}/public/listing/${ae}`:null},[a,s]),y=ae=>{ae&&(sessionStorage.setItem("social-studio-seed",JSON.stringify({caption:ae,source:"listing-launch-kit",sourceRef:s})),n(!1),l("/social-studio"),ne.success("Draft ready in Social Studio"))},b=()=>{s&&d.mutate({listingId:s,regenerate:!0},{onSuccess:()=>ne.success("Fresh launch kit ready"),onError:ae=>ne.error((ae==null?void 0:ae.message)||"Could not rebuild the launch kit.")})},w=((S=p==null?void 0:p.social)==null?void 0:S.hashtags)??[];return e.jsx(Is,{open:t,onOpenChange:n,children:e.jsxs(Ls,{className:"max-w-4xl p-0 gap-0 overflow-hidden border-border flex flex-col max-h-[92vh]",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 via-slate-900 to-primary/30 px-6 pt-6 pb-5",children:[e.jsx("div",{className:"absolute inset-0 opacity-30 bg-[radial-gradient(circle_at_top_right,hsl(var(--primary)/0.5),transparent_60%)]"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] text-white/60 mb-2",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Listing Launch Kit"]}),e.jsx("h2",{className:"font-display text-2xl sm:text-[28px] font-semibold text-white leading-tight",children:((C=p==null?void 0:p.angle)==null?void 0:C.headline)||r||"Your listing, ready to launch"}),((E=p==null?void 0:p.angle)==null?void 0:E.target_buyer)&&e.jsxs("p",{className:"mt-2 text-sm text-white/70 flex items-start gap-2 max-w-2xl",children:[e.jsx(bu,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary-foreground/80"}),p.angle.target_buyer]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[(((P=p==null?void 0:p.angle)==null?void 0:P.pillars)??[]).map((ae,J)=>e.jsxs(ze,{variant:"outline",className:"border-white/20 bg-white/10 text-white/90 font-normal backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),ae]},J)),e.jsx("div",{className:"ml-auto",children:e.jsxs(z,{size:"sm",variant:"outline",className:"h-8 border-white/25 bg-white/10 text-white hover:bg-white/20 hover:text-white",onClick:b,disabled:g||!s,children:[e.jsx(Gi,{className:`h-3.5 w-3.5 mr-1.5 ${g?"animate-spin":""}`}),g?"Building…":"Regenerate"]})})]})]})]}),g&&!p?e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin text-primary"}),"Writing your scripts, captions, sphere emails and community guide…"]}),e.jsx(ln,{className:"h-24 w-full"}),e.jsx(ln,{className:"h-24 w-full"}),e.jsx(ln,{className:"h-24 w-full"})]}):p?e.jsxs(Qr,{defaultValue:"video",className:"w-full flex-1 min-h-0 flex flex-col",children:[e.jsx("div",{className:"px-4 pt-4 border-b border-border",children:e.jsx(Jr,{className:"w-full justify-start gap-1 bg-transparent p-0 h-auto flex-wrap",children:[{v:"video",label:"Video & Reels",icon:Xr},{v:"social",label:"Social",icon:sd},{v:"sphere",label:"Sphere Blast",icon:Fr},{v:"openhouse",label:"Open House",icon:fj},{v:"guide",label:"Community Guide",icon:ip}].map(({v:ae,label:J,icon:te})=>e.jsxs(Wt,{value:ae,className:"rounded-t-lg rounded-b-none border-b-2 border-transparent px-3 py-2 text-sm data-[state=active]:border-primary data-[state=active]:bg-primary/5 data-[state=active]:text-primary data-[state=active]:shadow-none",children:[e.jsx(te,{className:"h-4 w-4 mr-1.5"}),J]},ae))})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs(Kt,{value:"video",className:"m-0 space-y-4",children:[e.jsx(FT,{label:"3-second hook",value:(I=(M=p.video)==null?void 0:M.reel_script)==null?void 0:I.hook}),e.jsx(FT,{label:"Walkthrough script",value:(F=(D=p.video)==null?void 0:D.reel_script)==null?void 0:F.walkthrough}),e.jsx(FT,{label:"Call to action",value:(G=(q=p.video)==null?void 0:q.reel_script)==null?void 0:G.cta}),(((V=p.video)==null?void 0:V.hooks)??[]).length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Story & Reel text overlays"}),e.jsx("ul",{className:"divide-y divide-border",children:p.video.hooks.map((ae,J)=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-4 py-2.5",children:[e.jsx("span",{className:"text-sm",children:ae}),e.jsx(z,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs shrink-0",onClick:()=>{navigator.clipboard.writeText(ae),ne.success("Copied")},children:e.jsx(Sa,{className:"h-3.5 w-3.5"})})]},J))})]})]}),e.jsxs(Kt,{value:"social",className:"m-0 space-y-4",children:[["instagram","facebook","linkedin"].map(ae=>{var ce;const J=(ce=p.social)==null?void 0:ce[ae];if(!J)return null;const te=ae==="linkedin"?"LinkedIn":ae==="instagram"?"Instagram":"Facebook";return e.jsxs("div",{className:"space-y-2",children:[e.jsx(FT,{label:`${te} caption`,value:J}),e.jsxs(z,{size:"sm",variant:"secondary",onClick:()=>y(J),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"}),"Send to Social Studio"]})]},ae)}),w.length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Hashtags"}),e.jsxs(z,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>{navigator.clipboard.writeText(w.join(" ")),ne.success("Hashtags copied")},children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),"Copy all"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:w.map((ae,J)=>e.jsx(ze,{variant:"secondary",className:"font-normal",children:ae},J))})]})]}),e.jsxs(Kt,{value:"sphere",className:"m-0 space-y-4",children:[e.jsx(FT,{label:"Email subject",value:(H=p.outreach)==null?void 0:H.email_subject,multiline:!1}),e.jsx(FT,{label:"Email to your sphere",value:(K=p.outreach)==null?void 0:K.email_body}),e.jsx(FT,{label:"VIP text message",value:(Z=p.outreach)==null?void 0:Z.sms})]}),e.jsxs(Kt,{value:"openhouse",className:"m-0 space-y-4",children:[e.jsx(FT,{label:"60-second door pitch",value:(oe=p.open_house)==null?void 0:oe.pitch}),(((re=p.open_house)==null?void 0:re.neighborhood_points)??[]).length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Neighborhood talking points"}),e.jsx("ul",{className:"divide-y divide-border",children:p.open_house.neighborhood_points.map((ae,J)=>e.jsxs("li",{className:"px-4 py-2.5 text-sm flex gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"}),ae]},J))})]})]}),e.jsx(Kt,{value:"guide",className:"m-0 space-y-4",children:f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-primary/25 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4 text-primary"}),"Show the free guide download on your public listing page"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Visitors trade their name, email and cell for the guide — each one lands in your CRM as a new lead."})]}),e.jsx(mn,{checked:f.is_enabled,disabled:u.isPending,onCheckedChange:ae=>u.mutate({guideId:f.id,enabled:ae,listingId:s},{onSuccess:()=>ne.success(ae?"Guide download is live":"Guide download hidden"),onError:()=>ne.error("Could not update the guide")})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-4",children:[e.jsxs(ze,{variant:"secondary",className:"font-normal",children:[f.download_count," download",f.download_count===1?"":"s"]}),v&&e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(v),ne.success("Share link copied — great for neighborhood groups")},children:[e.jsx(Oc,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy share link"]})]})]}),e.jsx("div",{className:"rounded-xl border border-border bg-card/60 p-5",children:e.jsx(eOt,{title:f.title,subtitle:f.subtitle,areaLabel:f.area_label,sections:f.sections??[]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No community guide was generated for this listing yet. Try Regenerate."})})]})})]}):e.jsxs("div",{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"No launch kit yet for this listing."}),e.jsxs(z,{onClick:b,disabled:!s,children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Build my launch kit"]})]})]})})}const yWn={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"},vWn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},bWn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function _Wn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,onLaunchKit:i,showActions:l}){var C,E;const{user:o}=hs(),{data:c}=pzt(s.id),d=mzt(),[u,h]=_.useState(!1),m=P=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(P),p=((C=s.photos)==null?void 0:C.find(P=>P.is_primary))||((E=s.photos)==null?void 0:E[0]),f=nzt(s.agent_id)||(o==null?void 0:o.id)===s.agent_id,g=s.listing_class==="commercial",v=s.commercial??null,y=s.lifecycle_stage==="pitch",b=g?[OA(v==null?void 0:v.building_sf)?`${OA(v==null?void 0:v.building_sf)} building`:null,OA(v==null?void 0:v.available_sf)?`${OA(v==null?void 0:v.available_sf)} available`:null,kAe(v==null?void 0:v.cap_rate)?`${kAe(v==null?void 0:v.cap_rate)} cap`:null,(v==null?void 0:v.price_per_sf)!=null?`${J2(v.price_per_sf,2)}/SF`:null,(v==null?void 0:v.units)!=null?`${v.units} units`:null].filter(Boolean).slice(0,3):[],w=async P=>{P.stopPropagation();try{const M=await d.mutateAsync(s.id);ne.success(M.saved?"Listing saved!":"Listing removed from saved")}catch{ne.error("Failed to save listing")}},S=P=>{if(P.stopPropagation(),o)h(!0);else{const M=`${s.listing_class==="commercial"?"https://commercial.relevelup.com":"https://listings.relevelup.com"}/${s.slug||s.id}`;navigator.clipboard.writeText(M),ne.success("Link copied to clipboard!")}};return e.jsxs(be,{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(jb,{className:"h-12 w-12"})}),e.jsxs("div",{className:"absolute top-2 left-2 flex flex-wrap gap-1",children:[e.jsx(ze,{className:`${yWn[s.status]} text-white border-0`,children:g&&y?"Pitch":vWn[s.status]}),g&&e.jsx(ze,{className:"border-0 bg-[#0b0f14]/90 text-white",children:v!=null&&v.deal_type?GP[v.deal_type]:"Commercial"})]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(Ia,{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(z,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:w,children:e.jsx(Fo,{className:`h-4 w-4 ${c?"fill-pink-500 text-pink-500":""}`})}),e.jsx(z,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:S,title:f?"Copy link":"Share & earn leads",children:f?e.jsx(sd,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(yLe,{open:u,onOpenChange:h,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`,isCommercial:s.listing_class==="commercial"}),e.jsxs(Le,{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:g?RH(v,s.price):m(s.price)}),s.open_to_referrals&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[e.jsx(On,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[g?e.jsx("p",{className:"font-medium truncate",children:vP(s,v)}):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(Ha,{className:"h-3 w-3"}),g?nae(s,v):`${s.city}, ${s.state}${s.neighborhood?` • ${s.neighborhood}`:""}`]})]}),e.jsx("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:g?b.map(P=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jb,{className:"h-4 w-4"}),P]},P)):e.jsxs(e.Fragment,{children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mj,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ey,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jb,{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:g?v!=null&&v.commercial_type?wL[v.commercial_type]:"Commercial":bWn[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(xa,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fo,{className:"h-3 w-3"}),s.save_count]})]}),l&&(n||r||a||i)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[i&&e.jsxs(z,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:P=>{P.stopPropagation(),i()},children:[e.jsx(Xf,{className:"h-4 w-4"}),"Launch Kit"]}),a&&e.jsxs(z,{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:P=>{P.stopPropagation(),a()},children:[e.jsx(sq,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(z,{variant:"outline",size:"sm",className:"flex-1",onClick:P=>{P.stopPropagation(),n()},children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(z,{variant:"destructive",size:"sm",onClick:P=>{P.stopPropagation(),r()},children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})]})}const Lat="lu_listing_selection_v1",b6e=24,_6e=new Set;function Mss(){try{return JSON.parse(sessionStorage.getItem(Lat)||"{}")}catch{return{}}}function xBe(s){try{sessionStorage.setItem(Lat,JSON.stringify(s))}catch{}_6e.forEach(t=>t())}let U3=Mss();function wWn(){U3=Mss(),_6e.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===Lat&&wWn()});const C6={getSnapshot:()=>U3,subscribe(s){return _6e.add(s),()=>_6e.delete(s)},toggle(s){const t={...U3};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=b6e)return!1;t[s.mlsNumber]=s}return U3=t,xBe(t),!0},remove(s){const t={...U3};delete t[s],U3=t,xBe(t)},clear(){U3={},xBe({})},has(s){return!!U3[s]},all(){return Object.values(U3)}};function Pss(){const s=_.useSyncExternalStore(C6.subscribe,C6.getSnapshot,C6.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:C6.toggle,remove:C6.remove,clear:C6.clear}}const jWn=new Set(["office_exclusive","coming_soon","pre_market"]);function NWn(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=jWn.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 PZ(s){const{has:t}=Pss(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(_Wn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),C6.toggle(NWn(s.listing))||ne.error(`You can select up to ${b6e} 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(Wr,{className:"h-4 w-4"}):e.jsx(on,{className:"h-4 w-4"})})]})}function kWn({open:s,onOpenChange:t,listings:n}){const{user:r}=hs(),{leadSite:a}=mf(),[i,l]=_.useState("grid"),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(new Set),[g,v]=_.useState(!1),[y,b]=_.useState(!1),{data:w}=xae(),[S,C]=_.useState(!1);_.useEffect(()=>{!s||!(r!=null&&r.id)||U.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:H})=>b(!!(H!=null&&H.gmail_email)))},[s,r==null?void 0:r.id]),_.useEffect(()=>{if(s){if(!o){const H=Array.from(new Set(n.map(Z=>Z.city).filter(Boolean))),K=H.length===1?` in ${H[0]}`:"";c(n.length===1?`New listing for you${K}`:`${n.length} hand-picked listings${K}`)}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:E=[],isLoading:P}=rt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:H}=await U.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 H||[]},enabled:!!(r!=null&&r.id)&&s}),{data:M}=rt({queryKey:["send-listings-suggestions",n.map(H=>H.mlsNumber).join(",")],queryFn:async()=>{const{data:H,error:K}=await U.functions.invoke("listing-email-suggestions",{body:{listings:n.map(Z=>({mlsNumber:Z.mlsNumber,city:Z.city,state:Z.state,price:Z.price,bedrooms:Z.bedrooms,bathrooms:Z.bathrooms}))}});if(K)throw K;return H},enabled:s&&n.length>0}),I=(M==null?void 0:M.suggestions)||[],D=_.useMemo(()=>{const H=h.trim().toLowerCase();return H?E.filter(K=>`${K.first_name??""} ${K.last_name??""} ${K.email} ${K.city??""}`.toLowerCase().includes(H)):E},[E,h]),F=H=>{f(K=>{const Z=new Set(K);return Z.has(H)?Z.delete(H):Z.add(H),Z})},q=()=>{f(H=>{const K=new Set(H);return I.forEach(Z=>K.add(Z.contact_id)),K})},G=n.length>0&&n.every(H=>H.mlsNumber.startsWith("lx-")),V=async()=>{if(!G&&!(a!=null&&a.id)){ne.error("You need an active lead site to send listings.");return}if(!o.trim())return ne.error("Subject is required");if(p.size===0)return ne.error("Pick at least one recipient");if(!y&&w&&!w.hasVerifiedSes){C(!0);return}const H=E.filter(K=>p.has(K.id)).map(K=>({contact_id:K.id,email:K.email,first_name:K.first_name,last_name:K.last_name}));v(!0);try{const{data:K,error:Z}=await U.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(oe=>({mlsNumber:oe.mlsNumber,address:oe.address,city:oe.city,state:oe.state,zip:oe.zip,price:oe.price,bedrooms:oe.bedrooms,bathrooms:oe.bathrooms,sqft:oe.sqft,status:oe.status,photos:(oe.photos||[]).slice(0,1),description:oe.description||"",external_url:oe.externalUrl||null,is_private:oe.is_private===!0})),recipients:H}});if(Z)throw Z;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Send failed");ne.success(`Sent ${K.sent}/${H.length} via ${y?"Gmail":"Amazon SES"}${K.failed?` · ${K.failed} failed`:""}`),C6.clear(),f(new Set),t(!1)}catch(K){ne.error((K==null?void 0:K.message)||"Failed to send")}finally{v(!1)}};return e.jsxs(Is,{open:s,onOpenChange:t,children:[e.jsxs(Ls,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-2",children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(_r,{children:G?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(ee,{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(H=>{var K;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:((K=H.photos)==null?void 0:K[0])&&e.jsx("img",{src:H.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:["$",(H.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[H.city,", ",H.state]})]})]},H.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(ee,{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(op,{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(nc,{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(ee,{htmlFor:"subject",children:"Subject"}),e.jsx(pe,{id:"subject",value:o,onChange:H=>c(H.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ps,{id:"intro",value:d,onChange:H=>u(H.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:y?"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:[I.length>0&&e.jsxs(be,{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:[I.length," smart ",I.length===1?"match":"matches"]})]}),e.jsx(z,{size:"sm",variant:"outline",onClick:q,children:"Add all"})]}),e.jsx(Ki,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:I.slice(0,12).map(H=>{const K=p.has(H.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(za,{checked:K,onCheckedChange:()=>F(H.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[H.first_name," ",H.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",H.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:H.reason})]})]},H.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",D.length,")"]}),p.size>0&&e.jsxs(ze,{variant:"secondary",children:[p.size," selected"]})]}),e.jsx(pe,{placeholder:"Search contacts…",value:h,onChange:H=>m(H.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(Ki,{className:"h-full",children:P?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):D.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:D.map(H=>{const K=p.has(H.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(za,{checked:K,onCheckedChange:()=>F(H.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[H.first_name," ",H.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[H.email,H.city&&e.jsxs(e.Fragment,{children:[" · ",H.city]})]})]})]},H.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:p.size})," recipients"]}),p.size>0&&e.jsxs(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>f(new Set),children:[e.jsx(er,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(hr,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx(z,{onClick:V,disabled:g||p.size===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send to ",p.size," ",p.size===1?"contact":"contacts"]})})]})]}),e.jsx(wLe,{open:S,onOpenChange:C,hasPending:!!(w!=null&&w.hasPendingSes),pendingEmails:w==null?void 0:w.pendingEmails})]})}function SWn(){const{selected:s,count:t,remove:n,clear:r}=Pss(),[a,i]=_.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>=b6e?"Max reached":`Pick up to ${b6e}`})]})]}),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(er,{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(z,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Cn,{className:"h-4 w-4"})," Clear"]}),e.jsxs(z,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Fr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(kWn,{open:a,onOpenChange:i,listings:s})]})}const CWn=[{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"}],AWn=[{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 EWn({filters:s,onFiltersChange:t,onClose:n,showCommercial:r}){const a=s.commercial??{},i=o=>t({...s,commercial:{...a,...o}}),l=()=>{t({sortBy:"newest"})};return e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Nt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:l,children:"Clear All"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(er,{className:"h-4 w-4"})})]})]}),e.jsxs(Le,{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(ee,{children:"Status"}),e.jsxs(ls,{value:s.status||"all",onValueChange:o=>t({...s,status:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"All statuses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),CWn.map(o=>e.jsx(He,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property Type"}),e.jsxs(ls,{value:s.propertyType||"all",onValueChange:o=>t({...s,propertyType:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"All types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),AWn.map(o=>e.jsx(He,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Price"}),e.jsx(pe,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:o=>t({...s,minPrice:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Max Price"}),e.jsx(pe,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:o=>t({...s,maxPrice:o.target.value?Number(o.target.value):void 0})})]})]}),r&&e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-4 border-t pt-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal Type"}),e.jsxs(ls,{value:a.dealType||"all",onValueChange:o=>i({dealType:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any deal type"}),Object.entries(GP).map(([o,c])=>e.jsx(He,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Asset Type"}),e.jsxs(ls,{value:a.commercialType||"all",onValueChange:o=>i({commercialType:o==="all"?void 0:o}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Any"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Any asset type"}),Object.entries(wL).map(([o,c])=>e.jsx(He,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Building SF"}),e.jsx(pe,{type:"number",placeholder:"Any size",value:a.minBuildingSf??"",onChange:o=>i({minBuildingSf:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Cap Rate (%)"}),e.jsx(pe,{type:"number",step:"0.1",placeholder:"Any",value:a.minCapRate??"",onChange:o=>i({minCapRate:o.target.value?Number(o.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(ee,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(mn,{checked:s.openToReferrals||!1,onCheckedChange:o=>t({...s,openToReferrals:o||void 0})})]})]})]})}function TWn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(jl,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(YA,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Kh,{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(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(jl,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Le,{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(sd,{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(sa,{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(YA,{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(jl,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Community Leaderboard"})}),e.jsx(Le,{children:e.jsxs(Qr,{defaultValue:"sharers",children:[e.jsxs(Jr,{className:"w-full",children:[e.jsxs(Wt,{value:"sharers",className:"flex-1",children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Wt,{value:"listers",className:"flex-1",children:[e.jsx(sa,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Kt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Kt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const n5t={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},r5t={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 MWn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function PWn({listings:s,isLoading:t}){const n=zn(),r=_.useRef(null),a=_.useRef(null),i=_.useRef([]),{isAdmin:l}=hs(),[o,c]=_.useState(""),[d,u]=_.useState(!0),[h,m]=_.useState(!1),p=s.filter(g=>g.latitude!=null&&g.longitude!=null),f=s.filter(g=>(g.latitude==null||g.longitude==null)&&(g.property_address||g.city));return _.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await U.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)})()},[]),_.useEffect(()=>{if(!o||f.length===0||h)return;(async()=>{var v;m(!0);for(const y of f){const b=[y.property_address,y.city,y.state].filter(Boolean).join(", ");if(b)try{const S=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(b)}.json?access_token=${o}&limit=1`)).json();if((v=S.features)!=null&&v[0]){const[C,E]=S.features[0].center;await U.from("listings").update({latitude:E,longitude:C}).eq("id",y.id),y.latitude=E,y.longitude=C}}catch(w){console.error("Geocode error:",w)}}m(!1)})()},[o,s]),_.useEffect(()=>{if(!r.current||!o||a.current)return;Od.accessToken=o;const g=s.filter(b=>b.latitude!=null&&b.longitude!=null);let v=[-98.5795,39.8283],y=4;if(g.length>0){const b=g.reduce((S,C)=>S+C.longitude,0)/g.length,w=g.reduce((S,C)=>S+C.latitude,0)/g.length;v=[b,w],y=g.length===1?12:10}return a.current=new Od.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:y,center:v}),a.current.addControl(new Od.NavigationControl,"top-right"),()=>{var b;(b=a.current)==null||b.remove(),a.current=null}},[o]),_.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(v=>v.remove()),i.current=[];const g=s.filter(v=>v.latitude!=null&&v.longitude!=null);if(g.forEach(v=>{var E,P,M;const y=n5t[v.status]||"#10B981",b=((E=v.photos)==null?void 0:E.find(I=>I.is_primary))||((P=v.photos)==null?void 0:P[0]),w=document.createElement("div");w.className="cursor-pointer",w.innerHTML=`
`;const S=new Od.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${MWn(v.price)}
${v.property_address||""}
${v.city}, ${v.state}
${r5t[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 →
`),C=new Od.Marker(w).setLngLat([v.longitude,v.latitude]).setPopup(S).addTo(a.current);i.current.push(C)}),g.length>1){const v=new Od.LngLatBounds;g.forEach(y=>v.extend([y.longitude,y.latitude])),a.current.fitBounds(v,{padding:60,maxZoom:13})}else g.length===1&&a.current.flyTo({center:[g[0].longitude,g[0].latitude],zoom:12})},[s,o,h]),_.useEffect(()=>(window.__navigateToListing__=g=>{n(`/mission-control/listings/${g}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(be,{children:e.jsx(Le,{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(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Ha,{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(n5t).map(([g,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:r5t[g]})]},g)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[p.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Ho,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in Settings to enable maps.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const WYe="homereel_mv_prefill",KYe="homereel_mv_badge_default";function Lss(s){try{sessionStorage.setItem(WYe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(KYe,JSON.stringify(s.badge))}catch{}}function Ljr(){try{const s=sessionStorage.getItem(WYe);return s?(sessionStorage.removeItem(WYe),JSON.parse(s)):null}catch{return null}}function Ijr(){try{const s=sessionStorage.getItem(KYe);return s?(sessionStorage.removeItem(KYe),JSON.parse(s)):null}catch{return null}}function Iss(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 LWn(){var Z,oe,re,ae,J,te,ce,ve;const s=zn(),{brokerageId:t}=hs(),{data:n,isLoading:r}=rzt(),[a,i]=_.useState("feed"),[l,o]=_.useState(!1),[c,d]=_.useState(null),[u,h]=_.useState(""),[m,p]=_.useState("all"),[f,g]=_.useState({sortBy:"newest"}),{data:v,isLoading:y}=azt({...f,listingClass:m==="all"?void 0:m,city:u||f.city}),{data:b,isLoading:w}=M9s(),{data:S,isLoading:C}=Met(),{data:E,isLoading:P}=D9s(),{data:M,isLoading:I}=O9s(),{data:D}=F9s(),F=lzt(),q=f.commercial,G=(v??[]).filter(me=>{if(!q||me.listing_class!=="commercial")return!q||Object.values(q).every(ge=>ge===void 0)||me.listing_class!=="commercial";const he=me.commercial??{};return!(q.dealType&&he.deal_type!==q.dealType||q.commercialType&&he.commercial_type!==q.commercialType||q.minBuildingSf&&Number(he.building_sf??0)me.lifecycle_stage==="pitch"),H=me=>s(me.listing_class==="commercial"?`/mission-control/listings/${me.id}/commercial`:`/mission-control/listings/${me.id}`),K=async me=>{if(await Qi("Are you sure you want to delete this listing? This action cannot be undone."))try{await F.mutateAsync(me),ne.success("Listing deleted successfully")}catch{ne.error("Failed to delete listing")}};return r?e.jsx($s,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs($s,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(z,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(sa,{className:"h-5 w-5 text-primary"})}),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:"Active Listings"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(Fo,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(sP,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(S==null?void 0:S.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(On,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((Z=E==null?void 0:E.sent)==null?void 0:Z.length)||0)+(((oe=E==null?void 0:E.received)==null?void 0:oe.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(Qr,{value:a,onValueChange:i,children:[e.jsxs(Jr,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Wt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Wt,{value:"brokerage",children:"Brokerage"}),e.jsx(Wt,{value:"my-listings",children:"My Listings"}),V.length>0&&e.jsxs(Wt,{value:"pitches",children:["Pitches (",V.length,")"]}),e.jsx(Wt,{value:"saved",children:"Saved"}),e.jsx(Wt,{value:"referrals",children:"Referrals"}),e.jsx(Wt,{value:"map",children:"Map"}),e.jsx(Wt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Kt,{value:"feed",className:"space-y-4",children:[e.jsx("div",{className:"inline-flex rounded-lg border bg-muted/40 p-1",children:["all","residential","commercial"].map(me=>e.jsx("button",{type:"button",onClick:()=>p(me),className:`rounded-md px-4 py-1.5 text-sm font-medium capitalize transition ${m===me?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:me==="all"?"All listings":me},me))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by city or neighborhood...",value:u,onChange:me=>h(me.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:f.sortBy,onValueChange:me=>g({...f,sortBy:me}),children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"Sort by"})}),e.jsxs(as,{children:[e.jsx(He,{value:"newest",children:"Newest First"}),e.jsx(He,{value:"updated",children:"Recently Updated"}),e.jsx(He,{value:"price_asc",children:"Price: Low to High"}),e.jsx(He,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(z,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(F_,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(EWn,{filters:f,onFiltersChange:g,onClose:()=>o(!1),showCommercial:m!=="residential"}),y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((me,he)=>e.jsxs(be,{children:[e.jsx(ln,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(ln,{className:"h-5 w-3/4"}),e.jsx(ln,{className:"h-4 w-1/2"}),e.jsx(ln,{className:"h-4 w-1/4"})]})]},he))}):(v==null?void 0:v.length)===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(sa,{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(z,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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:G.map(me=>e.jsx(PZ,{listing:me,onClick:()=>H(me)},me.id))})]}),e.jsx(Kt,{value:"my-listings",className:"space-y-4",children:C?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((me,he)=>e.jsxs(be,{children:[e.jsx(ln,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(ln,{className:"h-5 w-3/4"}),e.jsx(ln,{className:"h-4 w-1/2"})]})]},he))}):(S==null?void 0:S.length)===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(sP,{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(z,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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:S==null?void 0:S.map(me=>e.jsx(PZ,{listing:me,showActions:!0,onClick:()=>H(me),onEdit:()=>s(me.listing_class==="commercial"?`/mission-control/listings/${me.id}/commercial`:`/mission-control/listings/${me.id}/edit`),onDelete:()=>K(me.id),onLaunchKit:()=>d(me),onCreateMusicVideo:()=>{const he=(me.photos??[]).slice().sort((ge,Ee)=>(Ee.is_primary?1:0)-(ge.is_primary?1:0)||(ge.sort_order??0)-(Ee.sort_order??0)).map(ge=>ge.photo_url).filter(Boolean);if(he.length===0){ne.error("Add photos to this listing first.");return}Lss({photos:he,details:{address:me.property_address||`${me.city??""} ${me.state??""}`.trim(),beds:me.bedrooms?String(me.bedrooms):"",baths:me.bathrooms?String(me.bathrooms):"",sqft:me.square_footage?String(me.square_footage):"",price:me.price?String(me.price):"",highlights:me.description||""},sourceLabel:"My Listings",badge:Iss(me.status,me.price)}),s("/admin/beta/homereel?tab=music-video")}},me.id))})}),e.jsxs(Kt,{value:"pitches",className:"space-y-4",children:[e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{className:"py-4 text-sm text-muted-foreground",children:"Pitches are private to you. They never appear in the Exchange, public search, or sitemaps until you mark the assignment as won."})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map(me=>e.jsx(PZ,{listing:me,showActions:!0,onClick:()=>s(`/mission-control/listings/${me.id}/commercial`),onEdit:()=>s(`/mission-control/listings/${me.id}/commercial`),onDelete:()=>K(me.id)},me.id))})]}),e.jsx(Kt,{value:"saved",className:"space-y-4",children:w?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((me,he)=>e.jsxs(be,{children:[e.jsx(ln,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(ln,{className:"h-5 w-3/4"}),e.jsx(ln,{className:"h-4 w-1/2"})]})]},he))}):(b==null?void 0:b.length)===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Fo,{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:b==null?void 0:b.map(me=>e.jsx(PZ,{listing:me.listing,onClick:()=>H(me.listing)},me.id))})}),e.jsx(Kt,{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(sd,{className:"h-4 w-4"}),"Referrals Sent (",((re=E==null?void 0:E.sent)==null?void 0:re.length)||0,")"]}),((ae=E==null?void 0:E.sent)==null?void 0:ae.length)===0?e.jsx(be,{children:e.jsx(Le,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(J=E==null?void 0:E.sent)==null?void 0:J.map(me=>{var he,ge;return e.jsx(be,{children:e.jsx(Le,{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:me.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((he=me.listing)==null?void 0:he.property_address)||((ge=me.listing)==null?void 0:ge.city)})]}),e.jsx(ze,{variant:me.status==="closed"?"default":"secondary",children:me.status.replace("_"," ")})]})})},me.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(On,{className:"h-4 w-4"}),"Referrals Received (",((te=E==null?void 0:E.received)==null?void 0:te.length)||0,")"]}),((ce=E==null?void 0:E.received)==null?void 0:ce.length)===0?e.jsx(be,{children:e.jsx(Le,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ve=E==null?void 0:E.received)==null?void 0:ve.map(me=>{var he;return e.jsx(be,{children:e.jsxs(Le,{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:me.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(he=me.sender)==null?void 0:he.name]})]}),e.jsx(ze,{variant:me.status==="closed"?"default":"secondary",children:me.status.replace("_"," ")})]}),e.jsx(z,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${me.listing_id}`),children:"View Listing"})]})},me.id)})})]})]})}),t&&e.jsx(Kt,{value:"brokerage",className:"space-y-4",children:I?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((me,he)=>e.jsxs(be,{children:[e.jsx(ln,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(ln,{className:"h-5 w-3/4"}),e.jsx(ln,{className:"h-4 w-1/2"})]})]},he))}):(M==null?void 0:M.length)===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(sP,{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(z,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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:M==null?void 0:M.map(me=>e.jsx(PZ,{listing:me,onClick:()=>H(me)},me.id))})}),e.jsx(Kt,{value:"map",children:e.jsx(PWn,{listings:v||[],isLoading:y})}),e.jsx(Kt,{value:"leaderboard",children:e.jsx(TWn,{leaderboard:D})})]})]}),e.jsx(SWn,{}),e.jsx(Tss,{listingId:(c==null?void 0:c.id)??null,open:!!c,onOpenChange:me=>!me&&d(null),listingAddress:c==null?void 0:c.property_address,listingSlug:(c==null?void 0:c.slug)??null})]}):e.jsx($s,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(sa,{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!"})]})})})}const IWn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function DWn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=iLe(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 Pet(i);window.open(l,"_blank")}catch{ne.error("Failed to open document")}};return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:[e.jsx($r,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Le,{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($r,{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:IWn(i.file_size)})]}),e.jsx(Ga,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function k_(s){const t=s.expected_commission,n=Number(s.bonus_amount)||0;if(!t)return n>0?n:null;if((s.commission_calc_method||"standard")==="referral_first"){let i=t;s.referral_fee_pct&&(i-=t*(s.referral_fee_pct/100));let l=i;return s.brokerage_split_pct&&(l-=i*(s.brokerage_split_pct/100)),s.team_split_pct&&(l-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(l-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(l-=s.transaction_fee),Math.max(0,l)+n}let a=t;return s.brokerage_split_pct&&(a-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(a-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(a-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(a-=s.transaction_fee),Math.max(0,a)+n}function cie(){const s=ha();return rt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Dss(){const s=ha(),t=$t();return mt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await U.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function xK(){const s=ha();return rt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Rss(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 U.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 Fss(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 RWn(){const s=$t();return mt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a}=await U.from("deal_pipeline_stages").select("default_probability").eq("id",n).maybeSingle(),i={stage_id:n};typeof(a==null?void 0:a.default_probability)=="number"&&(i.probability=a.default_probability);const{data:l,error:o}=await U.from("deal_pipeline").update(i).eq("id",t).select().single();if(o)throw o;return await U.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),l},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function FWn(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.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 OWn(s){return rt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function zWn(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function BWn(s){return rt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function $Wn(){const s=$t();return mt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await U.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 UWn(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function qWn(){const s=ha();return rt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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)+(c.bonus_amount||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(k_(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)+(c.bonus_amount||0))*d},0),weightedNet:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(k_(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0)+(c.bonus_amount||0),0),ytdWonNet:l.reduce((o,c)=>o+(k_(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(k_(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(k_(c)||0)*d},0)}},enabled:!!s})}function VWn(s){const t=ha();return rt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await U.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 HWn(){const s=$t();return mt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await U.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await U.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function GWn(){const s=$t();return mt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await U.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 WWn({listing:s}){const t=zn(),[n,r]=_.useState(""),[a,i]=_.useState(!1),{data:l,isLoading:o}=VWn(s.id),{data:c,isLoading:d}=cie(),{data:u,isLoading:h}=xK(),m=Dss(),p=HWn(),f=GWn(),g=Rss(),v=(u==null?void 0:u.filter(C=>!C.listing_id))||[],y=C=>{if(!(c!=null&&c.length))return null;switch(C){case"coming_soon":case"active":case"price_improvement":return c.find(E=>E.name==="Active");case"under_contract":return c.find(E=>E.name==="Under Contract");case"sold":return c.find(E=>E.is_won_stage);default:return c.find(E=>E.name==="Active")}},b=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const C=y(s.status);await g.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(C==null?void 0:C.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}),ne.success("Deal created and linked to listing!")}catch(C){console.error("Failed to create deal:",C),ne.error("Failed to create deal")}finally{i(!1)}},w=async()=>{if(!n){ne.error("Please select a deal");return}try{await p.mutateAsync({dealId:n,listingId:s.id}),ne.success("Listing linked to deal!"),r("")}catch{ne.error("Failed to link listing")}},S=async()=>{if(l)try{await f.mutateAsync({dealId:l.id,listingId:s.id}),ne.success("Listing unlinked from deal")}catch{ne.error("Failed to unlink listing")}};return o||d?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(gj,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Le,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(be,{className:"border-primary/20 bg-primary/5",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Oc,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Le,{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(z,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(Da,{className:"h-3 w-3 ml-1"})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:S,disabled:f.isPending,children:f.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(rE,{className:"h-4 w-4"})})]})]})]}):e.jsxs(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(gj,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Le,{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(z,{onClick:b,disabled:a||g.isPending,className:"w-full",size:"sm",children:[a||g.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(sn,{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(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"flex-1 text-sm",children:e.jsx(cs,{placeholder:"Link to existing deal..."})}),e.jsx(as,{children:v.map(C=>e.jsx(He,{value:C.id,children:C.deal_name},C.id))})]}),e.jsx(z,{variant:"secondary",size:"icon",onClick:w,disabled:!n||p.isPending,children:p.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Oc,{className:"h-4 w-4"})})]})]})]})]})}const KWn={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"},YWn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},a5t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function ZWn(){var me,he,ge,Ee,Ne,Pe,Oe,ke,Ve;const{listingId:s}=Mi(),t=zn(),{user:n,isAdmin:r}=hs(),{data:a,isLoading:i}=dae(s||""),{data:l}=pzt(s||""),{data:o}=L9s(s||""),c=mzt(),d=P9s(),u=I9s(),h=lzt(),m=R9s(),[p,f]=_.useState(!1),[g,v]=_.useState(!1),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=Gl();_.useEffect(()=>{C.get("launchkit")==="1"&&(S(!0),C.delete("launchkit"),E(C,{replace:!0}))},[C,E]);const[P,M]=_.useState(!1),[I,D]=_.useState(!1),[F,q]=_.useState(!1),[G,V]=_.useState(null),[H,K]=_.useState({buyerName:"",buyerType:"",notes:""}),Z=nzt(a==null?void 0:a.agent_id),oe=(n==null?void 0:n.id)===(a==null?void 0:a.agent_id)||Z,re=_e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(_e),ae=async _e=>{const Ae=`https://listings.relevelup.com/${(a==null?void 0:a.slug)||(a==null?void 0:a.id)}`,Se=`Check out this listing: ${(a==null?void 0:a.property_address)||(a==null?void 0:a.city)}`;u.mutate({listingId:a.id,shareType:_e});try{switch(_e){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ae)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ae),ne.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Se} ${Ae}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Se)}&body=${encodeURIComponent(`Check out this listing: ${Ae}`)}`);break}}catch(We){console.error("Share error:",We),ne.error("Failed to share")}},J=async()=>{try{await h.mutateAsync(a.id),ne.success("Listing deleted"),t("/mission-control/listings")}catch{ne.error("Failed to delete listing")}},te=async()=>{if(!H.buyerName.trim()){ne.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:a.id,listingAgentId:a.agent_id,buyerName:H.buyerName,buyerType:H.buyerType||void 0,notes:H.notes||void 0}),ne.success("Referral sent successfully!"),v(!1),K({buyerName:"",buyerType:"",notes:""})}catch{ne.error("Failed to send referral")}},ce=_e=>{var $e,Xe;const Ae=(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`,Se=re((a==null?void 0:a.price)||0),We=a!=null&&a.bedrooms?`${a.bedrooms}BD`:"",qe=a!=null&&a.bathrooms?`${a.bathrooms}BA`:"",Be=a!=null&&a.square_footage?`${a.square_footage.toLocaleString()}SF`:"",Ze=[We,qe,Be].filter(Boolean).join(" | ");switch(_e){case"just_listed":return`🏡 JUST LISTED! ${Ae} ${Se} ${Ze} ${(a==null?void 0:a.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${($e=a==null?void 0:a.city)==null?void 0:$e.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ae} Now ${Se}! ${Ze} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${a5t[(a==null?void 0:a.property_type)||"single_family"].toLowerCase()} in ${a==null?void 0:a.city}? 👀 I've got just the one for you! ${Ze} DM me for details! 📩 #ComingSoon #RealEstate #${(Xe=a==null?void 0:a.city)==null?void 0:Xe.replace(/\s/g,"")}`;default:return""}};if(a&&a.listing_class==="commercial")return e.jsx(ed,{to:`/mission-control/listings/${a.id}/commercial`,replace:!0});if(i)return e.jsx($s,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-10 w-32"}),e.jsx(ln,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(ln,{className:"h-48"}),e.jsx(ln,{className:"h-48"}),e.jsx(ln,{className:"h-48"})]})]})});if(!a)return e.jsx($s,{title:"Listing Not Found",description:"",children:e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(z,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ve=((me=a.photos)==null?void 0:me.find(_e=>_e.is_primary))||((he=a.photos)==null?void 0:he[0]);return e.jsxs($s,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(z,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(ka,{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:()=>ve&&V(ve.photo_url),children:ve?e.jsx("img",{src:ve.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:(ge=a.photos)==null?void 0:ge.slice(1,5).map((_e,Ae)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>V(_e.photo_url),children:e.jsx("img",{src:_e.photo_url,alt:`Photo ${Ae+2}`,className:"w-full h-full object-cover"})},_e.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(be,{children:e.jsxs(Le,{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:`${KWn[a.status]} text-white border-0`,children:YWn[a.status]}),a.is_featured&&e.jsxs(ze,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),a.open_to_referrals&&e.jsxs(ze,{variant:"outline",children:[e.jsx(On,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:re(a.price)}),a.property_address&&e.jsx("p",{className:"text-xl font-medium",children:a.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Ha,{className:"h-4 w-4"}),a.city,", ",a.state,a.neighborhood&&` • ${a.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(z,{variant:"outline",size:"icon",onClick:()=>c.mutate(a.id),children:e.jsx(Fo,{className:`h-4 w-4 ${l?"fill-pink-500 text-pink-500":""}`})}),e.jsx(z,{variant:"outline",size:"icon",onClick:()=>d.mutate(a.id),children:o?e.jsx(pS,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),!oe&&e.jsxs(z,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>b(!0),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"outline",children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(qd,{children:[e.jsxs(ua,{onClick:()=>ae("copy"),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ua,{onClick:()=>ae("facebook"),children:[e.jsx(of,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ua,{onClick:()=>ae("text"),children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ua,{onClick:()=>ae("email"),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",onClick:()=>{const _e=(a.photos??[]).slice().sort((Ae,Se)=>(Se.is_primary?1:0)-(Ae.is_primary?1:0)||(Ae.sort_order??0)-(Se.sort_order??0)).map(Ae=>Ae.photo_url).filter(Boolean);if(_e.length===0){ne.error("Add photos to this listing first.");return}Lss({photos:_e,details:{address:a.property_address||`${a.city??""} ${a.state??""}`.trim(),beds:a.bedrooms?String(a.bedrooms):"",baths:a.bathrooms?String(a.bathrooms):"",sqft:a.square_footage?String(a.square_footage):"",price:a.price?String(a.price):"",highlights:a.description||""},sourceLabel:"Listing Exchange",badge:Iss(a.status,a.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(sq,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(z,{onClick:()=>S(!0),className:"gap-2 bg-gradient-to-r from-slate-900 to-primary text-white shadow-md hover:opacity-95",children:[e.jsx(Xf,{className:"h-4 w-4"}),"Launch Kit"]}),r&&e.jsxs(z,{variant:"outline",className:"gap-2",onClick:()=>t(`/mission-control/direct-mail?listing=${s}`),children:[e.jsx(on,{className:"h-4 w-4"}),"Mail Studio"]}),e.jsxs(z,{variant:"outline",onClick:()=>D(!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(z,{variant:"outline",onClick:()=>q(!0),className:"gap-2",children:[e.jsx(lf,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs(z,{variant:"outline",onClick:()=>M(!0),className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(z,{onClick:()=>t(`/mission-control/listings/${a.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(z,{variant:"outline",onClick:()=>t(`/mission-control/listings/${a.id}/edit`),children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(z,{variant:"destructive",size:"icon",onClick:()=>f(!0),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[a.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(mj,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),a.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Ey,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),a.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(jb,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),a.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(ya,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.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(oi,{className:"h-3 w-3 mr-1"}),a5t[a.property_type]]}),a.lot_size&&e.jsxs(ze,{variant:"secondary",children:["Lot: ",a.lot_size]}),a.has_hoa&&e.jsx(ze,{variant:"secondary",children:"HOA"})]}),a.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:a.description})]}),a.agent_notes&&a.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:a.agent_notes})]}),a.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:a.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:a.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[a.co_agent_email,a.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),a.mls_link&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(mr,{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(xa,{className:"h-4 w-4"}),a.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sd,{className:"h-4 w-4"}),a.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fo,{className:"h-4 w-4"}),a.save_count," saves"]})]})]})}),a.allow_sharing&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Share Content"})}),e.jsx(Le,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(_e=>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:[_e.replace("_"," ")," Caption"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(ce(_e)),ne.success("Caption copied!")},children:e.jsx(Sa,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:ce(_e)})]},_e))})]}),e.jsx(DWn,{listingId:a.id,ownerOnly:oe})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Le,{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:((Ne=(Ee=a.agent)==null?void 0:Ee.name)==null?void 0:Ne.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Pe=a.agent)==null?void 0:Pe.name)||"Unknown"}),((ke=(Oe=a.agent)==null?void 0:Oe.brokerage)==null?void 0:ke.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:a.agent.brokerage.name})]})]}),!oe&&e.jsx("div",{className:"space-y-2",children:((Ve=a.agent)==null?void 0:Ve.email)&&e.jsx(z,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),oe&&e.jsx(WWn,{listing:a}),!oe&&a.open_to_referrals&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Le,{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(z,{className:"w-full",onClick:()=>v(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(Is,{open:!!G,onOpenChange:()=>V(null),children:e.jsx(Ls,{className:"max-w-4xl",children:e.jsx("img",{src:G||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(Is,{open:p,onOpenChange:f,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Delete Listing"}),e.jsx(_r,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(z,{variant:"destructive",onClick:J,disabled:h.isPending,children:h.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Is,{open:g,onOpenChange:v,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Send Buyer Referral"}),e.jsx(_r,{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(ee,{children:"Buyer Name *"}),e.jsx(pe,{value:H.buyerName,onChange:_e=>K({...H,buyerName:_e.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Buyer Type"}),e.jsxs(ls,{value:H.buyerType,onValueChange:_e=>K({...H,buyerType:_e}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select type"})}),e.jsxs(as,{children:[e.jsx(He,{value:"first_time",children:"First-Time Buyer"}),e.jsx(He,{value:"investor",children:"Investor"}),e.jsx(He,{value:"relocating",children:"Relocating"}),e.jsx(He,{value:"upgrade",children:"Upgrading"}),e.jsx(He,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ps,{value:H.notes,onChange:_e=>K({...H,notes:_e.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(z,{onClick:te,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(Jzt,{open:F,onOpenChange:q,url:`https://listings.relevelup.com/${a.slug||a.id}`,title:a.property_address||`${a.city}, ${a.state}`,fileBase:a.slug||a.property_address||a.city}),e.jsx(yLe,{open:y,onOpenChange:b,listingId:(a==null?void 0:a.id)||"",listingSlug:(a==null?void 0:a.slug)||null,listingTitle:(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`}),a&&e.jsx(dBt,{open:P,onOpenChange:M,listing:a}),e.jsx($et,{listingId:(a==null?void 0:a.id)||null,open:I,onOpenChange:D,initialStatus:VAe(a==null?void 0:a.status)}),e.jsx(Tss,{listingId:(a==null?void 0:a.id)||null,open:w,onOpenChange:S,listingAddress:(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`,listingSlug:(a==null?void 0:a.slug)||null,autoGenerate:!0})]})}function XWn({onImport:s}){const[t,n]=_.useState(""),[r,a]=_.useState([]),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(null),h=_.useRef(),m=_.useRef(null);_.useEffect(()=>{const b=w=>{m.current&&!m.current.contains(w.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const p=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:w,error:S}=await U.functions.invoke("mls-listing-search",{body:{query:b}});if(S)throw S;a((w==null?void 0:w.listings)||[]),c(!0)}catch(w){console.error("MLS search error:",w),a([])}finally{l(!1)}},f=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(b),400)},g=b=>{u(b.mlsNumber),s(b),c(!1),n(`${b.address}, ${b.city}`),ne.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},v=b=>b?`$${b.toLocaleString()}`:"",y=b=>{const w=(b||"").toLowerCase();return w.includes("single")||w.includes("detached")?"Single Family":w.includes("condo")?"Condo":w.includes("town")?"Townhouse":w.includes("land")||w.includes("lot")?"Land":w.includes("multi")?"Multi-Family":w.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(be,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ga,{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(Le,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:t,onChange:b=>f(b.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(bt,{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(er,{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(b=>e.jsxs("button",{type:"button",onClick:()=>g(b),disabled:d===b.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:[b.photos[0]?e.jsx("img",{src:b.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(Ha,{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:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.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(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(mj,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ey,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Q4,{className:"h-3 w-3"})," ",b.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:y(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function QWn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=zn(),{user:a}=hs(),[i,l]=_.useState(!1),[o,c]=_.useState([]),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState({});_.useEffect(()=>{s&&a?g():m(null)},[s,a]);const g=async()=>{if(!s)return;const{data:I,error:D}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!D&&I&&(m(I),v(I))},v=async I=>{try{const{data:D,error:F}=await U.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:I.bunny_video_id,isAgentVideo:!0}});!F&&(D!=null&&D.thumbnailUrl)&&f(q=>({...q,[I.id]:{thumbnailUrl:D.thumbnailUrl}}))}catch(D){console.warn("Failed to get signed URL",D)}},y=async()=>{if(a){u(!0);try{const{data:I,error:D}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(D)throw D;c(I||[]),I!=null&&I.length&&b(I)}catch(I){console.error("Error fetching videos:",I),ne.error("Failed to load videos")}finally{u(!1)}}},b=async I=>{var D;try{const F=I.map(K=>K.bunny_video_id),{data:q,error:G}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:F,isAgentVideo:!0}});if(G)throw G;const V=(q==null?void 0:q.assets)||{},H={};for(const K of I)(D=V[K.bunny_video_id])!=null&&D.thumbnailUrl&&(H[K.id]={thumbnailUrl:V[K.bunny_video_id].thumbnailUrl});f(K=>({...K,...H}))}catch(F){console.warn("Failed to bulk-fetch signed URLs",F)}},w=()=>{l(!0),y()},S=I=>{t(I.id),m(I),l(!1),ne.success("Video selected")},C=()=>{t(null),m(null)},E=()=>{const I=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(I)}`)},P=I=>{if(!I)return"0:00";const D=Math.floor(I/60),F=I%60;return`${D}:${F.toString().padStart(2,"0")}`},M=I=>{var D;return((D=p[I.id])==null?void 0:D.thumbnailUrl)||I.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(be,{className:"overflow-hidden",children:e.jsx(Le,{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(Xr,{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(su,{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:P(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(z,{type:"button",variant:"outline",size:"sm",onClick:w,children:"Change"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",onClick:C,className:"text-destructive hover:text-destructive",children:e.jsx(er,{className:"h-4 w-4"})})]})]})})}):e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Xr,{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(z,{type:"button",variant:"outline",onClick:w,className:"gap-2",children:[e.jsx(vj,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(z,{type:"button",variant:"outline",onClick:E,className:"gap-2",children:[e.jsx(Lx,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(vj,{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(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Xr,{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(z,{onClick:E,className:"gap-2",children:[e.jsx(Lx,{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(I=>e.jsxs("button",{type:"button",onClick:()=>S(I),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===I.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(I)?e.jsx("img",{src:M(I),alt:I.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(Xr,{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(su,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),I.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:P(I.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:I.title||"Untitled Video"})})]},I.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(z,{type:"button",variant:"ghost",onClick:E,className:"gap-2",children:[e.jsx(Lx,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(z,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const JWn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function eKn({listingId:s}){const t=_.useRef(null),{data:n=[],isLoading:r}=iLe(s),a=fzt(),i=xzt(),l=q9s(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ne.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ne.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ne.success("Documents uploaded")}},c=async d=>{try{const u=await Pet(d);window.open(u,"_blank")}catch{ne.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(z,{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(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ra,{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(be,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx($r,{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:JWn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(xa,{className:"h-3 w-3"}):e.jsx(Yf,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(mn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(Ga,{className:"h-4 w-4"})}),e.jsx(z,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await Qi(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(er,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const tKn=[{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"}],sKn=[{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 nKn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=gLe({id:s}),u={transform:YP.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(Zf,{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(er,{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(Ia,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function rKn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=lLe($H(kW,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),p=o.indexOf(h.id),f=[...s],g=[...t],[v]=f.splice(m,1),[y]=g.splice(m,1);f.splice(p,0,v),g.splice(p,0,y),r(f,g)};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(pLe,{sensors:l,collisionDetection:cLe,onDragEnd:c,children:e.jsx(xLe,{items:o,strategy:pae,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(nKn,{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(bt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{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 i5t(){const{listingId:s}=Mi(),[t]=Gl(),n=t.get("brokerage"),r=zn(),{user:a}=hs(),{hasLeadSite:i}=mf(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=_.useState([]),[u,h]=_.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:p}=dae(l?s:""),f=izt(),g=T9s(),v=ozt(),y=czt(),b=dzt(),w=uzt(),S=hzt(),{data:C=[]}=rt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:Ae,error:Se}=await U.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Se)throw Se;return Ae||[]},enabled:o}),[E,P]=_.useState(""),{data:M=[]}=Kre(),I=M.filter(Ae=>Ae.role==="team_leader").map(Ae=>Ae.teamId),D=M.map(Ae=>Ae.teamId),F=I.length>0,{data:q=[]}=rt({queryKey:["team-agent-profiles",D.join(",")],queryFn:async()=>{if(!D.length)return[];const{data:Ae,error:Se}=await U.from("team_members").select("user_id").in("team_id",D);if(Se)throw Se;const We=Array.from(new Set((Ae||[]).map(Ze=>Ze.user_id)));if(!We.length)return[];const{data:qe,error:Be}=await U.from("profiles").select("id, name, email, phone, avatar_url, brokerage_name").in("id",We).order("name");if(Be)throw Be;return qe||[]},enabled:D.length>0}),[G,V]=_.useState(""),H=G||(a==null?void 0:a.id)||"",K=F&&!o&&q.length>1,[Z,oe]=_.useState(!1),[re,ae]=_.useState([]),[J,te]=_.useState([]),[ce,ve]=_.useState(!1),me=async Ae=>{if(Ae.size>5*1024*1024){ne.error("Image must be under 5MB");return}ve(!0);try{const Se=Ae.name.split(".").pop()||"jpg",We=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${Se}`,{error:qe}=await U.storage.from("listing-photos").upload(We,Ae,{upsert:!0});if(qe)throw qe;const{data:Be}=U.storage.from("listing-photos").getPublicUrl(We);ge(Ze=>({...Ze,co_agent_photo_url:Be.publicUrl})),ne.success("Headshot uploaded")}catch(Se){ne.error((Se==null?void 0:Se.message)||"Failed to upload headshot")}finally{ve(!1)}},[he,ge]=_.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,co_agent_name:"",co_agent_email:"",co_agent_phone:"",co_agent_brokerage:"",co_agent_photo_url:"",allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0,site_only:!1,show_on_lead_site:!0});_.useEffect(()=>{var Ae,Se,We,qe,Be;m&&l&&(ge({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((Ae=m.price)==null?void 0:Ae.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((Se=m.bedrooms)==null?void 0:Se.toString())||"",bathrooms:((We=m.bathrooms)==null?void 0:We.toString())||"",square_footage:((qe=m.square_footage)==null?void 0:qe.toString())||"",lot_size:m.lot_size||"",year_built:((Be=m.year_built)==null?void 0:Be.toString())||"",has_hoa:m.has_hoa,description:m.description||"",agent_notes:m.agent_notes||"",agent_notes_public:m.agent_notes_public,mls_link:m.mls_link||"",video_link:m.video_link||"",video_id:m.video_id||null,co_agent_name:m.co_agent_name||"",co_agent_email:m.co_agent_email||"",co_agent_phone:m.co_agent_phone||"",co_agent_brokerage:m.co_agent_brokerage||"",co_agent_photo_url:m.co_agent_photo_url||"",allow_sharing:m.allow_sharing,open_to_referrals:m.open_to_referrals,open_to_social_promotion:m.open_to_social_promotion,share_with_brokerage:m.share_with_brokerage??!1,is_public:m.is_public,site_only:m.site_only??!1,show_on_lead_site:m.show_on_lead_site??!0}),V(m.agent_id||""))},[m,l]);const Ee=Ae=>{var Be,Ze;const Se={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},We=(Ae.propertyType||"").toLowerCase(),qe=((Be=Object.entries(Se).find(([$e])=>We.includes($e)))==null?void 0:Be[1])||"other";ge($e=>({...$e,property_address:Ae.address||$e.property_address,city:Ae.city||$e.city,state:Ae.state||$e.state,price:Ae.price?String(Ae.price):$e.price,property_type:qe,bedrooms:Ae.bedrooms?String(Ae.bedrooms):$e.bedrooms,bathrooms:Ae.bathrooms?String(Ae.bathrooms):$e.bathrooms,square_footage:Ae.sqft?String(Ae.sqft):$e.square_footage,lot_size:Ae.lotSize?String(Ae.lotSize):$e.lot_size,year_built:Ae.yearBuilt?String(Ae.yearBuilt):$e.year_built,description:Ae.description||$e.description})),((Ze=Ae.photos)==null?void 0:Ze.length)>0&&(d(Ae.photos),J.forEach($e=>URL.revokeObjectURL($e)),ae([]),te([]))},Ne=Ae=>{if(!Ae)return;const Se=Array.from(Ae);ae(qe=>[...qe,...Se]);const We=Se.map(qe=>URL.createObjectURL(qe));te(qe=>[...qe,...We])},Pe=Ae=>{URL.revokeObjectURL(J[Ae]),ae(Se=>Se.filter((We,qe)=>qe!==Ae)),te(Se=>Se.filter((We,qe)=>qe!==Ae))},Oe=async Ae=>{var Se;if(!(!Ae||!m)){oe(!0);try{for(const We of Array.from(Ae)){const qe=We.name.split(".").pop(),Be=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${qe}`,{error:Ze}=await U.storage.from("listing-photos").upload(Be,We);if(Ze)throw Ze;const{data:{publicUrl:$e}}=U.storage.from("listing-photos").getPublicUrl(Be);await y.mutateAsync({listingId:m.id,photoUrl:$e,isPrimary:!((Se=m.photos)!=null&&Se.length)})}ne.success("Photos uploaded!")}catch(We){console.error("Upload error:",We),ne.error("Failed to upload photos")}finally{oe(!1)}}},ke=async Ae=>{for(let Se=0;Se{if(m)try{await b.mutateAsync({photoId:Ae,listingId:m.id}),ne.success("Photo removed")}catch{ne.error("Failed to remove photo")}},_e=async Ae=>{if(Ae.preventDefault(),!he.city.trim()||!he.state.trim()||!he.price){ne.error("Please fill in required fields (City, State, Price)");return}if(o&&!E){ne.error("Please select an agent to assign this listing to");return}try{const Se={property_address:he.property_address||null,city:he.city,state:he.state,neighborhood:he.neighborhood||null,price:Number(he.price),property_type:he.property_type,status:he.status,bedrooms:he.bedrooms?Number(he.bedrooms):null,bathrooms:he.bathrooms?Number(he.bathrooms):null,square_footage:he.square_footage?Number(he.square_footage):null,lot_size:he.lot_size||null,year_built:he.year_built?Number(he.year_built):null,has_hoa:he.has_hoa,description:he.description||null,agent_notes:he.agent_notes||null,agent_notes_public:he.agent_notes_public,mls_link:he.mls_link||null,video_link:he.video_link||null,video_id:he.video_id||null,co_agent_name:he.co_agent_name||null,co_agent_email:he.co_agent_email||null,co_agent_phone:he.co_agent_phone||null,co_agent_brokerage:he.co_agent_brokerage||null,co_agent_photo_url:he.co_agent_photo_url||null,allow_sharing:he.allow_sharing,open_to_referrals:he.open_to_referrals,open_to_social_promotion:he.open_to_social_promotion,share_with_brokerage:he.share_with_brokerage,is_public:he.site_only?!1:he.is_public,site_only:he.site_only,show_on_lead_site:he.site_only?!0:he.show_on_lead_site};if(l){const We=K&&H&&H!==(m==null?void 0:m.agent_id)?{agent_id:H}:{},qe=m==null?void 0:m.status;await v.mutateAsync({id:s,...Se,...We}),ne.success("Listing updated!");const Be=`/mission-control/listings/${s}`;qe&&qe!==he.status?h({open:!0,listingId:s,nextPath:Be,socialStatus:VAe(he.status)}):r(Be)}else{oe(!0);let We;if(o&&E?We=await g.mutateAsync({agentId:E,...Se}):K&&H&&H!==(a==null?void 0:a.id)?We=await g.mutateAsync({agentId:H,...Se}):We=await f.mutateAsync(Se),re.length>0)try{await ke(We.id),J.forEach(Be=>URL.revokeObjectURL(Be)),ae([]),te([])}catch(Be){console.error("Photo upload error:",Be),ne.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Be=0;Ber(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(ka,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Assign to Agent *"})}),e.jsxs(Le,{children:[e.jsxs(ls,{value:E,onValueChange:P,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select an agent..."})}),e.jsx(as,{children:C.map(Ae=>e.jsx(He,{value:Ae.id,children:Ae.name||Ae.email},Ae.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),K&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Primary Listing Agent"})}),e.jsxs(Le,{children:[e.jsxs(ls,{value:H,onValueChange:V,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select the listing agent..."})}),e.jsx(as,{children:q.map(Ae=>e.jsx(He,{value:Ae.id,children:(Ae.name||Ae.email)+(Ae.id===(a==null?void 0:a.id)?" (you)":"")},Ae.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"As a team leader you can credit this listing to any agent on your team. It will appear on their Listing Exchange and website."})]})]}),!l&&i&&!o&&e.jsx(XWn,{onImport:Ee}),c.length>0&&e.jsxs(be,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ga,{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(Le,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((Ae,Se)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:Ae,alt:"",className:"w-full h-full object-cover"})},Se)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(er,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Property Details"})}),e.jsx(Le,{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(ee,{children:"Property Address"}),e.jsx(pe,{value:he.property_address,onChange:Ae=>ge({...he,property_address:Ae.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City *"}),e.jsx(pe,{value:he.city,onChange:Ae=>ge({...he,city:Ae.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State *"}),e.jsx(pe,{value:he.state,onChange:Ae=>ge({...he,state:Ae.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Neighborhood"}),e.jsx(pe,{value:he.neighborhood,onChange:Ae=>ge({...he,neighborhood:Ae.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Price *"}),e.jsx(pe,{type:"number",value:he.price,onChange:Ae=>ge({...he,price:Ae.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property Type"}),e.jsxs(ls,{value:he.property_type,onValueChange:Ae=>ge({...he,property_type:Ae}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:sKn.map(Ae=>e.jsx(He,{value:Ae.value,children:Ae.label},Ae.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ls,{value:he.status,onValueChange:Ae=>ge({...he,status:Ae}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:tKn.map(Ae=>e.jsx(He,{value:Ae.value,children:Ae.label},Ae.value))})]})]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Property Specs (Optional)"})}),e.jsx(Le,{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(ee,{children:"Bedrooms"}),e.jsx(pe,{type:"number",value:he.bedrooms,onChange:Ae=>ge({...he,bedrooms:Ae.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Bathrooms"}),e.jsx(pe,{type:"number",step:"0.5",value:he.bathrooms,onChange:Ae=>ge({...he,bathrooms:Ae.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Sq Ft"}),e.jsx(pe,{type:"number",value:he.square_footage,onChange:Ae=>ge({...he,square_footage:Ae.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lot Size"}),e.jsx(pe,{value:he.lot_size,onChange:Ae=>ge({...he,lot_size:Ae.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Year Built"}),e.jsx(pe,{type:"number",value:he.year_built,onChange:Ae=>ge({...he,year_built:Ae.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(mn,{checked:he.has_hoa,onCheckedChange:Ae=>ge({...he,has_hoa:Ae})}),e.jsx(ee,{children:"Has HOA"})]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Description & Links"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:he.description,onChange:Ae=>ge({...he,description:Ae.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Agent Notes"}),e.jsx(Ps,{value:he.agent_notes,onChange:Ae=>ge({...he,agent_notes:Ae.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{checked:he.agent_notes_public,onCheckedChange:Ae=>ge({...he,agent_notes_public:Ae})}),e.jsx(ee,{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(ee,{children:"MLS Link"}),e.jsx(pe,{value:he.mls_link,onChange:Ae=>ge({...he,mls_link:Ae.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video Link"}),e.jsx(pe,{value:he.video_link,onChange:Ae=>ge({...he,video_link:Ae.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Credit a second agent on this listing. Their info appears on the listing page alongside yours."}),q.length>1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Choose a team member"}),e.jsxs(ls,{value:"",onValueChange:Ae=>{const Se=q.find(We=>We.id===Ae);Se&&(ge(We=>({...We,co_agent_name:Se.name||We.co_agent_name,co_agent_email:Se.email||"",co_agent_phone:Se.phone||"",co_agent_brokerage:Se.brokerage_name||We.co_agent_brokerage,co_agent_photo_url:Se.avatar_url||""})),ne.success("Co-listing agent details filled in"))},children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Auto-fill from your team..."})}),e.jsx(as,{children:q.filter(Ae=>Ae.id!==H).map(Ae=>e.jsx(He,{value:Ae.id,children:Ae.name||Ae.email},Ae.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Details fill in automatically and stay editable. For agents outside your team, just type below."})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:he.co_agent_name,onChange:Ae=>ge({...he,co_agent_name:Ae.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:he.co_agent_brokerage,onChange:Ae=>ge({...he,co_agent_brokerage:Ae.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:he.co_agent_email,onChange:Ae=>ge({...he,co_agent_email:Ae.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:he.co_agent_phone,onChange:Ae=>ge({...he,co_agent_phone:Ae.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[he.co_agent_photo_url?e.jsx("img",{src:he.co_agent_photo_url,alt:"Co-listing agent headshot",className:"h-20 w-20 rounded-full object-cover border"}):e.jsx("div",{className:"h-20 w-20 rounded-full border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(Ra,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"co-agent-headshot",type:"file",accept:"image/*",className:"hidden",onChange:Ae=>{var We;const Se=(We=Ae.target.files)==null?void 0:We[0];Ae.target.value="",Se&&me(Se)}}),e.jsx(z,{type:"button",variant:"outline",disabled:ce,onClick:()=>{var Ae;return(Ae=document.getElementById("co-agent-headshot"))==null?void 0:Ae.click()},children:ce?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," ",he.co_agent_photo_url?"Replace photo":"Upload photo"]})}),he.co_agent_photo_url&&e.jsxs(z,{type:"button",variant:"ghost",onClick:()=>ge(Ae=>({...Ae,co_agent_photo_url:""})),children:[e.jsx(er,{className:"h-4 w-4 mr-1"})," Remove"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"JPG or PNG, up to 5MB."})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Le,{children:e.jsx(QWn,{selectedVideoId:he.video_id,onVideoSelect:Ae=>ge({...he,video_id:Ae}),listingId:l?s:void 0})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Photos"})}),e.jsx(Le,{children:l&&(m!=null&&m.photos)?e.jsx(Bzt,{photos:m.photos,uploading:Z,onUpload:Ae=>Oe(Ae),onRemove:Ae=>Ve(Ae),onReorder:Ae=>{w.mutate({photos:Ae.map(Se=>({id:Se.id,sort_order:Se.sort_order,is_primary:Se.is_primary}))})},onSetPrimary:Ae=>{m&&S.mutate({photoId:Ae,listingId:m.id})}}):e.jsx(rKn,{photoUrls:J,onRemove:Pe,onReorder:(Ae,Se)=>{te(Ae),ae(Se)},pendingPhotos:re,uploading:Z,onUpload:Ne})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Le,{children:l&&s?e.jsx(eKn,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Sharing & Collaboration"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(mn,{checked:he.allow_sharing,onCheckedChange:Ae=>ge({...he,allow_sharing:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(mn,{checked:he.open_to_referrals,onCheckedChange:Ae=>ge({...he,open_to_referrals:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(mn,{checked:he.open_to_social_promotion,onCheckedChange:Ae=>ge({...he,open_to_social_promotion:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(mn,{checked:he.share_with_brokerage,onCheckedChange:Ae=>ge({...he,share_with_brokerage:Ae})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"My Website Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange and other agents — only show it on your own website"})]}),e.jsx(mn,{checked:he.site_only,onCheckedChange:Ae=>ge({...he,site_only:Ae,is_public:Ae?!1:he.is_public,show_on_lead_site:Ae?!0:he.show_on_lead_site,share_with_brokerage:Ae?!1:he.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(mn,{checked:he.is_public,disabled:he.site_only,onCheckedChange:Ae=>ge({...he,is_public:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:he.status==="sold"?"Sold listings are hidden from the Listing Exchange and public marketplace — they only build your track record on your website's Sold page.":"Feature this listing on your lead site homepage and listings page"})]}),e.jsx(mn,{checked:he.show_on_lead_site,onCheckedChange:Ae=>ge({...he,show_on_lead_site:Ae})})]})]})]}),e.jsx(z,{type:"submit",className:"w-full",size:"lg",disabled:f.isPending||v.isPending,children:f.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx($et,{listingId:u.listingId,open:u.open,initialStatus:u.socialStatus,onOpenChange:Ae=>{if(!Ae){const{nextPath:Se}=u;h({open:!1,listingId:null,nextPath:Se}),r(Se)}}})]})}const YYe=[{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"}],Oss=[{type:"extra_video",label:"Extra Video / Reel",icon:Xr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:TQ,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:nc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:wj,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:Zr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Kc,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],aKn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],gBe={sections:Object.fromEntries(YYe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},iKn=()=>Math.random().toString(36).slice(2,10);function oKn(){const{listingId:s}=Mi(),t=zn(),{user:n}=hs(),r=$t(),[a,i]=_.useState("desktop"),[l,o]=_.useState(gBe),[c,d]=_.useState(!1),[u,h]=_.useState(0),{data:m,isLoading:p}=rt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:D,error:F}=await U.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(F)throw F;return D},enabled:!!s});_.useEffect(()=>{var D,F;m!=null&&m.page_config&&o({...gBe,...m.page_config||{},sections:{...gBe.sections,...((D=m.page_config)==null?void 0:D.sections)||{}},addons:((F=m.page_config)==null?void 0:F.addons)||[]})},[m==null?void 0:m.id]);const f=!!n&&!!m&&n.id===m.agent_id,g=_.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),v=_.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),y=mt({mutationFn:async()=>{const{error:D}=await U.from("listings").update({page_config:l}).eq("id",s);if(D)throw D},onSuccess:()=>{ne.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(D=>D+1)},onError:D=>ne.error(`Save failed: ${D.message||"Try again"}`)}),b=D=>{o(F=>({...F,...D})),d(!0)},w=(D,F)=>b({sections:{...l.sections||{},[D]:F}}),S=D=>b({addons:[...l.addons||[],{id:iKn(),type:D,data:{}}]}),C=(D,F)=>b({addons:(l.addons||[]).map(q=>q.id===D?{...q,data:{...q.data,...F}}:q)}),E=D=>b({addons:(l.addons||[]).filter(F=>F.id!==D)}),P=(D,F)=>{const q=[...l.addons||[]],G=q.findIndex(H=>H.id===D);if(G<0)return;const V=G+F;V<0||V>=q.length||([q[G],q[V]]=[q[V],q[G]],b({addons:q}))};if(p)return e.jsx($s,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx($s,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!f)return e.jsx($s,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(z,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const M=(l.addons||[]).length,I=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs($s,{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(z,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${m.id}`),children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"hidden md:flex flex-col leading-tight",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"Customize Public Page"}),e.jsx("p",{className:"text-sm font-medium truncate max-w-[420px]",children:m.property_address||`${m.city}, ${m.state}`})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[c&&e.jsx("span",{className:"text-xs text-amber-600 hidden sm:inline",children:"Unsaved changes"}),e.jsxs("div",{className:"hidden md:inline-flex rounded-lg border bg-muted p-0.5",children:[e.jsxs("button",{onClick:()=>i("desktop"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="desktop"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(yN,{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(p1,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>h(D=>D+1),children:[e.jsx(Gi,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(z,{size:"sm",onClick:()=>y.mutate(),disabled:!c||y.isPending,children:y.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Bo,{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(Ki,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(LZ,{icon:e.jsx(un,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(D=>e.jsx("button",{onClick:()=>b({hero_style:D}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===D?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:D},D))})]})}),e.jsx(LZ,{icon:e.jsx(yc,{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:()=>b({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"}),aKn.map(D=>e.jsx("button",{onClick:()=>b({accent_color:D}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===D?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:D},"aria-label":D},D))]})}),e.jsx(LZ,{icon:e.jsx(rg,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ps,{value:l.custom_note||"",onChange:D=>b({custom_note:D.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(LZ,{icon:e.jsx(tA,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${I} of ${YYe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:YYe.map(D=>{var q;const F=((q=l.sections)==null?void 0:q[D.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:D.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:D.hint})]}),e.jsx(mn,{checked:F,onCheckedChange:G=>w(D.key,G)})]},D.key)})})}),e.jsxs(LZ,{icon:e.jsx(sn,{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:Oss.map(D=>e.jsxs("button",{onClick:()=>S(D.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${D.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(D.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:D.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:D.desc})]},D.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((D,F)=>e.jsx(lKn,{addon:D,onChange:q=>C(D.id,q),onRemove:()=>E(D.id),onMoveUp:F>0?()=>P(D.id,-1):void 0,onMoveDown:FP(D.id,1):void 0},D.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(z,{className:"w-full",onClick:()=>y.mutate(),disabled:!c||y.isPending,children:y.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Bo,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(be,{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(xa,{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(Wr,{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(yN,{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(p1,{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:g,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function LZ({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 lKn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Oss.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(Zf,{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(z,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Zf,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Video URL"}),e.jsx(pe,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Title (optional)"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ps,{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(ee,{className:"text-xs",children:"Quote"}),e.jsx(Ps,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Attribution"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Headline"}),e.jsx(pe,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Button label"}),e.jsx(pe,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Link URL"}),e.jsx(pe,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const zss="teleprompter_settings",yBe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function cKn(){try{const s=localStorage.getItem(zss);return s?{...yBe,...JSON.parse(s)}:yBe}catch{return yBe}}function dKn(s){try{localStorage.setItem(zss,JSON.stringify(s))}catch{}}function Iat({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=_.useRef(null),c=_.useRef(null),d=_.useRef(0),u=_.useRef(0),[h,m]=_.useState(cKn),{scrollSpeed:p,fontSize:f,lineHeight:g,opacity:v,position:y,isMirrored:b}=h,w=_.useCallback((q,G)=>{m(V=>{const H={...V,[q]:G};return dKn(H),H})},[]),[S,C]=_.useState(!1),[E,P]=_.useState(null),M=_.useCallback(q=>{if(!o.current)return;d.current===0&&(d.current=q);const G=q-d.current;d.current=q,u.current+=p*G/1e3;const V=Math.floor(u.current);V>0&&(o.current.scrollTop+=V,u.current-=V);const{scrollTop:H,scrollHeight:K,clientHeight:Z}=o.current;if(H+Z>=K){C(!1);return}c.current=requestAnimationFrame(M)},[p]);_.useEffect(()=>(S?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[S,M]),_.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){P(3);let q=3;const G=setInterval(()=>{q-=1,q<=0?(clearInterval(G),P(null),i==null||i(),C(!0)):P(q)},1e3);return()=>clearInterval(G)}else setTimeout(()=>C(!0),100);else r||(C(!1),P(null))},[r,t,a,i]);const I=_.useCallback(()=>{o.current&&(o.current.scrollTop=0),C(!1)},[]),D=_.useCallback(()=>{C(q=>!q)},[]);if(!t)return e.jsx("div",{className:Ct("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(z,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const F={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Ct("absolute inset-0 pointer-events-none",l),children:[E!==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:E},E),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Ct("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",F[y],E!==null&&"opacity-30"),style:{opacity:E!==null?.3:v},children:e.jsxs("div",{ref:o,className:Ct("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",b&&"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:`${f}px`,lineHeight:g,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(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsx(z,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Gc,{className:"h-4 w-4"})})}),e.jsx(nd,{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(ee,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p})]}),e.jsx(Mx,{value:[p],onValueChange:([q])=>w("scrollSpeed",q),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(ee,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[f,"px"]})]}),e.jsx(Mx,{value:[f],onValueChange:([q])=>w("fontSize",q),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(ee,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.toFixed(1)})]}),e.jsx(Mx,{value:[g*10],onValueChange:([q])=>w("lineHeight",q/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(ee,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(v*100),"%"]})]}),e.jsx(Mx,{value:[v*100],onValueChange:([q])=>w("opacity",q/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:y==="top"?"default":"outline",size:"sm",onClick:()=>w("position","top"),children:e.jsx(h1,{className:"h-4 w-4"})}),e.jsx(z,{variant:y==="center"?"default":"outline",size:"sm",onClick:()=>w("position","center"),children:e.jsx(gN,{className:"h-4 w-4"})}),e.jsx(z,{variant:y==="bottom"?"default":"outline",size:"sm",onClick:()=>w("position","bottom"),children:e.jsx(cl,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Mirror Mode"}),e.jsx(mn,{checked:b,onCheckedChange:q=>w("isMirrored",q)})]})]})})]}),e.jsx(z,{variant:"secondary",size:"icon",onClick:D,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:S?e.jsx(S0,{className:"h-4 w-4"}):e.jsx(su,{className:"h-4 w-4"})}),e.jsx(z,{variant:"secondary",size:"icon",onClick:I,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Dx,{className:"h-4 w-4"})}),e.jsxs(z,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Yf,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function uKn({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=_i(),[i,l]=_.useState(""),[o,c]=_.useState(null),[d,u]=_.useState("levelup"),{data:h,isLoading:m}=cFn(),{data:p,isLoading:f}=dFn(),{data:g,isLoading:v}=uFn(),y=hFn(),b=_.useMemo(()=>p?p.filter(P=>{const M=!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())||P.tags.some(D=>D.toLowerCase().includes(i.toLowerCase())),I=!o||P.category_id===o;return M&&I}):[],[p,i,o]),w=_.useMemo(()=>g?g.filter(P=>!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())):[],[g,i]),S=P=>{s({title:P.title,text:P.script_text})},C=async P=>{try{await y.mutateAsync(P),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},E=m||f||v;return e.jsxs("div",{className:Ct("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search scripts...",value:i,onChange:P=>l(P.target.value),className:"pl-9"})]})}),e.jsxs(Qr,{value:d,onValueChange:P=>u(P),className:"flex-1 flex flex-col",children:[e.jsxs(Jr,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Wt,{value:"levelup",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Wt,{value:"my-scripts",children:[e.jsx(Ty,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Kt,{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(P=>e.jsx(ze,{variant:o===P.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(P.id),children:P.name},P.id))]}),e.jsx(Ki,{className:"flex-1 max-h-[50vh]",children:E?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx($r,{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:b.map(P=>e.jsxs(be,{className:Ct("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>S(P),children:[e.jsx(_t,{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(Nt,{className:"text-sm font-medium truncate",children:P.title}),P.category&&e.jsx(ze,{variant:"secondary",className:"mt-1 text-xs",children:P.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),C(P)},children:e.jsx(Ty,{className:"h-4 w-4"})}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Le,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:P.script_text})})]},P.id))})})]}),e.jsxs(Kt,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(z,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Ki,{className:"flex-1 max-h-[50vh]",children:v?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ty,{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:w.map(P=>e.jsxs(be,{className:Ct("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>S(P),children:[e.jsx(_t,{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(Nt,{className:"text-sm font-medium truncate",children:P.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:P.is_custom?e.jsx(ze,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Le,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:P.script_text})})]},P.id))})})]})]})]})}function hKn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=_.useState(()=>{const o=Lq(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(ee,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(bt,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:N9s.map(o=>{const c=k9s(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(f1,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(x1,{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(cl,{className:Ct("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(g1,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(h=>{const m=s===h.id;return e.jsxs("button",{type:"button",onClick:()=>t(h.id),disabled:r,className:Ct("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",m?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[m&&e.jsx("div",{className:"absolute top-1 right-1 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:e.jsx(Wr,{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: "',Lq(s).headerText(n),'"']})]})}function Bss({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=_.useState(n.page_template||"default"),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(n.page_template||"default"),[p,f]=_.useState([]),[g,v]=_.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[y,b]=_.useState(!1),[w,S]=_.useState(!1),C=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";_.useEffect(()=>{s&&p.length===0&&E()},[s]);const E=async()=>{S(!0);try{const{data:H,error:K}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(K)throw K;const Z=(H||[]).map(oe=>({id:oe.id,name:[oe.first_name,oe.last_name].filter(Boolean).join(" ")||"Unnamed",email:oe.email||null}));f(Z)}catch(H){console.error("Failed to fetch contacts:",H)}finally{S(!1)}},P=async H=>{v(H),b(!1),c(!0);try{const{error:K}=await U.from("agent_videos").update({contact_id:(H==null?void 0:H.id)||null,recipient_name:(H==null?void 0:H.name)||null}).eq("id",n.id);if(K)throw K;ne.success(H?`Assigned to ${H.name}`:"Contact removed"),a==null||a()}catch(K){console.error("Failed to update contact:",K),ne.error("Failed to update contact")}finally{c(!1)}},M=async H=>{l(H),c(!0);try{const{error:K}=await U.from("agent_videos").update({page_template:H}).eq("id",n.id);if(K)throw K;m(H),ne.success("Template saved!"),a==null||a()}catch(K){console.error("Failed to save template:",K),ne.error("Failed to save template"),l(h)}finally{c(!1)}},I=(g==null?void 0:g.name)||null,D=()=>{const H=n.title||"Video Message",K=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},F=async()=>{if(!n.thumbnail_url){ne.error("Video thumbnail not available yet");return}const H=D(),K=`Watch: ${n.title||"Video Message"} ${C}`;try{const Z=new Blob([H],{type:"text/html"}),oe=new Blob([K],{type:"text/plain"}),re=new ClipboardItem({"text/html":Z,"text/plain":oe});await navigator.clipboard.write([re]),ne.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(K+` `+H),ne.success("Copied! Paste into your email.")}},q=async()=>{await navigator.clipboard.writeText(C),u(!0),ne.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},G=()=>{const K=Lq(i).headerText(I),Z=i==="default"?`Check out this video: ${C}`:`${K} Check out this special video: ${C}`;window.open(`sms:?body=${encodeURIComponent(Z)}`,"_self")},V=()=>{const H=Lq(i),K=H.headerText(I),Z=i==="default"?n.title||"Video Message":K,oe=`${H.subText} Watch the video: ${C}`,re=g!=null&&g.email?encodeURIComponent(g.email):"";window.open(`mailto:${re}?subject=${encodeURIComponent(Z)}&body=${encodeURIComponent(oe)}`,"_self")};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Kc,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(_r,{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(ee,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(hd,{open:y,onOpenChange:b,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox","aria-expanded":y,className:"flex-1 justify-between",disabled:o,children:[g?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Oo,{className:"h-4 w-4 text-muted-foreground"}),g.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(R_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search contacts..."}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:w?"Loading...":"No contacts found."}),e.jsx(G_,{children:p.map(H=>e.jsxs(c1,{value:H.name,onSelect:()=>P(H),children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",(g==null?void 0:g.id)===H.id?"opacity-100":"opacity-0")}),H.name]},H.id))})]})]})})]}),g&&e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>P(null),disabled:o,className:"shrink-0",children:e.jsx(er,{className:"h-4 w-4"})})]}),g&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',Lq(i).headerText(g.name),'"']})]}),e.jsx(hKn,{selectedTemplate:i,onSelect:M,contactName:I,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:C,readOnly:!0,className:"font-mono text-sm"}),e.jsx(z,{onClick:q,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sa,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share for Email"}),e.jsxs(z,{variant:"outline",className:"w-full gap-2",onClick:F,children:[e.jsx(nc,{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(ee,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",className:"flex-1 gap-2",onClick:G,children:[e.jsx(qi,{className:"h-4 w-4"}),"Text"]}),e.jsxs(z,{variant:"outline",className:"flex-1 gap-2",onClick:V,children:[e.jsx(on,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(hr,{children:e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function mKn(){var qe;const s=zn(),[t]=Gl(),{toast:n}=_i(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=fZt(),{data:u}=Rb(),h=RC(),m=gFn(),[p,f]=_.useState("record"),[g,v]=_.useState(""),[y,b]=_.useState(!1),[w,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(null),[I,D]=_.useState(0),[F,q]=_.useState(0),[G,V]=_.useState(null),[H,K]=_.useState(null),[Z,oe]=_.useState(r||""),[re,ae]=_.useState(""),[J,te]=_.useState(""),[ce,ve]=_.useState(null),[me,he]=_.useState(null),[ge,Ee]=_.useState(null),[Ne,Pe]=_.useState(!1),Oe=_.useCallback(async(Be,Ze)=>{M(Be),f("uploading");try{const{videoId:$e,uploadUrl:Xe}=await qL(re||"Quick Video Touch");V($e);const{apiKey:nt}=await VL($e),Ge=new XMLHttpRequest;Ge.upload.onprogress=qt=>{qt.lengthComputable&&D(qt.loaded/qt.total*100)},await new Promise((qt,zt)=>{Ge.onload=()=>{Ge.status>=200&&Ge.status<300?qt():zt(new Error(`Upload failed: ${Ge.status}`))},Ge.onerror=()=>zt(new Error("Upload failed")),Ge.open("PUT",Xe),Ge.setRequestHeader("AccessKey",nt),Ge.send(Be)}),f("processing");let Je=0;const ut=Date.now(),lt=90*1e3;for(;Je<4;){if(await new Promise(zt=>setTimeout(zt,3e3)),Date.now()-ut>lt){const zt=Be.size/1048576,Zt=`https://iframe.mediadelivery.net/play/${$e}/${$e}`;await h.mutateAsync({bunny_video_id:$e,playback_url:Zt,file_size_mb:zt,title:re||"Quick Video Touch",notes:J||void 0,contact_id:Z&&Z!=="none"?Z: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 DN($e);if(Je=qt.status,q(qt.encodeProgress||0),Je===4)K({playbackUrl:qt.directPlayUrl,thumbnailUrl:qt.thumbnailUrl,previewUrl:qt.previewUrl||null,duration:qt.length||Ze,fileSizeMb:(qt.storageSize||Be.size)/(1024*1024)});else if(Je===5||Je===6)throw new Error("Video processing failed")}f("details")}catch($e){console.error("Upload error:",$e),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),f("record")}},[re,n]),ke=async()=>{if(!(!G||!H))try{const Be=Z&&Z!=="none"?Z:null,Ze=await h.mutateAsync({bunny_video_id:G,contact_id:Be,playback_url:H.playbackUrl,thumbnail_url:H.thumbnailUrl,preview_url:H.previewUrl,duration_seconds:H.duration,file_size_mb:H.fileSizeMb,title:re||"Quick Video Touch",notes:J,task_id:a||null,status:"ready"});ve(Ze.id),he(Ze.share_token||null),Be&&await m.mutateAsync({contactId:Be,videoId:Ze.id,notes:J}),n({title:"Video saved successfully!"}),f("share")}catch(Be){console.error("Save video error:",Be),n({title:"Failed to save video",description:(Be==null?void 0:Be.message)||"Please try again.",variant:"destructive"})}},Ve=(Be,Ze)=>{navigator.clipboard.writeText(Ze),Ee(Be),setTimeout(()=>Ee(null),2e3),n({title:"Copied to clipboard!"})},_e=()=>me?`https://video.relevelup.com/${me}`:(H==null?void 0:H.playbackUrl)||"",Ae=()=>{const Be=u==null?void 0:u.find(Ge=>Ge.id===Z),Ze=Be?`${Be.first_name}`:"",$e=(Be==null?void 0:Be.phone)||"",Xe=(Be==null?void 0:Be.email)||"",nt=_e();return{text:`Hey${Ze?` ${Ze}`:""}! I recorded a quick video for you: ${nt}`,link:nt,contactPhone:$e,contactEmail:Xe}},Se=()=>{const{text:Be,contactPhone:Ze}=Ae(),$e=Ze?`sms:${Ze}?body=${encodeURIComponent(Be)}`:`sms:?body=${encodeURIComponent(Be)}`;window.open($e,"_self")},We=()=>{const{link:Be,contactEmail:Ze}=Ae(),$e="Check out this video",Xe=`I recorded a quick video for you: ${Be}`,nt=Ze?`mailto:${Ze}?subject=${encodeURIComponent($e)}&body=${encodeURIComponent(Xe)}`:`mailto:?subject=${encodeURIComponent($e)}&body=${encodeURIComponent(Xe)}`;window.open(nt,"_self")};return i?e.jsx($s,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(ka,{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(z,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx($r,{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"]})]})]})]}),p==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(YE,{maxDurationSeconds:600,onRecordingComplete:Oe,onRecordingStateChange:E,className:"w-full",teleprompterContent:y&&g&&e.jsx(Iat,{text:g,isVisible:y,onToggleVisibility:()=>b(!1),isRecording:C,startCountdown:!1})}),!y&&g&&e.jsxs(z,{variant:"outline",className:"mt-4",onClick:()=>b(!0),children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(be,{className:"lg:col-span-1",children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(Ps,{placeholder:"Type or paste your script here...",value:g,onChange:Be=>v(Be.target.value),rows:6}),e.jsxs(Wg,{open:w,onOpenChange:S,children:[e.jsx(Yre,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"w-full",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(gg,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(Dy,{className:"p-4 border-b",children:e.jsx(Ry,{children:"Select a Script"})}),e.jsx(uKn,{onSelectScript:Be=>{v(Be.text),S(!1),b(!0)},className:"h-[calc(100vh-80px)]"})]})]}),g&&e.jsx(z,{className:"w-full",onClick:()=>b(!0),children:"Use Script"})]})]})]}),p==="uploading"&&e.jsx(be,{className:"max-w-md mx-auto",children:e.jsxs(Le,{className:"pt-6 text-center",children:[e.jsx(Ra,{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(Di,{value:I,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.toFixed(0),"%"]})]})}),p==="processing"&&e.jsx(be,{className:"max-w-md mx-auto",children:e.jsxs(Le,{className:"pt-6 text-center space-y-4",children:[e.jsx(bt,{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(Di,{value:F,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[F.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.`})]})}),p==="details"&&e.jsxs(be,{className:"max-w-lg mx-auto",children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Video Details"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:re,onChange:Be=>ae(Be.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Attach to Contact (Optional)"}),e.jsxs(ls,{value:Z,onValueChange:oe,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"No contact - use anywhere"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Kc,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Be=>e.jsx(He,{value:Be.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oo,{className:"h-4 w-4"}),Be.first_name," ",Be.last_name]})},Be.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ps,{value:J,onChange:Be=>te(Be.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(z,{className:"w-full",onClick:ke,disabled:h.isPending,children:[h.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),p==="share"&&e.jsxs(be,{className:"max-w-lg mx-auto",children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Le,{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(z,{variant:"outline",className:"justify-start",onClick:Se,children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(z,{variant:"outline",className:"justify-start",onClick:We,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>Ve("link",Ae().link),children:[e.jsx(Kc,{className:"h-4 w-4 mr-2"}),"Copy Video Link",ge==="link"&&e.jsx(Wr,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(z,{variant:"outline",className:"justify-start",onClick:()=>Pe(!0),children:[e.jsx(yc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(z,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(z,{onClick:()=>{f("record"),M(null),V(null),K(null)},children:"Record Another"})]})]})]}),ce&&me&&e.jsx(Bss,{open:Ne,onOpenChange:Pe,video:{id:ce,share_token:me,title:re||null,contact_id:Z||null,thumbnail_url:(H==null?void 0:H.thumbnailUrl)||null},contactName:((qe=u==null?void 0:u.find(Be=>Be.id===Z))==null?void 0:qe.first_name)||null})]})}):e.jsx($s,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(nl,{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(z,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function pKn({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=_.useState([]),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState(""),[v,y]=_.useState(""),[b,w]=_.useState(""),[S,C]=_.useState(!1),E=dZt(),P=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||"",I=n.title||"Video Message";_.useEffect(()=>{s&&l.length===0&&D()},[s]),_.useEffect(()=>{if(s&&(y(`I recorded a video for you — ${I}`),w("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),g(""),n.contact_id)){const K=l.find(Z=>Z.id===n.contact_id);K&&(d(K),g(K.email||""))}},[s,n.contact_id,l]);const D=async()=>{p(!0);try{const{data:K,error:Z}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Z)throw Z;o(K||[])}catch{console.error("Failed to fetch contacts")}finally{p(!1)}},F=K=>{d(K),h(!1),g(K.email||""),w(`Hey ${K.first_name}! I recorded a quick video just for you. Click below to watch it:`),y(`I recorded a video for you — ${I}`)},q=()=>{d(null),g(""),w("Hey! I recorded a quick video just for you. Click below to watch it:")},G=K=>{const Z=`${K.first_name||""} ${K.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return Z?Z.length>60?`${Z.slice(0,60)}…`:Z:K.email||"Unnamed contact"},V=K=>{const Z=b.split(/\n\n+/).map(ae=>`

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

`).join(""),oe=K?hZt(K):P,re=K?``:"";return`
${Z}

▶ Watch Video

${re}
`},H=async()=>{var K;if(!f){ne.error("Please enter a recipient email");return}if(!P){ne.error("Video does not have a share link");return}C(!0);try{let Z;try{const te=c?G(c):f.split("@")[0];Z=(await E.mutateAsync({video_id:n.id,recipient_email:f,recipient_name:te,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(te){console.warn("Failed to create tracking record, sending without tracking:",te)}const oe=V(Z),{data:re,error:ae}=await U.functions.invoke("gmail-send",{body:{to:f,subject:v,body:oe,contactId:(c==null?void 0:c.id)||null}});let J=null;if(ae&&((K=ae.context)!=null&&K.json))try{J=await ae.context.json()}catch{}if((J==null?void 0:J.error)==="insufficient_scope"||(re==null?void 0:re.error)==="insufficient_scope"){ne.error((J==null?void 0:J.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ae)throw new Error((J==null?void 0:J.message)||ae.message);if(!(re!=null&&re.success))throw new Error((re==null?void 0:re.error)||"Failed to send");ne.success("Video email sent!"),t(!1),i==null||i()}catch(Z){console.error("Gmail send error:",Z),ne.error("Failed to send: "+(Z instanceof Error?Z.message:"Unknown error"))}finally{C(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{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(ee,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(hd,{open:u,onOpenChange:h,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Oo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:G(c)}),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs truncate",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(R_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search contacts..."}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:m?"Loading...":"No contacts found."}),e.jsx(G_,{children:l.filter(K=>K.email).map(K=>e.jsxs(c1,{value:`${G(K)} ${K.email||""}`,onSelect:()=>F(K),children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",(c==null?void 0:c.id)===K.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:G(K)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:K.email})]})]},K.id))})]})]})})]}),c&&e.jsx(z,{variant:"ghost",size:"icon",onClick:q,className:"shrink-0",children:e.jsx(er,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(pe,{id:"video-to",value:f,onChange:K=>g(K.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-subject",children:"Subject"}),e.jsx(pe,{id:"video-subject",value:v,onChange:K=>y(K.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ps,{id:"video-message",value:b,onChange:K=>w(K.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(ee,{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:I,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(su,{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(su,{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(z,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs(z,{onClick:H,disabled:S||!f||!v,className:"gap-2",children:[S?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),S?"Sending...":"Send Video Email"]})]})]})]})})}const fKn=()=>{const{user:s}=hs();return rt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function xKn({recipient:s}){return s.watched_at?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(su,{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(wy,{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(xa,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[e.jsx(Fr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function gKn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=GRn(n);return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(ln,{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(Ki,{className:"h-[400px]",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Recipient"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Sent"}),e.jsx(Tt,{children:"Last Activity"})]})}),e.jsx(Qa,{children:a.map(l=>e.jsxs(fn,{children:[e.jsx(yt,{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(yt,{children:e.jsx(xKn,{recipient:l})}),e.jsx(yt,{className:"text-xs text-muted-foreground",children:Ys(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(yt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Md(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function yKn(){const{data:s,isLoading:t}=WRn(),{data:n=[],isLoading:r}=KRn(),[a,i]=_.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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(ln,{className:"h-4 w-20"})}),e.jsx(Le,{children:e.jsx(ln,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(xa,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(wy,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Le,{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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(En,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Le,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(h=>h.opened_at).length,u=c.recipients.filter(h=>h.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:h=>{const m=h.currentTarget;m.style.display="none",m.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Xr,{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(Fr,{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(xa,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(wy,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(gKn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function vKn({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=_.useState(!1),[l,o]=_.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(Xr,{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 bKn({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:p,getShareUrl:f,copyToClipboard:g,formatDuration:v}){const[y,b]=_.useState(!1);return e.jsxs(be,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(vKn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:y}),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(su,{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(Le,{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(Oo,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),e.jsx("span",{children:Ys(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(xa,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs(z,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:w=>{w.stopPropagation(),h==null||h()},children:[e.jsx(on,{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(Oo,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),e.jsx("span",{children:Ys(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(xa,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:w=>w.stopPropagation(),children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",className:"bg-popover",children:[e.jsxs(ua,{onClick:w=>{w.stopPropagation(),r()},children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(Iy,{}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),u()},children:[e.jsx(yc,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),g(f(s),"Share link")},children:[e.jsx(Kc,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),o()},children:[e.jsx(GA,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),c()},children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),d()},children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(ua,{onClick:w=>{w.stopPropagation(),h==null||h()},children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),i()},children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(Iy,{}),s.contact_id&&e.jsxs(ua,{onClick:w=>{w.stopPropagation(),l()},children:[e.jsx(Oo,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(ua,{onClick:w=>{w.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function _Kn(){var Zt,ms;const s=zn(),{data:t,isLoading:n,refetch:r}=mFn(),{data:a}=h8e(),{data:i}=Rb(),l=xFn(),o=fFn(),{isGmailConnected:c,gmailEmail:d}=bg(),{data:u}=K_(),{data:h=[],isLoading:m}=fKn(),[p,f]=_.useState("my"),[g,v]=_.useState(""),[y,b]=_.useState(null),[w,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[F,q]=_.useState(!1),[G,V]=_.useState(""),[H,K]=_.useState(!1),[Z,oe]=_.useState(!1),[re,ae]=_.useState(!1),[J,te]=_.useState(!1),[ce,ve]=_.useState(""),[me,he]=_.useState({}),ge=Dt=>{if(!Dt)return"Unassigned";const It=i==null?void 0:i.find(qs=>qs.id===Dt);return It?`${It.first_name} ${It.last_name||""}`.trim():"Unknown"},Ee=Dt=>{if(!Dt)return"0:00";const It=Math.floor(Dt/60),qs=Dt%60;return`${It}:${qs.toString().padStart(2,"0")}`},[Ne,Pe]=_.useState("all"),Oe=t==null?void 0:t.filter(Dt=>{const It=Dt.category||"general";if(Ne==="general"&&It!=="general"||Ne==="open_house"&&It!=="open_house")return!1;if(!g)return!0;const qs=ge(Dt.contact_id).toLowerCase(),wt=(Dt.title||"").toLowerCase(),Us=(Dt.notes||"").toLowerCase();return qs.includes(g.toLowerCase())||wt.includes(g.toLowerCase())||Us.includes(g.toLowerCase())}),ke=(t==null?void 0:t.filter(Dt=>(Dt.category||"general")==="open_house").length)||0,Ve=(t==null?void 0:t.filter(Dt=>(Dt.category||"general")==="general").length)||0,_e=(t||[]).filter(Dt=>Dt.status==="processing"&&Dt.bunny_video_id).map(Dt=>Dt.id).join(",");_.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const It=t.filter(wt=>wt.status==="processing"&&wt.bunny_video_id);if(!It.length)return;let qs=!1;for(const wt of It)try{const{data:Us,error:Es}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:wt.bunny_video_id,isAgentVideo:!0}});if(Es||!Us)continue;Us.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:Us.directPlayUrl,thumbnail_url:Us.thumbnailUrl,preview_url:Us.previewUrl,duration_seconds:Us.length||wt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",wt.id),qs=!0)}catch(Us){console.warn("Reconcile check failed for video",wt.id,Us)}qs&&r()})()},[_e,r]),_.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const It=t.filter(kn=>(kn==null?void 0:kn.bunny_video_id)&&!me[kn.id]);if(!It.length)return;const qs=It.map(kn=>kn.bunny_video_id),{data:wt,error:Us}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:qs,isAgentVideo:!0}});if(Us)throw Us;const Es=(wt==null?void 0:wt.assets)||{};he(kn=>{const Sn={...kn};for(const bn of It)Es[bn.bunny_video_id]&&(Sn[bn.id]={previewUrl:Es[bn.bunny_video_id].previewUrl,thumbnailUrl:Es[bn.bunny_video_id].thumbnailUrl});return Sn})})().catch(It=>console.warn("Failed to load signed Bunny asset URLs",It))},[t,me]);const Ae=(a==null?void 0:a.total_storage_mb)||0,Se=(a==null?void 0:a.max_storage_mb)||1024,We=Ae/Se*100,qe=We>=80,Be=We>=100,Ze=async(Dt,It)=>{await navigator.clipboard.writeText(Dt),ne.success(`${It} copied to clipboard`)},$e=Dt=>Dt.share_token?`https://video.relevelup.com/${Dt.share_token}`:Dt.playback_url||"",Xe=Dt=>{const It=$e(Dt),qs=i==null?void 0:i.find(bn=>bn.id===Dt.contact_id),wt=ge(Dt.contact_id),Us=wt!=="Unassigned"?wt.split(" ")[0]:"",Es=(qs==null?void 0:qs.phone)||"",kn=`Hey${Us?` ${Us}`:""}! I recorded a quick video message for you. Check it out: ${It}`,Sn=Es?`sms:${Es}?body=${encodeURIComponent(kn)}`:`sms:?body=${encodeURIComponent(kn)}`;window.open(Sn,"_self")},nt=Dt=>{const It=i==null?void 0:i.find(Sn=>Sn.id===Dt.contact_id),qs=(It==null?void 0:It.email)||"",wt=$e(Dt),Us="Check out this video",Es=`I recorded a quick video for you: ${wt}`,kn=qs?`mailto:${qs}?subject=${encodeURIComponent(Us)}&body=${encodeURIComponent(Es)}`:`mailto:?subject=${encodeURIComponent(Us)}&body=${encodeURIComponent(Es)}`;window.open(kn,"_self")},Ge=Dt=>{var Us;const It=$e(Dt),qs=Dt.title||"Video Message",wt=Dt.share_token?`https://video.relevelup.com/thumb/${Dt.share_token}`:((Us=me[Dt.id])==null?void 0:Us.thumbnailUrl)||Dt.thumbnail_url||"";return``},Je=async Dt=>{if(!Dt.thumbnail_url&&!Dt.share_token){ne.error("Video thumbnail not available yet");return}const It=Ge(Dt),qs=$e(Dt),wt=`Watch: ${Dt.title||"Video Message"} ${qs}`;try{const Us=new Blob([It],{type:"text/html"}),Es=new Blob([wt],{type:"text/plain"}),kn=new ClipboardItem({"text/html":Us,"text/plain":Es});await navigator.clipboard.write([kn]),ne.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(wt+` `+It),ne.success("Copied! Paste into your email.")}},ut=async Dt=>{try{ne.loading("Preparing download...",{id:"download"});const{data:It,error:qs}=await U.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Dt.bunny_video_id,isAgentVideo:!0}});if(qs||!(It!=null&&It.downloadUrl))throw new Error((qs==null?void 0:qs.message)||"Failed to get download URL");const Us=`${((Dt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Es=await fetch(It.downloadUrl);if(!Es.ok)throw new Error("Failed to fetch video file");const kn=await Es.blob(),Sn=URL.createObjectURL(kn),bn=document.createElement("a");bn.href=Sn,bn.download=Us,bn.rel="noreferrer",document.body.appendChild(bn),bn.click(),bn.remove(),URL.revokeObjectURL(Sn),ne.success("Download started",{id:"download"})}catch(It){console.error("Download error:",It),ne.error("Could not force download (your browser may block it).",{id:"download"})}},lt=async Dt=>{b(Dt),K(!0),V(""),q(!0);try{const{data:It,error:qs}=await U.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Dt.bunny_video_id,title:Dt.title,isAgentVideo:!0,shareToken:Dt.share_token}});if(qs||!(It!=null&&It.html))throw new Error("Failed to generate CRM embed code");V(It.html)}catch(It){console.error("CRM embed error:",It),ne.error("Failed to generate CRM embed code"),q(!1)}finally{K(!1)}},qt=Dt=>{b(Dt),S(!0)},zt=async()=>{if(y)try{await l.mutateAsync({id:y.id,bunnyVideoId:y.bunny_video_id,hardDelete:!0}),E(!1),b(null),ne.success("Video deleted successfully")}catch{ne.error("Failed to delete video")}};return e.jsx($s,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>f("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${p==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Zt=u.team)==null?void 0:Zt.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>f("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(On,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>f("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(wl,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),p==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(z,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),p==="team"?e.jsx(wKn,{videos:h,isLoading:m,searchTerm:g,setSearchTerm:v}):p==="analytics"?e.jsx(yKn,{}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:qe?"border-amber-500":Be?"border-destructive":"",children:e.jsxs(Le,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(VQ,{className:`h-5 w-5 ${Be?"text-destructive":qe?"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:[Ae.toFixed(1)," MB / ",Se>=1024?`${(Se/1024).toFixed(0)} GB`:`${Se} MB`]})]}),e.jsx(Di,{value:Math.min(We,100),className:`h-2 ${Be?"[&>div]:bg-destructive":qe?"[&>div]:bg-amber-500":""}`})]}),qe&&!Be&&e.jsxs(ze,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Be&&e.jsxs(ze,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Be&&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:Ve},{id:"open_house",label:"Open House Tours",count:ke}].map(Dt=>e.jsxs("button",{onClick:()=>Pe(Dt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ne===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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos by contact, title, or notes...",value:g,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"})}):(Oe==null?void 0:Oe.length)===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Xr,{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(z,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(sn,{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:Oe==null?void 0:Oe.map(Dt=>{var It,qs;return e.jsx(bKn,{video:Dt,previewSrc:(It=me[Dt.id])==null?void 0:It.previewUrl,thumbnailSrc:(qs=me[Dt.id])==null?void 0:qs.thumbnailUrl,onOpen:()=>qt(Dt),onDelete:()=>{b(Dt),E(!0)},onRename:()=>{b(Dt),ve(Dt.title||""),te(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Dt.contact_id}`),onGetEmbedCode:()=>{b(Dt),D(!0)},onCopyEmailHtml:()=>Je(Dt),onEmbedToCrm:()=>lt(Dt),onShareWithTemplate:()=>{b(Dt),oe(!0)},onSendViaGmail:()=>{b(Dt),ae(!0)},isGmailConnected:c,getContactName:ge,getShareUrl:$e,copyToClipboard:Ze,formatDuration:Ee},Dt.id)})}),e.jsx(Is,{open:w,onOpenChange:S,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:(y==null?void 0:y.title)||"Video Preview"}),e.jsx(_r,{children:(y==null?void 0:y.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Oo,{className:"h-3 w-3"}),ge(y.contact_id)]})})]}),y&&e.jsxs("div",{className:"space-y-4",children:[y.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(bt,{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(z,{variant:"outline",size:"sm",onClick:()=>{S(!1),r()},children:[e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:y.playback_url?(()=>{let Dt=y.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:y.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:y.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:y.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ne.error("Video preview failed to load")},y.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(Xr,{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(z,{variant:"outline",onClick:()=>Xe(y),children:[e.jsx(qi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(z,{variant:"outline",onClick:()=>nt(y),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(z,{variant:"outline",onClick:()=>Ze($e(y),"Share link"),children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(z,{variant:"outline",onClick:()=>Je(y),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(z,{variant:"outline",onClick:()=>ut(y),children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(z,{variant:"outline",onClick:()=>{S(!1),lt(y)},children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(z,{variant:"outline",onClick:()=>{S(!1),oe(!0)},children:[e.jsx(yc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(y==null?void 0:y.share_token)&&e.jsxs(z,{variant:"outline",onClick:()=>{S(!1),ae(!0)},children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(z,{variant:"destructive",onClick:()=>{S(!1),E(!0)},children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(Is,{open:C,onOpenChange:E,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Delete Video"}),e.jsx(_r,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(z,{variant:"destructive",onClick:zt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(xZt,{open:P,onOpenChange:M}),e.jsx(Is,{open:I,onOpenChange:D,children:e.jsxs(Ls,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Embed Video"}),e.jsx(_r,{children:"Copy this code to embed the video on your website."})]}),y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Embed Code"}),e.jsx(Ps,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(z,{className:"flex-1",onClick:()=>{const Dt=``;Ze(Dt,"Embed code")},children:[e.jsx(Sa,{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."})]})]})}),y&&e.jsx(Bss,{open:Z,onOpenChange:oe,video:y,contactName:ge(y.contact_id)}),y&&e.jsx(pKn,{open:re,onOpenChange:ae,video:y,gmailEmail:d,signedThumbnailUrl:(ms=me[y.id])==null?void 0:ms.thumbnailUrl}),e.jsx(Is,{open:J,onOpenChange:te,children:e.jsxs(Ls,{className:"max-w-sm",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Rename Video"}),e.jsx(_r,{children:"Enter a new title for this video."})]}),e.jsx(pe,{value:ce,onChange:Dt=>ve(Dt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Dt=>{Dt.key==="Enter"&&ce.trim()&&o.mutate({id:y.id,title:ce.trim()},{onSuccess:()=>{ne.success("Video renamed"),te(!1)}})}}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>te(!1),children:"Cancel"}),e.jsx(z,{disabled:!ce.trim()||o.isPending,onClick:()=>{o.mutate({id:y.id,title:ce.trim()},{onSuccess:()=>{ne.success("Video renamed"),te(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(Is,{open:F,onOpenChange:q,children:e.jsxs(Ls,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(mr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(_r,{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."})]}),H?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):G?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"CRM Email HTML"}),e.jsx(Ps,{readOnly:!0,rows:12,value:G,className:"font-mono text-xs"})]}),e.jsxs(z,{className:"w-full",onClick:()=>{Ze(G,"CRM embed code")},children:[e.jsx(Sa,{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 wKn({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=_.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=_.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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{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(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(On,{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(ja,{className:"h-7 w-7",children:[e.jsx(xi,{src:c.avatar||""}),e.jsx(Na,{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(be,{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(Xr,{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(Le,{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(Oo,{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(xa,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),Ys(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const jKn=()=>{const{user:s}=hs();return rt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},o5t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function NKn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=jKn(),[a,i]=_.useState(""),[l,o]=_.useState("all"),c=_.useMemo(()=>{if(!n)return new Map;const f=new Map;let g=0;return n.forEach(v=>{f.has(v.owner_user_id)||(f.set(v.owner_user_id,{name:v.owner_name||"Unknown",avatar:v.owner_avatar_url,color:o5t[g%o5t.length]}),g++)}),f},[n]),d=_.useMemo(()=>Array.from(c.entries()).map(([f,g])=>({id:f,...g})),[c]),u=_.useMemo(()=>{if(!n)return[];let f=n;if(l!=="all"&&(f=f.filter(g=>g.owner_user_id===l)),a.trim()){const g=a.toLowerCase();f=f.filter(v=>{var y,b,w,S;return v.deal_name.toLowerCase().includes(g)||((y=v.contact_name)==null?void 0:y.toLowerCase().includes(g))||((b=v.property_address)==null?void 0:b.toLowerCase().includes(g))||((w=v.city)==null?void 0:w.toLowerCase().includes(g))||((S=v.owner_name)==null?void 0:S.toLowerCase().includes(g))})}return f},[n,a,l]),h=_.useMemo(()=>{const f=new Map;return u.forEach(g=>{const v=g.stage_name||"Unknown";f.has(v)||f.set(v,{name:v,color:g.stage_color,icon:g.stage_icon,deals:[],totalValue:0});const y=f.get(v);y.deals.push(g),y.totalValue+=g.sale_price||0}),Array.from(f.values())},[u]),m=f=>f>=1e6?`$${(f/1e6).toFixed(1)}M`:f>=1e3?`$${(f/1e3).toFixed(0)}K`:`$${f.toFixed(0)}`,p=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):null;return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(On,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search deals...",value:a,onChange:f=>i(f.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{placeholder:"All Members"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Members"}),d.map(f=>e.jsx(He,{value:f.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:f.color}}),f.name]})},f.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(f=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:f.color}}),f.name.split(" ")[0]]},f.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(f=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(ln,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(ln,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(ln,{className:"h-24 w-full rounded-lg"})]},f))}):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(On,{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(f=>{const g=f.icon&&FMe[f.icon]||Gf;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:f.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:f.color?`${f.color}20`:void 0},children:e.jsx(g,{className:"h-3.5 w-3.5",style:{color:f.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:f.name})]}),e.jsx(ze,{variant:"secondary",className:"text-xs px-2",children:f.deals.length})]}),f.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(f.totalValue)})]}),e.jsx(Ki,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:f.deals.map(v=>{const y=c.get(v.owner_user_id);return e.jsx(kKn,{deal:v,ownerColor:(y==null?void 0:y.color)||"#888",ownerName:(y==null?void 0:y.name)||"Unknown",ownerAvatar:(y==null?void 0:y.avatar)||null,formatPrice:p},v.id)})})})]},f.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 kKn({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(ja,{className:"h-4 w-4",children:[e.jsx(xi,{src:r||""}),e.jsx(Na,{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:Ct("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(sa,{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(Nd,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function SKn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a,showOwnDeals:i=!0,onToggleOwnDeals:l}){const o=t.size+(i?1:0);return e.jsxs("div",{className:Ct("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(z,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(On,{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"}),o>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:o}),e.jsx(Wc,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&o>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:o})]})}),r?e.jsxs(Ki,{className:"flex-1 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[l&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:l,className:Ct("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",i?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/20 flex items-center justify-center shrink-0",children:e.jsx(On,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("span",{className:Ct("text-xs truncate flex-1",i?"font-medium text-foreground":"text-muted-foreground"),children:"My deals"}),e.jsx(mn,{checked:i,onCheckedChange:l,className:"scale-75",onClick:c=>c.stopPropagation()})]}),e.jsx("div",{className:"h-px bg-border/60 my-1"})]}),s.map(c=>{const d=t.has(c.id);return e.jsxs("button",{onClick:()=>n(c.id),className:Ct("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",d?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(xi,{src:c.avatar_url||""}),e.jsx(Na,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]}),d&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:c.color}})]}),e.jsx("span",{className:Ct("text-xs truncate flex-1",d?"font-medium text-foreground":"text-muted-foreground"),children:c.name}),e.jsx(mn,{checked:d,onCheckedChange:()=>n(c.id),className:"scale-75",onClick:u=>u.stopPropagation()})]},c.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(c=>{const d=t.has(c.id);return e.jsx("button",{onClick:()=>n(c.id),className:"relative",title:c.name,children:e.jsxs(ja,{className:Ct("h-7 w-7 transition-all",d?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:d?{"--tw-ring-color":c.color}:{},children:[e.jsx(xi,{src:c.avatar_url||""}),e.jsx(Na,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]})},c.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const l5t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function CKn(){const s=ha(),{data:t}=K_(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=rt({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await U.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 U.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:l5t[h%l5t.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function AKn(s){return rt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await U.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(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 EKn(){const s=ha();return rt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await U.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 $ss({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=_.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(ru,{open:a,onOpenChange:i,children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{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(yi,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(qd,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&FMe[c.icon]||Gf,u=c.id===t;return e.jsxs(ua,{onClick:()=>o(c),className:Ct("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(Wr,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const TKn={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"}},MKn={low:{color:"bg-slate-100 text-slate-600",dot:"bg-slate-400",stripe:"bg-slate-300"},medium:{color:"bg-amber-100 text-amber-700",dot:"bg-amber-500",stripe:"bg-amber-400"},high:{color:"bg-orange-100 text-orange-700",dot:"bg-orange-500",stripe:"bg-orange-500"},urgent:{color:"bg-red-100 text-red-700",dot:"bg-red-500",stripe:"bg-red-500"}};function Uss({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,isLostStage:o=!1,ownerInfo:c=null,tags:d=[],overdueTaskCount:u=0}){var E,P;const h=XW(),m=TKn[s.deal_type],p=MKn[s.priority],f=_.useMemo(()=>s.target_close_date?PN(Ou(s.target_close_date),new Date):null,[s.target_close_date]),g=l||o||!!s.actual_close_date,v=!g&&f!==null&&f<0,y=!g&&f!==null&&f<=7&&f>=0,b=_.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const M=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!M)return null;const I=s.contract_date?Ou(s.contract_date):new Date;return PN(I,Ou(M))},[s]),w=l&&!s.scorecard_transaction_id,S=!!s.scorecard_transaction_id,C=M=>M?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(M):null;return e.jsxs(be,{className:Ct("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",v&&"border-red-200 bg-red-50/30",w&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:c?{borderLeftWidth:4,borderLeftColor:c.color}:void 0,children:[!c&&e.jsx("div",{className:Ct("h-1 w-full",p.stripe),"aria-hidden":!0}),e.jsxs(Le,{className:"p-3 space-y-2.5",children:[c&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(ja,{className:"h-4 w-4",children:[e.jsx(xi,{src:c.avatar_url||""}),e.jsx(Na,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:c.color},children:c.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:Ct("text-[10px] px-1.5 py-0 shrink-0",m.color),children:m.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ja,{className:"h-5 w-5",children:e.jsxs(Na,{className:"text-[10px] bg-primary/10 text-primary",children:[(E=s.contact.first_name)==null?void 0:E[0],(P=s.contact.last_name)==null?void 0:P[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(Oc,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),w&&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(jl,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),S&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(Mr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),b!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Ud,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Ct("font-medium",b>90?"text-red-600":b>60?"text-amber-600":"text-muted-foreground"),children:[b," 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(sa,{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(Nd,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:C(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",C(s.expected_commission)," GCI"]}),(()=>{const M=k_(s);return M!==null&&M!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",C(M)," Net"]}):null})()]}),u>0&&e.jsxs("div",{className:"flex items-center gap-1.5 rounded bg-destructive/10 px-2 py-1 text-xs font-medium text-destructive",children:[e.jsx(k0,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:[u," overdue task",u>1?"s":""]})]}),d.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[d.slice(0,3).map(M=>e.jsx(jZt,{label:M},M)),d.length>3&&e.jsxs("span",{className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium text-muted-foreground",children:["+",d.length-3]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[e.jsx("span",{children:"Win probability"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[s.probability,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.max(0,s.probability??0))}%`}})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:Ct("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",p.color),children:[e.jsx("div",{className:Ct("w-1.5 h-1.5 rounded-full",p.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]})}),i&&h&&r&&a?e.jsx($ss,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(M,I)=>a(s.id,M,I)}):s.target_close_date?e.jsxs("div",{className:Ct("flex items-center gap-1 text-[10px]",v&&"text-red-600",y&&!v&&"text-amber-600",!v&&!y&&"text-muted-foreground"),children:[v?e.jsx(Ho,{className:"h-3 w-3"}):e.jsx(ya,{className:"h-3 w-3"}),e.jsx("span",{children:v?`${Math.abs(f)}d overdue`:y?`${f}d left`:Ys(Ou(s.target_close_date),"MMM d")})]}):null]})]})]})}function PKn({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,isLostStage:d=!1,getOwnerInfo:u,tagsByDeal:h={},overdueTasksByDeal:m={}}){const p=_.useRef(null),[f,g]=_.useState(!1),v=t.reduce((C,E)=>C+(E.expected_price||0),0),y=t.reduce((C,E)=>C+(E.expected_commission||0),0),b=t.reduce((C,E)=>C+(k_(E)||0),0),w=C=>C>=1e6?`$${(C/1e6).toFixed(1)}M`:C>=1e3?`$${(C/1e3).toFixed(0)}K`:`$${C.toFixed(0)}`,S=s.icon&&FMe[s.icon]||Gf;return f?e.jsxs("div",{className:"flex h-full w-12 shrink-0 flex-col items-center gap-3 rounded-xl border border-border/50 bg-muted/30 py-3",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsx("button",{onClick:()=>g(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(yi,{className:"h-4 w-4"})}),e.jsx(ze,{variant:"secondary",className:"px-1.5 text-[10px]",children:t.length}),e.jsx("span",{className:"mt-1 whitespace-nowrap text-xs font-semibold",style:{writingMode:"vertical-rl",color:s.color},children:s.name})]}):e.jsxs("div",{ref:p,className:Ct("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:C=>i(C,s.id),onDrop:C=>l(C,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(S,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ze,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length}),e.jsx("button",{onClick:()=>g(!0),"aria-label":`Collapse ${s.name}`,className:"rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:e.jsx(Wc,{className:"h-3.5 w-3.5"})})]})]}),v>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:w(v)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[w(y)," GCI"]}),b>0&&b!==y&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[w(b)," Net"]})]})]})]}),e.jsx(Ki,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(C=>e.jsx("div",{draggable:!0,onDragStart:E=>{E.dataTransfer.effectAllowed="move",a(C.id,s.id)},children:e.jsx(Uss,{deal:C,onClick:()=>n(C),isWonStage:c,isLostStage:d,ownerInfo:(u==null?void 0:u(C))||null,tags:h[C.id]||[],overdueTaskCount:m[C.id]||0})},C.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}const SN=U;function LKn(s,t=!1){return rt({queryKey:["commission-plans",s,t],enabled:!!s,queryFn:async()=>{let n=SN.from("brokerage_commission_plans").select("*").eq("brokerage_id",s).order("name",{ascending:!0});t||(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r||[]}})}function IKn(s){const t=$t();return mt({mutationFn:async n=>{const r={brokerage_id:s,name:n.name,description:n.description||null,agent_split_pct:n.agent_split_pct??70,team_split_pct:n.team_split_pct??0,cap_amount:n.cap_amount??null,monthly_fee:n.monthly_fee??0,transaction_fee:n.transaction_fee??0,franchise_fee_pct:n.franchise_fee_pct??0,referral_fee_pct:n.referral_fee_pct??null,commission_calc_method:n.commission_calc_method||"standard",is_active:n.is_active??!0};if(n.id){const{error:a}=await SN.from("brokerage_commission_plans").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await SN.from("brokerage_commission_plans").insert(r);if(a)throw a}},onSuccess:()=>{t.invalidateQueries({queryKey:["commission-plans",s]}),ne.success("Commission plan saved")},onError:n=>ne.error(n.message||"Could not save plan")})}function DKn(s){return rt({queryKey:["cap-progress",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await SN.rpc("get_agent_cap_progress",{_agent_user_id:s});if(n)throw n;return(t||[])[0]??null}})}function RKn(s){return rt({queryKey:["agent-plan-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;const{data:r,error:a}=await SN.from("agent_plan_assignments").select("*").eq("brokerage_id",s).is("end_date",null);if(a)throw a;const i=[...new Set((r||[]).map(c=>c.plan_id))];let l=[];if(i.length){const{data:c,error:d}=await SN.from("brokerage_commission_plans").select("*").in("id",i);if(d)throw d;l=c||[]}return await Promise.all((t||[]).map(async c=>{const d=(r||[]).find(m=>m.agent_user_id===c.id)||null,u=d&&l.find(m=>m.id===d.plan_id)||null;let h=null;if(d){const{data:m}=await SN.rpc("get_agent_cap_progress",{_agent_user_id:c.id});h=(m||[])[0]??null}return{agentId:c.id,name:c.name||c.email,email:c.email,avatarUrl:c.avatar_url||null,assignment:d,plan:u,progress:h}}))}})}function FKn(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await SN.from("agent_plan_assignments").update({end_date:n.start_date}).eq("brokerage_id",s).eq("agent_user_id",n.agent_user_id).is("end_date",null);if(r)throw r;const{error:a}=await SN.from("agent_plan_assignments").insert({agent_user_id:n.agent_user_id,brokerage_id:s,plan_id:n.plan_id,start_date:n.start_date,anniversary_date:n.anniversary_date||null,notes:n.notes||null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),ne.success("Plan assigned")},onError:n=>ne.error(n.message||"Could not assign plan")})}function OKn(s){const t=$t();return mt({mutationFn:async n=>{const r=new Date().toISOString().slice(0,10),{error:a}=await SN.from("agent_plan_assignments").update({end_date:r}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),ne.success("Plan removed from agent")},onError:n=>ne.error(n.message||"Could not remove plan")})}function qss(){const{user:s}=hs();return rt({queryKey:["my-commission-plan",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:t,error:n}=await SN.from("agent_plan_assignments").select("*").eq("agent_user_id",s.id).is("end_date",null).order("start_date",{ascending:!1}).limit(1).maybeSingle();if(n)throw n;if(!t)return null;const{data:r,error:a}=await SN.from("brokerage_commission_plans").select("*").eq("id",t.plan_id).maybeSingle();if(a)throw a;return r?{assignment:t,plan:r}:null}})}function zKn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=hs(),[a,i]=_.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(f1,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(x1,{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(cl,{className:Ct("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(g1,{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(ee,{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(mn,{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(ee,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(C_,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Ct("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(am,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hl,{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:Ct("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(am,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Wo,{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(za,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(ee,{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(za,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(ee,{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(ee,{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(ee,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(pe,{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(ee,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(pe,{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(ee,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(pe,{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(ee,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(ls,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"email",children:"Email"}),e.jsxs(He,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const BKn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],$Kn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function vBe({label:s,date:t,onChange:n,placeholder:r="Pick a date",disabled:a}){const[i,l]=_.useState(t?Ys(t,"MM/dd/yyyy"):"");_.useEffect(()=>{const c=tgt(i);t&&c&&c.getTime()===t.getTime()||l(t?Ys(t,"MM/dd/yyyy"):"")},[t]);const o=c=>{l(c);const d=tgt(c);d?n(d):c.trim()||n(void 0)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:s}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("w-full justify-start text-left font-normal",!t&&"text-muted-foreground"),disabled:a,children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),t?Ys(t,"PPP"):r]})}),e.jsxs(nd,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx(pe,{type:"text",placeholder:"MM/DD/YYYY",value:i,onChange:c=>o(c.target.value),className:"h-8 text-sm"})}),e.jsx(Oj,{mode:"single",selected:t,onSelect:c=>{n(c),l(c?Ys(c,"MM/dd/yyyy"):"")},initialFocus:!0,className:"pointer-events-auto",captionLayout:"dropdown",fromYear:1900,toYear:2100})]})]})]})}function UKn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=cie(),{data:i}=Rb(),{data:l}=Met(),o=vLe(),c=Rss(),d=Fss(),u=trt(),{data:h}=qss(),{data:m}=Kre(),p=((m==null?void 0:m.length)??0)>0,f=_.useMemo(()=>{const Z=h==null?void 0:h.plan;return Z?{brokerage_split_pct:String(Math.max(0,100-(Z.agent_split_pct??100))),team_split_pct:p&&Z.team_split_pct?String(Z.team_split_pct):"",franchise_fee_pct:Z.franchise_fee_pct?String(Z.franchise_fee_pct):"",transaction_fee:Z.transaction_fee?String(Z.transaction_fee):"",referral_fee_pct:Z.referral_fee_pct!=null?String(Z.referral_fee_pct):"",commission_calc_method:Z.commission_calc_method||"standard"}:{brokerage_split_pct:"",team_split_pct:"",franchise_fee_pct:"",transaction_fee:"",referral_fee_pct:"",commission_calc_method:"standard"}},[h,p]);_.useEffect(()=>{if(!s||n||!h)return;const Z=h.plan;F(oe=>oe.brokerage_split_pct||oe.franchise_fee_pct||oe.transaction_fee||oe.referral_fee_pct||oe.team_split_pct?oe:{...oe,brokerage_split_pct:String(Math.max(0,100-(Z.agent_split_pct??100))),team_split_pct:p&&Z.team_split_pct?String(Z.team_split_pct):"",franchise_fee_pct:Z.franchise_fee_pct?String(Z.franchise_fee_pct):"",transaction_fee:Z.transaction_fee?String(Z.transaction_fee):"",referral_fee_pct:Z.referral_fee_pct!=null?String(Z.referral_fee_pct):"",commission_calc_method:Z.commission_calc_method||"standard"})},[h,s,n,p]);const[g,v]=_.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[y,b]=_.useState(""),[w,S]=_.useState(!1),[C,E]=_.useState(!1),[P,M]=_.useState({first_name:"",last_name:"",email:"",phone:""}),I=(l==null?void 0:l.filter(Z=>((n==null?void 0:n.listing_id)===Z.id,!0)))||[],[D,F]=_.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:"",bonus_amount:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});_.useEffect(()=>{var Z,oe,re,ae,J,te,ce,ve,me,he;s&&(n?(F({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:((Z=n.expected_price)==null?void 0:Z.toString())||"",commission_percentage:((oe=n.commission_percentage)==null?void 0:oe.toString())||"3",brokerage_split_pct:((re=n.brokerage_split_pct)==null?void 0:re.toString())||"",team_split_pct:((ae=n.team_split_pct)==null?void 0:ae.toString())||"",referral_fee_pct:((J=n.referral_fee_pct)==null?void 0:J.toString())||"",franchise_fee_pct:((te=n.franchise_fee_pct)==null?void 0:te.toString())||"",transaction_fee:((ce=n.transaction_fee)==null?void 0:ce.toString())||"",bonus_amount:((ve=n.bonus_amount)==null?void 0:ve.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Ou(n.target_close_date):void 0,contract_date:n.contract_date?Ou(n.contract_date):void 0,listing_date:n.listing_date?Ou(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&b(`${n.contact.first_name} ${n.contact.last_name}`)):(F({deal_name:"",deal_type:"buyer",stage_id:r||((me=a==null?void 0:a[0])==null?void 0:me.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:f.brokerage_split_pct,team_split_pct:f.team_split_pct,referral_fee_pct:f.referral_fee_pct,franchise_fee_pct:f.franchise_fee_pct,transaction_fee:f.transaction_fee,bonus_amount:"",commission_calc_method:f.commission_calc_method,target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:String(((he=a==null?void 0:a.find(ge=>{var Ee;return ge.id===(r||((Ee=a==null?void 0:a[0])==null?void 0:Ee.id))}))==null?void 0:he.default_probability)??50),notes:""}),b(""),v({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 q=i==null?void 0:i.filter(Z=>{var he,ge,Ee,Ne,Pe;const oe=y.toLowerCase().trim();if(!oe)return!0;const re=((he=Z.first_name)==null?void 0:he.toLowerCase())||"",ae=((ge=Z.last_name)==null?void 0:ge.toLowerCase())||"",J=((Ee=Z.email)==null?void 0:Ee.toLowerCase())||"",te=((Pe=(Ne=Z.phone)==null?void 0:Ne.toLowerCase)==null?void 0:Pe.call(Ne))||"",ce=`${re} ${ae}`.trim(),ve=`${ae} ${re}`.trim();if(ce.includes(oe)||ve.includes(oe)||re.includes(oe)||ae.includes(oe)||J.includes(oe)||te.includes(oe))return!0;const me=oe.split(/\s+/).filter(Boolean);return me.length>1?me.every(Oe=>re.includes(Oe)||ae.includes(Oe)||J.includes(Oe)||te.includes(Oe)):!1}).slice(0,8),G=()=>{const Z=parseFloat(D.expected_price)||0,oe=parseFloat(D.commission_percentage)||0;return Z*(oe/100)},V=()=>{const Z=G(),oe=parseFloat(D.bonus_amount)||0;if(!Z)return oe>0?oe:null;const re=parseFloat(D.brokerage_split_pct)||0,ae=parseFloat(D.team_split_pct)||0,J=parseFloat(D.referral_fee_pct)||0,te=parseFloat(D.franchise_fee_pct)||0,ce=parseFloat(D.transaction_fee)||0,ve=parseFloat(D.bonus_amount)||0;if(D.commission_calc_method==="referral_first"){let he=Z;J&&(he-=Z*J/100);let ge=he;return re&&(ge-=he*re/100),ae&&(ge-=Z*ae/100),te&&(ge-=Z*te/100),ce&&(ge-=ce),Math.max(0,ge)+ve}let me=Z;return re&&(me=me*((100-re)/100)),ae&&(me=me*((100-ae)/100)),J&&(me=me-Z*J/100),te&&(me=me-Z*te/100),ce&&(me=me-ce),Math.max(0,me)+ve},H=async Z=>{var oe,re,ae;if(Z.preventDefault(),!D.deal_name.trim()){ne.error("Please enter a deal name");return}try{const J={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:G()||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,bonus_amount:D.bonus_amount?parseFloat(D.bonus_amount):null,commission_calc_method:D.commission_calc_method,target_close_date:((oe=D.target_close_date)==null?void 0:oe.toISOString().split("T")[0])||null,contract_date:((re=D.contract_date)==null?void 0:re.toISOString().split("T")[0])||null,listing_date:((ae=D.listing_date)==null?void 0:ae.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,...J}),ne.success("Deal updated successfully");else{const te=await c.mutateAsync(J);if(ne.success("Deal created successfully"),g.portal_enabled&&(te!=null&&te.id))try{await u.mutateAsync({deal_id:te.id,visibility:g.visibility,require_onboarding:g.require_onboarding,allow_spouse:g.allow_spouse,client_name:g.client_name||null,client_email:g.client_email||null,client_phone:g.client_phone||null,invite_method:g.invite_method}),ne.success("Client portal created!")}catch{ne.error("Deal created, but portal setup failed")}}t(!1)}catch{ne.error("Failed to save deal")}},K=c.isPending||d.isPending;return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(_r,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:H,className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(ee,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(pe,{id:"deal_name",value:D.deal_name,onChange:Z=>F(oe=>({...oe,deal_name:Z.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal Type"}),e.jsxs(ls,{value:D.deal_type,onValueChange:Z=>F(oe=>({...oe,deal_type:Z})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:BKn.map(Z=>e.jsx(He,{value:Z.value,children:Z.label},Z.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Stage"}),e.jsxs(ls,{value:D.stage_id||"none",onValueChange:Z=>{const oe=Z==="none"?"":Z,re=a==null?void 0:a.find(ae=>ae.id===oe);F(ae=>({...ae,stage_id:oe,probability:typeof(re==null?void 0:re.default_probability)=="number"?String(re.default_probability):ae.probability}))},children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select stage"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No Stage"}),a==null?void 0:a.map(Z=>e.jsx(He,{value:Z.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Z.color}}),Z.name]})},Z.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:y,onChange:Z=>{b(Z.target.value),S(!0),E(!1),Z.target.value||F(oe=>({...oe,contact_id:""}))},onFocus:()=>S(!0),placeholder:"Search contacts...",className:"pl-9"}),w&&y&&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:[q&&q.length>0?q.map(Z=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{F(oe=>({...oe,contact_id:Z.id})),b(`${Z.first_name} ${Z.last_name}`),S(!1)},children:[e.jsx(Oo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[Z.first_name," ",Z.last_name]}),Z.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:Z.email})]},Z.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 Z=y.trim().split(/\s+/);M({first_name:Z[0]||"",last_name:Z.slice(1).join(" ")||"",email:"",phone:""}),E(!0),S(!1)},children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',y.trim(),'"']})]})]})]}),C&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>E(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{placeholder:"First name *",value:P.first_name,onChange:Z=>M(oe=>({...oe,first_name:Z.target.value})),className:"h-8 text-sm"}),e.jsx(pe,{placeholder:"Last name",value:P.last_name,onChange:Z=>M(oe=>({...oe,last_name:Z.target.value})),className:"h-8 text-sm"}),e.jsx(pe,{placeholder:"Email",type:"email",value:P.email,onChange:Z=>M(oe=>({...oe,email:Z.target.value})),className:"h-8 text-sm"}),e.jsx(pe,{placeholder:"Phone",type:"tel",value:P.phone,onChange:Z=>M(oe=>({...oe,phone:Z.target.value})),className:"h-8 text-sm"})]}),e.jsx(z,{type:"button",size:"sm",className:"w-full h-8",disabled:!P.first_name.trim()||o.isPending,onClick:async()=>{try{const Z=await o.mutateAsync({first_name:P.first_name.trim(),last_name:P.last_name.trim()||null,email:P.email.trim()||null,phone:P.phone.trim()||null});Z&&(F(oe=>({...oe,contact_id:Z.id})),b(`${Z.first_name} ${Z.last_name||""}`.trim()),E(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),I.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Oc,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(ls,{value:D.listing_id||"none",onValueChange:Z=>{const oe=Z==="none"?"":Z,re=I.find(ae=>ae.id===oe);F(re?ae=>{var J;return{...ae,listing_id:oe,deal_type:"seller",property_address:re.property_address||ae.property_address,city:re.city||ae.city,state:re.state||ae.state,expected_price:((J=re.price)==null?void 0:J.toString())||ae.expected_price}}:ae=>({...ae,listing_id:oe}))},children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"None"}),I.map(Z=>e.jsx(He,{value:Z.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Z.property_address||`${Z.city}, ${Z.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(Z.price/1e3).toFixed(0),"K"]})]})},Z.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(ee,{htmlFor:"property_address",children:"Address"}),e.jsx(pe,{id:"property_address",value:D.property_address,onChange:Z=>F(oe=>({...oe,property_address:Z.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:D.city,onChange:Z=>F(oe=>({...oe,city:Z.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:D.state,onChange:Z=>F(oe=>({...oe,state:Z.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(pe,{id:"zip_code",value:D.zip_code,onChange:Z=>F(oe=>({...oe,zip_code:Z.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(ee,{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(pe,{id:"expected_price",type:"number",value:D.expected_price,onChange:Z=>F(oe=>({...oe,expected_price:Z.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:Z=>F(oe=>({...oe,commission_percentage:Z.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(ee,{children:"Expected GCI"}),e.jsx(pe,{value:G()?`$${G().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(ee,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(ls,{value:D.commission_calc_method,onValueChange:Z=>F(oe=>({...oe,commission_calc_method:Z})),children:[e.jsx(rs,{className:"h-7 text-xs",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(He,{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(ee,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:Z=>F(oe=>({...oe,brokerage_split_pct:Z.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(ee,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:Z=>F(oe=>({...oe,team_split_pct:Z.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(ee,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:Z=>F(oe=>({...oe,referral_fee_pct:Z.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(ee,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:Z=>F(oe=>({...oe,franchise_fee_pct:Z.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(ee,{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(pe,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:Z=>F(oe=>({...oe,transaction_fee:Z.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(ee,{className:"text-xs",children:"Bonus"}),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(pe,{type:"number",step:"1",min:"0",value:D.bonus_amount,onChange:Z=>F(oe=>({...oe,bonus_amount:Z.target.value})),className:"pl-7 h-8 text-sm",placeholder:"5000"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Builder/other bonus — paid on top, not split"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Net to Agent"}),e.jsx(pe,{value:V()?`$${Math.round(V()).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.jsx(vBe,{label:"Target Close Date",date:D.target_close_date,onChange:Z=>F(oe=>({...oe,target_close_date:Z}))}),e.jsx(vBe,{label:"Contract Date",date:D.contract_date,onChange:Z=>F(oe=>({...oe,contract_date:Z}))}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(vBe,{label:"Listing Date (for Days on Market)",date:D.listing_date,onChange:Z=>F(oe=>({...oe,listing_date:Z}))}),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(ee,{children:"Priority"}),e.jsxs(ls,{value:D.priority,onValueChange:Z=>F(oe=>({...oe,priority:Z})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:$Kn.map(Z=>e.jsx(He,{value:Z.value,children:Z.label},Z.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",min:"0",max:"100",value:D.probability,onChange:Z=>F(oe=>({...oe,probability:Z.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(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Ps,{id:"notes",value:D.notes,onChange:Z=>F(oe=>({...oe,notes:Z.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(zKn,{formData:g,onChange:v}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{type:"submit",disabled:K,children:[K&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function qKn({dealId:s}){const t=ha(),n=$t(),[r,a]=_.useState(""),[i,l]=_.useState(!1),{data:o=[]}=rt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:f,error:g}=await U.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(g)throw g;return f},enabled:!!s}),{data:c=[]}=rt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:f,error:g}=await U.from("deal_tags").select("tag").eq("owner_user_id",t);if(g)throw g;return[...new Set(f.map(y=>y.tag))].sort()},enabled:!!t}),d=mt({mutationFn:async f=>{if(!t)throw new Error("Not authenticated");const{error:g}=await U.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:f.trim()});if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=mt({mutationFn:async f=>{const{error:g}=await U.from("deal_tags").delete().eq("id",f);if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const f=r.trim();f&&(o.some(g=>g.tag.toLowerCase()===f.toLowerCase())||d.mutate(f))},m=o.map(f=>f.tag.toLowerCase()),p=c.filter(f=>f.toLowerCase().includes(r.toLowerCase())&&!m.includes(f.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(f=>e.jsxs(ze,{variant:"secondary",className:"gap-1 text-xs",children:[f.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(f.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(er,{className:"h-3 w-3"})})]},f.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(sn,{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(pe,{value:r,onChange:f=>a(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),h()),f.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&p.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:p.map(f=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:g=>{g.preventDefault(),d.mutate(f)},children:f},f))})]})]})}function VKn(s){return rt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_files").select("id, deal_id, owner_user_id, file_name, file_size, file_type, storage_path, visible_on_portal, client_visible, compliance_item_id, version_no, is_current, source, source_ref, created_at").eq("deal_id",s).eq("is_current",!0).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function HKn(){const s=ha(),t=$t();return mt({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 U.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await U.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,source:"levelup"}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function GKn(){const s=$t();return mt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await U.storage.from("deal-files").remove([n]);const{error:a}=await U.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function WKn(){const s=$t();return mt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await U.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 KKn(s){const{data:t,error:n}=await U.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const YKn={pending:"bg-muted text-muted-foreground",submitted:"bg-amber-500/15 text-amber-600",approved:"bg-emerald-500/15 text-emerald-600",rejected:"bg-destructive/15 text-destructive"},ZKn={pending:"Needed",submitted:"In review",approved:"Approved",rejected:"Changes requested"};function Vss({dealId:s,canReview:t=!1,canUpload:n=!1}){const{data:r=[],isLoading:a}=HRt(s),{data:i=[]}=bTs(s),l=yTs(),o=_Ts(),[c,d]=_.useState(null),[u,h]=_.useState(""),[m,p]=_.useState(null),[f,g]=_.useState(null),v=_.useRef(null),y=_.useRef(null),b=C=>{var E;y.current=C,(E=v.current)==null||E.click()},w=async C=>{const E=y.current;if(!(!C||!E)){g(E.id);try{await o.mutateAsync({item:E,file:C}),ne.success("Document uploaded for review")}catch(P){ne.error(P.message||"Upload failed")}finally{g(null),y.current=null,v.current&&(v.current.value="")}}},S=async C=>{try{await l.mutateAsync({item:C,status:"rejected",note:u.trim()||"Changes requested"}),d(null),h("")}catch(E){ne.error(E.message||"Could not update item")}};return a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No compliance checklist on this deal yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:v,type:"file",className:"hidden",onChange:C=>{var E;return w((E=C.target.files)==null?void 0:E[0])}}),r.map(C=>{var I;const E=i.filter(D=>D.compliance_item_id===C.id),P=E.find(D=>D.is_current)||E[0],M=C.status!=="approved"&&C.due_date&&C.due_dateD.value===C.phase))==null?void 0:I.label)||C.phase}),C.due_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," Due ",C.due_date]}),E.length>0&&e.jsxs("button",{className:"flex items-center gap-1 hover:text-foreground",onClick:()=>p(m===C.id?null:C.id),children:[e.jsx(O_,{className:"h-3 w-3"})," ",E.length," version",E.length>1?"s":""]})]}),C.status==="rejected"&&C.review_note&&e.jsx("p",{className:"mt-2 rounded-md bg-destructive/10 p-2 text-xs text-destructive",children:C.review_note})]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[P&&e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>pft(P.storage_path),children:e.jsx(Ga,{className:"h-4 w-4"})}),n&&C.requires_document&&e.jsx(z,{variant:"outline",size:"sm",onClick:()=>b(C),disabled:f===C.id,children:f===C.id?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(OQ,{className:"mr-1 h-4 w-4"}),P?"Replace":"Upload"]})}),t&&e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"icon",title:"Approve",onClick:()=>l.mutate({item:C,status:"approved",note:null}),children:e.jsx(Mr,{className:"h-4 w-4 text-emerald-600"})}),e.jsx(z,{variant:"ghost",size:"icon",title:"Request changes",onClick:()=>{d(c===C.id?null:C.id),h("")},children:e.jsx(Bd,{className:"h-4 w-4 text-destructive"})})]})]})]}),c===C.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ps,{rows:2,placeholder:"What needs to change?",value:u,onChange:D=>h(D.target.value)}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>d(null),children:"Cancel"}),e.jsx(z,{size:"sm",onClick:()=>S(C),children:"Send back to agent"})]})]}),m===C.id&&E.length>0&&e.jsx("div",{className:"mt-3 space-y-1 border-t pt-2",children:E.map(D=>e.jsxs("button",{onClick:()=>pft(D.storage_path),className:"flex w-full items-center justify-between rounded px-2 py-1 text-left text-xs hover:bg-muted",children:[e.jsxs("span",{className:"truncate",children:["v",D.version_no," — ",D.file_name]}),e.jsx("span",{className:"text-muted-foreground",children:new Date(D.created_at).toLocaleDateString()})]},D.id))})]},C.id)})]})}function Hss({dealId:s,brokerageId:t,role:n,counterpartName:r}){const{user:a}=hs(),{data:i=[],isLoading:l}=wTs(s),o=jTs(),c=NTs(),[d,u]=_.useState(""),h=_.useRef(null),m=_.useRef(null);_.useEffect(()=>{var f;(f=h.current)==null||f.scrollIntoView({block:"nearest"})},[i.length]),_.useEffect(()=>{if(l||m.current===s)return;i.some(g=>g.sender_role!==n&&!g.read_at)&&(m.current=s,c.mutate({dealId:s,senderRole:n}))},[s,l,i,n,c]);const p=async()=>{const f=d.trim();if(f)try{await o.mutateAsync({dealId:s,brokerageId:t,body:f,senderRole:n}),u(""),ne.success("Message sent — an email notification is on the way")}catch(g){ne.error(g.message||"Could not send the message")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),n==="staff"?`Private thread with ${r||"the agent"} — they get an email for every message.`:"Private thread with your transaction team — they get an email for every message."]}),e.jsxs("div",{className:"max-h-[320px] space-y-3 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:[l?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):i.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No messages yet. Start the conversation about what this file still needs."}):i.map(f=>{const g=f.sender_user_id===(a==null?void 0:a.id);return e.jsx("div",{className:`flex ${g?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] rounded-lg px-3 py-2 text-sm ${g?"bg-primary text-primary-foreground":"bg-background border"}`,children:[e.jsxs("p",{className:`mb-1 text-[11px] ${g?"text-primary-foreground/75":"text-muted-foreground"}`,children:[g?"You":f.sender_name||(f.sender_role==="staff"?"Transaction team":"Agent")," ·"," ",new Date(f.created_at).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),e.jsx("p",{className:"whitespace-pre-wrap leading-relaxed",children:f.body})]})},f.id)}),e.jsx("div",{ref:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ps,{value:d,onChange:f=>u(f.target.value),rows:3,placeholder:n==="staff"?"e.g. Please upload the signed disclosure — we need it before Friday.":"Ask a question or let the team know what you uploaded…"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:p,disabled:!d.trim()||o.isPending,className:"gap-2",children:[o.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),"Send & notify"]})})]})]})}function XKn({dealId:s}){var a;const{data:t=[]}=HRt(s);if(t.length===0)return null;const n=((a=t[0])==null?void 0:a.brokerage_id)??null,r=t.filter(i=>i.status==="approved").length;return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ch,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Brokerage compliance"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[r," of ",t.length," approved"]})]}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"This file is shared with your brokerage's compliance team. Upload each required document below."}),e.jsx(Vss,{dealId:s,canUpload:!0}),n&&e.jsxs("div",{className:"mt-4 border-t pt-4",children:[e.jsx("p",{className:"mb-2 text-sm font-medium",children:"Messages with your transaction team"}),e.jsx(Hss,{dealId:s,brokerageId:n,role:"agent"})]})]})}/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var ZYe=function(s,t){return ZYe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var a in r)r.hasOwnProperty(a)&&(n[a]=r[a])},ZYe(s,t)};function di(s,t){ZYe(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var pc=function(){return pc=Object.assign||function(t){for(var n,r=1,a=arguments.length;r0&&i[i.length-1])&&(d[0]===6||d[0]===2)){n=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]>2],t+=_U[(s[r]&3)<<4|s[r+1]>>4],t+=_U[(s[r+1]&15)<<2|s[r+2]>>6],t+=_U[s[r+2]&63];return n%3===2?t=t.substring(0,t.length-1)+"=":n%3===1&&(t=t.substring(0,t.length-2)+"=="),t},c5t=function(s){var t=s.length*.75,n=s.length,r,a=0,i,l,o,c;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);var d=new Uint8Array(t);for(r=0;r>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},eYn=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,tYn=function(s){var t=s.trim(),n=t.substring(0,100),r=n.match(eYn);if(!r)return c5t(t);var a=r[0],i=t.substring(a.length);return c5t(i)},hc=function(s){return s.charCodeAt(0)},sYn=function(s){return s.codePointAt(0)},die=function(s,t){return rS(s.toString(16),t,"0").toUpperCase()},K8e=function(s){return die(s,2)},cE=function(s){return String.fromCharCode(s)},nYn=function(s){return cE(parseInt(s,16))},rS=function(s,t,n){for(var r="",a=0,i=t-s.length;a=55296&&n<=56319&&s.length>a&&(r=s.charCodeAt(a),r>=56320&&r<=57343&&(i=2)),[s.slice(t,t+i),i]},iYn=function(s){for(var t=[],n=0,r=s.length;nn&&d(),l+=m,o+=p}}return d(),c},cYn=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,Zss=function(s){var t=s.match(cYn);if(t){var n=t[1],r=t[2],a=r===void 0?"01":r,i=t[3],l=i===void 0?"01":i,o=t[4],c=o===void 0?"00":o,d=t[5],u=d===void 0?"00":d,h=t[6],m=h===void 0?"00":h,p=t[7],f=p===void 0?"Z":p,g=t[8],v=g===void 0?"00":g,y=t[9],b=y===void 0?"00":y,w=f==="Z"?"Z":""+f+v+":"+b,S=new Date(n+"-"+a+"-"+l+"T"+c+":"+u+":"+m+w);return S}},Dat=function(s,t){for(var n,r=0,a;r=0&&s<=65535},bYn=function(s){return s>=65536&&s<=1114111},Qss=function(s){return Math.floor((s-65536)/1024)+55296},Jss=function(s){return(s-65536)%1024+56320},PP;(function(s){s.BigEndian="BigEndian",s.LittleEndian="LittleEndian"})(PP||(PP={}));var DZ="�".codePointAt(0),ens=function(s,t){if(t===void 0&&(t=!0),s.length<=1)return String.fromCodePoint(DZ);for(var n=t?wYn(s):PP.BigEndian,r=t?2:0,a=[];s.length-r>=2;){var i=u5t(s[r++],s[r++],n);if(_Yn(i))if(s.length-r<2)a.push(DZ);else{var l=u5t(s[r++],s[r++],n);d5t(l)?a.push(i,l):a.push(DZ)}else d5t(i)?(r+=2,a.push(DZ)):a.push(i)}return r=55296&&s<=56319},d5t=function(s){return s>=56320&&s<=57343},u5t=function(s,t,n){if(n===PP.LittleEndian)return t<<8|s;if(n===PP.BigEndian)return s<<8|t;throw new Error("Invalid byteOrder: "+n)},wYn=function(s){return tns(s)?PP.BigEndian:sns(s)?PP.LittleEndian:PP.BigEndian},tns=function(s){return s[0]===254&&s[1]===255},sns=function(s){return s[0]===255&&s[1]===254},nns=function(s){return tns(s)||sns(s)},jYn=function(s){var t=String(s);if(Math.abs(s)<1){var n=parseInt(s.toString().split("e-")[1]);if(n){var r=s<0;r&&(s*=-1),s*=Math.pow(10,n-1),t="0."+new Array(n).join("0")+s.toString().substring(2),r&&(t="-"+t)}}else{var n=parseInt(s.toString().split("+")[1]);n>20&&(n-=20,s/=Math.pow(10,n),t=s.toString()+new Array(n+1).join("0"))}return t},YCe=function(s){return Math.ceil(s.toString(2).length/8)},s$=function(s){for(var t=new Uint8Array(YCe(s)),n=1;n<=t.length;n++)t[n-1]=s>>(t.length-n)*8;return t},hie=function(s){throw new Error(s)},ZE={};(function(s){var t=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function n(i,l){return Object.prototype.hasOwnProperty.call(i,l)}s.assign=function(i){for(var l=Array.prototype.slice.call(arguments,1);l.length;){var o=l.shift();if(o){if(typeof o!="object")throw new TypeError(o+"must be non-object");for(var c in o)n(o,c)&&(i[c]=o[c])}}return i},s.shrinkBuf=function(i,l){return i.length===l?i:i.subarray?i.subarray(0,l):(i.length=l,i)};var r={arraySet:function(i,l,o,c,d){if(l.subarray&&i.subarray){i.set(l.subarray(o,o+c),d);return}for(var u=0;u=0;)s[t]=0}var CYn=0,rns=1,AYn=2,EYn=3,TYn=258,Rat=29,pie=256,Ose=pie+1+Rat,eV=30,Fat=19,ans=2*Ose+1,$F=15,bBe=16,MYn=7,Oat=256,ins=16,ons=17,lns=18,QYe=[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],ZCe=[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],PYn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],cns=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],LYn=512,rA=new Array((Ose+2)*2);yK(rA);var bee=new Array(eV*2);yK(bee);var zse=new Array(LYn);yK(zse);var Bse=new Array(TYn-EYn+1);yK(Bse);var zat=new Array(Rat);yK(zat);var j6e=new Array(eV);yK(j6e);function _Be(s,t,n,r,a){this.static_tree=s,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=a,this.has_stree=s&&s.length}var dns,uns,hns;function wBe(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}function mns(s){return s<256?zse[s]:zse[256+(s>>>7)]}function $se(s,t){s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255}function T_(s,t,n){s.bi_valid>bBe-n?(s.bi_buf|=t<>bBe-s.bi_valid,s.bi_valid+=n-bBe):(s.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function IYn(s){s.bi_valid===16?($se(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8)}function DYn(s,t){var n=t.dyn_tree,r=t.max_code,a=t.stat_desc.static_tree,i=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length,d,u,h,m,p,f,g=0;for(m=0;m<=$F;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,g++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,p=0,u>=o&&(p=l[u-o]),f=n[u*2],s.opt_len+=f*(m+p),i&&(s.static_len+=f*(a[u*2+1]+p)));if(g!==0){do{for(m=c-1;s.bl_count[m]===0;)m--;s.bl_count[m]--,s.bl_count[m+1]+=2,s.bl_count[c]--,g-=2}while(g>0);for(m=c;m!==0;m--)for(u=s.bl_count[m];u!==0;)h=s.heap[--d],!(h>r)&&(n[h*2+1]!==m&&(s.opt_len+=(m-n[h*2+1])*n[h*2],n[h*2+1]=m),u--)}}function fns(s,t,n){var r=new Array($F+1),a=0,i,l;for(i=1;i<=$F;i++)r[i]=a=a+n[i-1]<<1;for(l=0;l<=t;l++){var o=s[l*2+1];o!==0&&(s[l*2]=pns(r[o]++,o))}}function RYn(){var s,t,n,r,a,i=new Array($F+1);for(n=0,r=0;r>=7;r8?$se(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0}function FYn(s,t,n,r){gns(s),$se(s,n),$se(s,~n),NYn.arraySet(s.pending_buf,s.window,t,n,s.pending),s.pending+=n}function p5t(s,t,n,r){var a=t*2,i=n*2;return s[a]>1;l>=1;l--)jBe(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],jBe(s,n,1),o=s.heap[1],s.heap[--s.heap_max]=l,s.heap[--s.heap_max]=o,n[d*2]=n[l*2]+n[o*2],s.depth[d]=(s.depth[l]>=s.depth[o]?s.depth[l]:s.depth[o])+1,n[l*2+1]=n[o*2+1]=d,s.heap[1]=d++,jBe(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],DYn(s,t),fns(n,c,s.bl_count)}function x5t(s,t,n){var r,a=-1,i,l=t[0*2+1],o=0,c=7,d=4;for(l===0&&(c=138,d=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)i=l,l=t[(r+1)*2+1],!(++o=3&&s.bl_tree[cns[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t}function zYn(s,t,n,r){var a;for(T_(s,t-257,5),T_(s,n-1,5),T_(s,r-4,4),a=0;a>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return h5t;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return m5t;for(n=32;n0?(s.strm.data_type===SYn&&(s.strm.data_type=BYn(s)),JYe(s,s.l_desc),JYe(s,s.d_desc),l=OYn(s),a=s.opt_len+3+7>>>3,i=s.static_len+3+7>>>3,i<=a&&(a=i)):a=i=n+5,n+4<=a&&t!==-1?yns(s,t,n,r):s.strategy===kYn||i===a?(T_(s,(rns<<1)+(r?1:0),3),f5t(s,rA,bee)):(T_(s,(AYn<<1)+(r?1:0),3),zYn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),f5t(s,s.dyn_ltree,s.dyn_dtree)),xns(s),r&&gns(s)}function VYn(s,t,n){return s.pending_buf[s.d_buf+s.last_lit*2]=t>>>8&255,s.pending_buf[s.d_buf+s.last_lit*2+1]=t&255,s.pending_buf[s.l_buf+s.last_lit]=n&255,s.last_lit++,t===0?s.dyn_ltree[n*2]++:(s.matches++,t--,s.dyn_ltree[(Bse[n]+pie+1)*2]++,s.dyn_dtree[mns(t)*2]++),s.last_lit===s.lit_bufsize-1}gK._tr_init=$Yn;gK._tr_stored_block=yns;gK._tr_flush_block=qYn;gK._tr_tally=VYn;gK._tr_align=UYn;function HYn(s,t,n,r){for(var a=s&65535|0,i=s>>>16&65535|0,l=0;n!==0;){l=n>2e3?2e3:n,n-=l;do a=a+t[r++]|0,i=i+a|0;while(--l);a%=65521,i%=65521}return a|i<<16|0}var vns=HYn;function GYn(){for(var s,t=[],n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=s&1?3988292384^s>>>1:s>>>1;t[n]=s}return t}var WYn=GYn();function KYn(s,t,n,r){var a=WYn,i=r+n;s^=-1;for(var l=r;l>>8^a[(s^t[l])&255];return s^-1}var bns=KYn,Bat={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},ub=ZE,CN=gK,_ns=vns,l6=bns,YYn=Bat,Cz=0,ZYn=1,XYn=3,LP=4,v5t=5,P4=0,b5t=1,AN=-2,QYn=-3,NBe=-5,JYn=-1,eZn=1,Cde=2,tZn=3,sZn=4,nZn=0,rZn=2,Y8e=8,aZn=9,iZn=15,oZn=8,lZn=29,cZn=256,eZe=cZn+1+lZn,dZn=30,uZn=19,hZn=2*eZe+1,mZn=15,fu=3,zM=258,AS=zM+fu+1,pZn=32,Z8e=42,tZe=69,XCe=73,QCe=91,JCe=103,UF=113,aQ=666,Ny=1,fie=2,D9=3,vK=4,fZn=3;function BM(s,t){return s.msg=YYn[t],t}function _5t(s){return(s<<1)-(s>4?9:0)}function U6(s){for(var t=s.length;--t>=0;)s[t]=0}function c6(s){var t=s.state,n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(ub.arraySet(s.output,t.pending_buf,t.pending_out,n,s.next_out),s.next_out+=n,t.pending_out+=n,s.total_out+=n,s.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function vv(s,t){CN._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,c6(s.strm)}function Hu(s,t){s.pending_buf[s.pending++]=t}function RZ(s,t){s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255}function xZn(s,t,n,r){var a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,ub.arraySet(t,s.input,s.next_in,a,n),s.state.wrap===1?s.adler=_ns(s.adler,t,a,n):s.state.wrap===2&&(s.adler=l6(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)}function wns(s,t){var n=s.max_chain_length,r=s.strstart,a,i,l=s.prev_length,o=s.nice_match,c=s.strstart>s.w_size-AS?s.strstart-(s.w_size-AS):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+zM,p=d[r+l-1],f=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==f||d[a+l-1]!==p||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;p=d[r+l-1],f=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead}function R9(s){var t=s.w_size,n,r,a,i,l;do{if(i=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-AS)){ub.arraySet(s.window,s.window,t,t,0),s.match_start-=t,s.strstart-=t,s.block_start-=t,r=s.hash_size,n=r;do a=s.head[--n],s.head[n]=a>=t?a-t:0;while(--r);r=t,n=r;do a=s.prev[--n],s.prev[n]=a>=t?a-t:0;while(--r);i+=t}if(s.strm.avail_in===0)break;if(r=xZn(s.strm,s.window,s.strstart+s.lookahead,i),s.lookahead+=r,s.lookahead+s.insert>=fu)for(l=s.strstart-s.insert,s.ins_h=s.window[l],s.ins_h=(s.ins_h<s.pending_buf_size-5&&(n=s.pending_buf_size-5);;){if(s.lookahead<=1){if(R9(s),s.lookahead===0&&t===Cz)return Ny;if(s.lookahead===0)break}s.strstart+=s.lookahead,s.lookahead=0;var r=s.block_start+n;if((s.strstart===0||s.strstart>=r)&&(s.lookahead=s.strstart-r,s.strstart=r,vv(s,!1),s.strm.avail_out===0)||s.strstart-s.block_start>=s.w_size-AS&&(vv(s,!1),s.strm.avail_out===0))return Ny}return s.insert=0,t===LP?(vv(s,!0),s.strm.avail_out===0?D9:vK):(s.strstart>s.block_start&&(vv(s,!1),s.strm.avail_out===0),Ny)}function kBe(s,t){for(var n,r;;){if(s.lookahead=fu&&(s.ins_h=(s.ins_h<=fu)if(r=CN._tr_tally(s,s.strstart-s.match_start,s.match_length-fu),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=fu){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=fu&&(s.ins_h=(s.ins_h<4096)&&(s.match_length=fu-1)),s.prev_length>=fu&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-fu,r=CN._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-fu),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=(s.ins_h<=fu&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+zM;do;while(r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&as.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=fu?(n=CN._tr_tally(s,1,s.match_length-fu),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=CN._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(vv(s,!1),s.strm.avail_out===0))return Ny}return s.insert=0,t===LP?(vv(s,!0),s.strm.avail_out===0?D9:vK):s.last_lit&&(vv(s,!1),s.strm.avail_out===0)?Ny:fie}function vZn(s,t){for(var n;;){if(s.lookahead===0&&(R9(s),s.lookahead===0)){if(t===Cz)return Ny;break}if(s.match_length=0,n=CN._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(vv(s,!1),s.strm.avail_out===0))return Ny}return s.insert=0,t===LP?(vv(s,!0),s.strm.avail_out===0?D9:vK):s.last_lit&&(vv(s,!1),s.strm.avail_out===0)?Ny:fie}function E5(s,t,n,r,a){this.good_length=s,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=a}var wU;wU=[new E5(0,0,0,0,gZn),new E5(4,4,8,4,kBe),new E5(4,5,16,8,kBe),new E5(4,6,32,32,kBe),new E5(4,4,16,16,n$),new E5(8,16,32,32,n$),new E5(8,16,128,128,n$),new E5(8,32,128,256,n$),new E5(32,128,258,1024,n$),new E5(32,258,258,4096,n$)];function bZn(s){s.window_size=2*s.w_size,U6(s.head),s.max_lazy_match=wU[s.level].max_lazy,s.good_match=wU[s.level].good_length,s.nice_match=wU[s.level].nice_length,s.max_chain_length=wU[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=fu-1,s.match_available=0,s.ins_h=0}function _Zn(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y8e,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new ub.Buf16(hZn*2),this.dyn_dtree=new ub.Buf16((2*dZn+1)*2),this.bl_tree=new ub.Buf16((2*uZn+1)*2),U6(this.dyn_ltree),U6(this.dyn_dtree),U6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new ub.Buf16(mZn+1),this.heap=new ub.Buf16(2*eZe+1),U6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new ub.Buf16(2*eZe+1),U6(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function jns(s){var t;return!s||!s.state?BM(s,AN):(s.total_in=s.total_out=0,s.data_type=rZn,t=s.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?Z8e:UF,s.adler=t.wrap===2?0:1,t.last_flush=Cz,CN._tr_init(t),P4)}function Nns(s){var t=jns(s);return t===P4&&bZn(s.state),t}function wZn(s,t){return!s||!s.state||s.state.wrap!==2?AN:(s.state.gzhead=t,P4)}function kns(s,t,n,r,a,i){if(!s)return AN;var l=1;if(t===JYn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>aZn||n!==Y8e||r<8||r>15||t<0||t>9||i<0||i>sZn)return BM(s,AN);r===8&&(r=9);var o=new _Zn;return s.state=o,o.strm=s,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<v5t||t<0)return s?BM(s,AN):AN;if(r=s.state,!s.output||!s.input&&s.avail_in!==0||r.status===aQ&&t!==LP)return BM(s,s.avail_out===0?NBe:AN);if(r.strm=s,n=r.last_flush,r.last_flush=t,r.status===Z8e)if(r.wrap===2)s.adler=0,Hu(r,31),Hu(r,139),Hu(r,8),r.gzhead?(Hu(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Hu(r,r.gzhead.time&255),Hu(r,r.gzhead.time>>8&255),Hu(r,r.gzhead.time>>16&255),Hu(r,r.gzhead.time>>24&255),Hu(r,r.level===9?2:r.strategy>=Cde||r.level<2?4:0),Hu(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Hu(r,r.gzhead.extra.length&255),Hu(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(s.adler=l6(s.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=tZe):(Hu(r,0),Hu(r,0),Hu(r,0),Hu(r,0),Hu(r,0),Hu(r,r.level===9?2:r.strategy>=Cde||r.level<2?4:0),Hu(r,fZn),r.status=UF);else{var l=Y8e+(r.w_bits-8<<4)<<8,o=-1;r.strategy>=Cde||r.level<2?o=0:r.level<6?o=1:r.level===6?o=2:o=3,l|=o<<6,r.strstart!==0&&(l|=pZn),l+=31-l%31,r.status=UF,RZ(r,l),r.strstart!==0&&(RZ(r,s.adler>>>16),RZ(r,s.adler&65535)),s.adler=1}if(r.status===tZe)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=l6(s.adler,r.pending_buf,r.pending-a,a)),c6(s),a=r.pending,r.pending===r.pending_buf_size));)Hu(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(s.adler=l6(s.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=XCe)}else r.status=XCe;if(r.status===XCe)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=l6(s.adler,r.pending_buf,r.pending-a,a)),c6(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=l6(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.gzindex=0,r.status=QCe)}else r.status=QCe;if(r.status===QCe)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=l6(s.adler,r.pending_buf,r.pending-a,a)),c6(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=l6(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.status=JCe)}else r.status=JCe;if(r.status===JCe&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&c6(s),r.pending+2<=r.pending_buf_size&&(Hu(r,s.adler&255),Hu(r,s.adler>>8&255),s.adler=0,r.status=UF)):r.status=UF),r.pending!==0){if(c6(s),s.avail_out===0)return r.last_flush=-1,P4}else if(s.avail_in===0&&_5t(t)<=_5t(n)&&t!==LP)return BM(s,NBe);if(r.status===aQ&&s.avail_in!==0)return BM(s,NBe);if(s.avail_in!==0||r.lookahead!==0||t!==Cz&&r.status!==aQ){var c=r.strategy===Cde?vZn(r,t):r.strategy===tZn?yZn(r,t):wU[r.level].func(r,t);if((c===D9||c===vK)&&(r.status=aQ),c===Ny||c===D9)return s.avail_out===0&&(r.last_flush=-1),P4;if(c===fie&&(t===ZYn?CN._tr_align(r):t!==v5t&&(CN._tr_stored_block(r,0,0,!1),t===XYn&&(U6(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),c6(s),s.avail_out===0))return r.last_flush=-1,P4}return t!==LP?P4:r.wrap<=0?b5t:(r.wrap===2?(Hu(r,s.adler&255),Hu(r,s.adler>>8&255),Hu(r,s.adler>>16&255),Hu(r,s.adler>>24&255),Hu(r,s.total_in&255),Hu(r,s.total_in>>8&255),Hu(r,s.total_in>>16&255),Hu(r,s.total_in>>24&255)):(RZ(r,s.adler>>>16),RZ(r,s.adler&65535)),c6(s),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?P4:b5t)}function kZn(s){var t;return!s||!s.state?AN:(t=s.state.status,t!==Z8e&&t!==tZe&&t!==XCe&&t!==QCe&&t!==JCe&&t!==UF&&t!==aQ?BM(s,AN):(s.state=null,t===UF?BM(s,QYn):P4))}function SZn(s,t){var n=t.length,r,a,i,l,o,c,d,u;if(!s||!s.state||(r=s.state,l=r.wrap,l===2||l===1&&r.status!==Z8e||r.lookahead))return AN;for(l===1&&(s.adler=_ns(s.adler,t,n,0)),r.wrap=0,n>=r.w_size&&(l===0&&(U6(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new ub.Buf8(r.w_size),ub.arraySet(u,t,n-r.w_size,r.w_size,0),t=u,n=r.w_size),o=s.avail_in,c=s.next_in,d=s.input,s.avail_in=n,s.next_in=0,s.input=t,R9(r);r.lookahead>=fu;){a=r.strstart,i=r.lookahead-(fu-1);do r.ins_h=(r.ins_h<=252?6:OT>=248?5:OT>=240?4:OT>=224?3:OT>=192?2:1;Use[254]=Use[254]=1;Az.string2buf=function(s){var t,n,r,a,i,l=s.length,o=0;for(a=0;a>>6,t[i++]=128|n&63):n<65536?(t[i++]=224|n>>>12,t[i++]=128|n>>>6&63,t[i++]=128|n&63):(t[i++]=240|n>>>18,t[i++]=128|n>>>12&63,t[i++]=128|n>>>6&63,t[i++]=128|n&63);return t};function Ans(s,t){if(t<65534&&(s.subarray&&Cns||!s.subarray&&Sns))return String.fromCharCode.apply(null,X8e.shrinkBuf(s,t));for(var n="",r=0;r4){o[r++]=65533,n+=i-1;continue}for(a&=i===2?31:i===3?15:7;i>1&&n1){o[r++]=65533;continue}a<65536?o[r++]=a:(a-=65536,o[r++]=55296|a>>10&1023,o[r++]=56320|a&1023)}return Ans(o,r)};Az.utf8border=function(s,t){var n;for(t=t||s.length,t>s.length&&(t=s.length),n=t-1;n>=0&&(s[n]&192)===128;)n--;return n<0||n===0?t:n+Use[s[n]]>t?n:t};function CZn(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var Ens=CZn,_ee=VC,wee=ZE,sZe=Az,nZe=Bat,AZn=Ens,Tns=Object.prototype.toString,EZn=0,SBe=4,tV=0,w5t=1,j5t=2,TZn=-1,MZn=0,PZn=8;function F9(s){if(!(this instanceof F9))return new F9(s);this.options=wee.assign({level:TZn,method:PZn,chunkSize:16384,windowBits:15,memLevel:8,strategy:MZn,to:""},s||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new AZn,this.strm.avail_out=0;var n=_ee.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==tV)throw new Error(nZe[n]);if(t.header&&_ee.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(typeof t.dictionary=="string"?r=sZe.string2buf(t.dictionary):Tns.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=_ee.deflateSetDictionary(this.strm,r),n!==tV)throw new Error(nZe[n]);this._dict_set=!0}}F9.prototype.push=function(s,t){var n=this.strm,r=this.options.chunkSize,a,i;if(this.ended)return!1;i=t===~~t?t:t===!0?SBe:EZn,typeof s=="string"?n.input=sZe.string2buf(s):Tns.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;do{if(n.avail_out===0&&(n.output=new wee.Buf8(r),n.next_out=0,n.avail_out=r),a=_ee.deflate(n,i),a!==w5t&&a!==tV)return this.onEnd(a),this.ended=!0,!1;(n.avail_out===0||n.avail_in===0&&(i===SBe||i===j5t))&&(this.options.to==="string"?this.onData(sZe.buf2binstring(wee.shrinkBuf(n.output,n.next_out))):this.onData(wee.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||n.avail_out===0)&&a!==w5t);return i===SBe?(a=_ee.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===tV):(i===j5t&&(this.onEnd(tV),n.avail_out=0),!0)};F9.prototype.onData=function(s){this.chunks.push(s)};F9.prototype.onEnd=function(s){s===tV&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=wee.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function $at(s,t){var n=new F9(t);if(n.push(s,!0),n.err)throw n.msg||nZe[n.err];return n.result}function LZn(s,t){return t=t||{},t.raw=!0,$at(s,t)}function IZn(s,t){return t=t||{},t.gzip=!0,$at(s,t)}mie.Deflate=F9;mie.deflate=$at;mie.deflateRaw=LZn;mie.gzip=IZn;var xie={},YS={},Ade=30,DZn=12,RZn=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,f,g,v,y,b,w,S,C,E,P,M,I,D,F;r=t.state,a=t.next_in,D=t.input,i=a+(t.avail_in-5),l=t.next_out,F=t.output,o=l-(n-t.avail_out),c=l+(t.avail_out-257),d=r.dmax,u=r.wsize,h=r.whave,m=r.wnext,p=r.window,f=r.hold,g=r.bits,v=r.lencode,y=r.distcode,b=(1<>>24,f>>>=C,g-=C,C=S>>>16&255,C===0)F[l++]=S&65535;else if(C&16){E=S&65535,C&=15,C&&(g>>=C,g-=C),g<15&&(f+=D[a++]<>>24,f>>>=C,g-=C,C=S>>>16&255,C&16){if(P=S&65535,C&=15,gd){t.msg="invalid distance too far back",r.mode=Ade;break e}if(f>>>=C,g-=C,C=l-o,P>C){if(C=P-C,C>h&&r.sane){t.msg="invalid distance too far back",r.mode=Ade;break e}if(M=0,I=p,m===0){if(M+=u-C,C2;)F[l++]=I[M++],F[l++]=I[M++],F[l++]=I[M++],E-=3;E&&(F[l++]=I[M++],E>1&&(F[l++]=I[M++]))}else{M=l-P;do F[l++]=F[M++],F[l++]=F[M++],F[l++]=F[M++],E-=3;while(E>2);E&&(F[l++]=F[M++],E>1&&(F[l++]=F[M++]))}}else if(C&64){t.msg="invalid distance code",r.mode=Ade;break e}else{S=y[(S&65535)+(f&(1<>3,a-=E,g-=E<<3,f&=(1<=1&&q[p]===0;p--);if(f>p&&(f=p),p===0)return i[l++]=1<<24|64<<16|0,i[l++]=1<<24|64<<16|0,c.bits=1,0;for(m=1;m0&&(t===C5t||p!==1))return-1;for(G[1]=0,u=1;uk5t||t===A5t&&b>S5t)return 1;for(;;){K=u-v,o[h]F?(Z=V[H+o[h]],oe=I[D+o[h]]):(Z=96,oe=0),S=1<>v)+C]=K<<24|Z<<16|oe|0;while(C!==0);for(S=1<>=1;if(S!==0?(w&=S-1,w+=S):w=0,h++,--q[u]===0){if(u===p)break;u=n[r+o[h]]}if(u>f&&(w&P)!==E){for(v===0&&(v=f),M+=m,g=u-v,y=1<k5t||t===A5t&&b>S5t)return 1;E=w&P,i[E]=f<<24|g<<16|M-l|0}}return w!==0&&(i[M+w]=u-v<<24|64<<16|0),c.bits=f,0},cj=ZE,rZe=vns,T5=bns,UZn=RZn,jee=$Zn,qZn=0,Mns=1,Pns=2,E5t=4,VZn=5,Ede=6,O9=0,HZn=1,GZn=2,ON=-2,Lns=-3,Ins=-4,WZn=-5,T5t=8,Dns=1,M5t=2,P5t=3,L5t=4,I5t=5,D5t=6,R5t=7,F5t=8,O5t=9,z5t=10,N6e=11,M3=12,ABe=13,B5t=14,EBe=15,$5t=16,U5t=17,q5t=18,V5t=19,Tde=20,Mde=21,H5t=22,G5t=23,W5t=24,K5t=25,Y5t=26,TBe=27,Z5t=28,X5t=29,Zp=30,Rns=31,KZn=32,YZn=852,ZZn=592,XZn=15,QZn=XZn;function Q5t(s){return(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24)}function JZn(){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 cj.Buf16(320),this.work=new cj.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Fns(s){var t;return!s||!s.state?ON:(t=s.state,s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=Dns,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new cj.Buf32(YZn),t.distcode=t.distdyn=new cj.Buf32(ZZn),t.sane=1,t.back=-1,O9)}function Ons(s){var t;return!s||!s.state?ON:(t=s.state,t.wsize=0,t.whave=0,t.wnext=0,Fns(s))}function zns(s,t){var n,r;return!s||!s.state||(r=s.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?ON:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Ons(s))}function Bns(s,t){var n,r;return s?(r=new JZn,s.state=r,r.window=null,n=zns(s,t),n!==O9&&(s.state=null),n):ON}function eXn(s){return Bns(s,QZn)}var J5t=!0,MBe,PBe;function tXn(s){if(J5t){var t;for(MBe=new cj.Buf32(512),PBe=new cj.Buf32(32),t=0;t<144;)s.lens[t++]=8;for(;t<256;)s.lens[t++]=9;for(;t<280;)s.lens[t++]=7;for(;t<288;)s.lens[t++]=8;for(jee(Mns,s.lens,0,288,MBe,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;jee(Pns,s.lens,0,32,PBe,0,s.work,{bits:5}),J5t=!1}s.lencode=MBe,s.lenbits=9,s.distcode=PBe,s.distbits=5}function $ns(s,t,n,r){var a,i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(cj.arraySet(i.window,t,n-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),cj.arraySet(i.window,t,n-r,a,i.wnext),r-=a,r?(cj.arraySet(i.window,t,n-r,r,0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,n.check=T5(n.check,I,2,0),d=0,u=0,n.mode=M5t;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Zp;break}if((d&15)!==T5t){s.msg="unknown compression method",n.mode=Zp;break}if(d>>>=4,u-=4,P=(d&15)+8,n.wbits===0)n.wbits=P;else if(P>n.wbits){s.msg="invalid window size",n.mode=Zp;break}n.dmax=1<>8&1),n.flags&512&&(I[0]=d&255,I[1]=d>>>8&255,n.check=T5(n.check,I,2,0)),d=0,u=0,n.mode=P5t;case P5t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,I[2]=d>>>16&255,I[3]=d>>>24&255,n.check=T5(n.check,I,4,0)),d=0,u=0,n.mode=L5t;case L5t:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&(I[0]=d&255,I[1]=d>>>8&255,n.check=T5(n.check,I,2,0)),d=0,u=0,n.mode=I5t;case I5t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=T5(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=D5t;case D5t:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),cj.arraySet(n.head.extra,r,i,p,P)),n.flags&512&&(n.check=T5(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=R5t;case R5t:if(n.flags&2048){if(o===0)break e;p=0;do P=r[i+p++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P));while(P&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=M3;break;case z5t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=TBe;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=B5t;break;case 1:if(tXn(n),n.mode=Tde,t===Ede){d>>>=2,u-=2;break e}break;case 2:n.mode=U5t;break;case 3:s.msg="invalid block type",n.mode=Zp}d>>>=2,u-=2;break;case B5t:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Zp;break}if(n.length=d&65535,d=0,u=0,n.mode=EBe,t===Ede)break e;case EBe:n.mode=$5t;case $5t:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;cj.arraySet(a,r,i,p,l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=M3;break;case U5t:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Zp;break}n.have=0,n.mode=q5t;case q5t:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[q[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},M=jee(qZn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid code lengths set",n.mode=Zp;break}n.have=0,n.mode=V5t;case V5t:for(;n.have>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=y,u-=y,n.lens[n.have++]=w;else{if(w===16){for(F=y+2;u>>=y,u-=y,n.have===0){s.msg="invalid bit length repeat",n.mode=Zp;break}P=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(w===17){for(F=y+3;u>>=y,u-=y,P=0,p=3+(d&7),d>>>=3,u-=3}else{for(F=y+7;u>>=y,u-=y,P=0,p=11+(d&127),d>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Zp;break}for(;p--;)n.lens[n.have++]=P}}if(n.mode===Zp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Zp;break}if(n.lenbits=9,D={bits:n.lenbits},M=jee(Mns,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid literal/lengths set",n.mode=Zp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},M=jee(Pns,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,M){s.msg="invalid distances set",n.mode=Zp;break}if(n.mode=Tde,t===Ede)break e;case Tde:n.mode=Mde;case Mde:if(o>=6&&c>=258){s.next_out=l,s.avail_out=c,s.next_in=i,s.avail_in=o,n.hold=d,n.bits=u,UZn(s,m),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,n.mode===M3&&(n.back=-1);break}for(n.back=0;v=n.lencode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,n.length=w,b===0){n.mode=Y5t;break}if(b&32){n.back=-1,n.mode=M3;break}if(b&64){s.msg="invalid literal/length code",n.mode=Zp;break}n.extra=b&15,n.mode=H5t;case H5t:if(n.extra){for(F=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=G5t;case G5t:for(;v=n.distcode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,b&64){s.msg="invalid distance code",n.mode=Zp;break}n.offset=w,n.extra=b&15,n.mode=W5t;case W5t:if(n.extra){for(F=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Zp;break}n.mode=K5t;case K5t:if(c===0)break e;if(p=m-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Zp;break}p>n.wnext?(p-=n.wnext,f=n.wsize-p):f=n.wnext-p,p>n.length&&(p=n.length),g=n.window}else g=a,f=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=g[f++];while(--p);n.length===0&&(n.mode=Mde);break;case Y5t:if(c===0)break e;a[l++]=n.length,c--,n.mode=Mde;break;case TBe:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(s&&s.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new lXn,this.strm.avail_out=0;var n=sV.inflateInit2(this.strm,t.windowBits);if(n!==Qx.Z_OK)throw new Error(aZe[n]);if(this.header=new cXn,sV.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=e3e.string2buf(t.dictionary):qns.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=sV.inflateSetDictionary(this.strm,t.dictionary),n!==Qx.Z_OK)))throw new Error(aZe[n])}z9.prototype.push=function(s,t){var n=this.strm,r=this.options.chunkSize,a=this.options.dictionary,i,l,o,c,d,u=!1;if(this.ended)return!1;l=t===~~t?t:t===!0?Qx.Z_FINISH:Qx.Z_NO_FLUSH,typeof s=="string"?n.input=e3e.binstring2buf(s):qns.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;do{if(n.avail_out===0&&(n.output=new Nee.Buf8(r),n.next_out=0,n.avail_out=r),i=sV.inflate(n,Qx.Z_NO_FLUSH),i===Qx.Z_NEED_DICT&&a&&(i=sV.inflateSetDictionary(this.strm,a)),i===Qx.Z_BUF_ERROR&&u===!0&&(i=Qx.Z_OK,u=!1),i!==Qx.Z_STREAM_END&&i!==Qx.Z_OK)return this.onEnd(i),this.ended=!0,!1;n.next_out&&(n.avail_out===0||i===Qx.Z_STREAM_END||n.avail_in===0&&(l===Qx.Z_FINISH||l===Qx.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=e3e.utf8border(n.output,n.next_out),c=n.next_out-o,d=e3e.buf2string(n.output,o),n.next_out=c,n.avail_out=r-c,c&&Nee.arraySet(n.output,n.output,o,c,0),this.onData(d)):this.onData(Nee.shrinkBuf(n.output,n.next_out))),n.avail_in===0&&n.avail_out===0&&(u=!0)}while((n.avail_in>0||n.avail_out===0)&&i!==Qx.Z_STREAM_END);return i===Qx.Z_STREAM_END&&(l=Qx.Z_FINISH),l===Qx.Z_FINISH?(i=sV.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Qx.Z_OK):(l===Qx.Z_SYNC_FLUSH&&(this.onEnd(Qx.Z_OK),n.avail_out=0),!0)};z9.prototype.onData=function(s){this.chunks.push(s)};z9.prototype.onEnd=function(s){s===Qx.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Nee.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function Uat(s,t){var n=new z9(t);if(n.push(s,!0),n.err)throw n.msg||aZe[n.err];return n.result}function dXn(s,t){return t=t||{},t.raw=!0,Uat(s,t)}xie.Inflate=z9;xie.inflate=Uat;xie.inflateRaw=dXn;xie.ungzip=Uat;var uXn=ZE.assign,hXn=mie,mXn=xie,pXn=Uns,Vns={};uXn(Vns,hXn,mXn,pXn);var fXn=Vns;const Q8e=kd(fXn);var e4t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",iQ=new Uint8Array(256);for(var Pde=0;Pde>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},gXn=function(s){for(var t="",n=0;nr)throw new Error(hy(t)+" must be at least "+n+" and at most "+r+", but was actually "+s)},Ck=function(s,t,n,r){wr(s,t,["number","undefined"]),typeof s=="number"&&dj(s,t,n,r)},Wns=function(s,t,n){if(wr(s,t,["number"]),s%n!==0)throw new Error(hy(t)+" must be a multiple of "+n+", but was actually "+s)},VXn=function(s,t){if(!Number.isInteger(s))throw new Error(hy(t)+" must be an integer, but was actually "+s)},eDe=function(s,t){if(![1,0].includes(Math.sign(s)))throw new Error(hy(t)+" must be a positive number or 0, but was actually "+s)},vc=new Uint16Array(256);for(var Dde=0;Dde<256;Dde++)vc[Dde]=Dde;vc[22]=hc("");vc[24]=hc("˘");vc[25]=hc("ˇ");vc[26]=hc("ˆ");vc[27]=hc("˙");vc[28]=hc("˝");vc[29]=hc("˛");vc[30]=hc("˚");vc[31]=hc("˜");vc[127]=hc("�");vc[128]=hc("•");vc[129]=hc("†");vc[130]=hc("‡");vc[131]=hc("…");vc[132]=hc("—");vc[133]=hc("–");vc[134]=hc("ƒ");vc[135]=hc("⁄");vc[136]=hc("‹");vc[137]=hc("›");vc[138]=hc("−");vc[139]=hc("‰");vc[140]=hc("„");vc[141]=hc("“");vc[142]=hc("”");vc[143]=hc("‘");vc[144]=hc("’");vc[145]=hc("‚");vc[146]=hc("™");vc[147]=hc("fi");vc[148]=hc("fl");vc[149]=hc("Ł");vc[150]=hc("Œ");vc[151]=hc("Š");vc[152]=hc("Ÿ");vc[153]=hc("Ž");vc[154]=hc("ı");vc[155]=hc("ł");vc[156]=hc("œ");vc[157]=hc("š");vc[158]=hc("ž");vc[159]=hc("�");vc[160]=hc("€");vc[173]=hc("�");var Kns=function(s){for(var t=new Array(s.length),n=0,r=s.length;n=rn.ExclamationPoint&&s<=rn.Tilde&&!Gat[s]},o4t={},l4t=new Map,Qs=function(s){di(t,s);function t(n,r){var a=this;if(n!==o4t)throw new qat("PDFName");a=s.call(this)||this;for(var i="/",l=0,o=r.length;l=rn.Zero&&d<=rn.Nine||d>=rn.a&&d<=rn.f||d>=rn.A&&d<=rn.F?(r+=c,(r.length===2||!(u>="0"&&u<="9"||u>="a"&&u<="f"||u>="A"&&u<="F"))&&(i(parseInt(r,16)),r="")):i(d):d===rn.Hash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return String.fromCharCode.apply(String,Array.from(n))},t.prototype.asString=function(){return this.encodedName},t.prototype.value=function(){return this.encodedName},t.prototype.clone=function(){return this},t.prototype.toString=function(){return this.encodedName},t.prototype.sizeInBytes=function(){return this.encodedName.length},t.prototype.copyBytesInto=function(n,r){return r+=yv(this.encodedName,n,r),this.encodedName.length},t.of=function(n){var r=lQn(n),a=l4t.get(r);return a||(a=new t(o4t,r),l4t.set(r,a)),a},t.Length=t.of("Length"),t.FlateDecode=t.of("FlateDecode"),t.Resources=t.of("Resources"),t.Font=t.of("Font"),t.XObject=t.of("XObject"),t.ExtGState=t.of("ExtGState"),t.Contents=t.of("Contents"),t.Type=t.of("Type"),t.Parent=t.of("Parent"),t.MediaBox=t.of("MediaBox"),t.Page=t.of("Page"),t.Annots=t.of("Annots"),t.TrimBox=t.of("TrimBox"),t.ArtBox=t.of("ArtBox"),t.BleedBox=t.of("BleedBox"),t.CropBox=t.of("CropBox"),t.Rotate=t.of("Rotate"),t.Title=t.of("Title"),t.Author=t.of("Author"),t.Subject=t.of("Subject"),t.Creator=t.of("Creator"),t.Keywords=t.of("Keywords"),t.Producer=t.of("Producer"),t.CreationDate=t.of("CreationDate"),t.ModDate=t.of("ModDate"),t}(Cb),dQn=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.asNull=function(){return null},t.prototype.clone=function(){return this},t.prototype.toString=function(){return"null"},t.prototype.sizeInBytes=function(){return 4},t.prototype.copyBytesInto=function(n,r){return n[r++]=rn.n,n[r++]=rn.u,n[r++]=rn.l,n[r++]=rn.l,4},t}(Cb);const __=new dQn;var Ac=function(s){di(t,s);function t(n,r){var a=s.call(this)||this;return a.dict=n,a.context=r,a}return t.prototype.keys=function(){return Array.from(this.dict.keys())},t.prototype.values=function(){return Array.from(this.dict.values())},t.prototype.entries=function(){return Array.from(this.dict.entries())},t.prototype.set=function(n,r){this.dict.set(n,r)},t.prototype.get=function(n,r){r===void 0&&(r=!1);var a=this.dict.get(n);if(!(a===__&&!r))return a},t.prototype.has=function(n){var r=this.dict.get(n);return r!==void 0&&r!==__},t.prototype.lookupMaybe=function(n){for(var r,a=[],i=1;ithis.largestObjectNumber&&(this.largestObjectNumber=t.objectNumber)},s.prototype.nextRef=function(){return this.largestObjectNumber+=1,lh.of(this.largestObjectNumber)},s.prototype.register=function(t){var n=this.nextRef();return this.assign(n,t),n},s.prototype.delete=function(t){return this.indirectObjects.delete(t)},s.prototype.lookupMaybe=function(t){for(var n=[],r=1;r1?(this.subsections.push([t]),this.chunkIdx+=1,this.chunkLength=1):(n.push(t),this.chunkLength+=1)},s.create=function(){return new s({ref:lh.of(0,65535),offset:0,deleted:!0})},s.createEmpty=function(){return new s},s}(),Kat=function(){function s(t){this.lastXRefOffset=String(t)}return s.prototype.toString=function(){return`startxref `+this.lastXRefOffset+` %%EOF`},s.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},s.prototype.copyBytesInto=function(t,n){var r=n;return t[n++]=rn.s,t[n++]=rn.t,t[n++]=rn.a,t[n++]=rn.r,t[n++]=rn.t,t[n++]=rn.x,t[n++]=rn.r,t[n++]=rn.e,t[n++]=rn.f,t[n++]=rn.Newline,n+=yv(this.lastXRefOffset,t,n),t[n++]=rn.Newline,t[n++]=rn.Percent,t[n++]=rn.Percent,t[n++]=rn.E,t[n++]=rn.O,t[n++]=rn.F,n-r},s.forLastCrossRefSectionOffset=function(t){return new s(t)},s}(),mQn=function(){function s(t){this.dict=t}return s.prototype.toString=function(){return`trailer `+this.dict.toString()},s.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},s.prototype.copyBytesInto=function(t,n){var r=n;return t[n++]=rn.t,t[n++]=rn.r,t[n++]=rn.a,t[n++]=rn.i,t[n++]=rn.l,t[n++]=rn.e,t[n++]=rn.r,t[n++]=rn.Newline,n+=this.dict.copyBytesInto(t,n),n-r},s.of=function(t){return new s(t)},s}(),Xns=function(s){di(t,s);function t(n,r,a){a===void 0&&(a=!0);var i=s.call(this,n.obj({}),a)||this;return i.objects=r,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(Qs.of("Type"),Qs.of("ObjStm")),i.dict.set(Qs.of("N"),tc.of(i.objects.length)),i.dict.set(Qs.of("First"),tc.of(i.offsetsString.length)),i}return t.prototype.getObjectsCount=function(){return this.objects.length},t.prototype.clone=function(n){return t.withContextAndObjects(n||this.dict.context,this.objects.slice(),this.encode)},t.prototype.getContentsString=function(){for(var n=this.offsetsString,r=0,a=this.objects.length;r1&&(l.push(o),l.push(u.ref.objectNumber),o=0),o+=1}return l.push(o),l},i.computeEntryTuples=function(){for(var l=new Array(i.entries.length),o=0,c=i.entries.length;oo[0]&&(o[0]=f),g>o[1]&&(o[1]=g),v>o[2]&&(o[2]=v)}return o},i.entries=r||[],i.entryTuplesCache=dE.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=dE.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=dE.populatedBy(i.computeIndex),n.set(Qs.of("Type"),Qs.of("XRef")),i}return t.prototype.addDeletedEntry=function(n,r){var a=A6.Deleted;this.entries.push({type:a,ref:n,nextFreeObjectNumber:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addUncompressedEntry=function(n,r){var a=A6.Uncompressed;this.entries.push({type:a,ref:n,offset:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addCompressedEntry=function(n,r,a){var i=A6.Compressed;this.entries.push({type:i,ref:n,objectStreamRef:r,index:a}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.clone=function(n){var r=this,a=r.dict,i=r.entries,l=r.encode;return t.of(a.clone(n),i.slice(),l)},t.prototype.getContentsString=function(){for(var n=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),a="",i=0,l=n.length;i=0;f--)a+=(h[f]||0).toString(2);for(var f=r[1]-1;f>=0;f--)a+=(m[f]||0).toString(2);for(var f=r[2]-1;f>=0;f--)a+=(p[f]||0).toString(2)}return a},t.prototype.getUnencodedContents=function(){for(var n=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),a=new Uint8Array(this.getUnencodedContentsSize()),i=0,l=0,o=n.length;l=0;g--)a[i++]=m[g]||0;for(var g=r[1]-1;g>=0;g--)a[i++]=p[g]||0;for(var g=r[2]-1;g>=0;g--)a[i++]=f[g]||0}return a},t.prototype.getUnencodedContentsSize=function(){var n=this.maxByteWidthsCache.access(),r=pYn(n);return r*this.entries.length},t.prototype.updateDict=function(){s.prototype.updateDict.call(this);var n=this.maxByteWidthsCache.access(),r=this.indexCache.access(),a=this.dict.context;this.dict.set(Qs.of("W"),a.obj(n)),this.dict.set(Qs.of("Index"),a.obj(r))},t.create=function(n,r){r===void 0&&(r=!0);var a=new t(n,[],r);return a.addDeletedEntry(lh.of(0,65535),0),a},t.of=function(n,r,a){return a===void 0&&(a=!0),new t(n,r,a)},t}(Wat),fQn=function(s){di(t,s);function t(n,r,a,i){var l=s.call(this,n,r)||this;return l.encodeStreams=a,l.objectsPerStream=i,l}return t.prototype.computeBufferSize=function(){return Ic(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d,f,g,u,y,h,m,v,p,f,g,v,y,b,w,S,C;return Dc(this,function(E){switch(E.label){case 0:n=this.context.largestObjectNumber+1,r=tDe.forVersion(1,7),a=r.sizeInBytes()+2,i=pQn.create(this.createTrailerDict(),this.encodeStreams),l=[],o=[],c=[],d=this.context.enumerateIndirectObjects(),f=0,g=d.length,E.label=1;case 1:return f"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=rn.LessThan,r+=yv(this.value,n,r),n[r++]=rn.GreaterThan,this.value.length+2},t.of=function(n){return new t(n)},t.fromText=function(n){for(var r=yYn(n),a="",i=0,l=r.length;i> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange `+s.length+` beginbfchar `+s.map(function(t){var n=t[0],r=t[1];return n+" "+r}).join(` `)+` endbfchar endcmap CMapName currentdict /CMap defineresource pop end end`},h4t=function(){for(var s=[],t=0;t"},t3e=function(s){return die(s,4)},yQn=function(s){if(vYn(s))return t3e(s);if(bYn(s)){var t=Qss(s),n=Jss(s);return""+t3e(t)+t3e(n)}var r=K8e(s),a="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(a)},vQn=function(s){var t=0,n=function(r){t|=1<=rn.Zero&&d<=rn.Seven?(r+=c,(r.length===3||!(u>="0"&&u<="7"))&&(i(parseInt(r,8)),r="")):i(d):d===rn.BackSlash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return nns(n)?ens(n):Kns(n)},t.prototype.decodeDate=function(){var n=this.decodeText(),r=Zss(n);if(!r)throw new Yns(n);return r},t.prototype.asString=function(){return this.value},t.prototype.clone=function(){return t.of(this.value)},t.prototype.toString=function(){return"("+this.value+")"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=rn.LeftParen,r+=yv(this.value,n,r),n[r++]=rn.RightParen,this.value.length+2},t.of=function(n){return new t(n)},t.fromDate=function(n){var r=rS(String(n.getUTCFullYear()),4,"0"),a=rS(String(n.getUTCMonth()+1),2,"0"),i=rS(String(n.getUTCDate()),2,"0"),l=rS(String(n.getUTCHours()),2,"0"),o=rS(String(n.getUTCMinutes()),2,"0"),c=rS(String(n.getUTCSeconds()),2,"0");return new t("D:"+r+a+i+l+o+c+"Z")},t}(Cb),Yat=function(){function s(t,n,r,a){var i=this;this.allGlyphsInFontSortedById=function(){for(var l=new Array(i.font.characterSet.length),o=0,c=l.length;o>3)]>>7-((p&7)<<0)&1,F=3*D;o[w]=S[F],o[w+1]=S[F+1],o[w+2]=S[F+2],o[w+3]=D>2)]>>6-((p&3)<<1)&3,F=3*D;o[w]=S[F],o[w+1]=S[F+1],o[w+2]=S[F+2],o[w+3]=D>1)]>>4-((p&1)<<2)&15,F=3*D;o[w]=S[F],o[w+1]=S[F+1],o[w+2]=S[F+2],o[w+3]=D>>3)]>>>7-(K&7)&1),Z=G==v*255?0:255;c[H+K]=Z<<24|G<<16|G<<8|G}else if(u==2)for(var K=0;K>>2)]>>>6-((K&3)<<1)&3),Z=G==v*85?0:255;c[H+K]=Z<<24|G<<16|G<<8|G}else if(u==4)for(var K=0;K>>1)]>>>4-((K&1)<<2)&15),Z=G==v*17?0:255;c[H+K]=Z<<24|G<<16|G<<8|G}else if(u==8)for(var K=0;K>>2<<3));a==0;){if(a=v(t,m,1),i=v(t,m+1,2),m+=3,i==0){m&7&&(m+=8-(m&7));var M=(m>>>3)+4,I=t[M-4]|t[M-3]<<8;P&&(n=s.H.W(n,h+I)),n.set(new r(t.buffer,t.byteOffset+M,I),h),m=M+I<<3,h+=I;continue}if(P&&(n=s.H.W(n,h+(1<<17))),i==1&&(p=E.J,f=E.h,d=511,u=31),i==2){l=y(t,m,5)+257,o=y(t,m+5,5)+1,c=y(t,m+10,4)+4,m+=14;for(var D=1,F=0;F<38;F+=2)E.Q[F]=0,E.Q[F+1]=0;for(var F=0;FD&&(D=q)}m+=3*c,w(E.Q,D),S(E.Q,D,E.u),p=E.w,f=E.d,m=b(E.u,(1<>>4;if(!(K>>>8))n[h++]=K;else{if(K==256)break;var Z=h+K-254;if(K>264){var oe=E.q[K-257];Z=h+(oe>>>3)+y(t,m,oe&7),m+=oe&7}var re=f[C(t,m)&u];m+=re&15;var ae=re>>>4,J=E.c[ae],te=(J>>>4)+v(t,m,J&15);for(m+=J&15;h>>4;if(h<=15)l[d]=h,d++;else{var m=0,p=0;h==16?(p=3+o(a,i,2),i+=2,m=l[d-1]):h==17?(p=3+o(a,i,3),i+=3):h==18&&(p=11+o(a,i,7),i+=7);for(var f=d+p;d>>1;li&&(i=c),l++}for(;l>1,d=t[o+1],u=c<<4|d,h=n-d,m=t[o]<>>15-n;r[f]=u,m++}},s.H.l=function(t,n){for(var r=s.H.m.r,a=15-n,i=0;i>>a}},s.H.M=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8},s.H.I=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8,t[a+2]|=r>>>16},s.H.e=function(t,n,r){return(t[n>>>3]|t[(n>>>3)+1]<<8)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)},s.H.i=function(t,n){return(t[n>>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16|t[(n>>>3)+3]<<24)>>>(n&7)},s.H.m=function(){var t=Uint16Array,n=Uint32Array;return{K:new t(16),j:new t(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[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],q:new t(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[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],c:new n(32),J:new t(512),_:[],h:new t(32),$:[],w:new t(32768),C:[],v:[],d:new t(32768),D:[],u:new t(512),Q:[],r:new t(32768),s:new n(286),Y:new n(30),a:new n(19),t:new n(15e3),k:new t(65536),g:new t(32768)}}(),function(){for(var t=s.H.m,n=32768,r=0;r>>1|(a&1431655765)<<1,a=(a&3435973836)>>>2|(a&858993459)<<2,a=(a&4042322160)>>>4|(a&252645135)<<4,a=(a&4278255360)>>>8|(a&16711935)<<8,t.r[r]=(a>>>16|a<<16)>>>17}function i(l,o,c){for(;o--!=0;)l.push(0,c)}for(var r=0;r<32;r++)t.q[r]=t.S[r]<<3|t.T[r],t.c[r]=t.p[r]<<4|t.z[r];i(t._,144,8),i(t._,112,9),i(t._,24,7),i(t._,8,8),s.H.n(t._,9),s.H.A(t._,9,t.J),s.H.l(t._,9),i(t.$,32,5),s.H.n(t.$,5),s.H.A(t.$,5,t.h),s.H.l(t.$,5),i(t.Q,19,0),i(t.C,286,0),i(t.D,30,0),i(t.v,320,0)}(),s.H.N}();La.decode._readInterlace=function(s,t){for(var n=t.width,r=t.height,a=La.decode._getBPP(t),i=a>>3,l=Math.ceil(n*a/8),o=new Uint8Array(r*l),c=0,d=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],h=[8,8,8,4,4,2,2],m=[8,8,4,4,2,2,1],p=0;p<7;){for(var f=h[p],g=m[p],v=0,y=0,b=d[p];b>3];I=I>>7-(M&7)&1,o[E*l+(P>>3)]|=I<<7-((P&7)<<0)}if(a==2){var I=s[M>>3];I=I>>6-(M&7)&3,o[E*l+(P>>2)]|=I<<6-((P&3)<<1)}if(a==4){var I=s[M>>3];I=I>>4-(M&7)&15,o[E*l+(P>>1)]|=I<<4-((P&1)<<2)}if(a>=8)for(var D=E*l+P*i,F=0;F>3)+F];M+=a,P+=g}C++,E+=f}v*y!=0&&(c+=y*(1+S)),p=p+1}return o};La.decode._getBPP=function(s){var t=[1,null,3,1,2,null,4][s.ctype];return t*s.depth};La.decode._filterZero=function(s,t,n,r,a){var i=La.decode._getBPP(t),l=Math.ceil(r*i/8),o=La.decode._paeth;i=Math.ceil(i/8);var c=0,d=1,u=s[n],h=0;if(u>1&&(s[n]=[0,0,1][u-2]),u==3)for(h=i;h>>1)&255;for(var m=0;m>>1);for(;h>>1)}else{for(;h>8&255,s[t+1]=n&255},readUint:function(s,t){return s[t]*(256*256*256)+(s[t+1]<<16|s[t+2]<<8|s[t+3])},writeUint:function(s,t,n){s[t]=n>>24&255,s[t+1]=n>>16&255,s[t+2]=n>>8&255,s[t+3]=n&255},readASCII:function(s,t,n){for(var r="",a=0;a=0&&o>=0?(h=p*t+f<<2,m=(o+p)*a+l+f<<2):(h=(-o+p)*t-l+f<<2,m=p*a+f<<2),c==0)r[m]=s[h],r[m+1]=s[h+1],r[m+2]=s[h+2],r[m+3]=s[h+3];else if(c==1){var g=s[h+3]*.00392156862745098,v=s[h]*g,y=s[h+1]*g,b=s[h+2]*g,w=r[m+3]*(1/255),S=r[m]*w,C=r[m+1]*w,E=r[m+2]*w,P=1-g,M=g+w*P,I=M==0?0:1/M;r[m+3]=255*M,r[m+0]=(v+S*P)*I,r[m+1]=(y+C*P)*I,r[m+2]=(b+E*P)*I}else if(c==2){var g=s[h+3],v=s[h],y=s[h+1],b=s[h+2],w=r[m+3],S=r[m],C=r[m+1],E=r[m+2];g==w&&v==S&&y==C&&b==E?(r[m]=0,r[m+1]=0,r[m+2]=0,r[m+3]=0):(r[m]=v,r[m+1]=y,r[m+2]=b,r[m+3]=g)}else if(c==3){var g=s[h+3],v=s[h],y=s[h+1],b=s[h+2],w=r[m+3],S=r[m],C=r[m+1],E=r[m+2];if(g==w&&v==S&&y==C&&b==E)continue;if(g<220&&w>20)return!1}return!0};La.encode=function(s,t,n,r,a,i,l){r==null&&(r=0),l==null&&(l=!1);var o=La.encode.compress(s,t,n,r,[!1,!1,!1,0,l]);return La.encode.compressPNG(o,-1),La.encode._main(o,t,n,a,i)};La.encodeLL=function(s,t,n,r,a,i,l,o){for(var c={ctype:0+(r==1?0:2)+(a==0?0:4),depth:i,frames:[]},d=(r+a)*i,u=d*t,h=0;h1,h=!1,m=33+(u?20:0);if(a.sRGB!=null&&(m+=13),a.pHYs!=null&&(m+=21),s.ctype==3){for(var p=s.plte.length,f=0;f>>24!=255&&(h=!0);m+=8+p*3+4+(h?8+p*1+4:0)}for(var g=0;g>>8&255,P=S>>>16&255;y[d+w+0]=C,y[d+w+1]=E,y[d+w+2]=P}if(d+=p*3,l(y,d,i(y,d-p*3-4,p*3+4)),d+=4,h){l(y,d,p),d+=4,c(y,d,"tRNS"),d+=4;for(var f=0;f>>24&255;d+=p,l(y,d,i(y,d-p-4,p+4)),d+=4}}for(var M=0,g=0;g>2,q>>2));for(var p=0;pH&&Z==V[v-H])K[v]=K[v-H];else{var oe=w[Z];if(oe==null&&(w[Z]=oe=S.length,S.push(Z),S.length>=300))break;K[v]=oe}}}var re=S.length;re<=256&&d==!1&&(re<=2?h=1:re<=4?h=2:re<=16?h=4:h=8,h=Math.max(h,c));for(var p=0;p>1)]|=me[ge+Ee]<<4-(Ee&1)*4;else if(h==2)for(var Ee=0;Ee>2)]|=me[ge+Ee]<<6-(Ee&3)*2;else if(h==1)for(var Ee=0;Ee>3)]|=me[ge+Ee]<<7-(Ee&7)*1}J=ve,u=3,ce=1}else if(y==!1&&b.length==1){for(var ve=new Uint8Array(H*ae*3),Ne=H*ae,v=0;vP&&(P=D),IM&&(M=I))}P==-1&&(C=E=P=M=0),a&&((C&1)==1&&C--,(E&1)==1&&E--);var q=(P-C+1)*(M-E+1);qv&&(v=S),Cy&&(y=C))}v==-1&&(f=g=v=y=0),l&&((f&1)==1&&f--,(g&1)==1&&g--),i={x:f,y:g,width:v-f+1,height:y-g+1};var M=r[a];M.rect=i,M.blend=1,M.img=new Uint8Array(i.width*i.height*4),r[a-1].dispose==0?(La._copyTile(d,t,n,M.img,i.width,i.height,-i.x,-i.y,0),La.encode._prepareDiff(m,t,n,M.img,i)):La._copyTile(m,t,n,M.img,i.width,i.height,-i.x,-i.y,0)};La.encode._prepareDiff=function(s,t,n,r,a){La._copyTile(s,t,n,r,a.width,a.height,-a.x,-a.y,2)};La.encode._filterZero=function(s,t,n,r,a,i,l){var o=[],c=[0,1,2,3,4];i!=-1?c=[i]:(t*r>5e5||n==1)&&(c=[0]);var d;l&&(d={level:0});for(var u=l&&UZIP!=null?UZIP:Q8e,h=0;h>1)+256&255;if(i==4)for(var d=a;d>1)&255;for(var d=a;d>1)&255}if(i==4){for(var d=0;d>>1:n=n>>>1;s[t]=n}return s}(),update:function(s,t,n,r){for(var a=0;a>>8;return s},crc:function(s,t,n){return La.crc.update(4294967295,s,t,n)^4294967295}};La.quantize=function(s,t){var n=new Uint8Array(s),r=n.slice(0),a=new Uint32Array(r.buffer),i=La.quantize.getKDtree(r,t),l=i[0],o=i[1];La.quantize.planeDst;for(var c=n,d=a,u=c.length,h=new Uint8Array(n.length>>2),m=0;m>2]=y.ind,d[m>>2]=y.est.rgba}return{abuf:r.buffer,inds:h,plte:o}};La.quantize.getKDtree=function(s,t,n){n==null&&(n=1e-4);var r=new Uint32Array(s.buffer),a={i0:0,i1:s.length,bst:null,est:null,tdst:0,left:null,right:null};a.bst=La.quantize.stats(s,a.i0,a.i1),a.est=La.quantize.estats(a.bst);for(var i=[a];i.lengthl&&(l=i[c].est.L,o=c);if(l=u||d.i1<=u;if(h){d.est.L=0;continue}var m={i0:d.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};m.bst=La.quantize.stats(s,m.i0,m.i1),m.est=La.quantize.estats(m.bst);var p={i0:u,i1:d.i1,bst:null,est:null,tdst:0,left:null,right:null};p.bst={R:[],m:[],N:d.bst.N-m.bst.N};for(var c=0;c<16;c++)p.bst.R[c]=d.bst.R[c]-m.bst.R[c];for(var c=0;c<4;c++)p.bst.m[c]=d.bst.m[c]-m.bst.m[c];p.est=La.quantize.estats(p.bst),d.left=m,d.right=p,i[o]=m,i.push(p)}i.sort(function(f,g){return g.bst.N-f.bst.N});for(var c=0;c0&&(l=s.right,o=s.left);var c=La.quantize.getNearest(l,t,n,r,a);if(c.tdst<=i*i)return c;var d=La.quantize.getNearest(o,t,n,r,a);return d.tdsti;)r-=4;if(n>=r)break;var o=t[n>>2];t[n>>2]=t[r>>2],t[r>>2]=o,n+=4,r-=4}for(;l(s,n,a)>i;)n-=4;return n+4};La.quantize.vecDot=function(s,t,n){return s[t]*n[0]+s[t+1]*n[1]+s[t+2]*n[2]+s[t+3]*n[3]};La.quantize.stats=function(s,t,n){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=[0,0,0,0],i=n-t>>2,l=t;l>>0}};La.M4={multVec:function(s,t){return[s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3],s[4]*t[0]+s[5]*t[1]+s[6]*t[2]+s[7]*t[3],s[8]*t[0]+s[9]*t[1]+s[10]*t[2]+s[11]*t[3],s[12]*t[0]+s[13]*t[1]+s[14]*t[2]+s[15]*t[3]]},dot:function(s,t){return s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3]},sml:function(s,t){return[s*t[0],s*t[1],s*t[2],s*t[3]]}};La.encode.concatRGBA=function(s){for(var t=0,n=0;n1)throw new Error("Animated PNGs are not supported");var a=new Uint8Array(r[0]),i=kQn(a),l=i.rgbChannel,o=i.alphaChannel;this.rgbChannel=l;var c=o.some(function(d){return d<255});c&&(this.alphaChannel=o),this.type=NQn(n.ctype),this.width=n.width,this.height=n.height,this.bitsPerComponent=8}return s.load=function(t){return new s(t)},s}(),trs=function(){function s(t){this.image=t,this.bitsPerComponent=t.bitsPerComponent,this.width=t.width,this.height=t.height,this.colorSpace="DeviceRGB"}return s.for=function(t){return Ic(this,void 0,void 0,function(){var n;return Dc(this,function(r){return n=SQn.load(t),[2,new s(n)]})})},s.prototype.embedIntoContext=function(t,n){return Ic(this,void 0,void 0,function(){var r,a;return Dc(this,function(i){return r=this.embedAlphaChannel(t),a=t.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:r}),n?(t.assign(n,a),[2,n]):[2,t.register(a)]})})},s.prototype.embedAlphaChannel=function(t){if(this.image.alphaChannel){var n=t.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return t.register(n)}},s}(),srs=function(){function s(t,n,r){this.bytes=t,this.start=n||0,this.pos=this.start,this.end=n&&r?n+r:this.bytes.length}return Object.defineProperty(s.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),s.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},s.prototype.getUint16=function(){var t=this.getByte(),n=this.getByte();return t===-1||n===-1?-1:(t<<8)+n},s.prototype.getInt32=function(){var t=this.getByte(),n=this.getByte(),r=this.getByte(),a=this.getByte();return(t<<24)+(n<<16)+(r<<8)+a},s.prototype.getBytes=function(t,n){n===void 0&&(n=!1);var r=this.bytes,a=this.pos,i=this.end;if(t){var o=a+t;o>i&&(o=i),this.pos=o;var l=r.subarray(a,o);return n?new Uint8ClampedArray(l):l}else{var l=r.subarray(a,i);return n?new Uint8ClampedArray(l):l}},s.prototype.peekByte=function(){var t=this.getByte();return this.pos--,t},s.prototype.peekBytes=function(t,n){n===void 0&&(n=!1);var r=this.getBytes(t,n);return this.pos-=r.length,r},s.prototype.skip=function(t){t||(t=1),this.pos+=t},s.prototype.reset=function(){this.pos=this.start},s.prototype.moveStart=function(){this.start=this.pos},s.prototype.makeSubStream=function(t,n){return new s(this.bytes,t,n)},s.prototype.decode=function(){return this.bytes},s}(),CQn=new Uint8Array(0),gie=function(){function s(t){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=CQn,this.minBufferLength=512,t)for(;this.minBufferLengthi&&(r=i)}else{for(;!this.eof;)this.readBlock();r=this.bufferLength}this.pos=r;var l=this.buffer.subarray(a,r);return n&&!(l instanceof Uint8ClampedArray)?new Uint8ClampedArray(l):l},s.prototype.peekByte=function(){var t=this.getByte();return this.pos--,t},s.prototype.peekBytes=function(t,n){n===void 0&&(n=!1);var r=this.getBytes(t,n);return this.pos-=r.length,r},s.prototype.skip=function(t){t||(t=1),this.pos+=t},s.prototype.reset=function(){this.pos=0},s.prototype.makeSubStream=function(t,n){for(var r=t+n;this.bufferLength<=r&&!this.eof;)this.readBlock();return new srs(this.buffer,t,n)},s.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},s.prototype.readBlock=function(){throw new hN(this.constructor.name,"readBlock")},s.prototype.ensureBuffer=function(t){var n=this.buffer;if(t<=n.byteLength)return n;for(var r=this.minBufferLength;r=0;--d)c[o+d]=h&255,h>>=8}},t}(gie),EQn=function(s){di(t,s);function t(n,r){var a=s.call(this,r)||this;return a.stream=n,a.firstDigit=-1,r&&(r=.5*r),a}return t.prototype.readBlock=function(){var n=8e3,r=this.stream.getBytes(n);if(!r.length){this.eof=!0;return}for(var a=r.length+1>>1,i=this.ensureBuffer(this.bufferLength+a),l=this.bufferLength,o=this.firstDigit,c=0,d=r.length;c=48&&u<=57)h=u&15;else if(u>=65&&u<=70||u>=97&&u<=102)h=(u&15)+9;else if(u===62){this.eof=!0;break}else continue;o<0?o=h:(i[l++]=o<<4|h,o=-1)}o>=0&&this.eof&&(i[l++]=o<<4,o=-1),this.firstDigit=o,this.bufferLength=l},t}(gie),f4t=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),TQn=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),MQn=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),PQn=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],LQn=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],IQn=function(s){di(t,s);function t(n,r){var a=s.call(this,r)||this;a.stream=n;var i=n.getByte(),l=n.getByte();if(i===-1||l===-1)throw new Error("Invalid header in flate stream: "+i+", "+l);if((i&15)!==8)throw new Error("Unknown compression method in flate stream: "+i+", "+l);if(((i<<8)+l)%31!==0)throw new Error("Bad FCHECK in flate stream: "+i+", "+l);if(l&32)throw new Error("FDICT bit set in flate stream: "+i+", "+l);return a.codeSize=0,a.codeBuf=0,a}return t.prototype.readBlock=function(){var n,r,a=this.stream,i=this.getBits(3);if(i&1&&(this.eof=!0),i>>=1,i===0){var l=void 0;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");var o=l;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");if(o|=l<<8,(l=a.getByte())===-1)throw new Error("Bad block header in flate stream");var c=l;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");if(c|=l<<8,c!==(~o&65535)&&(o!==0||c!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var d=this.bufferLength;n=this.ensureBuffer(d+o);var u=d+o;if(this.bufferLength=u,o===0)a.peekByte()===-1&&(this.eof=!0);else for(var h=d;h0;)C[b++]=M}m=this.generateHuffmanTable(C.subarray(0,f)),p=this.generateHuffmanTable(C.subarray(f,S))}else throw new Error("Unknown block type in flate stream");n=this.buffer;for(var F=n?n.length:0,q=this.bufferLength;;){var G=this.getCode(m);if(G<256){q+1>=F&&(n=this.ensureBuffer(q+1),F=n.length),n[q++]=G;continue}if(G===256){this.bufferLength=q;return}G-=257,G=TQn[G];var V=G>>16;V>0&&(V=this.getBits(V)),r=(G&65535)+V,G=this.getCode(p),G=MQn[G],V=G>>16,V>0&&(V=this.getBits(V));var H=(G&65535)+V;q+r>=F&&(n=this.ensureBuffer(q+r),F=n.length);for(var K=0;K>n,this.codeSize=a-=n,l},t.prototype.getCode=function(n){for(var r=this.stream,a=n[0],i=n[1],l=this.codeSize,o=this.codeBuf,c;l>16,h=d&65535;if(u<1||l>u,this.codeSize=l-u,h},t.prototype.generateHuffmanTable=function(n){var r=n.length,a=0,i;for(i=0;ia&&(a=n[i]);for(var l=1<>=1;for(i=m;i0;if(!C||C<256)v[0]=C,y=1;else if(C>=258)if(C=0;l--)v[l]=h[o],o=p[o];else v[y++]=v[0];else if(C===256){f=9,u=258,y=0;continue}else{this.eof=!0,delete this.lzwState;break}if(E&&(p[u]=g,m[u]=m[g]+1,h[u]=v[0],u++,f=u+d&u+d-1?f:Math.min(Math.log(u+d)/.6931471805599453+1,12)|0),g=C,b+=y,r>>r&(1<0){var l=this.stream.getBytes(i);r.set(l,a),a+=i}}else{i=257-i;var o=n[1];r=this.ensureBuffer(a+i+1);for(var c=0;cr.size())throw new S6e(n,0,r.size());r.remove(n)}else{if(n!==0)throw new S6e(n,0,0);this.setKids([])}},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([this.ref]),this.dict.set(Qs.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t}(ars),Zat=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(Qs.of("Opt"),ih,Ol,Ru)},t.prototype.setOpt=function(n){this.dict.set(Qs.of("Opt"),this.dict.context.obj(n))},t.prototype.getExportValues=function(){var n=this.Opt();if(n){if(n instanceof ih||n instanceof Ol)return[n];for(var r=[],a=0,i=n.size();ar.size())throw new S6e(n,0,r.size());r.remove(n)}},t.prototype.normalizeExportValues=function(){for(var n,r,a,i,l=(n=this.getExportValues())!==null&&n!==void 0?n:[],o=[],c=this.getWidgets(),d=0,u=c.length;d1){if(!this.hasFlag(rh.MultiSelect))throw new ZXn;this.dict.set(Qs.of("V"),this.dict.context.obj(n))}this.updateSelectedIndices(n)},t.prototype.valuesAreValid=function(n){for(var r=this.getOptions(),a=function(c,d){var u=n[c].decodeText();if(!r.find(function(h){return u===(h.display||h.value).decodeText()}))return{value:!1}},i=0,l=n.length;i1){for(var r=new Array(n.length),a=this.getOptions(),i=function(c,d){var u=n[c].decodeText();r[c]=a.findIndex(function(h){return u===(h.display||h.value).decodeText()})},l=0,o=n.length;l0){var o=l.lookup(0,ih,Ol),c=l.lookupMaybe(1,ih,Ol);r.push({value:o,display:c||o})}}return r}return[]},t}(bK),nDe=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Ch",Ff:rh.Combo,Kids:[]}),a=n.register(r);return new t(r,a)},t}(irs),E6e=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.addField=function(n){var r=this.normalizedEntries().Kids;r==null||r.push(n)},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([]),this.dict.set(Qs.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({}),a=n.register(r);return new t(r,a)},t}(ars),Xat=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t}(bK),rDe=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var n=this.dict.lookup(Qs.of("MaxLen"));if(n instanceof tc)return n},t.prototype.Q=function(){var n=this.dict.lookup(Qs.of("Q"));if(n instanceof tc)return n},t.prototype.setMaxLength=function(n){this.dict.set(Qs.of("MaxLen"),tc.of(n))},t.prototype.removeMaxLength=function(){this.dict.delete(Qs.of("MaxLen"))},t.prototype.getMaxLength=function(){var n;return(n=this.MaxLen())===null||n===void 0?void 0:n.asNumber()},t.prototype.setQuadding=function(n){this.dict.set(Qs.of("Q"),tc.of(n))},t.prototype.getQuadding=function(){var n;return(n=this.Q())===null||n===void 0?void 0:n.asNumber()},t.prototype.setValue=function(n){this.dict.set(Qs.of("V"),n)},t.prototype.removeValue=function(){this.dict.delete(Qs.of("V"))},t.prototype.getValue=function(){var n=this.V();if(n instanceof ih||n instanceof Ol)return n},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Tx",Kids:[]}),a=n.register(r);return new t(r,a)},t}(bK),aDe=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Btn",Ff:X2.PushButton,Kids:[]}),a=n.register(r);return new t(r,a)},t}(Zat),iDe=function(s){di(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.setValue=function(n){var r=this.getOnValues();if(!r.includes(n)&&n!==Qs.of("Off"))throw new Hat;this.dict.set(Qs.of("V"),n);for(var a=this.getWidgets(),i=0,l=a.length;ii)throw new r4t(r,i);for(var l=r,o=0,c=a.size();ol)return u.insertLeafNode(n,l)||d;l-=u.Count().asNumber()}u instanceof uE&&(l-=1)}if(l===0){this.insertLeafKid(a.size(),n);return}throw new a4t(r,"insertLeafNode")},t.prototype.removeLeafNode=function(n,r){r===void 0&&(r=!0);var a=this.Kids(),i=this.Count().asNumber();if(n>=i)throw new r4t(n,i);for(var l=n,o=0,c=a.size();ol){u.removeLeafNode(l,r),r&&u.Kids().size()===0&&a.remove(o);return}else l-=u.Count().asNumber();if(u instanceof uE)if(l===0){this.removeKid(o);return}else l-=1}throw new a4t(n,"removeLeafNode")},t.prototype.ascend=function(n){n(this);var r=this.Parent();r&&r.ascend(n)},t.prototype.traverse=function(n){for(var r=this.Kids(),a=0,i=r.size();aNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var a="Parsed number that is too large for some PDF readers: "+t+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(a),Number.MAX_SAFE_INTEGER}else{var a="Parsed number that is too large for some PDF readers: "+t+", not capping.";console.warn(a)}return r},s.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&XE[this.bytes.peek()];)this.bytes.next()},s.prototype.skipLine=function(){for(;!this.bytes.done();){var t=this.bytes.peek();if(t===y4t||t===v4t)return;this.bytes.next()}},s.prototype.skipComment=function(){if(this.bytes.peek()!==rn.Percent)return!1;for(;!this.bytes.done();){var t=this.bytes.peek();if(t===y4t||t===v4t)return!0;this.bytes.next()}return!0},s.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},s.prototype.matchKeyword=function(t){for(var n=this.bytes.offset(),r=0,a=t.length;r=this.length},s.prototype.offset=function(){return this.idx},s.prototype.slice=function(t,n){return this.bytes.slice(t,n)},s.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},s.of=function(t){return new s(t)},s.fromPDFRawStream=function(t){return s.of(nrs(t).decode())},s}(),WQn=rn.Space,zZ=rn.CarriageReturn,BZ=rn.Newline,$Z=[rn.s,rn.t,rn.r,rn.e,rn.a,rn.m],Fde=[rn.e,rn.n,rn.d,rn.s,rn.t,rn.r,rn.e,rn.a,rn.m],nm={header:[rn.Percent,rn.P,rn.D,rn.F,rn.Dash],eof:[rn.Percent,rn.Percent,rn.E,rn.O,rn.F],obj:[rn.o,rn.b,rn.j],endobj:[rn.e,rn.n,rn.d,rn.o,rn.b,rn.j],xref:[rn.x,rn.r,rn.e,rn.f],trailer:[rn.t,rn.r,rn.a,rn.i,rn.l,rn.e,rn.r],startxref:[rn.s,rn.t,rn.a,rn.r,rn.t,rn.x,rn.r,rn.e,rn.f],true:[rn.t,rn.r,rn.u,rn.e],false:[rn.f,rn.a,rn.l,rn.s,rn.e],null:[rn.n,rn.u,rn.l,rn.l],stream:$Z,streamEOF1:xu($Z,[WQn,zZ,BZ]),streamEOF2:xu($Z,[zZ,BZ]),streamEOF3:xu($Z,[zZ]),streamEOF4:xu($Z,[BZ]),endstream:Fde,EOF1endstream:xu([zZ,BZ],Fde),EOF2endstream:xu([zZ],Fde),EOF3endstream:xu([BZ],Fde)},urs=function(s){di(t,s);function t(n,r,a){a===void 0&&(a=!1);var i=s.call(this,n,a)||this;return i.context=r,i}return t.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(nm.true))return Vse.True;if(this.matchKeyword(nm.false))return Vse.False;if(this.matchKeyword(nm.null))return __;var n=this.bytes.peek();if(n===rn.LessThan&&this.bytes.peekAhead(1)===rn.LessThan)return this.parseDictOrStream();if(n===rn.LessThan)return this.parseHexString();if(n===rn.LeftParen)return this.parseString();if(n===rn.ForwardSlash)return this.parseName();if(n===rn.LeftSquareBracket)return this.parseArray();if(eit[n])return this.parseNumberOrRef();throw new eQn(this.bytes.position(),n)},t.prototype.parseNumberOrRef=function(){var n=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(j1[this.bytes.peek()]){var a=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===rn.R)return this.bytes.assertNext(rn.R),lh.of(n,a)}return this.bytes.moveTo(r),tc.of(n)},t.prototype.parseHexString=function(){var n="";for(this.bytes.assertNext(rn.LessThan);!this.bytes.done()&&this.bytes.peek()!==rn.GreaterThan;)n+=cE(this.bytes.next());return this.bytes.assertNext(rn.GreaterThan),Ol.of(n)},t.prototype.parseString=function(){for(var n=0,r=!1,a="";!this.bytes.done();){var i=this.bytes.next();if(a+=cE(i),r||(i===rn.LeftParen&&(n+=1),i===rn.RightParen&&(n-=1)),i===rn.BackSlash?r=!r:r&&(r=!1),n===0)return ih.of(a.substring(1,a.length-1))}throw new nQn(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(rn.ForwardSlash);for(var n="";!this.bytes.done();){var r=this.bytes.peek();if(XE[r]||XN[r])break;n+=cE(r),this.bytes.next()}return Qs.of(n)},t.prototype.parseArray=function(){this.bytes.assertNext(rn.LeftSquareBracket),this.skipWhitespaceAndComments();for(var n=Ru.withContext(this.context);this.bytes.peek()!==rn.RightSquareBracket;){var r=this.parseObject();n.push(r),this.skipWhitespaceAndComments()}return this.bytes.assertNext(rn.RightSquareBracket),n},t.prototype.parseDict=function(){this.bytes.assertNext(rn.LessThan),this.bytes.assertNext(rn.LessThan),this.skipWhitespaceAndComments();for(var n=new Map;!this.bytes.done()&&this.bytes.peek()!==rn.GreaterThan&&this.bytes.peekAhead(1)!==rn.GreaterThan;){var r=this.parseName(),a=this.parseObject();n.set(r,a),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(rn.GreaterThan),this.bytes.assertNext(rn.GreaterThan);var i=n.get(Qs.of("Type"));return i===Qs.of("Catalog")?crs.fromMapWithContext(n,this.context):i===Qs.of("Pages")?drs.fromMapWithContext(n,this.context):i===Qs.of("Page")?uE.fromMapWithContext(n,this.context):Ac.fromMapWithContext(n,this.context)},t.prototype.parseDictOrStream=function(){var n=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(nm.streamEOF1)&&!this.matchKeyword(nm.streamEOF2)&&!this.matchKeyword(nm.streamEOF3)&&!this.matchKeyword(nm.streamEOF4)&&!this.matchKeyword(nm.stream))return r;var a=this.bytes.offset(),i,l=r.get(Qs.of("Length"));l instanceof tc?(i=a+l.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(nm.endstream)||(this.bytes.moveTo(a),i=this.findEndOfStreamFallback(n))):i=this.findEndOfStreamFallback(n);var o=this.bytes.slice(a,i);return Hse.of(r,o)},t.prototype.findEndOfStreamFallback=function(n){for(var r=1,a=this.bytes.offset();!this.bytes.done()&&(a=this.bytes.offset(),this.matchKeyword(nm.stream)?r+=1:this.matchKeyword(nm.EOF1endstream)||this.matchKeyword(nm.EOF2endstream)||this.matchKeyword(nm.EOF3endstream)||this.matchKeyword(nm.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new sQn(n);return a},t.forBytes=function(n,r,a){return new t(cDe.of(n),r,a)},t.forByteStream=function(n,r,a){return a===void 0&&(a=!1),new t(n,r,a)},t}(GQn),KQn=function(s){di(t,s);function t(n,r){var a=s.call(this,cDe.fromPDFRawStream(n),n.dict.context)||this,i=n.dict;return a.alreadyParsed=!1,a.shouldWaitForTick=r||function(){return!1},a.firstOffset=i.lookup(Qs.of("First"),tc).asNumber(),a.objectCount=i.lookup(Qs.of("N"),tc).asNumber(),a}return t.prototype.parseIntoContext=function(){return Ic(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d;return Dc(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new Vat("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,n=this.parseOffsetsAndObjectNumbers(),r=0,a=n.length,u.label=1;case 1:return r=rn.Space&&r<=rn.Tilde;if(a&&(this.matchKeyword(nm.xref)||this.matchKeyword(nm.trailer)||this.matchKeyword(nm.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(n);break}this.bytes.next()}},t.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var n=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(n)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},t.forBytesWithOptions=function(n,r,a,i){return new t(n,r,a,i)},t}(urs),M5=function(s){return 1<0&&(r[r.length]=+a),n[n.length]={cmd:t,args:r},r=[],a="",i=!1),t=d;else if([" ",","].includes(d)||d==="-"&&a.length>0&&a[a.length-1]!=="e"||d==="."&&i){if(a.length===0)continue;r.length===l?(n[n.length]={cmd:t,args:r},r=[+a],t==="M"&&(t="L"),t==="m"&&(t="l")):r[r.length]=+a,i=d===".",a=["-","."].includes(d)?d:""}else a+=d,d==="."&&(i=!0)}return a.length>0&&(r.length===l?(n[n.length]={cmd:t,args:r},r=[+a],t==="M"&&(t="L"),t==="m"&&(t="l")):r[r.length]=+a),n[n.length]={cmd:t,args:r},n},cJn=function(s){Uo=qo=Xd=Qd=oQ=lQ=0;for(var t=[],n=0;n1&&(m=Math.sqrt(m),n*=m,r*=m);var p=h/n,f=u/n,g=-u/r,v=h/r,y=p*o+f*c,b=g*o+v*c,w=p*s+f*t,S=g*s+v*t,C=(w-y)*(w-y)+(S-b)*(S-b),E=1/C-.25;E<0&&(E=0);var P=Math.sqrt(E);i===a&&(P=-P);var M=.5*(y+w)-P*(S-b),I=.5*(b+S)+P*(w-y),D=Math.atan2(b-I,y-M),F=Math.atan2(S-I,w-M),q=F-D;q<0&&i===1?q+=2*Math.PI:q>0&&i===0&&(q-=2*Math.PI);for(var G=Math.ceil(Math.abs(q/(Math.PI*.5+.001))),V=[],H=0;Hs.length)return a-1;var v=t.heightAtSize(a),y=v+v*.2,b=y*i;if(b>Math.abs(n.height))return a-1;a+=1}return a},MJn=function(s,t,n,r){for(var a=n.width/r,i=n.height,l=Ers,o=iYn(s);la*.75;if(h)return l-1}var m=t.heightAtSize(l,{descender:!1});if(m>i)return l-1;l+=1}return l},PJn=function(s){for(var t=s.length;t>0;t--)if(/\s/.test(s[t]))return t},LJn=function(s,t,n,r){for(var a,i=s.length;i>0;){var l=s.substring(0,i),o=n.encodeText(l),c=n.widthOfTextAtSize(l,r);if(cm&&(m=P+C),f+o>p&&(p=f+o),d.push({text:w,encoded:S,width:C,height:o,x:P,y:f}),y=E==null?void 0:E.trim()}return{fontSize:r,lineHeight:c,lines:d,bounds:{x:u,y:h,width:m-u,height:p-h}}},IJn=function(s,t){var n=t.fontSize,r=t.font,a=t.bounds,i=t.cellCount,l=Kss(uie(s));if(l.length>i)throw new AJn(l.length,i);(n===void 0||n===0)&&(n=MJn(l,r,a,i));for(var o=a.width/i,c=r.heightAtSize(n,{descender:!1}),d=a.y+(a.height/2-c/2),u=[],h=a.x,m=a.y,p=a.x+a.width,f=a.y+a.height,g=0,v=0;gp&&(p=P+C),d+c>f&&(f=d+c),u.push({text:l,encoded:S,width:C,height:c,x:P,y:d}),g+=1,v+=w}return{fontSize:n,cells:u,bounds:{x:h,y:m,width:p-h,height:f-m}}},D6e=function(s,t){var n=t.alignment,r=t.fontSize,a=t.font,i=t.bounds,l=Kss(uie(s));(r===void 0||r===0)&&(r=Mrs([l],a,i));var o=a.encodeText(l),c=a.widthOfTextAtSize(l,r),d=a.heightAtSize(r,{descender:!1}),u=n===gy.Left?i.x:n===gy.Center?i.x+i.width/2-c/2:n===gy.Right?i.x+i.width-c:i.x,h=i.y+(i.height/2-d/2);return{fontSize:r,line:{text:l,encoded:o,width:c,height:d,x:u,y:h},bounds:{x:u,y:h,width:c,height:d}}},wK=function(s){return"normal"in s?s:{normal:s}},DJn=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,iL=function(s){var t,n,r=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",a=(n=Dat(r,DJn).match)!==null&&n!==void 0?n:[],i=Number(a[2]);return isFinite(i)?i:void 0},RJn=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,zN=function(s){var t,n=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",r=Dat(n,RJn).match,a=r??[],i=a[1],l=a[2],o=a[3],c=a[4],d=a[5];if(d==="g"&&i)return Nrs(Number(i));if(d==="rg"&&i&&l&&o)return zu(Number(i),Number(l),Number(o));if(d==="k"&&i&&l&&o&&c)return krs(Number(i),Number(l),Number(o),Number(c))},BN=function(s,t,n,r){var a;r===void 0&&(r=0);var i=[Mz(t).toString(),rit((a=n==null?void 0:n.name)!==null&&a!==void 0?a:"dummy__noop",r).toString()].join(` `);s.setDefaultAppearance(i)},FJn=function(s,t){var n,r,a,i=zN(t),l=zN(s.acroField),o=t.getRectangle(),c=t.getAppearanceCharacteristics(),d=t.getBorderStyle(),u=(n=d==null?void 0:d.getWidth())!==null&&n!==void 0?n:0,h=QE(c==null?void 0:c.getRotation()),m=Ez(o,h),p=m.width,f=m.height,g=YL(pc(pc({},o),{rotation:h})),v=zu(0,0,0),y=(r=Ab(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:v,b=Ab(c==null?void 0:c.getBackgroundColor()),w=Ab(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:v;BN(i?t:s.acroField,S);var C={x:0+u/2,y:0+u/2,width:p-u,height:f-u,thickness:1.5,borderWidth:u,borderColor:y,markColor:S};return{normal:{on:xu(g,Bde(pc(pc({},C),{color:b,filled:!0}))),off:xu(g,Bde(pc(pc({},C),{color:b,filled:!1})))},down:{on:xu(g,Bde(pc(pc({},C),{color:w,filled:!0}))),off:xu(g,Bde(pc(pc({},C),{color:w,filled:!1})))}}},OJn=function(s,t){var n,r,a,i=zN(t),l=zN(s.acroField),o=t.getRectangle(),c=t.getAppearanceCharacteristics(),d=t.getBorderStyle(),u=(n=d==null?void 0:d.getWidth())!==null&&n!==void 0?n:0,h=QE(c==null?void 0:c.getRotation()),m=Ez(o,h),p=m.width,f=m.height,g=YL(pc(pc({},o),{rotation:h})),v=zu(0,0,0),y=(r=Ab(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:v,b=Ab(c==null?void 0:c.getBackgroundColor()),w=Ab(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:v;BN(i?t:s.acroField,S);var C={x:p/2,y:f/2,width:p-u,height:f-u,borderWidth:u,borderColor:y,dotColor:S};return{normal:{on:xu(g,$de(pc(pc({},C),{color:b,filled:!0}))),off:xu(g,$de(pc(pc({},C),{color:b,filled:!1})))},down:{on:xu(g,$de(pc(pc({},C),{color:w,filled:!0}))),off:xu(g,$de(pc(pc({},C),{color:w,filled:!1})))}}},zJn=function(s,t,n){var r,a,i,l,o,c=zN(t),d=zN(s.acroField),u=iL(t),h=iL(s.acroField),m=t.getRectangle(),p=t.getAppearanceCharacteristics(),f=t.getBorderStyle(),g=p==null?void 0:p.getCaptions(),v=(r=g==null?void 0:g.normal)!==null&&r!==void 0?r:"",y=(i=(a=g==null?void 0:g.down)!==null&&a!==void 0?a:v)!==null&&i!==void 0?i:"",b=(l=f==null?void 0:f.getWidth())!==null&&l!==void 0?l:0,w=QE(p==null?void 0:p.getRotation()),S=Ez(m,w),C=S.width,E=S.height,P=YL(pc(pc({},m),{rotation:w})),M=zu(0,0,0),I=Ab(p==null?void 0:p.getBorderColor()),D=Ab(p==null?void 0:p.getBackgroundColor()),F=Ab(p==null?void 0:p.getBackgroundColor(),.8),q={x:b,y:b,width:C-b*2,height:E-b*2},G=D6e(v,{alignment:gy.Center,fontSize:u??h,font:n,bounds:q}),V=D6e(y,{alignment:gy.Center,fontSize:u??h,font:n,bounds:q}),H=Math.min(G.fontSize,V.fontSize),K=(o=c??d)!==null&&o!==void 0?o:M;BN(c||u!==void 0?t:s.acroField,K,n,H);var Z={x:0+b/2,y:0+b/2,width:C-b,height:E-b,borderWidth:b,borderColor:I,textColor:K,font:n.name,fontSize:H};return{normal:xu(P,S4t(pc(pc({},Z),{color:D,textLines:[G.line]}))),down:xu(P,S4t(pc(pc({},Z),{color:F,textLines:[V.line]})))}},BJn=function(s,t,n){var r,a,i,l,o=zN(t),c=zN(s.acroField),d=iL(t),u=iL(s.acroField),h=t.getRectangle(),m=t.getAppearanceCharacteristics(),p=t.getBorderStyle(),f=(r=s.getText())!==null&&r!==void 0?r:"",g=(a=p==null?void 0:p.getWidth())!==null&&a!==void 0?a:0,v=QE(m==null?void 0:m.getRotation()),y=Ez(h,v),b=y.width,w=y.height,S=YL(pc(pc({},h),{rotation:v})),C=zu(0,0,0),E=Ab(m==null?void 0:m.getBorderColor()),P=Ab(m==null?void 0:m.getBackgroundColor()),M,I,D=s.isCombed()?0:1,F={x:g+D,y:g+D,width:b-(g+D)*2,height:w-(g+D)*2};if(s.isMultiline()){var q=Prs(f,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:F});M=q.lines,I=q.fontSize}else if(s.isCombed()){var q=IJn(f,{fontSize:d??u,font:n,bounds:F,cellCount:(i=s.getMaxLength())!==null&&i!==void 0?i:0});M=q.cells,I=q.fontSize}else{var q=D6e(f,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:F});M=[q.line],I=q.fontSize}var G=(l=o??c)!==null&&l!==void 0?l:C;BN(o||d!==void 0?t:s.acroField,G,n,I);var V={x:0+g/2,y:0+g/2,width:b-g,height:w-g,borderWidth:g??0,borderColor:E,textColor:G,font:n.name,fontSize:I,color:P,textLines:M,padding:D};return xu(S,Crs(V))},$Jn=function(s,t,n){var r,a,i,l=zN(t),o=zN(s.acroField),c=iL(t),d=iL(s.acroField),u=t.getRectangle(),h=t.getAppearanceCharacteristics(),m=t.getBorderStyle(),p=(r=s.getSelected()[0])!==null&&r!==void 0?r:"",f=(a=m==null?void 0:m.getWidth())!==null&&a!==void 0?a:0,g=QE(h==null?void 0:h.getRotation()),v=Ez(u,g),y=v.width,b=v.height,w=YL(pc(pc({},u),{rotation:g})),S=zu(0,0,0),C=Ab(h==null?void 0:h.getBorderColor()),E=Ab(h==null?void 0:h.getBackgroundColor()),P=1,M={x:f+P,y:f+P,width:y-(f+P)*2,height:b-(f+P)*2},I=D6e(p,{alignment:gy.Left,fontSize:c??d,font:n,bounds:M}),D=I.line,F=I.fontSize,q=(i=l??o)!==null&&i!==void 0?i:S;BN(l||c!==void 0?t:s.acroField,q,n,F);var G={x:0+f/2,y:0+f/2,width:y-f,height:b-f,borderWidth:f??0,borderColor:C,textColor:q,font:n.name,fontSize:F,color:E,textLines:[D],padding:P};return xu(w,Crs(G))},UJn=function(s,t,n){var r,a,i=zN(t),l=zN(s.acroField),o=iL(t),c=iL(s.acroField),d=t.getRectangle(),u=t.getAppearanceCharacteristics(),h=t.getBorderStyle(),m=(r=h==null?void 0:h.getWidth())!==null&&r!==void 0?r:0,p=QE(u==null?void 0:u.getRotation()),f=Ez(d,p),g=f.width,v=f.height,y=YL(pc(pc({},d),{rotation:p})),b=zu(0,0,0),w=Ab(u==null?void 0:u.getBorderColor()),S=Ab(u==null?void 0:u.getBackgroundColor()),C=s.getOptions(),E=s.getSelected();s.isSorted()&&C.sort();for(var P="",M=0,I=C.length;M1||a.length===1&&r)&&this.enableMultiselect();for(var o=new Array(a.length),c=0,d=a.length;c1||a.length===1&&r)&&this.enableMultiselect();for(var l=new Array(a.length),o=0,c=a.length;or)throw new EJn(n.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),n?this.acroField.setValue(Ol.fromText(n)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var n=this.acroField.getQuadding();return n===0?gy.Left:n===1?gy.Center:n===2?gy.Right:gy.Left},t.prototype.setAlignment=function(n){$M(n,"alignment",gy),this.markAsDirty(),this.acroField.setQuadding(n)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(n){if(Ck(n,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),n===void 0)this.acroField.removeMaxLength();else{var r=this.getText();if(r&&r.length>n)throw new TJn(r.length,n,this.getName());this.acroField.setMaxLength(n)}},t.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},t.prototype.setImage=function(n){for(var r=this.getAlignment(),a=r===gy.Center?IP.Center:r===gy.Right?IP.Right:IP.Left,i=this.acroField.getWidgets(),l=0,o=i.length;l{let l=null;try{const o=i.acroField.getWidgets()[0],c=o==null?void 0:o.P();if(c){const d=n.findIndex(u=>u.ref===c);l=d>=0?d:null}}catch{l=null}return{name:i.getName(),type:Irs(i),page:l}})}catch{r=[]}return{pageCount:n.length,hasAcroform:r.length>0,fields:r}}function C4t(s,t){return s.mapping_mode==="blank"?"":s.mapping_mode==="static"||!s.merge_key?s.static_value||"":t[s.merge_key]??""}async function Drs(s,t,n){const r=await wC.load(s,{updateMetadata:!1}),a=await r.embedFont($G.Helvetica),i={},l=[],o=t.filter(u=>u.mapping_mode!=="overlay"&&u.pdf_field_name);if(o.length){const u=r.getForm();for(const h of o){const m=C4t(h,n),p=h.pdf_field_name;if(!m){l.push(p);continue}try{const f=u.getField(p),g=Irs(f);if(g==="text")f.setText(m);else if(g==="checkbox")/^(true|yes|x|1|checked)$/i.test(m.trim())?f.check():f.uncheck();else if(g==="dropdown"||g==="optionlist")f.select(m);else if(g==="radio")f.select(m);else{l.push(p);continue}i[p]=m}catch{l.push(p)}}try{u.updateFieldAppearances(a)}catch{}try{u.flatten()}catch{}}const c=t.filter(u=>u.mapping_mode==="overlay"&&(u.field_kind==null||u.field_kind==="data"));if(c.length){const u=r.getPages();for(const h of c){const m=C4t(h,n),p=h.pdf_field_name||h.merge_key||h.field_kind||"overlay",f=u[h.page_index??0];if(!m||!f||h.pos_x==null||h.pos_y==null){l.push(p);continue}const{width:g,height:v}=f.getSize(),y=!!h.coords_normalized,b=Number(h.pos_x)*(y?g:1),w=Number(h.width??(y?.2:120))*(y?g:1),S=Number(h.height??(y?.03:18))*(y?v:1),C=Number(h.pos_y)*(y?v:1),E=y?v-C-S:C,P=Number(h.font_size)||(y?Math.min(11,Math.max(7,S*.7)):10);f.drawText(m,{x:y?b+1:b,y:y?E+Math.max(2,(S-P)/2):E,size:P,font:a,color:zu(0,0,0),maxWidth:y?Math.max(10,w-2):void 0}),i[p]=m}}return{bytes:await r.save(),applied:i,skipped:l}}function dit(s){const t=s instanceof Error?s.message:String(s);return/encrypt/i.test(t)?"This PDF is password-protected or encrypted. Please upload an unlocked copy.":/xfa/i.test(t)?"This PDF uses an XFA form layer that LevelUp cannot read yet.":/Failed to parse|Invalid PDF|no PDF header/i.test(t)?"That file could not be read as a PDF.":t||"Something went wrong reading the PDF."}const Rrs=20*1024*1024,uit=[{value:"purchase",label:"Purchase"},{value:"listing",label:"Listing"},{value:"disclosure",label:"Disclosure"},{value:"addendum",label:"Addendum"},{value:"other",label:"Other"}];function Cx(s){var t;return(t=s==null?void 0:s.versions)!=null&&t.length?[...s.versions].sort((n,r)=>r.version_number-n.version_number)[0]:null}function hit(s=!1){const t=ha();return rt({queryKey:["form-templates",t,s],enabled:!!t,queryFn:async()=>{let n=U.from("form_templates").select("*, versions:form_template_versions(*)").or(`owner_user_id.eq.${t},brokerage_id.not.is.null`).order("created_at",{ascending:!1});s||(n=n.eq("is_archived",!1));const{data:r,error:a}=await n;if(a)throw a;return(r||[]).map(i=>({...i,scope:i.brokerage_id?"brokerage":"mine"}))}})}function QJn(s,t=!1){return rt({queryKey:["brokerage-form-templates",s,t],enabled:!!s,queryFn:async()=>{let n=U.from("form_templates").select("*, versions:form_template_versions(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t||(n=n.eq("is_archived",!1));const{data:r,error:a}=await n;if(a)throw a;return(r||[]).map(i=>({...i,scope:"brokerage"}))}})}function JJn(){const s=ha(),t=$t();return mt({mutationFn:async({name:n,description:r,category:a,file:i,templateId:l,brokerageId:o})=>{var y;if(!s)throw new Error("Not authenticated");if(i.type!=="application/pdf"&&!i.name.toLowerCase().endsWith(".pdf"))throw new Error("Only PDF files can be uploaded.");if(i.size>Rrs)throw new Error("That PDF is larger than the 20MB limit.");let c;try{c=await XJn(await i.arrayBuffer())}catch(b){throw new Error(dit(b))}let d=l;if(!d){const{data:b,error:w}=await U.from("form_templates").insert({owner_user_id:s,name:n,description:r||null,category:a,source_type:o?"brokerage":"user_upload",brokerage_id:o||null,is_published:!1}).select().single();if(w)throw w;d=b.id}const{data:u,error:h}=await U.from("form_template_versions").select("version_number").eq("template_id",d).order("version_number",{ascending:!1}).limit(1);if(h)throw h;const m=(((y=u==null?void 0:u[0])==null?void 0:y.version_number)??0)+1,p=`${s}/${d}/v${m}-${crypto.randomUUID()}.pdf`,{error:f}=await U.storage.from("form-templates").upload(p,i,{contentType:"application/pdf"});if(f)throw f;const{data:g,error:v}=await U.from("form_template_versions").insert({template_id:d,version_number:m,storage_path:p,file_name:i.name,file_size:i.size,page_count:c.pageCount,has_acroform:c.hasAcroform,detected_fields:c.fields,mapping_status:c.hasAcroform?"needs_mapping":"needs_placement",effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(v)throw await U.storage.from("form-templates").remove([p]),v;return{templateId:d,version:g}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]}),t.invalidateQueries({queryKey:["form-template"]})}})}function Frs(){const s=$t();return mt({mutationFn:async({id:t,patch:n})=>{const{error:r}=await U.from("form_templates").update(n).eq("id",t);if(r)throw r;return t},onSuccess:()=>{s.invalidateQueries({queryKey:["form-templates"]}),s.invalidateQueries({queryKey:["brokerage-form-templates"]}),s.invalidateQueries({queryKey:["form-template"]})}})}function eer(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r=Cx(n);if(!r)throw new Error("That template has no uploaded PDF yet.");const a=await pDe(r.storage_path),{data:i,error:l}=await U.from("form_templates").insert({owner_user_id:s,name:`${n.name} (copy)`,description:n.description,category:n.category,source_type:"user_upload"}).select().single();if(l)throw l;const o=`${s}/${i.id}/v1-${crypto.randomUUID()}.pdf`,{error:c}=await U.storage.from("form-templates").upload(o,new Blob([a],{type:"application/pdf"}),{contentType:"application/pdf"});if(c)throw c;const{data:d,error:u}=await U.from("form_template_versions").insert({template_id:i.id,version_number:1,storage_path:o,file_name:r.file_name,file_size:r.file_size,page_count:r.page_count,has_acroform:r.has_acroform,detected_fields:r.detected_fields,mapping_status:r.mapping_status,effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(u)throw await U.storage.from("form-templates").remove([o]),u;const{data:h}=await U.from("form_field_mappings").select("*").eq("version_id",r.id);if(h!=null&&h.length){const m=h.map(({id:f,created_at:g,updated_at:v,version_id:y,...b})=>({...b,version_id:d.id})),{error:p}=await U.from("form_field_mappings").insert(m);if(p)throw p}return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]})}})}function Ors(){const s=$t();return mt({mutationFn:async t=>{const n=(t.versions||[]).map(a=>a.storage_path);n.length&&await U.storage.from("form-templates").remove(n);const{error:r}=await U.from("form_templates").delete().eq("id",t.id);if(r)throw r;return t.id},onSuccess:()=>{s.invalidateQueries({queryKey:["form-templates"]})}})}async function pDe(s){const{data:t,error:n}=await U.storage.from("form-templates").download(s);if(n||!t)throw n||new Error("Could not download the template PDF.");return await t.arrayBuffer()}function Nk(s){if(!s)return"";try{const t=Ou(s);if(Number.isNaN(t.getTime()))return"";const n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${n}/${r}/${t.getFullYear()}`}catch{return""}}function ter(){const s=new Date,t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return`${t}/${n}/${s.getFullYear()}`}function ser(s){if(s==null||Number.isNaN(s))return"";const t=Math.round(s*100)%100!==0;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t?2:0,maximumFractionDigits:t?2:0}).format(s)}function mit(s){return s?s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`:"0 KB"}const UG=[{key:"deal.name",label:"Deal name",group:"Deal",aliases:["deal","transaction name","file name"]},{key:"deal.type",label:"Deal type",group:"Deal",aliases:["transaction type","side"]},{key:"deal.property_address",label:"Property address",group:"Deal",aliases:["property","subject property","street","address of property","premises"]},{key:"deal.city",label:"Property city",group:"Deal",aliases:["property city","city"]},{key:"deal.state",label:"Property state",group:"Deal",aliases:["property state","state"]},{key:"deal.zip",label:"Property ZIP",group:"Deal",aliases:["zip","zipcode","postal"]},{key:"deal.price",label:"Price",group:"Deal",aliases:["purchase price","sale price","sales price","list price","offer price","amount"]},{key:"deal.contract_date",label:"Contract date",group:"Deal",aliases:["contract","acceptance date","effective date","binding date"]},{key:"deal.target_close_date",label:"Target close date",group:"Deal",aliases:["closing date","close date","settlement date","coe"]},{key:"deal.actual_close_date",label:"Actual close date",group:"Deal",aliases:["closed date","actual close"]},{key:"deal.listing_date",label:"Listing date",group:"Deal",aliases:["list date","listing start"]},{key:"deal.inspection_date",label:"Inspection date",group:"Deal",aliases:["inspection"]},{key:"deal.inspection_contingency_date",label:"Inspection contingency date",group:"Deal",aliases:["inspection contingency","due diligence"]},{key:"deal.appraisal_date",label:"Appraisal date",group:"Deal",aliases:["appraisal"]},{key:"deal.loan_approval_date",label:"Loan approval date",group:"Deal",aliases:["loan approval","financing contingency","mortgage commitment"]},{key:"deal.earnest_money_due_date",label:"Earnest money due date",group:"Deal",aliases:["earnest money","emd","deposit due"]},{key:"deal.title_docs_due_date",label:"Title docs due date",group:"Deal",aliases:["title","title commitment"]},{key:"deal.final_walkthrough_date",label:"Final walkthrough date",group:"Deal",aliases:["walkthrough","walk through","final walk"]},{key:"contact.first_name",label:"Client first name",group:"Contact",aliases:["buyer first","seller first","client first","first name"]},{key:"contact.last_name",label:"Client last name",group:"Contact",aliases:["buyer last","seller last","client last","last name","surname"]},{key:"contact.full_name",label:"Client full name",group:"Contact",aliases:["buyer name","seller name","client name","purchaser","buyer","seller","client"]},{key:"contact.email",label:"Client email",group:"Contact",aliases:["buyer email","seller email","client email","email"]},{key:"contact.phone",label:"Client phone",group:"Contact",aliases:["buyer phone","seller phone","client phone","phone","telephone","mobile"]},{key:"contact.address",label:"Client address",group:"Contact",aliases:["buyer address","seller address","mailing address","client address"]},{key:"contact.city",label:"Client city",group:"Contact",aliases:["buyer city","seller city"]},{key:"contact.state",label:"Client state",group:"Contact",aliases:["buyer state","seller state"]},{key:"contact.zip",label:"Client ZIP",group:"Contact",aliases:["buyer zip","seller zip"]},{key:"contact.spouse_name",label:"Spouse name",group:"Contact",aliases:["spouse","co buyer","cobuyer","co seller","partner name","buyer 2","seller 2"]},{key:"contact.spouse_email",label:"Spouse email",group:"Contact",aliases:["spouse email","co buyer email","buyer 2 email"]},{key:"agent.name",label:"Agent name",group:"Agent",aliases:["agent","realtor","listing agent","broker name","salesperson"]},{key:"agent.email",label:"Agent email",group:"Agent",aliases:["agent email","broker email"]},{key:"agent.phone",label:"Agent phone",group:"Agent",aliases:["agent phone","broker phone"]},{key:"agent.brokerage_name",label:"Brokerage name",group:"Agent",aliases:["brokerage","firm","company","office"]},{key:"agent.license_number",label:"Agent license number",group:"Agent",aliases:["license","license no","dre","bre","lic"]},{key:"agent.license_state",label:"Agent license state",group:"Agent",aliases:["license state"]},{key:"agent.website_url",label:"Agent website",group:"Agent",aliases:["website","web site","url"]},{key:"agent.title",label:"Agent title",group:"Agent",aliases:["agent title","designation"]},{key:"today",label:"Today's date",group:"Other",aliases:["date","today","date signed","dated"]}],zrs=new Map(UG.map(s=>[s.key,s])),ner={buyer:"Buyer",seller:"Seller",dual:"Dual",referral:"Referral",lease:"Lease"};function rer(s){const t=s.deal||{},n=s.contact||{},r=s.profile||{},a=s.brand||{},i=[n.first_name,n.last_name].filter(Boolean).join(" ").trim(),l=t.sale_price??t.expected_price??null;return{"deal.name":t.deal_name||"","deal.type":ner[t.deal_type]||t.deal_type||"","deal.property_address":t.property_address||"","deal.city":t.city||"","deal.state":t.state||"","deal.zip":t.zip_code||"","deal.price":ser(l),"deal.contract_date":Nk(t.contract_date),"deal.target_close_date":Nk(t.target_close_date),"deal.actual_close_date":Nk(t.actual_close_date),"deal.listing_date":Nk(t.listing_date),"deal.inspection_date":Nk(t.inspection_date),"deal.inspection_contingency_date":Nk(t.inspection_contingency_date),"deal.appraisal_date":Nk(t.appraisal_date),"deal.loan_approval_date":Nk(t.loan_approval_date),"deal.earnest_money_due_date":Nk(t.earnest_money_due_date),"deal.title_docs_due_date":Nk(t.title_docs_due_date),"deal.final_walkthrough_date":Nk(t.final_walkthrough_date),"contact.first_name":n.first_name||"","contact.last_name":n.last_name||"","contact.full_name":i,"contact.email":n.email||"","contact.phone":n.phone||"","contact.address":n.address||"","contact.city":n.city||"","contact.state":n.state||"","contact.zip":n.zip||n.zip_code||"","contact.spouse_name":n.spouse_name||"","contact.spouse_email":n.spouse_email||"","agent.name":r.name||"","agent.email":r.email||"","agent.phone":r.phone||"","agent.brokerage_name":r.brokerage_name||a.brokerage_name||"","agent.license_number":a.license_number||"","agent.license_state":a.license_state||"","agent.website_url":r.website_url||"","agent.title":r.title||"",today:ter()}}function pit(s){const t=ha();return rt({queryKey:["form-merge-data",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("deal_pipeline").select("*").eq("id",s).maybeSingle();if(r)throw r;let a=null;if(n!=null&&n.contact_id){const{data:c}=await U.from("innercircle_contacts").select("*").eq("id",n.contact_id).maybeSingle();a=c}const[{data:i},{data:l}]=await Promise.all([U.from("profiles").select("*").eq("id",t).maybeSingle(),U.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle()]),o={deal:n,contact:a,profile:i,brand:l};return{sources:o,values:rer(o)}}})}function aer(s){return rt({queryKey:["form-generations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("form_generations").select("*, template:form_templates(name), version:form_template_versions(version_number)").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function ier(){const s=ha(),t=$t();return mt({mutationFn:async({dealId:n,template:r,version:a,values:i})=>{if(!s)throw new Error("Not authenticated");const{data:l,error:o}=await U.from("form_field_mappings").select("*").eq("version_id",a.id);if(o)throw o;if(!(l!=null&&l.length))throw new Error("This template has no field mapping yet.");const c=await pDe(a.storage_path);let d;try{d=await Drs(c,l,i)}catch(w){throw new Error(dit(w))}const h=`${r.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - v${a.version_number}.pdf`,m=d.bytes.buffer.slice(d.bytes.byteOffset,d.bytes.byteOffset+d.bytes.byteLength),p=new Blob([m],{type:"application/pdf"}),f=`${s}/${n}/${crypto.randomUUID()}.pdf`,{error:g}=await U.storage.from("deal-files").upload(f,p,{contentType:"application/pdf"});if(g)throw g;const{data:v,error:y}=await U.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:h,file_size:p.size,file_type:"application/pdf",storage_path:f}).select().single();if(y)throw y;const{error:b}=await U.from("form_generations").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,deal_file_id:v.id,merge_snapshot:{values:i,applied:d.applied,skipped:d.skipped}});if(b)throw b;return await U.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Generated ${r.name}`,description:`${h} was generated from a LevelUp form template (v${a.version_number}).`,metadata:{template_id:r.id,version_id:a.id,deal_file_id:v.id}}),{dealFile:v,blob:p,fileName:h,skipped:d.skipped}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]}),t.invalidateQueries({queryKey:["deal-activities"]}),t.invalidateQueries({queryKey:["form-generations",r.dealId]})}})}function _ie(s){return rt({queryKey:["form-field-mappings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("form_field_mappings").select("*").eq("version_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function oer(){const s=$t();return mt({mutationFn:async({versionId:t,mappings:n,hasAcroform:r})=>{const{error:a}=await U.from("form_field_mappings").delete().eq("version_id",t);if(a)throw a;const i=n.map(d=>({version_id:t,pdf_field_name:d.pdf_field_name,mapping_mode:d.mapping_mode,merge_key:d.merge_key,static_value:d.static_value,page_index:d.page_index??null,pos_x:d.pos_x??null,pos_y:d.pos_y??null,font_size:d.font_size??null}));if(i.length){const{error:d}=await U.from("form_field_mappings").insert(i);if(d)throw d}const l=n.some(d=>d.mapping_mode==="acroform"&&d.merge_key||d.mapping_mode==="static"||d.mapping_mode==="overlay"&&d.merge_key),o=r?l?"mapped":"needs_mapping":l?"mapped":"needs_placement",{error:c}=await U.from("form_template_versions").update({mapping_status:o}).eq("id",t);if(c)throw c;return t},onSuccess:t=>{s.invalidateQueries({queryKey:["form-field-mappings",t]}),s.invalidateQueries({queryKey:["form-templates"]}),s.invalidateQueries({queryKey:["form-template"]})}})}function Brs({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=hit(),[o,c]=_.useState(a),{data:d,isLoading:u,error:h}=pit(s?n:void 0),m=ier(),p=_.useMemo(()=>i.find(E=>E.id===o),[i,o]),f=Cx(p),{data:g=[],isLoading:v}=_ie(s?f==null?void 0:f.id:void 0);_.useEffect(()=>{s&&a&&c(a)},[s,a]);const y=i.filter(E=>{var P;return((P=Cx(E))==null?void 0:P.mapping_status)==="mapped"}),b=_.useMemo(()=>d?g.filter(E=>E.merge_key||E.static_value).map(E=>{var P;return{field:E.pdf_field_name||E.merge_key||"",label:E.merge_key?((P=zrs.get(E.merge_key))==null?void 0:P.label)||E.merge_key:"Fixed text",value:E.mapping_mode==="static"?E.static_value||"":d.values[E.merge_key||""]||""}}):[],[g,d]),w=b.filter(E=>!E.value).length,S=async()=>{if(!(!p||!f||!d))try{const E=await m.mutateAsync({dealId:n,template:p,version:f,values:d.values});ne.success(`${E.fileName} saved to this deal's files`),t(!1)}catch(E){ne.error((E==null?void 0:E.message)||"Could not generate the form")}},C=(f==null?void 0:f.mapping_status)==="mapped";return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Prepare a form"}),e.jsx(_r,{children:r?`Fill a template with data from ${r}.`:"Fill a template with this deal’s data."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs(ls,{value:o,onValueChange:c,disabled:l,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(as,{children:i.map(E=>{const P=Cx(E);return e.jsxs(He,{value:E.id,disabled:(P==null?void 0:P.mapping_status)!=="mapped",children:[E.name,E.scope==="brokerage"?" · Brokerage":"",(P==null?void 0:P.mapping_status)!=="mapped"?" — needs mapping":""]},E.id)})})]}),!l&&i.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:"No form templates yet. Upload one in Forms Library first."}),!l&&i.length>0&&y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"None of your templates are mapped yet. Finish mapping one in Forms Library."}),h&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load this deal’s data. Please try again."}),p&&e.jsxs(e.Fragment,{children:[(u||v)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),!u&&!v&&C&&e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{children:"What will be filled in"}),w>0&&e.jsxs(ze,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(nl,{className:"h-3 w-3"})," ",w," blank"]})]}),e.jsx(Ki,{className:"max-h-[280px]",children:e.jsxs("div",{className:"divide-y",children:[b.map((E,P)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx("span",{className:"w-1/3 shrink-0 truncate text-muted-foreground",children:E.label}),e.jsx("span",{className:E.value?"truncate":"truncate italic text-muted-foreground/60",children:E.value||"not set"})]},`${E.field}-${P}`)),b.length===0&&e.jsx("p",{className:"p-4 text-center text-sm text-muted-foreground",children:"This template has no mapped fields yet."})]})})]}),!C&&f&&e.jsx("p",{className:"rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:f.has_acroform?"This template still needs its fields mapped.":"This PDF has no fillable fields, so it needs field placement before it can be used."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:S,disabled:!C||m.isPending||b.length===0,children:[m.isPending?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(n7,{className:"mr-2 h-4 w-4"}),m.isPending?"Generating…":"Generate & save to deal"]})]})]})})}const ler=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function $rs(s){return rt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function cer(){const s=$t();return mt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await U.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]}),ne.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ne.error("This contact is already linked to this deal"):ne.error("Failed to link contact")}})}function der(){const s=$t();return mt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await U.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ne.success("Contact removed from deal")},onError:()=>{ne.error("Failed to remove contact")}})}const fit=[{value:"buyer_1",label:"Buyer 1"},{value:"buyer_2",label:"Buyer 2"},{value:"seller_1",label:"Seller 1"},{value:"seller_2",label:"Seller 2"},{value:"agent",label:"Agent (you)"}];function fDe(s){var t;return((t=fit.find(n=>n.value===s))==null?void 0:t.label)||s||"Signer"}function uer(s){const t=ha();return rt({queryKey:["form-envelopes",t,s||"all"],enabled:!!t,queryFn:async()=>{let n=U.from("form_envelopes").select("*, template:form_templates(name), version:form_template_versions(version_number), signers:form_envelope_signers(*)").eq("owner_user_id",t).neq("status","draft").order("created_at",{ascending:!1});s&&(n=n.eq("deal_id",s));const{data:r,error:a}=await n;if(a)throw a;return r||[]}})}function her(){const s=ha(),t=$t();return mt({mutationFn:async({dealId:n,template:r,version:a,title:i,message:l,values:o,signers:c})=>{if(!s)throw new Error("Not authenticated");const{data:d,error:u}=await U.from("form_envelopes").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,title:i,message:l||null,merge_snapshot:o}).select("id").single();if(u)throw u;const{data:h,error:m}=await U.functions.invoke("forms-envelope-send",{body:{action:"send",envelope_id:d.id,signers:c}});if(m)throw new Error(m.message||"Could not send the signature request");if(h!=null&&h.error)throw new Error(h.error);return await U.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Sent for signature: ${i}`,description:`${r.name} (v${a.version_number}) sent to ${c.length} signer${c.length===1?"":"s"}.`,metadata:{envelope_id:d.id,template_id:r.id,version_id:a.id}}),{envelopeId:d.id,result:h}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["form-envelopes"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function mer(){const s=$t();return mt({mutationFn:async({envelopeId:t,action:n,reason:r})=>{const{data:a,error:i}=await U.functions.invoke("forms-envelope-send",{body:{action:n,envelope_id:t,reason:r}});if(i)throw new Error(i.message||"That action failed");if(a!=null&&a.error)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["form-envelopes"]})}})}function Urs(){const s=ha();return rt({queryKey:["form-packets",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("form_packets").select("*, items:form_packet_items(*)").eq("owner_user_id",s).eq("is_archived",!1).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function xit(s,t){var n;return(n=s==null?void 0:s.items)!=null&&n.length?[...s.items].sort((r,a)=>r.sort_order-a.sort_order).map(r=>t.find(a=>a.id===r.template_id)).filter(Boolean):[]}function per(){const s=ha(),t=$t();return mt({mutationFn:async({id:n,name:r,description:a,templateIds:i})=>{if(!s)throw new Error("Not authenticated");let l=n;if(l){const{error:o}=await U.from("form_packets").update({name:r,description:a||null,updated_at:new Date().toISOString()}).eq("id",l);if(o)throw o;const{error:c}=await U.from("form_packet_items").delete().eq("packet_id",l);if(c)throw c}else{const{data:o,error:c}=await U.from("form_packets").insert({owner_user_id:s,name:r,description:a||null}).select("id").single();if(c)throw c;l=o.id}if(i.length){const{error:o}=await U.from("form_packet_items").insert(i.map((c,d)=>({packet_id:l,template_id:c,sort_order:d})));if(o)throw o}return l},onSuccess:()=>t.invalidateQueries({queryKey:["form-packets"]})})}function fer(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("form_packets").delete().eq("id",t);if(n)throw n;return t},onSuccess:()=>s.invalidateQueries({queryKey:["form-packets"]})})}function xer(){const s=ha(),t=$t();return mt({mutationFn:async({dealId:n,packet:r,templates:a,titlePrefix:i,message:l,values:o,signers:c})=>{if(!s)throw new Error("Not authenticated");const d=xit(r,a);if(!d.length)throw new Error("This packet has no templates in it yet.");const u=crypto.randomUUID(),h=[];for(let m=0;mE.field_kind&&E.field_kind!=="data"&&E.signer_role).map(E=>E.signer_role)),w=c.filter(E=>b.has(E.signer_role));if(!w.length)throw new Error(`${p.name} has no signature fields placed yet.`);const{data:S,error:C}=await U.functions.invoke("forms-envelope-send",{body:{action:"send",envelope_id:g.id,signers:w.map((E,P)=>({...E,order_index:P})),notify:m===0}});if(C)throw new Error(C.message||"Could not send the packet");if(S!=null&&S.error)throw new Error(S.error)}return await U.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Sent packet for signature: ${r.name}`,description:`${d.length} document${d.length===1?"":"s"} sent to ${c.length} signer${c.length===1?"":"s"}.`,metadata:{packet_id:r.id,packet_run_id:u,envelope_ids:h}}),{runId:u,envelopeIds:h}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-envelopes"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function qrs({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=hit(),[o,c]=_.useState(a),{data:d,isLoading:u}=pit(s?n:void 0),{data:h=[]}=$rs(n),{data:m=[]}=Urs(),p=her(),f=xer(),[g,v]=_.useState("single"),[y,b]=_.useState(void 0),w=_.useMemo(()=>m.find(ce=>ce.id===y),[m,y]),S=_.useMemo(()=>xit(w,i),[w,i]),{data:C=[],isLoading:E}=rt({queryKey:["packet-signer-roles",y,S.map(ce=>{var ve;return(ve=Cx(ce))==null?void 0:ve.id}).join(",")],enabled:g==="packet"&&S.length>0,queryFn:async()=>{const ce=S.map(ge=>{var Ee;return(Ee=Cx(ge))==null?void 0:Ee.id}).filter(Boolean);if(!ce.length)return[];const{data:ve,error:me}=await U.from("form_field_mappings").select("field_kind, signer_role").in("version_id",ce);if(me)throw me;const he=new Set;for(const ge of ve||[])ge.field_kind&&ge.field_kind!=="data"&&ge.signer_role&&he.add(ge.signer_role);return[...he]}}),P=_.useMemo(()=>i.find(ce=>ce.id===o),[i,o]),M=Cx(P),{data:I=[],isLoading:D}=_ie(s?M==null?void 0:M.id:void 0),[F,q]=_.useState(""),[G,V]=_.useState(""),[H,K]=_.useState({});_.useEffect(()=>{s&&a&&c(a)},[s,a]);const Z=_.useMemo(()=>{const ce=new Set;if(g==="packet")for(const me of C)ce.add(me);else for(const me of I)me.field_kind&&me.field_kind!=="data"&&me.signer_role&&ce.add(me.signer_role);const ve=fit.map(me=>me.value);return[...ce].sort((me,he)=>ve.indexOf(me)-ve.indexOf(he))},[I,g,C]);_.useEffect(()=>{var he,ge,Ee;const ce={},ve=h.filter(Ne=>Ne.contact);let me=0;for(const Ne of Z)if(Ne==="agent"){const Pe=(he=d==null?void 0:d.sources)==null?void 0:he.profile;ce[Ne]={name:(Pe==null?void 0:Pe.full_name)||"",email:(Pe==null?void 0:Pe.email)||"",contact_id:null}}else{const Pe=ve[me++],Oe=Pe!=null&&Pe.contact?`${Pe.contact.first_name||""} ${Pe.contact.last_name||""}`.trim():"";ce[Ne]={name:Oe,email:((ge=Pe==null?void 0:Pe.contact)==null?void 0:ge.email)||"",contact_id:((Ee=Pe==null?void 0:Pe.contact)==null?void 0:Ee.id)||null}}K(ce),g==="single"&&P&&!F&&q(r?`${P.name} – ${r}`:P.name)},[Z,h,d,o,y,g]);const oe=(M==null?void 0:M.mapping_status)==="mapped",re=(ce,ve)=>K(me=>({...me,[ce]:{...me[ce],...ve}})),ae=Z.length>0&&Z.every(ce=>{var ve,me,he;return((me=(ve=H[ce])==null?void 0:ve.name)==null?void 0:me.trim())&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(((he=H[ce])==null?void 0:he.email)||"")}),J=p.isPending||f.isPending,te=async()=>{if(!d)return;const ce=Z.map((ve,me)=>({full_name:H[ve].name.trim(),email:H[ve].email.trim(),signer_role:ve,contact_id:H[ve].contact_id,is_agent:ve==="agent",order_index:me}));try{if(g==="packet"){if(!w)return;await f.mutateAsync({dealId:n,packet:w,templates:i,titlePrefix:r||"",message:G.trim()||void 0,values:d.values,signers:ce}),ne.success(`${S.length} documents sent to ${ce[0].full_name}`)}else{if(!P||!M)return;await p.mutateAsync({dealId:n,template:P,version:M,title:F.trim()||P.name,message:G.trim()||void 0,values:d.values,signers:ce}),ne.success(`Signature request sent to ${ce[0].full_name}`)}t(!1)}catch(ve){ne.error((ve==null?void 0:ve.message)||"Could not send the signature request")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"flex max-h-[90vh] max-w-xl flex-col overflow-hidden",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Send for signature"}),e.jsx(_r,{children:r?`Fill a template with ${r}'s data, then email it for e-signature.`:"Fill a template with this deal’s data, then email it for e-signature."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[m.length>0&&e.jsx("div",{className:"flex gap-1 rounded-lg bg-muted p-1",children:["single","packet"].map(ce=>e.jsx("button",{onClick:()=>v(ce),className:`flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${g===ce?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:ce==="single"?"One form":"Packet"},ce))}),g==="packet"?e.jsxs(e.Fragment,{children:[e.jsxs(ls,{value:y,onValueChange:b,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose a packet"})}),e.jsx(as,{children:m.map(ce=>{var ve;return e.jsxs(He,{value:ce.id,children:[ce.name," (",((ve=ce.items)==null?void 0:ve.length)??0," forms)"]},ce.id)})})]}),S.length>0&&e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs",children:[e.jsx("p",{className:"mb-1.5 font-semibold",children:"Signers move through these in one session:"}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-muted-foreground",children:S.map(ce=>{var ve;return e.jsxs("li",{children:[ce.name,((ve=Cx(ce))==null?void 0:ve.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]})]}):e.jsxs(ls,{value:o,onValueChange:c,disabled:l,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(as,{children:i.map(ce=>{const ve=Cx(ce);return e.jsxs(He,{value:ce.id,disabled:(ve==null?void 0:ve.mapping_status)!=="mapped",children:[ce.name,ce.scope==="brokerage"?" · Brokerage":"",(ve==null?void 0:ve.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]}),(g==="packet"?w:P)&&(u||D||E)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(g==="packet"?!!w&&!E:!!P&&!D&&oe)&&Z.length===0&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:[e.jsx(nl,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{children:["This template has no signature fields yet. Open it in the Forms Library and use"," ",e.jsx("strong",{children:"Place fields & signatures"})," to add signature, initials, and date boxes first."]})]}),Z.length>0&&e.jsxs(e.Fragment,{children:[g==="single"&&P&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Document title"}),e.jsx(pe,{value:F,onChange:ce=>q(ce.target.value),placeholder:P.name})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Signers (sign in this order)"}),e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[Z.length," signer",Z.length===1?"":"s"]})]}),Z.map((ce,ve)=>{var me,he,ge;return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold",children:[ve+1,". ",fDe(ce)]}),ce!=="agent"&&h.length>0&&e.jsxs(ls,{value:((me=H[ce])==null?void 0:me.contact_id)||"",onValueChange:Ee=>{const Ne=h.find(Pe=>{var Oe;return((Oe=Pe.contact)==null?void 0:Oe.id)===Ee});Ne!=null&&Ne.contact&&re(ce,{contact_id:Ee,name:`${Ne.contact.first_name||""} ${Ne.contact.last_name||""}`.trim(),email:Ne.contact.email||""})},children:[e.jsx(rs,{className:"h-7 w-44 text-[11px]",children:e.jsx(cs,{placeholder:"Pick deal contact…"})}),e.jsx(as,{children:h.map(Ee=>Ee.contact?e.jsxs(He,{value:Ee.contact.id,className:"text-xs",children:[Ee.contact.first_name," ",Ee.contact.last_name]},Ee.contact.id):null)})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(pe,{className:"h-8 text-xs",placeholder:"Full name",value:((he=H[ce])==null?void 0:he.name)||"",onChange:Ee=>re(ce,{name:Ee.target.value,contact_id:null})}),e.jsx(pe,{className:"h-8 text-xs",type:"email",placeholder:"Email address",value:((ge=H[ce])==null?void 0:ge.email)||"",onChange:Ee=>re(ce,{email:Ee.target.value,contact_id:null})})]})]},ce)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Message (optional)"}),e.jsx(Ps,{rows:2,placeholder:"Added to the signature request email",value:G,onChange:ce=>V(ce.target.value)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g==="packet"?"The first signer gets one secure email link and moves straight through every document in the packet with the same adopted signature. Reminders go out automatically on day 3 and day 10.":"The first signer gets a secure email link now; each next signer is notified automatically after the previous one signs. The agent countersigns last, inside LevelUp. Reminders go out automatically on day 3 and day 10."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:te,disabled:!ae||J||u,children:[J?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Mm,{className:"mr-2 h-4 w-4"}),J?"Sending…":g==="packet"?`Send ${S.length||""} document${S.length===1?"":"s"}`.replace(" "," "):"Send signature request"]})]})]})})}function ger({status:s}){switch(s){case"completed":return e.jsx(ze,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Completed"});case"partially_signed":return e.jsx(ze,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:"Partially signed"});case"sent":return e.jsx(ze,{variant:"secondary",children:"Sent"});case"declined":return e.jsx(ze,{variant:"destructive",children:"Declined"});case"voided":return e.jsx(ze,{variant:"outline",children:"Voided"});case"expired":return e.jsx(ze,{variant:"outline",children:"Expired"});case"finalize_failed":return e.jsx(ze,{variant:"destructive",children:"Needs attention"});default:return e.jsx(ze,{variant:"secondary",children:s})}}function yer({envelope:s}){const t=zn(),n=mer(),r=[...s.signers||[]].sort((m,p)=>m.order_index-p.order_index),a=r.some((m,p)=>m.is_agent&&m.status!=="signed"&&r.slice(0,p).every(f=>f.status==="signed")),i=s.status==="sent"||s.status==="partially_signed",l=r.find(m=>m.declined_at),o=i&&s.expires_at?Math.ceil((new Date(s.expires_at).getTime()-Date.now())/864e5):null,c=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"audit_pdf"});if(!(m!=null&&m.pdf_base64))throw new Error("No audit trail was returned");const p=atob(m.pdf_base64),f=new Uint8Array(p.length);for(let y=0;y{if(!s.completed_storage_path)return;const{data:m,error:p}=await U.storage.from("deal-files").createSignedUrl(s.completed_storage_path,300);if(p||!m)return ne.error("Could not download the signed document");window.open(m.signedUrl,"_blank")},u=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"agent_link"});m!=null&&m.path&&t(m.path)}catch(m){ne.error((m==null?void 0:m.message)||"Could not open countersigning")}},h=async()=>{const m=window.prompt("Why is this being voided? (optional)")??void 0;if(m!==void 0)try{await n.mutateAsync({envelopeId:s.id,action:"void",reason:m}),ne.success("Envelope voided")}catch(p){ne.error((p==null?void 0:p.message)||"Could not void")}};return e.jsxs("div",{className:"rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-primary/10",children:e.jsx(Mm,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.map(m=>`${m.full_name} (${fDe(m.signer_role)}): ${m.status.replace("_"," ")}`).join(" · ")})]}),e.jsx(ger,{status:s.status})]}),l&&e.jsxs("div",{className:"mt-2 ml-11 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive",children:[e.jsxs("span",{className:"font-semibold",children:[l.full_name," declined."]})," ",l.decline_reason||"No reason was given."]}),o!==null&&o<=4&&e.jsx("p",{className:"mt-2 ml-11 text-xs text-amber-600",children:o>0?`Expires in ${o} day${o===1?"":"s"} — reminders go out automatically.`:"Expires today — reminders go out automatically."}),(i||s.status==="completed"||s.status==="declined")&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 pl-11",children:[i&&e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:async()=>{try{await n.mutateAsync({envelopeId:s.id,action:"remind"}),ne.success("Reminder sent")}catch(m){ne.error((m==null?void 0:m.message)||"Could not send a reminder")}},children:[e.jsx(fS,{className:"mr-1 h-3 w-3"})," Remind"]}),a&&e.jsxs(z,{size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:u,children:[e.jsx(QA,{className:"mr-1 h-3 w-3"})," Countersign now"]}),s.status==="completed"&&e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:d,children:[e.jsx(Ga,{className:"mr-1 h-3 w-3"})," Signed PDF"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:c,children:[e.jsx(cq,{className:"mr-1 h-3 w-3"})," Audit trail"]}),i&&e.jsxs(z,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",disabled:n.isPending,onClick:h,children:[e.jsx(JO,{className:"mr-1 h-3 w-3"})," Void"]})]})]})}function ver({dealId:s,dealName:t}){const[n,r]=_.useState(!1),[a,i]=_.useState(!1),{data:l=[],isLoading:o,error:c}=aer(s),{data:d=[]}=uer(s);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs(z,{className:"flex-1",onClick:()=>i(!0),children:[e.jsx(Mm,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(z,{variant:"outline",className:"flex-1",onClick:()=>r(!0),children:[e.jsx(UU,{className:"mr-2 h-4 w-4"})," Prepare a form"]}),e.jsxs(z,{variant:"outline",className:"sm:w-auto",onClick:()=>window.open("/mission-control/forms","_blank","noopener,noreferrer"),children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," Forms Library"]})]}),d.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Signature requests"}),d.map(u=>e.jsx(yer,{envelope:u},u.id))]}),o&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),c&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load generated forms."}),!o&&!c&&l.length===0&&d.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed py-8 text-center text-sm text-muted-foreground",children:"No forms generated for this deal yet."}),l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Generated forms"}),l.map(u=>{var h,m;return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-background p-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-muted",children:e.jsx($r,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:((h=u.template)==null?void 0:h.name)||"Deleted template"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",((m=u.version)==null?void 0:m.version_number)??"—"," · ",Ys(new Date(u.created_at),"MMM d, yyyy")]})]})]},u.id)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signature requests email each signer a secure link and remind them automatically on day 3 and day 10. The completed, audit-certified PDF lands in this deal’s Files tab and is emailed to everyone who signed."}),e.jsx(Brs,{open:n,onOpenChange:r,dealId:s,dealName:t}),e.jsx(qrs,{open:a,onOpenChange:i,dealId:s,dealName:t})]})}const A4t={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function Vrs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=YOn(),a=ZOn(),i=XOn(),l=QOn(),[o,c]=_.useState(!1),[d,u]=_.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=_.useState(""),p=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),m(""),c(!1),ne.success("Question added")}catch{ne.error("Failed to add question")}},f=async b=>{try{await l.mutateAsync(b),ne.success("Question removed")}catch{ne.error("Failed to remove question")}},g=async(b,w)=>{try{await i.mutateAsync({id:b,is_required:w})}catch{ne.error("Failed to update question")}},v=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},y=b=>{u(w=>({...w,options:w.options.filter((S,C)=>C!==b)}))};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Rs,{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(Ki,{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(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(b=>{var w;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(Zf,{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:b.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"secondary",className:"text-xs",children:A4t[b.field_type]||b.field_type}),b.is_required&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Required"})]}),b.field_type==="dropdown"&&((w=b.options)==null?void 0:w.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",b.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(mn,{checked:b.is_required,onCheckedChange:S=>g(b.id,S),className:"scale-75"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>f(b.id),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})},b.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(ee,{className:"text-sm font-medium",children:"Question"}),e.jsx(pe,{value:d.question_text,onChange:b=>u(w=>({...w,question_text:b.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(A4t).map(([b,w])=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,field_type:b,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===b?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:w},b))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((b,w)=>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:b}),e.jsx("button",{onClick:()=>y(w),className:"text-muted-foreground hover:text-destructive",children:e.jsx(er,{className:"h-3.5 w-3.5"})})]},w)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),v()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(z,{variant:"outline",size:"sm",onClick:v,disabled:!h.trim(),className:"h-8",children:e.jsx(sn,{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(mn,{checked:d.is_required,onCheckedChange:b=>u(w=>({...w,is_required:b}))}),e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(z,{size:"sm",onClick:p,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(bt,{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(z,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function ber({override:s,onChange:t}){const n=ha(),{data:r}=T9t(),[a,i]=_.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ne.error("Image must be under 5MB");return}i(u);try{const h=await M9t(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ne.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(E4t,{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(E4t,{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(T4t,{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(T4t,{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(ee,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(pe,{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(z,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(Cn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function E4t({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(ee,{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:Ct("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(nc,{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(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ra,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(z,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})]})}function T4t({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(ee,{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:Ct("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(pe,{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(z,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(Cn,{className:"h-3 w-3"})})]})]})}function _er({portalId:s,agentUserId:t}){const n=$t(),{data:r,isLoading:a}=rt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,p=U.from("vendors").select("*").eq("is_active",!0),f=m?p.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):p.eq("owner_type","agent").eq("owner_user_id",t),[{data:g,error:v},{data:y},{data:b}]=await Promise.all([f.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(v)throw v;const w=new Map;(y||[]).forEach(C=>w.set(C.vendor_id,C.is_visible));const S=new Map;return(b||[]).forEach(C=>S.set(C.vendor_id,C.is_visible)),{vendors:g||[],selMap:w,overrideMap:S}}}),i=mt({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:p}=await U.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(p){const{error:f}=await U.from("portal_vendor_overrides").update({is_visible:m}).eq("id",p.id);if(f)throw f}else{const{error:f}=await U.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(f)throw f}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>ne.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{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(jv,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const m=c.get(h.id);if(m!==void 0)return m;if(h.is_required)return!0;const p=o.get(h.id);return p===void 0?!0:p!==!1},u=h=>{var m;return((m=_W.find(p=>p.value===h))==null?void 0:m.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(Ki,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const m=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx(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(mn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:p=>i.mutate({vendorId:h.id,isVisible:p})})]},h.id)})})})]})}function wer({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=_.useState(""),[o,c]=_.useState(!1),{data:d,isLoading:u}=rt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:f,error:g}=await U.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(g)throw g;return f},enabled:o||!!r}),h=_.useMemo(()=>!r||!d?null:d.find(f=>f.id===r),[r,d]),m=_.useMemo(()=>!d||!n?[]:d.filter(f=>{var g;return((g=f.client_email)==null?void 0:g.toLowerCase())===n.toLowerCase()&&f.id!==s}),[d,n,s]),p=_.useMemo(()=>{if(!d||!i.trim())return[];const f=i.toLowerCase();return d.filter(g=>{var y,b,w,S;const v=g.deal_pipeline;return((y=g.client_name)==null?void 0:y.toLowerCase().includes(f))||((b=g.client_email)==null?void 0:b.toLowerCase().includes(f))||((w=v==null?void 0:v.deal_name)==null?void 0:w.toLowerCase().includes(f))||((S=v==null?void 0:v.property_address)==null?void 0:S.toLowerCase().includes(f))})},[d,i]);if(r){const f=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(Oc,{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)||(f==null?void 0:f.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(f==null?void 0:f.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(f==null?void 0:f.property_address)||"No address"]})]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(rE,{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(ee,{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(z,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(Oc,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&m.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),m.map(f=>{const g=f.deal_pipeline;return e.jsxs("button",{onClick:()=>a(f.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:(g==null?void 0:g.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:(g==null?void 0:g.deal_name)||f.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g==null?void 0:g.property_address})]}),e.jsx(Oc,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},f.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:i,onChange:f=>l(f.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(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),p.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:p.map(f=>{const g=f.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(f.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:(g==null?void 0:g.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:(g==null?void 0:g.deal_name)||f.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:f.client_email})]})]},f.id)})}),i&&p.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function git({contactId:s,onVideoReady:t}){const[n,r]=_.useState(!1),[a,i]=_.useState("record"),[l,o]=_.useState(0),[c,d]=_.useState(0),u=RC(),h=()=>{i("record"),o(0),d(0)},m=f=>{!f&&(a==="uploading"||a==="processing")||(r(f),f||h())},p=_.useCallback(async(f,g)=>{i("uploading");try{const v="Card Video",{videoId:y,libraryId:b}=await qL(v),{uploadUrl:w,apiKey:S}=await VL(y),C=new XMLHttpRequest;C.upload.onprogress=q=>{q.lengthComputable&&o(q.loaded/q.total*100)},await new Promise((q,G)=>{C.onload=()=>C.status>=200&&C.status<300?q():G(new Error("Upload failed")),C.onerror=()=>G(new Error("Upload failed")),C.open("PUT",w),C.setRequestHeader("AccessKey",S),C.send(f)}),i("processing");let E=0;const P=Date.now(),M=9e4,I=`https://iframe.mediadelivery.net/embed/${b}/${y}`;for(;E<4;){if(await new Promise(G=>setTimeout(G,3e3)),Date.now()-P>M){const G=f.size/1048576;await u.mutateAsync({bunny_video_id:y,playback_url:`https://iframe.mediadelivery.net/play/${b}/${y}`,file_size_mb:G,title:v,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(I),ne.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const q=await DN(y);if(E=q.status,d(q.encodeProgress||0),E===5||E===6)throw new Error("Video processing failed")}const D=await DN(y),F=(D.storageSize||f.size)/(1024*1024);await u.mutateAsync({bunny_video_id:y,contact_id:s||void 0,playback_url:D.directPlayUrl||I,thumbnail_url:D.thumbnailUrl,preview_url:D.previewUrl||null,duration_seconds:D.length||g,file_size_mb:F,title:v,status:"ready",touch_type:"video"}),t(I),ne.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(v){console.error("Recording upload error:",v),ne.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(Is,{open:n,onOpenChange:m,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Ls,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(YE,{maxDurationSeconds:600,onRecordingComplete:p,onError:f=>ne.error(f)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(bt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Di,{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(bt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Di,{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(Xl,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const jer=s=>`portal-settings-draft:${s}`;function yit({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=QW(),[i,l]=_.useState(!1),o=_.useMemo(()=>jer(n.id),[n.id]),[c,d]=_.useState(!1),[u,h]=_.useState(n.next_step_text||""),[m,p]=_.useState(n.next_step_video_url||""),[f,g]=_.useState(n.inspection_date||""),[v,y]=_.useState(n.appraisal_date||""),[b,w]=_.useState(n.welcome_message||""),[S,C]=_.useState(n.review_url||""),[E,P]=_.useState(n.show_post_close_tips),[M,I]=_.useState(n.notify_client),[D,F]=_.useState(n.require_onboarding),[q,G]=_.useState(n.allow_spouse),[V,H]=_.useState(n.visibility),[K,Z]=_.useState(n.stage_mapping||[]),[oe,re]=_.useState(null),[ae,J]=_.useState(n.linked_portal_id||null),[te,ce]=_.useState(n.referral_enabled??!0),[ve,me]=_.useState(n.referral_reward_text||""),[he,ge]=_.useState(n.referral_cta_headline||""),[Ee,Ne]=_.useState(n.homeowner_hub_video_url||""),[Pe,Oe]=_.useState(n.branding_override||{}),ke=()=>{h(n.next_step_text||""),p(n.next_step_video_url||""),g(n.inspection_date||""),y(n.appraisal_date||""),w(n.welcome_message||""),C(n.review_url||""),P(n.show_post_close_tips),I(n.notify_client),F(n.require_onboarding),G(n.allow_spouse),H(n.visibility),Z(n.stage_mapping||[]),J(n.linked_portal_id||null),ce(n.referral_enabled??!0),me(n.referral_reward_text||""),ge(n.referral_cta_headline||""),Ne(n.homeowner_hub_video_url||""),Oe(n.branding_override||{})};_.useEffect(()=>{d(!1);const Be=localStorage.getItem(o);if(Be)try{const Ze=JSON.parse(Be);h(Ze.nextStepText||""),p(Ze.nextStepVideo||""),g(Ze.inspectionDate||""),y(Ze.appraisalDate||""),w(Ze.welcomeMessage||""),C(Ze.reviewUrl||""),P(!!Ze.showPostClose),I(!!Ze.notifyClient),F(!!Ze.requireOnboarding),G(!!Ze.allowSpouse),H(Ze.visibility||n.visibility),Z(Ze.stageMapping||[]),J(Ze.linkedPortalId??null),ce(Ze.referralEnabled??!0),me(Ze.referralRewardText||""),ge(Ze.referralCtaHeadline||""),Ne(Ze.homeownerHubVideoUrl||""),Oe(Ze.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ke(),d(!0)},[o,n]),_.useEffect(()=>{if(!c)return;const Be={nextStepText:u,nextStepVideo:m,inspectionDate:f,appraisalDate:v,welcomeMessage:b,reviewUrl:S,showPostClose:E,notifyClient:M,requireOnboarding:D,allowSpouse:q,visibility:V,stageMapping:K,linkedPortalId:ae,referralEnabled:te,referralRewardText:ve,referralCtaHeadline:he,homeownerHubVideoUrl:Ee,brandingOverride:Pe};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||f!==(n.inspection_date||"")||v!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||S!==(n.review_url||"")||E!==n.show_post_close_tips||M!==n.notify_client||D!==n.require_onboarding||q!==n.allow_spouse||V!==n.visibility||JSON.stringify(K)!==JSON.stringify(n.stage_mapping||[])||ae!==(n.linked_portal_id||null)||te!==(n.referral_enabled??!0)||ve!==(n.referral_reward_text||"")||he!==(n.referral_cta_headline||"")||Ee!==(n.homeowner_hub_video_url||"")||JSON.stringify(Pe)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Be)):localStorage.removeItem(o)},[u,m,f,v,b,S,E,M,D,q,V,K,ae,te,ve,he,Ee,Pe,o,c,n]);const Ve=()=>{localStorage.removeItem(o),ke()},_e=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:f||null,appraisal_date:v||null,welcome_message:b||null,review_url:S||null,show_post_close_tips:E,notify_client:M,require_onboarding:D,allow_spouse:q,visibility:V,stage_mapping:K.length>0?K:null,linked_portal_id:ae,referral_enabled:te,referral_reward_text:ve||null,referral_cta_headline:he||null,homeowner_hub_video_url:Ee||null,branding_override:Object.values(Pe).some(Ze=>Ze!=null&&Ze!=="")?Pe:null});const Be=n.linked_portal_id;ae&&ae!==Be&&await U.from("client_portals").update({linked_portal_id:n.id}).eq("id",ae),!ae&&Be&&await U.from("client_portals").update({linked_portal_id:null}).eq("id",Be),localStorage.removeItem(o),ne.success("Portal settings saved"),t(!1)}catch{ne.error("Failed to save settings")}},Ae=()=>{Z([...K,{label:""}])},Se=Be=>{Z(K.filter((Ze,$e)=>$e!==Be)),oe===Be&&re(null)},We=(Be,Ze,$e)=>{const Xe=[...K];Xe[Be]={...Xe[Be],[Ze]:$e},Z(Xe)},qe=()=>{const Ze=JPe(null).map($e=>({label:$e.label,description:$e.description,stageId:void 0}));Z(Ze)};return e.jsxs(e.Fragment,{children:[e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Portal Settings"})}),e.jsxs(Qr,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Jr,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Wt,{value:"general",children:"General"}),e.jsx(Wt,{value:"timeline",children:"Timeline"}),e.jsx(Wt,{value:"content",children:"Content"}),e.jsx(Wt,{value:"vendors",children:"Vendors"}),e.jsx(Wt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Kt,{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(ee,{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(Be=>e.jsx("button",{onClick:()=>H(Be),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${V===Be?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Be.charAt(0).toUpperCase()+Be.slice(1)},Be))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:D,onCheckedChange:F})]}),D&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(z,{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(ee,{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(mn,{checked:q,onCheckedChange:G})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:E,onCheckedChange:P})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:M,onCheckedChange:I})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(wer,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:ae,onLink:J})}),e.jsx("div",{children:e.jsx(pe,{type:"date",value:f,onChange:Be=>g(Be.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(pe,{type:"date",value:v,onChange:Be=>y(Be.target.value),className:"mt-1"})]})]}),e.jsx(Kt,{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(ee,{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(z,{variant:"outline",size:"sm",onClick:qe,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.'}),K.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(z,{variant:"outline",size:"sm",onClick:qe,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:K.map((Be,Ze)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zf,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(pe,{value:Be.label,onChange:$e=>We(Ze,"label",$e.target.value),placeholder:`Stage ${Ze+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>re(oe===Ze?null:Ze),children:oe===Ze?"Less":"More"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Se(Ze),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]}),oe===Ze&&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(ee,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Be.description||"",onChange:$e=>We(Ze,"description",$e.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(ee,{className:"text-xs text-muted-foreground",children:"Video"}),Be.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:Be.video_url.length>40?Be.video_url.slice(0,40)+"...":Be.video_url}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>We(Ze,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(git,{onVideoReady:$e=>We(Ze,"video_url",$e)}),e.jsx(pz,{userId:r,onSelect:$e=>We(Ze,"video_url",$e),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const $e=prompt("Paste a YouTube or Loom URL:");$e&&We(Ze,"video_url",$e)},children:[e.jsx(Kc,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Ze))}),K.length>0&&e.jsxs(z,{variant:"outline",size:"sm",onClick:Ae,className:"mt-2 text-xs w-full",children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Kt,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:b,onChange:Be=>w(Be.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(ee,{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:Be=>h(Be.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(ee,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(pe,{value:m,onChange:Be=>p(Be.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:S,onChange:Be=>C(Be.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(ee,{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(ee,{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(mn,{checked:te,onCheckedChange:ce})]}),te&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Headline"}),e.jsx(pe,{value:he,onChange:Be=>ge(Be.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:ve,onChange:Be=>me(Be.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:Ee,onChange:Be=>Ne(Be.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Kt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(_er,{portalId:n.id,agentUserId:r})}),e.jsx(Kt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(ber,{override:Pe,onChange:Oe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(z,{variant:"ghost",onClick:Ve,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(z,{onClick:_e,disabled:a.isPending,children:[a.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(Vrs,{open:i,onOpenChange:l})]})}const Ner=s=>`portal-update-draft:${s}`;function vit({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=_.useMemo(()=>Ner(n),[n]),[l,o]=_.useState(""),[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState(!1),[f,g]=_.useState(a??!0),[v,y]=_.useState(!1),b=IZt();_.useEffect(()=>{y(!1);const C=localStorage.getItem(i);if(C)try{const E=JSON.parse(C);o(E.title||""),d(E.content||""),h(E.videoUrl||""),p(!!E.isStageChange),g(typeof E.sendNotification=="boolean"?E.sendNotification:a??!0),y(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),p(!1),g(a??!0),y(!0)},[i,a]),_.useEffect(()=>{if(!v)return;const C={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:f};l.trim()||c.trim()||u.trim()||m||f!==(a??!0)?localStorage.setItem(i,JSON.stringify(C)):localStorage.removeItem(i)},[l,c,u,m,f,v,i,a]);const w=()=>{localStorage.removeItem(i),o(""),d(""),h(""),p(!1),g(a??!0)},S=async()=>{if(l.trim())try{if(await b.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),f&&r)try{const C=SS(r),{data:E,error:P}=await U.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,video_url:u.trim()||null,is_stage_change:m,portal_url:C,force:!0}});if(P)throw P;E!=null&&E.emailSent?ne.success("Update posted & client emailed"):ne.success(`Update posted (${(E==null?void 0:E.reason)||"no email sent"})`)}catch(C){console.error("Notification failed:",C),ne.success("Update posted (notification failed to send)")}else ne.success("Update posted to portal");w(),t(!1)}catch{ne.error("Failed to post update")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Title *"}),e.jsx(pe,{value:l,onChange:C=>o(C.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:C=>d(C.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(ee,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(pe,{value:u,onChange:C=>h(C.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(Xr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>p(!m),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${m?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>g(!f),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${f?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[f?e.jsx($g,{className:"h-3 w-3"}):e.jsx(pS,{className:"h-3 w-3"}),f?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(z,{variant:"ghost",onClick:w,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(z,{onClick:S,disabled:!l.trim()||b.isPending,children:[b.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function bit({open:s,onOpenChange:t,portal:n,dealName:r}){const a=QW(),{isGmailConnected:i,gmailEmail:l}=bg(),[o,c]=_.useState(n.client_name||""),[d,u]=_.useState(n.client_email||""),[h,m]=_.useState(!1),[p,f]=_.useState(!1),g=SS(n.slug),v=o.split(" ")[0]||"there",y=`Your Transaction Portal – ${r}`,b=`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: ${g} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,w=()=>{navigator.clipboard.writeText(g),f(!0),setTimeout(()=>f(!1),2e3),ne.success("Portal link copied!")},S=async()=>{if(!d.trim()){ne.error("Please enter the client email");return}m(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:E}=await U.functions.invoke("gmail-send",{body:{to:d,subject:y,body:b.replace(/\n/g,"
")}});if(E){let P="";try{const M=E==null?void 0:E.context;if(M&&typeof M.json=="function"){const I=await M.json();P=(I==null?void 0:I.message)||(I==null?void 0:I.error)||""}}catch{}throw new Error(P||E.message||"Failed to send invite")}ne.success(`Invite sent to ${d}`),t(!1)}catch(E){ne.error(E.message||"Failed to send invite")}finally{m(!1)}},C=()=>{const E=encodeURIComponent(y),P=encodeURIComponent(b);window.open(`mailto:${d}?subject=${E}&body=${P}`,"_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(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(pe,{value:o,onChange:E=>c(E.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(pe,{type:"email",value:d,onChange:E=>u(E.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{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:g})}),e.jsx(z,{variant:"outline",size:"icon",onClick:w,className:"shrink-0",children:p?e.jsx(Wr,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Sa,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(z,{onClick:S,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(z,{onClick:C,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(z,{variant:"ghost",onClick:w,className:"w-full text-muted-foreground",children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function ker({deal:s}){const{isAdmin:t,user:n}=hs(),{data:r,isLoading:a}=WOn(s.id),i=trt(),l=QW(),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(!1),g=`portal-management-ui:${s.id}`;if(_.useEffect(()=>{const E=sessionStorage.getItem(g);if(E)try{const P=JSON.parse(E);u(!!P.settingsOpen),m(!!P.composerOpen),f(!!P.inviteOpen)}catch{sessionStorage.removeItem(g)}},[g]),_.useEffect(()=>{d||h||p?sessionStorage.setItem(g,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:p})):sessionStorage.removeItem(g)},[d,h,p,g]),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(bt,{className:"h-3 w-3 animate-spin ml-auto"})]})});const v=async()=>{var E,P;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:((E=s.contact)==null?void 0:E.email)||void 0,client_phone:((P=s.contact)==null?void 0:P.phone)||void 0}),ne.success("Client portal enabled!")}catch{ne.error("Failed to create portal")}finally{c(!1)}},y=async E=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:E}),ne.success(E?"Portal enabled":"Portal disabled")}catch{ne.error("Failed to update portal")}},b=()=>{if(!r)return;const E=SS(r.slug);navigator.clipboard.writeText(E),ne.success("Portal link copied!")},w=()=>{if(!r)return;const E=SS(r.slug);window.open(E,"_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(z,{onClick:v,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const S=SS(r.slug),C=(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(mn,{checked:r.is_enabled,onCheckedChange:y})]}),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:S})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:b,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:w,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(mr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Fr,{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(z,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(I4,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Gc,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(or,{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(Ko,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(yit,{open:d,onOpenChange:u,portal:r,dealOwnerId:C}),e.jsx(vit,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(bit,{open:p,onOpenChange:f,portal:r,dealName:s.deal_name})]})}function Ser({dealId:s,primaryContactId:t}){const n=zn(),{data:r,isLoading:a}=$rs(s),{data:i}=Rb(),l=cer(),o=der(),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState("Client"),f=new Set((r==null?void 0:r.map(w=>w.contact_id))||[]);t&&f.add(t);const g=i==null?void 0:i.filter(w=>{var C,E,P;if(f.has(w.id))return!1;if(!u.trim())return!0;const S=u.toLowerCase();return((C=w.first_name)==null?void 0:C.toLowerCase().includes(S))||((E=w.last_name)==null?void 0:E.toLowerCase().includes(S))||((P=w.email)==null?void 0:P.toLowerCase().includes(S))}).slice(0,8),v=w=>{l.mutate({dealId:s,contactId:w,role:m}),d(!1),h("")},y=w=>{o.mutate({id:w,dealId:s})},b={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(On,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(hd,{open:c,onOpenChange:d,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(nd,{className:"w-80 p-3",align:"start",children:e.jsx(M4t,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:g,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(On,{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(hd,{open:c,onOpenChange:d,children:[e.jsx(md,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})}),e.jsx(nd,{className:"w-80 p-3",align:"end",children:e.jsx(M4t,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:g,onAdd:v})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(w=>{var S,C,E,P,M,I,D,F;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(ja,{className:"h-7 w-7",children:e.jsxs(Na,{className:"text-[10px] bg-primary/10 text-primary",children:[(C=(S=w.contact)==null?void 0:S.first_name)==null?void 0:C[0],(P=(E=w.contact)==null?void 0:E.last_name)==null?void 0:P[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${w.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(M=w.contact)==null?void 0:M.first_name," ",(I=w.contact)==null?void 0:I.last_name]})}),e.jsx(ze,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${b[w.role]||b.Other}`,children:w.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((D=w.contact)==null?void 0:D.phone)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${w.contact.phone}`,children:e.jsx(va,{className:"h-3 w-3"})})}),((F=w.contact)==null?void 0:F.email)&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${w.contact.email}`,children:e.jsx(on,{className:"h-3 w-3"})})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>y(w.id),children:e.jsx(Cn,{className:"h-3 w-3"})})]})]},w.id)})})]})}function M4t({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"h-8 text-sm",children:e.jsx(cs,{placeholder:"Role"})}),e.jsx(as,{children:ler.map(l=>e.jsx(He,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Ki,{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 uQ=[{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"}],Cer=[{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 Aer(){const s=$t();return mt({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 U.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 Eer(){const s=$t();return mt({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await U.from("deal_pipeline").update({completed_key_dates:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function Ter(){return rt({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await U.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await U.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 Mer(){const s=ha(),t=$t();return mt({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([U.from("deal_pipeline").select("*").eq("id",r).single(),U.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 U.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(f=>String(f.title).toLowerCase())),u=a,h=(f,g)=>{const v=f==="stage_entry"?null:u[f],y=v?new Date(`${v}T12:00:00`):new Date;return y.setDate(y.getDate()+(g||0)),y.toISOString().split("T")[0]},m=l.filter(f=>!d.has(String(f.title).toLowerCase())).map((f,g)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:f.title,description:f.description,priority:f.priority,status:"todo",due_date:h(f.due_anchor,f.due_offset_days),sort_order:g}));if(m.length===0)return 0;const{error:p}=await U.from("deal_tasks").insert(m);if(p)throw p;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function Per(){const s=ha(),t=$t();return mt({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([U.from("tc_playbooks").select("deal_type").eq("id",n).single(),U.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 U.from("deal_task_templates").select("title").eq("owner_user_id",s).eq("stage_id",r),c=new Set((o||[]).map(h=>String(h.title).toLowerCase())),d=i.filter(h=>!c.has(String(h.title).toLowerCase())).map((h,m)=>({owner_user_id:s,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_anchor:h.due_anchor,default_due_offset_days:h.due_offset_days,deal_type:(a==null?void 0:a.deal_type)??null,playbook_id:n,sort_order:m}));if(d.length===0)return 0;const{error:u}=await U.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function Ler(){const s=ha();return rt({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 U.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 _it(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 K5(s){const t=_it(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 Ier(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const Der={done:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",overdue:"border-destructive/40 bg-destructive/10 text-destructive",today:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400",soon:"border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-400",upcoming:"border-border bg-muted/40 text-foreground",none:"border-dashed border-border bg-transparent text-muted-foreground"};function OBe(s){const t=_it(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function P4t(s,t){return s==="done"?"Completed":t===null?"Not set":t===0?"Today":t<0?`${Math.abs(t)}d past due`:`in ${t}d`}function Rer({deal:s,compact:t=!1}){const n=Aer(),r=Eer(),[a,i]=_.useState(!1),[l,o]=_.useState({}),c=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],[d,u]=_.useState(c),h=c.join(","),m=_.useRef(h);_.useEffect(()=>{m.current!==h&&(m.current=h,u(c))},[h]);const p=d,f=()=>{const H={};uQ.forEach(K=>{H[K.key]=(s==null?void 0:s[K.key])??""}),o(H),i(!0)},g=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),ne.success("Transaction dates updated"),i(!1)}catch(H){ne.error((H==null?void 0:H.message)||"Could not save dates")}},v=async(H,K)=>{const Z=p;u(H);try{await r.mutateAsync({dealId:s.id,completed:H}),ne.success(K)}catch(oe){u(Z),ne.error((oe==null?void 0:oe.message)||"Could not update milestone")}},y=_.useMemo(()=>uQ.map(H=>{const K=(s==null?void 0:s[H.key])??null,Z=K5(K),oe=p.includes(H.key),re=K?oe?"done":Ier(Z):"none";return{...H,value:K,days:Z,isDone:oe,state:re}}),[s,p.join(",")]),b=y.filter(H=>H.value).length,w=y.filter(H=>H.state==="done").length,S=K5(s==null?void 0:s.target_close_date),C=y.filter(H=>H.value&&!H.isDone&&H.days!==null&&H.days>=0).sort((H,K)=>(H.days??0)-(K.days??0))[0],E=y.filter(H=>H.state==="overdue"),P=()=>{const H=Array.from(new Set([...p,...E.map(K=>K.key)]));v(H,"Past milestones marked complete")},M=(H,K)=>{const Z=K?p.filter(oe=>oe!==H):[...p,H];v(Z,K?"Marked as not complete":"Milestone completed")},[I,D]=_.useState(null),[F,q]=_.useState(""),G=H=>{q((s==null?void 0:s[H])??""),D(H)},V=async(H,K)=>{try{await n.mutateAsync({dealId:s.id,dates:{[H]:K}}),ne.success(K?"Date saved":"Date cleared"),D(null)}catch(Z){ne.error((Z==null?void 0:Z.message)||"Could not save date")}};return e.jsx(UN,{delayDuration:200,children:e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 border-b bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Ud,{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:p.includes("target_close_date")||s!=null&&s.actual_close_date?`Closed${OBe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))?` ${OBe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))}`:""} · ${w}/${b} milestones done`:S!==null?S>=0?`${S} day${S===1?"":"s"} to closing · ${w}/${b} milestones done`:`Closing was ${Math.abs(S)} day${Math.abs(S)===1?"":"s"} ago`:`${b} of ${uQ.length} key dates set`})]})]}),e.jsxs(Is,{open:a,onOpenChange:H=>H?f():i(!1),children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(Wa,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Key transaction dates"})}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-3 max-h-[60vh] overflow-y-auto pr-1",children:uQ.map(H=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{htmlFor:`kd-${H.key}`,className:"text-xs text-muted-foreground",children:H.label}),e.jsx(pe,{id:`kd-${H.key}`,type:"date",value:l[H.key]??"",onChange:K=>o(Z=>({...Z,[H.key]:K.target.value})),className:"h-9"})]},H.key))}),e.jsxs(hr,{children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(z,{size:"sm",onClick:g,disabled:n.isPending,children:[n.isPending?e.jsx(bt,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Save all"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:y.map(H=>{const K=!!H.value;return e.jsxs("div",{className:"relative",children:[e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r.isPending,onClick:()=>K?M(H.key,H.isDone):G(H.key),className:Ct("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",Der[H.state],"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-10",children:H.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:OBe(H.value)??"Set date"}),H.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:P4t(H.state,H.days)}),K&&e.jsx("span",{className:Ct("absolute top-1.5 right-7 h-4 w-4 rounded-full border flex items-center justify-center",H.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:H.isDone&&e.jsx(Wr,{className:"h-2.5 w-2.5"})})]})}),e.jsx(Tx,{side:"top",children:H.value?H.isDone?`${H.label} completed — click to reopen`:`Click to mark ${H.label} complete`:`${H.label} — click to set the date`})]}),e.jsxs(hd,{open:I===H.key,onOpenChange:Z=>Z?G(H.key):D(null),children:[e.jsx(md,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`Edit ${H.label}`,className:"absolute top-1 right-1 h-5 w-5 rounded-md flex items-center justify-center text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:e.jsx(Wa,{className:"h-3 w-3"})})}),e.jsxs(nd,{className:"w-64 p-3",align:"end",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:H.label}),e.jsx(pe,{type:"date",autoFocus:!0,value:F,onChange:Z=>q(Z.target.value),className:"h-9 mt-1"}),e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-3",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>V(H.key,""),disabled:n.isPending||!H.value,children:"Clear"}),e.jsxs(z,{size:"sm",onClick:()=>V(H.key,F),disabled:n.isPending,children:[n.isPending?e.jsx(bt,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]},H.key)})}),(E.length>0||C||w>0)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[w>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 px-2.5 py-1 font-medium",children:[e.jsx(e7,{className:"h-3 w-3"}),w," completed"]}),E.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(nl,{className:"h-3 w-3"}),E.length," awaiting confirmation"]}),C&&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: ",C.label," · ",P4t(C.state,C.days)]}),E.length>0&&e.jsxs("button",{type:"button",onClick:P,disabled:r.isPending,className:"ml-auto inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-medium hover:bg-muted transition-colors",children:[e.jsx(e7,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),E.length>0&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"Dates in the past show as awaiting confirmation until you check them off — tap a tile to mark it complete."}),b===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 Fer={Home:sa,FileSignature:cb,Handshake:jv,CalendarClock:Ud,Sparkles:un,ClipboardCheck:fN},Oer={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 zer(s,t){var a;const n=((a=Cer.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 Hrs({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=Ter(),{data:l}=cie(),o=Mer(),c=Per(),[d,u]=_.useState(null),[h,m]=_.useState({}),p=v=>{if(h[v.id])return h[v.id];const y=l==null?void 0:l.find(b=>{var w,S;return((w=b.name)==null?void 0:w.toLowerCase())===((S=v.target_stage_name)==null?void 0:S.toLowerCase())});return(y==null?void 0:y.id)??""},f=async v=>{if(n){u(v.id);try{const y=await o.mutateAsync({playbookId:v.id,dealId:n});ne.success(y>0?`Added ${y} task${y===1?"":"s"} to this deal`:"All tasks already exist on this deal"),y>0&&t(!1)}catch(y){ne.error((y==null?void 0:y.message)||"Could not apply playbook")}finally{u(null)}}},g=async v=>{const y=p(v);if(!y){ne.error("Pick which stage this playbook should trigger on");return}u(`install-${v.id}`);try{const b=await c.mutateAsync({playbookId:v.id,stageId:y});ne.success(b>0?`Automated — ${b} task${b===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(b){ne.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Os,{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(ip,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rs,{children:"Transaction Playbooks"}),e.jsx(_r,{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(Ki,{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(ez,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(v=>{const y=Fer[v.icon||"ClipboardCheck"]||fN,b=v.accent_color||"hsl(var(--primary))";return e.jsxs(AL,{value:v.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(EL,{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:`${b}1a`},children:e.jsx(y,{className:"h-5 w-5",style:{color:b}})}),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(TL,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:v.tasks.map((w,S)=>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:S+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:w.title}),w.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:w.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:zer(w.due_anchor,w.due_offset_days)})]}),e.jsx("span",{className:Ct("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",Oer[w.priority]),children:w.priority})]},w.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs(z,{size:"sm",className:"gap-1.5",onClick:()=>f(v),disabled:d===v.id,children:[d===v.id?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(cf,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(ls,{value:p(v),onValueChange:w=>m(S=>({...S,[v.id]:w})),children:[e.jsx(rs,{className:"h-9 text-xs flex-1",children:e.jsx(cs,{placeholder:"Trigger stage"})}),e.jsx(as,{children:(l||[]).map(w=>e.jsx(He,{value:w.id,children:w.name},w.id))})]}),e.jsxs(z,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>g(v),disabled:d===`install-${v.id}`,children:[d===`install-${v.id}`?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(sE,{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(Mr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},v.id)})})})})]})})}function Ber(s){return rt({queryKey:["deal-email-links",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_email_links").select("id, gmail_message_id, gmail_thread_id, subject, from_address, participants, sent_at, note, created_at").eq("deal_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}).range(0,999);if(n)throw n;return t},enabled:!!s})}function $er(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await U.from("deal_email_links").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-email-links",s]})}})}function Uer(s,t){return s?`https://mail.google.com/mail/u/0/#all/${encodeURIComponent(s)}`:`https://mail.google.com/mail/u/0/#all/${encodeURIComponent(t)}`}function qer({dealId:s}){const{data:t=[],isLoading:n,error:r}=Ber(s),a=$er(s);return e.jsxs("section",{"aria-labelledby":"linked-emails-heading",className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{id:"linked-emails-heading",className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(on,{className:"h-4 w-4 text-primary"})," Linked emails"]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," connected"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading linked emails…"}):r?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",children:"We couldn't load the emails linked to this transaction. Please refresh and try again."}):t.length===0?e.jsx("p",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No emails linked yet — attach one from Gmail with the LevelUp Companion extension."}):e.jsx("div",{className:"divide-y rounded-md border",children:t.map(i=>{const l=i.sent_at||i.created_at;return e.jsxs("div",{className:"flex items-start gap-3 p-3",children:[e.jsx(on,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:i.subject||"Email from Gmail"}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[i.from_address||"Unknown sender",l?` · ${Ys(Ou(l),"MMM d, yyyy")}`:"",i.sent_at?"":" (attached)"]}),i.note&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:i.note})]}),e.jsx(z,{variant:"ghost",size:"icon",asChild:!0,title:"Open in Gmail",children:e.jsx("a",{href:Uer(i.gmail_thread_id,i.gmail_message_id),target:"_blank",rel:"noreferrer",children:e.jsx(mr,{className:"h-4 w-4"})})}),e.jsx(z,{variant:"ghost",size:"icon",title:"Remove link",disabled:a.isPending,onClick:()=>a.mutate(i.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]},i.id)})})]})}const Ver=10*1024*1024;function Her({dealId:s,photoUrl:t}){const n=_.useRef(null),r=$t(),[a,i]=_.useState(!1),l=async d=>{const{error:u}=await U.from("deal_pipeline").update({property_photo_url:d}).eq("id",s);if(u)throw u;r.invalidateQueries({queryKey:["deal-pipeline-deals"]}),r.invalidateQueries({queryKey:["deals"]})},o=async d=>{var u;if(!d.type.startsWith("image/")){ne.error("Please choose an image file");return}if(d.size>Ver){ne.error("Image must be under 10MB");return}i(!0);try{const{data:h}=await U.auth.getUser(),m=(d.name.split(".").pop()||"jpg").toLowerCase(),p=`deal-photos/${(u=h.user)==null?void 0:u.id}/${s}-${Date.now()}.${m}`,{error:f}=await U.storage.from("agent-uploads").upload(p,d,{upsert:!0,contentType:d.type});if(f)throw f;const{data:g}=U.storage.from("agent-uploads").getPublicUrl(p);await l(g.publicUrl),ne.success("Property photo updated")}catch(h){ne.error(h.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}},c=async()=>{i(!0);try{await l(null),ne.success("Photo removed")}catch(d){ne.error(d.message||"Could not remove photo")}finally{i(!1)}};return e.jsxs("div",{className:"col-span-2",children:[e.jsxs("button",{type:"button",onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:a,className:"group relative w-full h-36 rounded-lg overflow-hidden border border-border bg-muted/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":t?"Change property photo":"Add property photo",children:[t?e.jsx("img",{src:t,alt:"Property",className:"h-full w-full object-cover"}):e.jsxs("span",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(sa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Add property photo"})]}),e.jsx("span",{className:"absolute inset-0 bg-foreground/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:a?e.jsx(bt,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(Lx,{className:"h-5 w-5 text-background"})})]}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shows on the deal and in the Gmail companion panel."}),t&&e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-1.5 text-muted-foreground",onClick:c,disabled:a,children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"Remove"]})]}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&o(u)}})]})}const Ger={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"}},Wer={note:qi,call:va,email:on,meeting:ya,stage_change:mr,task_completed:Mr,document:sa,system:Zr};function Ker({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Pe,Oe;const l=zn(),{data:o,isLoading:c}=OWn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=BWn((s==null?void 0:s.id)||""),h=zWn(),m=UWn(),p=$Wn(),f=FWn(),{data:g,isLoading:v}=VKn((s==null?void 0:s.id)||""),y=HKn(),b=GKn(),w=WKn(),S=_.useRef(null),[C,E]=_.useState(""),[P,M]=_.useState(""),[I,D]=_.useState(!1),[F,q]=_.useState(!1),[G,V]=_.useState(!1);if(!s)return null;const H=Ger[s.deal_type],K=(()=>{var _e;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const ke=((_e=s.listing)==null?void 0:_e.created_at)||s.listing_date;if(!ke)return null;const Ve=s.contract_date?Ou(s.contract_date):new Date;return PN(Ve,Ou(ke))})(),Z=ke=>ke?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ke):"-",oe=async()=>{if(C.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:C}),E(""),ne.success("Note added")}catch{ne.error("Failed to add note")}},re=async()=>{if(P.trim())try{await m.mutateAsync({deal_id:s.id,title:P,sort_order:((d==null?void 0:d.length)||0)+1}),M(""),ne.success("Task added")}catch{ne.error("Failed to add task")}},ae=async(ke,Ve)=>{try{await p.mutateAsync({id:ke,is_completed:Ve,deal_id:s.id})}catch{ne.error("Failed to update task")}},J=async()=>{try{await f.mutateAsync(s.id),ne.success("Deal deleted"),n(!1)}catch{ne.error("Failed to delete deal")}},te=(d==null?void 0:d.filter(ke=>ke.is_completed).length)||0,ce=(d==null?void 0:d.length)||0,ve=(g==null?void 0:g.length)||0,me=ke=>ke<1024?`${ke} B`:ke<1024*1024?`${(ke/1024).toFixed(1)} KB`:`${(ke/(1024*1024)).toFixed(1)} MB`,he=ke=>ke?ke.startsWith("image/")?nc:ke.includes("pdf")?$r:qU:qU,ge=async ke=>{const Ve=ke.target.files;if(!(!Ve||!s)){V(!0);try{for(const _e of Array.from(Ve)){if(_e.size>20*1024*1024){ne.error(`${_e.name} exceeds 20MB limit`);continue}await y.mutateAsync({dealId:s.id,file:_e})}ne.success("File(s) uploaded")}catch{ne.error("Failed to upload file")}finally{V(!1),S.current&&(S.current.value="")}}},Ee=async(ke,Ve)=>{if(s)try{await b.mutateAsync({fileId:ke,storagePath:Ve,dealId:s.id}),ne.success("File deleted")}catch{ne.error("Failed to delete file")}},Ne=async(ke,Ve)=>{try{const _e=await KKn(ke),Ae=document.createElement("a");Ae.href=_e,Ae.download=Ve,Ae.target="_blank",document.body.appendChild(Ae),Ae.click(),document.body.removeChild(Ae)}catch{ne.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(Wg,{open:t,onOpenChange:n,children:e.jsxs(gg,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(Dy,{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:Ct("text-xs",H.color),children:H.label}),e.jsxs(ze,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(Ry,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(qKn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(Cp,{className:"h-4 w-4"})}),e.jsx(z,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>q(!0),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})}),e.jsx(Ki,{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(ja,{className:"h-10 w-10",children:e.jsxs(Na,{className:"bg-primary/10 text-primary",children:[(Pe=s.contact.first_name)==null?void 0:Pe[0],(Oe=s.contact.last_name)==null?void 0:Oe[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(z,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(va,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(z,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(on,{className:"h-4 w-4"})})}),e.jsx(z,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(mr,{className:"h-4 w-4"})})]})]}),e.jsx(Ser,{dealId:s.id,primaryContactId:s.contact_id}),e.jsx(qer,{dealId:s.id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Her,{dealId:s.id,photoUrl:s.property_photo_url}),(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(sa,{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:Z(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:Z(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee||s.bonus_amount)&&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?` (${Z(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:Z(s.transaction_fee)})]}),s.bonus_amount!=null&&Number(s.bonus_amount)>0&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bonus (not split)"}),e.jsxs("span",{className:"text-emerald-600",children:["+",Z(s.bonus_amount)]})]}),k_(s)!=null&&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:Z(k_(s))})]})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(z,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(jl,{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(Mr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),K!==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:Ct("text-lg font-bold",K>90?"text-red-600":K>60?"text-amber-600":"text-foreground"),children:[K," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Ys(Ou(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Nd,{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(Rer,{deal:s}),e.jsx(ker,{deal:s}),e.jsxs(Qr,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Jr,{className:"w-full grid grid-cols-4",children:[e.jsxs(Wt,{value:"tasks",className:"gap-1",children:[e.jsx(Mr,{className:"h-4 w-4"}),"Tasks ",ce>0&&`(${te}/${ce})`]}),e.jsxs(Wt,{value:"files",className:"gap-1",children:[e.jsx(dP,{className:"h-4 w-4"}),"Files ",ve>0&&`(${ve})`]}),e.jsxs(Wt,{value:"forms",className:"gap-1",children:[e.jsx(cb,{className:"h-4 w-4"}),"Forms"]}),e.jsxs(Wt,{value:"activity",className:"gap-1",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsx(Kt,{value:"forms",className:"mt-4",children:e.jsx(ver,{dealId:s.id,dealName:s.deal_name})}),e.jsxs(Kt,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add a new task...",value:P,onChange:ke=>M(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&re()}),e.jsx(z,{onClick:re,disabled:!P.trim(),children:e.jsx(sn,{className:"h-4 w-4"})}),e.jsxs(z,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>D(!0),children:[e.jsx(ip,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(ke=>e.jsxs("div",{className:Ct("flex items-center gap-3 p-3 rounded-lg border transition-colors",ke.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(za,{checked:ke.is_completed,onCheckedChange:Ve=>ae(ke.id,!!Ve)}),e.jsx("span",{className:Ct("flex-1 text-sm",ke.is_completed&&"line-through text-muted-foreground"),children:ke.title}),ke.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(ke.due_date),"MMM d")})]},ke.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(Kt,{value:"files",className:"mt-4 space-y-3",children:[(s==null?void 0:s.id)&&e.jsx(XKn,{dealId:s.id}),e.jsx("input",{type:"file",ref:S,className:"hidden",multiple:!0,onChange:ge,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(z,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var ke;return(ke=S.current)==null?void 0:ke.click()},disabled:G,children:[G?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-2"}),G?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[g==null?void 0:g.map(ke=>{const Ve=he(ke.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(Ve,{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:ke.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[me(ke.file_size)," · ",Ys(new Date(ke.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(UN,{children:e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${ke.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>w.mutate({fileId:ke.id,visible:!ke.visible_on_portal,dealId:s.id}),children:ke.visible_on_portal?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Yf,{className:"h-4 w-4"})})}),e.jsx(Tx,{side:"top",children:ke.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Ne(ke.storage_path,ke.file_name),children:e.jsx(Ga,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ee(ke.id,ke.storage_path),children:e.jsx(er,{className:"h-4 w-4"})})]})]},ke.id)}),(g==null?void 0:g.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(Kt,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ps,{placeholder:"Add a note...",value:C,onChange:ke=>E(ke.target.value),rows:2}),e.jsxs(z,{onClick:oe,disabled:!C.trim(),size:"sm",className:"w-full",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(ke=>{const Ve=Wer[ke.activity_type]||Zr;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(Ve,{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:ke.title}),ke.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:ke.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Md(new Date(ke.created_at),{addSuffix:!0})})]})]},ke.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(Hrs,{open:I,onOpenChange:D,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Ql,{open:F,onOpenChange:q,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Deal?"}),e.jsxs(ql,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:J,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function Yer({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=SLe(),i=Fss(),{data:l}=Q9(),{data:o}=Q_(),[c,d]=_.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Ys(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});_.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",p=n.expected_price||0,f=n.commission_percentage||3,g=n.expected_commission||p*f/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||Ys(new Date,"yyyy-MM-dd"),sale_price:p,commission_amount:g,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const p=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:p.id,actual_close_date:c.close_date}),ne.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(p){console.error("Error syncing to scorecard:",p),ne.error("Failed to add to scorecard")}},h=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(m);return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{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(jl,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(Rs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(_r,{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(ee,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(pe,{id:"property_address",value:c.property_address,onChange:m=>d(p=>({...p,property_address:m.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:c.city,onChange:m=>d(p=>({...p,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:c.state,onChange:m=>d(p=>({...p,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip",children:"Zip"}),e.jsx(pe,{id:"zip",value:c.zip,onChange:m=>d(p=>({...p,zip:m.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Transaction Type *"}),e.jsxs(ls,{value:c.transaction_type,onValueChange:m=>d(p=>({...p,transaction_type:m})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(pe,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(p=>({...p,close_date:m.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(pe,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(p=>({...p,sale_price:Number(m.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(z_,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(pe,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(p=>({...p,commission_amount:Number(m.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lead Source"}),e.jsxs(ls,{value:c.lead_source_id,onValueChange:m=>d(p=>({...p,lead_source_id:m})),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select source"})}),e.jsx(as,{children:l==null?void 0:l.map(m=>e.jsx(He,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Client Type"}),e.jsxs(ls,{value:c.client_type_id,onValueChange:m=>d(p=>({...p,client_type_id:m})),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select type"})}),e.jsx(as,{children:o==null?void 0:o.map(m=>e.jsx(He,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Ps,{id:"notes",value:c.notes,onChange:m=>d(p=>({...p,notes:m.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(hr,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(z,{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(Da,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const Zer={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"}},L4t={urgent:0,high:1,medium:2,low:3};function Xer({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=_.useState("target_close_date"),[l,o]=_.useState("asc"),c=p=>{a===p?o(f=>f==="asc"?"desc":"asc"):(i(p),o("asc"))},d=_.useMemo(()=>[...s].sort((p,f)=>{var v,y;let g=0;switch(a){case"deal_name":g=p.deal_name.localeCompare(f.deal_name);break;case"stage":{const b=((v=t.find(S=>S.id===p.stage_id))==null?void 0:v.sort_order)||0,w=((y=t.find(S=>S.id===f.stage_id))==null?void 0:y.sort_order)||0;g=b-w;break}case"expected_price":g=(p.expected_price||0)-(f.expected_price||0);break;case"expected_commission":g=(p.expected_commission||0)-(f.expected_commission||0);break;case"target_close_date":{const b=p.target_close_date?Ou(p.target_close_date).getTime():1/0,w=f.target_close_date?Ou(f.target_close_date).getTime():1/0;g=b-w;break}case"priority":g=L4t[p.priority]-L4t[f.priority];break}return l==="asc"?g:-g}),[s,t,a,l]),u=p=>p?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(p):"—",h=p=>p?t.find(f=>f.id===p):null,m=({field:p,children:f})=>e.jsxs(z,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(p),children:[f,a===p?l==="asc"?e.jsx(ap,{className:"ml-2 h-4 w-4"}):e.jsx(Vf,{className:"ml-2 h-4 w-4"}):e.jsx(Og,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Tt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Tt,{className:"w-[100px]",children:"Type"}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Tt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(Qa,{children:d.map(p=>{const f=h(p.stage_id),g=Zer[p.deal_type],v=p.target_close_date?PN(Ou(p.target_close_date),new Date):null,y=!!(f!=null&&f.is_won_stage)||!!(f!=null&&f.is_lost_stage)||!!p.actual_close_date,b=!y&&v!==null&&v<0,w=!y&&v!==null&&v<=7&&v>=0;return e.jsxs(fn,{className:Ct("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>n(p),children:[e.jsx(yt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:p.deal_name}),p.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[p.contact.first_name," ",p.contact.last_name]})]})}),e.jsx(yt,{onClick:S=>S.stopPropagation(),children:e.jsx($ss,{stages:t,currentStageId:p.stage_id||"",onStageSelect:(S,C)=>r(p.id,S,C)})}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",className:Ct("text-xs",g.color),children:g.label})}),e.jsx(yt,{children:e.jsx("span",{className:"font-medium",children:u(p.expected_price)})}),e.jsx(yt,{children:e.jsx("span",{className:"text-emerald-600",children:u(p.expected_commission)})}),e.jsx(yt,{children:p.target_close_date?e.jsxs("div",{className:Ct("flex items-center gap-1 text-sm",b&&"text-red-600",w&&!b&&"text-amber-600"),children:[b&&e.jsx(Ho,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Ys(Ou(p.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",className:Ct("text-xs capitalize",p.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",p.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",p.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",p.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:p.priority})})]},p.id)})})]})})}function Grs(){const s=ha();return rt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Qer(s){const t=ha();return rt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await U.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function Jer(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 etr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function ttr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function xDe(){const s=$t();return mt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await U.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 str(){const s=$t();return mt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await U.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 ntr(s){const t=ha();return rt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=U.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 rtr(){const s=ha(),t=$t();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 atr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function itr(){const s=ha(),t=$t();return mt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await U.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,m)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:m,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await U.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const otr={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function ltr({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=Qer(s?n:void 0),u=str(),h=itr(),[m,p]=_.useState(new Set),[f,g]=_.useState(!1),v=(c||[]).filter(S=>S.status!=="done");_.useEffect(()=>{v.length>0&&p(new Set(v.map(S=>S.id)))},[c]);const y=S=>{p(C=>{const E=new Set(C);return E.has(S)?E.delete(S):E.add(S),E})},b=async()=>{g(!0);try{const S=Array.from(m);S.length>0&&await u.mutateAsync(S),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move failed:",S),ne.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{g(!1)}},w=async()=>{g(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move (skip) failed:",S),ne.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{g(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[480px]",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Move Deal"}),e.jsxs(_r,{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(Da,{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(bt,{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(Ki,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:v.map(S=>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(za,{checked:m.has(S.id),onCheckedChange:()=>y(S.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[otr[S.priority]," ",S.title]}),S.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:S.stage.color+"20",color:S.stage.color},children:S.stage.name})]},S.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>{m.size===v.length?p(new Set):p(new Set(v.map(S=>S.id)))},children:m.size===v.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:w,disabled:f,children:"Skip"}),e.jsxs(z,{size:"sm",onClick:b,disabled:f,children:[f&&e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}),m.size>0?`Complete ${m.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Mr,{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(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:b,disabled:f,children:[f&&e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const ctr=[{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"}],dtr=[{id:"noir",name:"Luxury — Noir & Gold",description:"Dark, editorial, high-end concierge feel.",bg:"#0d0d0d",surface:"#171717",accent:"#c9a84c",ink:"#f5f2ea"},{id:"azure",name:"Professional Blue",description:"Light, clean and corporate — easy to read.",bg:"#f5f8fc",surface:"#ffffff",accent:"#1259ce",ink:"#1a2433"}];function Wrs({open:s,onOpenChange:t}){const n=ha(),{data:r,isLoading:a}=T9t(),i=UFs(),[l,o]=_.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=_.useState(null);_.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=p=>o(f=>({...f,...p})),h=async(p,f)=>{if(n){if(p.size>5*1024*1024){ne.error("Image must be under 5MB");return}d(f);try{const g=await M9t(n,p,f);u(f==="logo"?{logo_url:g}:{cover_photo_url:g})}catch(g){ne.error(`Upload failed: ${g.message||g}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),ne.success("Portal branding saved"),t(!1)}catch{ne.error("Failed to save branding")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(_r,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(Ki,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(utr,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Portal Theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The overall look and feel your clients see when they open their portal."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:dtr.map(p=>{const f=(l.portal_theme??"noir")===p.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:p.id}),className:Ct("rounded-xl border-2 p-3 text-left transition-all",f?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsx("div",{className:"rounded-lg overflow-hidden mb-2",style:{background:p.bg},children:e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsx("div",{className:"h-1.5 w-10 rounded-full",style:{background:p.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:p.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:p.surface,border:`1px solid ${p.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:p.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:p.description})]},p.id)})})]}),e.jsx(I4t,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:p=>h(p,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(I4t,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:p=>h(p,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{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:ctr.map(p=>{const f=l.brand_color===p.brand&&l.accent_color===p.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:p.brand,accent_color:p.accent}),className:Ct("group relative rounded-lg border-2 p-2 text-left transition-all",f?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:p.brand}}),e.jsx("div",{className:"flex-1",style:{background:p.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:p.name})]},p.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(D4t,{label:"Brand",value:l.brand_color,onChange:p=>u({brand_color:p})}),e.jsx(D4t,{label:"Accent",value:l.accent_color,onChange:p=>u({accent_color:p})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:l.tagline||"",onChange:p=>u({tagline:p.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:p=>u({welcome_message:p.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function utr({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 I4t({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(ee,{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:Ct("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(nc,{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(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ra,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx(z,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})]})}function D4t({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(ee,{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(pe,{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 htr(){const s=ha();return rt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function mtr({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=trt(),d=QW(),u=MZt(),h=PZt(),[m,p]=_.useState(!1),f=!!(r!=null&&r.archived_at),g=async()=>{p(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ne.success("Portal enabled!")}catch{ne.error("Failed to create portal")}finally{p(!1)}},v=async C=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:C}),ne.success(C?"Portal enabled":"Portal disabled")}catch{ne.error("Failed to update portal")}},y=()=>{r&&(navigator.clipboard.writeText(SS(r.slug)),ne.success("Link copied!"))},b=()=>{r&&window.open(SS(r.slug),"_blank")},w=async()=>{if(r)try{await u.mutateAsync(r.id),ne.success("Portal archived")}catch{ne.error("Failed to archive portal")}},S=async()=>{if(r)try{await h.mutateAsync(r.id),ne.success("Portal restored")}catch{ne.error("Failed to restore portal")}};return r?f?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(or,{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(z,{variant:"ghost",size:"sm",onClick:S,className:"text-xs gap-1",children:[e.jsx(eP,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(Cn,{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(or,{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(yi,{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(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:y,title:"Copy link",children:e.jsx(Sa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Preview",children:e.jsx(mr,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(I4,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(Gc,{className:"h-3.5 w-3.5"})}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(lb,{className:"h-3.5 w-3.5"})})}),e.jsx(qd,{align:"end",children:e.jsxs(ua,{onClick:w,children:[e.jsx(w0,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(mn,{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(z,{size:"sm",onClick:g,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(bt,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(un,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function Krs(){const{data:s,isLoading:t}=xK(),{data:n,isLoading:r}=htr(),[a,i]=_.useState(""),[l,o]=_.useState("all"),c=LZt(),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(null),[g,v]=_.useState(null),[y,b]=_.useState(!1),w=ha(),S=t||r,C=new Map;n==null||n.forEach(q=>C.set(q.deal_id,q));const P=[...(s||[]).filter(q=>{var Z,oe,re,ae,J;const G=C.get(q.id),V=a.toLowerCase(),H=!V||q.deal_name.toLowerCase().includes(V)||((oe=(Z=q.contact)==null?void 0:Z.first_name)==null?void 0:oe.toLowerCase().includes(V))||((ae=(re=q.contact)==null?void 0:re.last_name)==null?void 0:ae.toLowerCase().includes(V))||((J=G==null?void 0:G.client_name)==null?void 0:J.toLowerCase().includes(V));let K=!0;return l==="active"?K=!!(G!=null&&G.is_enabled)&&!(G!=null&&G.archived_at):l==="disabled"?K=!!G&&!G.is_enabled&&!G.archived_at:l==="archived"?K=!!(G!=null&&G.archived_at):l==="none"?K=!G:l==="all"&&(K=!(G!=null&&G.archived_at)||!G),H&&K})].sort((q,G)=>{const V=C.get(q.id),H=C.get(G.id);if(V!=null&&V.archived_at&&!(H!=null&&H.archived_at))return 1;if(!(V!=null&&V.archived_at)&&(H!=null&&H.archived_at)||V&&!H)return-1;if(!V&&H)return 1;if(V&&H){if(V.is_enabled&&!H.is_enabled)return-1;if(!V.is_enabled&&H.is_enabled)return 1}return 0}),M=(n==null?void 0:n.filter(q=>!q.archived_at).length)||0,I=(n==null?void 0:n.filter(q=>q.is_enabled&&!q.archived_at).length)||0,D=(n==null?void 0:n.filter(q=>q.archived_at).length)||0,F=async()=>{if(g)try{await c.mutateAsync({id:g.id,dealId:g.deal_id}),ne.success("Portal permanently deleted"),v(null)}catch{ne.error("Failed to delete portal")}};return S?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(bt,{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:[I," active · ",M-I," disabled",D>0&&` · ${D} archived`]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx(yc,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search deals or clients...",value:a,onChange:q=>i(q.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(er,{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(q=>e.jsx(z,{variant:l===q?"secondary":"ghost",size:"sm",onClick:()=>o(q),className:"text-xs px-3 capitalize",children:q==="none"?"No Portal":q},q))})]}),e.jsx(Ki,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[P.map(q=>{const G=C.get(q.id)||null,V=q.contact?`${q.contact.first_name||""} ${q.contact.last_name||""}`.trim():"";return e.jsx(mtr,{dealId:q.id,dealName:q.deal_name,contactName:V,portal:G,onSettingsOpen:u,onComposerOpen:H=>m(H),onInviteOpen:(H,K)=>f({portal:H,dealName:K}),onDeleteConfirm:v},q.id)}),P.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(yit,{open:!!d,onOpenChange:q=>!q&&u(null),portal:d,dealOwnerId:w||""}),h&&e.jsx(vit,{open:!!h,onOpenChange:q=>!q&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),p&&e.jsx(bit,{open:!!p,onOpenChange:q=>!q&&f(null),portal:p.portal,dealName:p.dealName}),e.jsx(Wrs,{open:y,onOpenChange:b}),e.jsx(Ql,{open:!!g,onOpenChange:q=>!q&&v(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Permanently delete this portal?"}),e.jsx(ql,{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($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:F,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function ptr({summary:s,stats:t,search:n,onSearchChange:r,onAddDeal:a,onRefresh:i,onTeam:l,viewControls:o,filters:c,activeFilters:d=[],onClearAll:u,resultLabel:h,showSearch:m=!0}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Deal Pipeline"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Deal"]}),l&&e.jsxs("button",{onClick:l,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(On,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Team"]}),e.jsx("button",{onClick:i,"aria-label":"Refresh pipeline",className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full transition-colors",children:e.jsx(Gi,{className:"h-4 w-4"})}),o]})]}),t.length>0&&e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 sm:grid sm:grid-cols-3 sm:overflow-visible lg:grid-cols-5",children:t.map(p=>{const f=p.onClick?"button":"div";return e.jsxs(f,{type:p.onClick?"button":void 0,onClick:p.onClick,title:p.hint,className:Ct("hub-glass min-w-[130px] shrink-0 rounded-xl px-3 py-2.5 text-left transition-all sm:min-w-0",p.onClick&&"hover:scale-[1.02]",p.active&&"ring-2"),style:p.active?{boxShadow:"0 0 0 2px hsl(var(--hub-glow))"}:void 0,children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide hub-ink-muted",children:p.label}),e.jsx("p",{className:"mt-0.5 text-lg font-bold leading-tight",children:p.value}),p.subtitle&&e.jsx("p",{className:"text-[11px] hub-ink-muted",children:p.subtitle})]},p.label)})}),m&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[200px] flex-1 sm:max-w-sm",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx("input",{value:n,onChange:p=>r(p.target.value),placeholder:"Search deals, contacts, addresses, tags...",className:"hub-glass h-10 w-full rounded-full border-0 pl-9 pr-8 text-sm outline-none placeholder:opacity-60 focus:ring-2 focus:ring-white/30"}),n&&e.jsx("button",{onClick:()=>r(""),"aria-label":"Clear search",className:"absolute right-3 top-1/2 -translate-y-1/2 opacity-70 hover:opacity-100",children:e.jsx(er,{className:"h-4 w-4"})})]}),c]}),(d.length>0||h)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.map(p=>e.jsxs("button",{onClick:p.onClear,className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium",children:[p.label,e.jsx(er,{className:"h-3 w-3 opacity-70"})]},p.key)),d.length>0&&u&&e.jsx("button",{onClick:u,className:"text-xs font-medium underline underline-offset-2 hub-ink-muted hover:opacity-90",children:"Clear all"}),h&&e.jsx("span",{className:"text-xs hub-ink-muted",children:h})]})]})]})})}const ftr={closing_soon:{label:"Closing in 7 days",icon:Ud,tone:"text-primary"},past_due:{label:"Past close date",icon:nl,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:Zw,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:GQ,tone:"text-muted-foreground"}};function xtr({items:s,active:t,onToggle:n}){const r=s.filter(a=>a.count>0);return r.length===0?null:e.jsxs("div",{className:"-mx-1 flex items-center gap-2 overflow-x-auto px-1 pb-1",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Needs attention"}),r.map(({key:a,count:i})=>{const l=ftr[a],o=l.icon,c=t===a;return e.jsxs("button",{onClick:()=>n(a),className:Ct("inline-flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",c?"border-primary bg-primary/10 text-primary":"border-border bg-card text-foreground hover:bg-accent"),children:[e.jsx(o,{className:Ct("h-3.5 w-3.5",!c&&l.tone)}),l.label,e.jsx("span",{className:Ct("ml-0.5 rounded-full px-1.5 text-[10px] font-bold",c?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:i})]},a)})]})}const H7=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function ZS(s){if(!s)return null;const[t,n,r]=s.split(/[-/T]/).map(a=>parseInt(a,10));return!t||!n||!r?null:{y:t,m:n,d:r}}function qG(s){return H7(s.sale_price)||H7(s.expected_price)}function VG(s){const t=H7(s.expected_commission);if(t>0)return t;const n=H7(s.commission_percentage);return n>0?qG(s)*n/100:0}function Kse(s){const t=VG(s);return t*H7(s.brokerage_split_pct)/100+t*H7(s.franchise_fee_pct)/100+H7(s.transaction_fee)}const gtr=s=>!!s.actual_close_date,ytr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function vtr(s){const t=new Date,n=t.getFullYear(),r=t.getMonth()+1,a=n*1e4+r*100+t.getDate(),i=new Date(t.getTime()+30*864e5),l=i.getFullYear()*1e4+(i.getMonth()+1)*100+i.getDate(),o={activeDeals:0,closedThisYear:0,pipelineVolume:0,pipelineGci:0,brokerageShare:0,closingThisMonth:0,closingNext30:0,closedVolumeThisYear:0,closedCompanyDollarYtd:0,needsReview:0,changesRequested:0,overdueItems:0,agents:[],outlook:[],totalVolume:0},c=new Map,d=new Map;for(let u=0;u<6;u++){const h=(r-1+u)%12+1,m=n+Math.floor((r-1+u)/12),p=`${m}-${String(h).padStart(2,"0")}`;d.set(p,{key:p,label:`${ytr[h-1]} ${String(m).slice(2)}`,deals:0,volume:0,gci:0,closed:!1})}return s.forEach(u=>{const h=qG(u),m=VG(u),p=gtr(u);o.totalVolume+=h,o.overdueItems+=u.overdue_items,u.submitted_items>0&&(o.needsReview+=1),u.rejected_items>0&&(o.changesRequested+=1);const f=ZS(u.actual_close_date||u.target_close_date);if(p)(f==null?void 0:f.y)===n&&(o.closedThisYear+=1,o.closedVolumeThisYear+=h,o.closedCompanyDollarYtd+=Kse(u));else if(o.activeDeals+=1,o.pipelineVolume+=h,o.pipelineGci+=m,o.brokerageShare+=Kse(u),f){const v=f.y*1e4+f.m*100+f.d;f.y===n&&f.m===r&&(o.closingThisMonth+=1),v>=a&&v<=l&&(o.closingNext30+=1)}if(f){const v=`${f.y}-${String(f.m).padStart(2,"0")}`,y=d.get(v);y&&(y.deals+=1,y.volume+=h,y.gci+=m,p&&(y.closed=!0))}const g=c.get(u.owner_user_id)||{userId:u.owner_user_id,name:u.agent_name||"Agent",avatarUrl:u.agent_avatar_url,activeDeals:0,closedDeals:0,volume:0,gci:0,overdue:0};p?g.closedDeals+=1:g.activeDeals+=1,g.volume+=h,g.gci+=m,g.overdue+=u.overdue_items,c.set(u.owner_user_id,g)}),o.agents=Array.from(c.values()).sort((u,h)=>h.volume-u.volume||h.activeDeals-u.activeDeals),o.outlook=Array.from(d.values()).sort((u,h)=>u.key.localeCompare(h.key)),o}function tp(s){return s?Math.abs(s)>=1e6?`$${(s/1e6).toFixed(1)}M`:Math.abs(s)>=1e3?`$${Math.round(s/1e3)}K`:`$${Math.round(s).toLocaleString()}`:"$0"}function btr(){var i;const{user:s}=hs(),{data:t}=qss(),{data:n}=DKn(t?s==null?void 0:s.id:null);if(!t)return null;const{plan:r}=t,a=Math.max(0,100-r.agent_split_pct);return e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(z_,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your commission plan"}),e.jsx("p",{className:"text-sm font-semibold",children:r.name})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 text-[12px] text-muted-foreground",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.agent_split_pct,"/",a]})," split"]}),r.transaction_fee>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:["$",r.transaction_fee.toLocaleString()]})," per deal"]}),r.franchise_fee_pct>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.franchise_fee_pct,"%"]})," franchise fee"]}),(r.team_split_pct??0)>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.team_split_pct,"%"]})," team split"]})]}),r.cap_amount&&n&&e.jsxs("div",{className:"min-w-[200px] flex-1",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["$",Math.round(n.cap_progress).toLocaleString()," of ",tp(r.cap_amount)," cap"]}),e.jsxs("span",{children:[Math.round(n.pct_to_cap??0),"%"]})]}),e.jsx(Di,{value:Math.min(100,n.pct_to_cap??0),className:"h-1.5"}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Resets ",((i=n.anniversary_year_end)==null?void 0:i.split(/[-/T]/).slice(0,3).join("/"))||"annually"]})]})]})})}class _tr extends _.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($s,{children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-2xl",children:"⚠️"})}),e.jsx("h2",{className:"text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"There was an error in the deal pipeline. Click below to try again."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90",children:"Try Again"}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-border rounded-md text-sm font-medium hover:bg-muted",children:"Refresh Page"})]})]})}):this.props.children}}const UZ="deal-pipeline-detail-sheet";function qZ(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function wtr(){var pr;const s=XW(),{data:t,isLoading:n}=cie(),{data:r,isLoading:a,refetch:i}=xK(),{data:l,isLoading:o}=qWn(),c=Dss(),d=RWn(),[u,h]=_.useState("board"),[m,p]=_.useState(!1),[f,g]=_.useState(!1),[v,y]=_.useState(null),[b,w]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(null),[M,I]=_.useState(!1),[D,F]=_.useState(null),[q,G]=_.useState(""),[V,H]=_.useState("all"),[K,Z]=_.useState("all"),[oe,re]=_.useState("all"),[ae,J]=_.useState(null),{data:te}=Grs(),{data:ce}=EKn(),[ve,me]=_.useState(!1),[he,ge]=_.useState(!1),[Ee,Ne]=_.useState(new Set),[Pe,Oe]=_.useState(!0),ke=_.useRef(!1),[Ve,_e]=_.useState(null),{data:Ae}=K_(),{isTeamLeader:Se,teamMembers:We}=CKn(),qe=_.useMemo(()=>Array.from(Ee),[Ee]),{data:Be}=AKn(qe),Ze=_.useMemo(()=>{const hn=new Map;return We.forEach(Pn=>hn.set(Pn.id,{name:Pn.name,avatar_url:Pn.avatar_url,color:Pn.color})),hn},[We]),$e=_.useCallback(hn=>hn.owner_user_id&&Ze.get(hn.owner_user_id)||null,[Ze]),Xe=_.useCallback(hn=>{Ne(Pn=>{const Gs=new Set(Pn);return Gs.has(hn)?Gs.delete(hn):Gs.add(hn),Gs})},[]);_.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[nt,Ge]=Gl(),Je=_.useRef(!1);_.useEffect(()=>{const hn=nt.get("deal");if(hn&&r&&r.length>0&&!Je.current){const Pn=r.find(Gs=>Gs.id===hn);Pn&&(Je.current=!0,y(Pn),g(!0),nt.delete("deal"),Ge(nt,{replace:!0}))}},[r,nt]);const ut=_.useMemo(()=>{if(!Be||!t)return[];const hn=new Map(t.map(Pn=>[Pn.name,Pn.id]));return Be.map(Pn=>{const Gs=Pn._stage_name&&hn.get(Pn._stage_name)||null;return{...Pn,stage_id:Gs||Pn.stage_id}})},[Be,t]),lt=_.useMemo(()=>[...Se&&!Pe?[]:r||[],...ut],[r,ut,Se,Pe]);_.useEffect(()=>{if(ke.current||lt.length===0)return;ke.current=!0;const hn=sessionStorage.getItem(UZ);if(hn)try{const Pn=JSON.parse(hn);if(!Pn.open||!Pn.dealId)return;const Gs=lt.find(an=>an.id===Pn.dealId);Gs&&(y(Gs),g(!0))}catch{sessionStorage.removeItem(UZ)}},[lt]),_.useEffect(()=>{f&&(v!=null&&v.id)?sessionStorage.setItem(UZ,JSON.stringify({dealId:v.id,open:!0})):sessionStorage.removeItem(UZ)},[f,v==null?void 0:v.id]);const qt=_.useMemo(()=>{const hn={},Pn=new Date;return Pn.setHours(0,0,0,0),(te||[]).forEach(Gs=>{!Gs.deal_id||Gs.status==="done"||!Gs.due_date||Ou(Gs.due_date){const hn=new Set((t||[]).filter(Yt=>Yt.is_won_stage).map(Yt=>Yt.id)),Pn=new Set((t||[]).filter(Yt=>Yt.is_lost_stage).map(Yt=>Yt.id)),Gs=new Date;Gs.setHours(0,0,0,0);const an=new Date(Gs);an.setDate(an.getDate()+7);const tr=new Date(Gs);tr.setDate(tr.getDate()-14);const Lr={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return lt.forEach(Yt=>{if(!(Yt.stage_id&&(hn.has(Yt.stage_id)||Pn.has(Yt.stage_id)))){if(Yt.target_close_date){const gt=Ou(Yt.target_close_date);gt[{key:"closing_soon",count:ms.closing_soon.size},{key:"past_due",count:ms.past_due.size},{key:"overdue_tasks",count:ms.overdue_tasks.size},{key:"stalled",count:ms.stalled.size}],[ms]),It=lt.filter(hn=>{var Lt,Mt,Qt,ks,gs,Vt;const Pn=q.toLowerCase(),Gs=zt[hn.id]||[],an=!Pn||hn.deal_name.toLowerCase().includes(Pn)||((Mt=(Lt=hn.contact)==null?void 0:Lt.first_name)==null?void 0:Mt.toLowerCase().includes(Pn))||((ks=(Qt=hn.contact)==null?void 0:Qt.last_name)==null?void 0:ks.toLowerCase().includes(Pn))||((gs=hn.property_address)==null?void 0:gs.toLowerCase().includes(Pn))||((Vt=hn.city)==null?void 0:Vt.toLowerCase().includes(Pn))||Gs.some(Vs=>Vs.toLowerCase().includes(Pn)),tr=V==="all"||hn.deal_type===V,Lr=K==="all"||Gs.includes(K),Yt=hn.actual_close_date||hn.target_close_date||hn.contract_date||hn.created_at,it=Yt?String(Yt).slice(0,4):null,gt=oe==="all"||it===oe,ft=!ae||ms[ae].has(hn.id);return an&&tr&&Lr&>&&ft}),qs=_.useMemo(()=>{const hn=new Set;return hn.add(String(new Date().getFullYear())),lt.forEach(Pn=>{const Gs=Pn.actual_close_date||Pn.target_close_date||Pn.contract_date||Pn.created_at;Gs&&hn.add(String(Gs).slice(0,4))}),Array.from(hn).sort((Pn,Gs)=>Number(Gs)-Number(Pn))},[lt]),wt=_.useMemo(()=>{if(!t)return l||null;const hn=new Set(t.filter(Yt=>Yt.is_won_stage).map(Yt=>Yt.id)),Pn=new Set(t.filter(Yt=>Yt.is_lost_stage).map(Yt=>Yt.id)),Gs=lt.filter(Yt=>Yt.stage_id&&!hn.has(Yt.stage_id)&&!Pn.has(Yt.stage_id)),an=lt.filter(Yt=>Yt.stage_id&&hn.has(Yt.stage_id)),tr=new Date().getFullYear(),Lr=an.filter(Yt=>Yt.actual_close_date?new Date(Yt.actual_close_date).getFullYear()===tr:!0);return{totalDeals:lt.length,activeDeals:Gs.length,wonDeals:an.length,pipelineValue:Gs.reduce((Yt,it)=>Yt+(it.expected_price||0),0),expectedCommission:Gs.reduce((Yt,it)=>Yt+(it.expected_commission||0),0),expectedNetToAgent:Gs.reduce((Yt,it)=>Yt+(k_(it)||0),0),wonValue:an.reduce((Yt,it)=>Yt+(it.expected_price||0),0),weightedGCI:Gs.reduce((Yt,it)=>Yt+(it.expected_commission||0)*((it.probability??50)/100),0),weightedNet:Gs.reduce((Yt,it)=>Yt+(k_(it)||0)*((it.probability??50)/100),0),ytdWonDeals:Lr.length,ytdWonGCI:Lr.reduce((Yt,it)=>Yt+(it.expected_commission||0),0),ytdWonNet:Lr.reduce((Yt,it)=>Yt+(k_(it)||0),0),projectedAnnualNet:Lr.reduce((Yt,it)=>Yt+(k_(it)||0),0)+Gs.reduce((Yt,it)=>Yt+(k_(it)||0)*((it.probability??50)/100),0)}},[lt,t,l]),Us=hn=>{y(hn),g(!0)},Es=hn=>{w(hn||null),y(null),p(!0)},kn=hn=>{y(hn),g(!1),p(!0)},Sn=hn=>{g(hn),hn||sessionStorage.removeItem(UZ)},bn=(hn,Pn)=>{C(hn)},cr=(hn,Pn)=>{hn.preventDefault(),hn.dataTransfer.dropEffect="move",P(Pn)},Fs=async(hn,Pn)=>{if(hn.preventDefault(),P(null),!S)return;const Gs=r==null?void 0:r.find(Lr=>Lr.id===S),an=t==null?void 0:t.find(Lr=>Lr.id===Pn),tr=t==null?void 0:t.find(Lr=>Lr.id===(Gs==null?void 0:Gs.stage_id));if(!Gs||!an||Gs.stage_id===Pn){C(null);return}_e({dealId:S,dealName:Gs.deal_name,fromStageName:(tr==null?void 0:tr.name)||"Unknown",toStageName:an.name,toStageId:Pn,isWonStage:an.is_won_stage,deal:Gs}),C(null)},cn=async()=>{if(!Ve)return;const{dealId:hn,toStageId:Pn,toStageName:Gs,isWonStage:an,deal:tr}=Ve;if(await d.mutateAsync({dealId:hn,stageId:Pn,stageName:Gs}),ne.success(`Moved to ${Gs}`),an&&!tr.scorecard_transaction_id){const Lr={...tr,stage_id:Pn};F(Lr),I(!0)}},lr=_.useCallback(async(hn,Pn,Gs)=>{const an=r==null?void 0:r.find(Yt=>Yt.id===hn),tr=t==null?void 0:t.find(Yt=>Yt.id===Pn),Lr=t==null?void 0:t.find(Yt=>Yt.id===(an==null?void 0:an.stage_id));!an||!tr||an.stage_id===Pn||_e({dealId:hn,dealName:an.deal_name,fromStageName:(Lr==null?void 0:Lr.name)||"Unknown",toStageName:Gs,toStageId:Pn,isWonStage:tr.is_won_stage,deal:an})},[r,t]),Tn=hn=>It.filter(Pn=>Pn.stage_id===hn),Yn=n||a,fs=s?"list":u,wn=[{label:"Active Deals",value:(wt==null?void 0:wt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:qZ((wt==null?void 0:wt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:qZ((wt==null?void 0:wt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:qZ((wt==null?void 0:wt.ytdWonNet)||0),subtitle:`${(wt==null?void 0:wt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:qZ((wt==null?void 0:wt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],As=[...V!=="all"?[{key:"type",label:`Type: ${V}`,onClear:()=>H("all")}]:[],...oe!=="all"?[{key:"year",label:`Year: ${oe}`,onClear:()=>re("all")}]:[],...K!=="all"?[{key:"tag",label:`Tag: ${K}`,onClear:()=>Z("all")}]:[],...q?[{key:"search",label:`"${q}"`,onClear:()=>G("")}]:[],...ae?[{key:"attention",label:"Needs attention",onClear:()=>J(null)}]:[]],Ss=()=>{G(""),H("all"),Z("all"),re("all"),J(null)};return e.jsxs($s,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.jsx(ptr,{summary:`${(wt==null?void 0:wt.activeDeals)||0} active deals • ${qZ((wt==null?void 0:wt.weightedNet)||0)} weighted net`,stats:fs==="portals"?[]:wn,search:q,onSearchChange:G,onAddDeal:()=>Es(),onRefresh:()=>i(),onTeam:Ae&&!Se?()=>me(!0):void 0,showSearch:fs!=="portals",activeFilters:As,onClearAll:Ss,resultLabel:As.length>0?`${It.length} of ${lt.length} deals`:null,viewControls:s?null:e.jsx(UN,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:op,label:"Board",hint:"Kanban board view"},{mode:"list",icon:My,label:"List",hint:"Grouped list view"},{mode:"table",icon:pq,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:un,label:"Portals",hint:"Client portal management"}].map(({mode:hn,icon:Pn,label:Gs,hint:an})=>e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(hn),className:Ct("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===hn?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Gs})]})}),e.jsx(Tx,{children:an})]},hn))})}),filters:fs!=="portals"?e.jsxs(e.Fragment,{children:[e.jsxs(ls,{value:V,onValueChange:H,children:[e.jsx(rs,{className:"hub-glass h-10 w-[130px] rounded-full border-0 text-sm",children:e.jsx(cs,{placeholder:"All Types"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"}),e.jsx(He,{value:"dual",children:"Dual"}),e.jsx(He,{value:"referral",children:"Referral"}),e.jsx(He,{value:"lease",children:"Lease"})]})]}),e.jsxs(ls,{value:oe,onValueChange:re,children:[e.jsx(rs,{className:"hub-glass h-10 w-[110px] rounded-full border-0 text-sm",children:e.jsx(cs,{placeholder:"Year"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Years"}),qs.map(hn=>e.jsx(He,{value:hn,children:hn},hn))]})]}),e.jsxs(ls,{value:K,onValueChange:Z,children:[e.jsxs(rs,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Ip,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(cs,{placeholder:"All Tags"})]}),e.jsxs(as,{className:"max-h-[300px]",children:[e.jsx(He,{value:"all",children:"All Tags"}),Zt.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Zt.map(hn=>e.jsx(He,{value:hn,children:hn},hn))]})]})]}):null}),e.jsx(btr,{}),fs!=="portals"&&e.jsx(xtr,{items:Dt,active:ae,onToggle:hn=>J(Pn=>Pn===hn?null:hn)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Se&&!s&&We.length>0&&e.jsx(SKn,{members:We,enabledMembers:Ee,onToggleMember:Xe,isOpen:he,onToggleOpen:()=>ge(hn=>!hn),showOwnDeals:Pe,onToggleOwnDeals:()=>Oe(hn=>!hn)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Yn?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(hn=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(ln,{className:"h-full rounded-xl"})},hn))}):fs==="board"?e.jsxs(Ki,{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(hn=>e.jsx(PKn,{stage:hn,deals:Tn(hn.id),onDealClick:Us,onAddDeal:Es,onDragStart:bn,onDragOver:cr,onDrop:Fs,isDragOver:E===hn.id,isWonStage:hn.is_won_stage,isLostStage:hn.is_lost_stage,getOwnerInfo:$e,tagsByDeal:zt,overdueTasksByDeal:qt},hn.id))}),e.jsx(Zre,{orientation:"horizontal"})]}):fs==="table"?e.jsx(Ki,{className:"h-full",children:e.jsx(Xer,{deals:It,stages:t||[],onDealClick:Us,onStageChange:lr})}):fs==="portals"?e.jsx(Krs,{}):e.jsx(Ki,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(hn=>{const Pn=Tn(hn.id);return Pn.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:hn.color}}),e.jsx("h3",{className:"font-semibold",children:hn.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",Pn.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Pn.map(Gs=>e.jsx(Uss,{deal:Gs,onClick:()=>Us(Gs),stages:t,onStageChange:lr,showStagePicker:!0,isWonStage:hn.is_won_stage,isLostStage:hn.is_lost_stage,ownerInfo:$e(Gs),tags:zt[Gs.id]||[],overdueTaskCount:qt[Gs.id]||0},Gs.id))})]},hn.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(op,{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(z,{onClick:()=>Es(),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&It.length===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Rr,{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(z,{variant:"outline",onClick:Ss,children:"Clear Filters"})]})]})})})]})]}),e.jsx(UKn,{open:m,onOpenChange:p,deal:v,defaultStageId:b}),e.jsx(Ker,{deal:v,open:f,onOpenChange:Sn,onEdit:kn,isWonStage:v?(pr=t==null?void 0:t.find(hn=>hn.id===v.stage_id))==null?void 0:pr.is_won_stage:!1,onAddToScorecard:hn=>{F(hn),I(!0),g(!1)}}),e.jsx(Yer,{open:M,onOpenChange:I,deal:D,onComplete:()=>{i(),F(null)}}),Ve&&e.jsx(ltr,{open:!!Ve,onOpenChange:hn=>{hn||_e(null)},dealId:Ve.dealId,dealName:Ve.dealName,fromStageName:Ve.fromStageName,toStageName:Ve.toStageName,toStageId:Ve.toStageId,onConfirm:cn}),e.jsx(NKn,{open:ve,onOpenChange:me})]})}function jtr(){return e.jsx(_tr,{children:e.jsx(wtr,{})})}function R6e({open:s,onOpenChange:t,templateId:n,templateName:r,brokerageId:a,onUploaded:i}){const l=!!n,o=_.useRef(null),[c,d]=_.useState(null),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState("other"),[v,y]=_.useState(!1),b=JJn(),w=()=>{d(null),h(""),p(""),g("other"),y(!1),o.current&&(o.current.value="")},S=E=>{if(E){if(E.type!=="application/pdf"&&!E.name.toLowerCase().endsWith(".pdf")){ne.error("Only PDF files can be uploaded.");return}if(E.size>Rrs){ne.error("That PDF is larger than the 20MB limit.");return}d(E),!u&&!l&&h(E.name.replace(/\.pdf$/i,""))}},C=async()=>{if(c)try{const E=await b.mutateAsync({name:u.trim()||c.name.replace(/\.pdf$/i,""),description:m,category:f,file:c,templateId:n,brokerageId:a});ne.success(E.version.has_acroform?`Found ${E.version.detected_fields.length} fillable fields — map them next.`:"Uploaded. This PDF has no fillable fields yet."),i==null||i(E.templateId,E.version.id),w(),t(!1)}catch(E){ne.error((E==null?void 0:E.message)||"Upload failed")}};return e.jsx(Is,{open:s,onOpenChange:E=>{E||w(),t(E)},children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:l?`New version of ${r}`:"Upload a form template"}),e.jsxs(_r,{children:["PDF only, up to 20MB."," ",a?"Brokerage templates stay in draft until you publish them to your agents.":"Templates stay private to your account."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:o,type:"file",accept:"application/pdf,.pdf",className:"hidden",onChange:E=>{var P;return S((P=E.target.files)==null?void 0:P[0])}}),e.jsx("button",{type:"button",onClick:()=>{var E;return(E=o.current)==null?void 0:E.click()},className:"w-full rounded-lg border border-dashed p-6 text-center transition-colors hover:bg-muted/50",children:c?e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx($r,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:c.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:mit(c.size)})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[e.jsx(Ra,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Choose a blank PDF form"})]})}),!l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"tpl-name",children:"Template name"}),e.jsx(pe,{id:"tpl-name",value:u,onChange:E=>h(E.target.value),placeholder:"Residential Purchase Agreement"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ls,{value:f,onValueChange:E=>g(E),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:uit.map(E=>e.jsx(He,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"tpl-desc",children:"Description (optional)"}),e.jsx(Ps,{id:"tpl-desc",rows:2,value:m,onChange:E=>p(E.target.value)})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[e.jsx(za,{checked:v,onCheckedChange:E=>y(!!E),className:"mt-0.5"}),e.jsx("span",{children:"I confirm I am legally permitted to use and store this form. LevelUp does not provide or license association forms."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(z,{onClick:C,disabled:!c||!v||b.isPending,children:[b.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Reading PDF…":"Upload"]})]})]})})}function xZe(s){return s.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").toLowerCase().trim()}function R4t(s){return xZe(s).split(" ").filter(Boolean)}function Ntr(s,t,n){const r=xZe(s),a=new Set(R4t(s));let i=0;const l=[t,...n];for(const o of l){const c=xZe(o);if(!c)continue;if(r===c){i=Math.max(i,100);continue}if(r.includes(c)){i=Math.max(i,60+Math.min(c.length,30));continue}const d=R4t(o),u=d.filter(h=>a.has(h)).length;u>0&&(i=Math.max(i,Math.round(u/d.length*45)))}return i}function ktr(s){if(!s)return null;let t=null;for(const n of UG){const r=Ntr(s,n.label,n.aliases);r>0&&(!t||r>t.confidence)&&(t={mergeKey:n.key,confidence:r})}return!t||t.confidence<35?null:t}const Str=["Deal","Contact","Agent","Other"],zBe="__blank__",BBe="__static__";function Yrs({version:s}){const{data:t,isLoading:n}=_ie(s.id),r=oer(),[a,i]=_.useState([]),[l,o]=_.useState("");_.useEffect(()=>{if(n)return;const p=new Map((t||[]).map(f=>[f.pdf_field_name||"",f]));i((s.detected_fields||[]).map(f=>{const g=p.get(f.name),v=ktr(f.name);return{pdf_field_name:f.name,mapping_mode:(g==null?void 0:g.mapping_mode)||"acroform",merge_key:(g==null?void 0:g.merge_key)??null,static_value:(g==null?void 0:g.static_value)??null,suggested:(v==null?void 0:v.mergeKey)??null}}))},[t,n,s.id,s.detected_fields]);const c=_.useMemo(()=>{if(!l.trim())return a;const p=l.toLowerCase();return a.filter(f=>(f.pdf_field_name||"").toLowerCase().includes(p))},[a,l]),d=a.filter(p=>p.merge_key||p.mapping_mode==="static"&&p.static_value).length,u=(p,f)=>{i(g=>g.map(v=>v.pdf_field_name===p?{...v,...f}:v))},h=()=>{let p=0;i(f=>f.map(g=>g.merge_key||!g.suggested?g:(p+=1,{...g,mapping_mode:"acroform",merge_key:g.suggested}))),ne.success(p?`Applied ${p} suggestion${p===1?"":"s"}`:"No new suggestions to apply")},m=async()=>{try{await r.mutateAsync({versionId:s.id,hasAcroform:s.has_acroform,mappings:a.map(({suggested:p,...f})=>f)}),ne.success("Field mapping saved")}catch(p){ne.error((p==null?void 0:p.message)||"Could not save the mapping")}};return s.has_acroform?n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[d," of ",a.length," fields mapped"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(un,{className:"mr-1.5 h-4 w-4"})," Apply suggestions"]}),e.jsxs(z,{size:"sm",onClick:m,disabled:r.isPending,children:[r.isPending?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-1.5 h-4 w-4"}),"Save mapping"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search fields…",value:l,onChange:p=>o(p.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[c.map(p=>{var g;const f=p.mapping_mode==="static"?BBe:p.merge_key?p.merge_key:zBe;return e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border bg-background p-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:p.pdf_field_name}),p.suggested&&!p.merge_key&&e.jsxs(ze,{variant:"secondary",className:"mt-1 text-[10px]",children:["Suggested: ",(g=UG.find(v=>v.key===p.suggested))==null?void 0:g.label]})]}),e.jsxs("div",{className:"flex w-full gap-2 sm:w-[420px]",children:[e.jsxs(ls,{value:f,onValueChange:v=>{v===zBe?u(p.pdf_field_name,{mapping_mode:"blank",merge_key:null,static_value:null}):v===BBe?u(p.pdf_field_name,{mapping_mode:"static",merge_key:null}):u(p.pdf_field_name,{mapping_mode:"acroform",merge_key:v,static_value:null})},children:[e.jsx(rs,{className:"flex-1",children:e.jsx(cs,{placeholder:"Leave blank"})}),e.jsxs(as,{className:"max-h-[320px]",children:[e.jsx(He,{value:zBe,children:"Leave blank"}),e.jsx(He,{value:BBe,children:"Fixed text…"}),Str.map(v=>e.jsxs(S3s,{children:[e.jsx(ARt,{children:v}),UG.filter(y=>y.group===v).map(y=>e.jsx(He,{value:y.key,children:y.label},y.key))]},v))]})]}),p.mapping_mode==="static"&&e.jsx(pe,{className:"flex-1",placeholder:"Fixed text",value:p.static_value||"",onChange:v=>u(p.pdf_field_name,{static_value:v.target.value})})]})]},p.pdf_field_name)}),c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No fields match that search."})]})]}):e.jsx(be,{children:e.jsxs(Le,{className:"p-6 text-center space-y-2",children:[e.jsx("p",{className:"font-medium",children:"Needs field placement"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"This PDF has no fillable form fields, so there is nothing to map yet. Visual field placement for flat PDFs is coming next — for now, upload a fillable (AcroForm) version of this form to use it from a deal."})]})})}Aat.workerSrc=Eat;const i3e={data:{w:.24,h:.028,label:"Data field"},signature:{w:.28,h:.055,label:"Signature"},initials:{w:.1,h:.035,label:"Initials"},date_signed:{w:.14,h:.028,label:"Date signed"},printed_name:{w:.24,h:.03,label:"Printed name"},text:{w:.24,h:.03,label:"Text input"}},$Be=["signature","initials","date_signed","printed_name","text"],F4t=12,Ctr={buyer_1:"border-emerald-500 bg-emerald-500/15 text-emerald-700",buyer_2:"border-emerald-500 bg-emerald-500/15 text-emerald-700",seller_1:"border-sky-500 bg-sky-500/15 text-sky-700",seller_2:"border-sky-500 bg-sky-500/15 text-sky-700",agent:"border-amber-500 bg-amber-500/15 text-amber-700"},Ude=s=>Math.min(1,Math.max(0,s));function Zrs({version:s,templateName:t,open:n,onOpenChange:r}){const a=$t(),{data:i=[],isLoading:l}=_ie(n?s.id:void 0),[o,c]=_.useState(null),[d,u]=_.useState(null),[h,m]=_.useState([]),[p,f]=_.useState("select"),[g,v]=_.useState(null),[y,b]=_.useState(!1),[w,S]=_.useState(!1),C=_.useRef(null),E=_.useRef([]),P=_.useRef(null),M=Math.min(s.page_count||1,F4t);_.useEffect(()=>{if(!n)return;let Z=!1;return c(null),u(null),pDe(s.storage_path).then(oe=>{Z||c(new Blob([oe],{type:"application/pdf"}))}).catch(()=>!Z&&u("Could not load the template PDF.")),()=>{Z=!0}},[n,s.storage_path]),_.useEffect(()=>{let Z=!1;const oe=C.current;return!o||!oe?void 0:((async()=>{try{const ae=await o.arrayBuffer(),J=await v6e({data:ae}).promise;if(Z)return;oe.innerHTML="",E.current=[];const te=Math.min(oe.clientWidth-32||720,860);for(let ce=1;ce<=J.numPages;ce++){const ve=await J.getPage(ce);if(Z)return;const me=ve.getViewport({scale:1}),he=te/me.width,ge=ve.getViewport({scale:he*(window.devicePixelRatio||1)}),Ee=document.createElement("div");Ee.className="relative mx-auto shadow-sm",Ee.style.width=`${te}px`,Ee.style.height=`${me.height*he}px`,Ee.dataset.pageIndex=String(ce-1);const Ne=document.createElement("canvas");Ne.width=Math.floor(ge.width),Ne.height=Math.floor(ge.height),Ne.style.width="100%",Ne.style.height="100%",Ne.className="rounded-md border border-border bg-white",Ee.appendChild(Ne),oe.appendChild(Ee),E.current[ce-1]=Ee;const Pe=Ne.getContext("2d");Pe&&await ve.render({canvasContext:Pe,viewport:ge}).promise}Z||m(ce=>[...ce])}catch(ae){Z||u((ae==null?void 0:ae.message)||"Could not render the PDF")}})(),()=>{Z=!0})},[o]),_.useEffect(()=>{if(!n||l)return;const Z=i.filter(oe=>oe.field_kind!=="data"||oe.mapping_mode==="overlay").filter(oe=>oe.pos_x!=null&&oe.pos_y!=null).map(oe=>({key:oe.id,page_index:oe.page_index??0,x:Number(oe.pos_x),y:Number(oe.pos_y),w:Number(oe.width??.2),h:Number(oe.height??.03),field_kind:oe.field_kind||"data",merge_key:oe.merge_key,static_value:oe.static_value,signer_role:oe.signer_role,label:oe.label,is_required:oe.is_required??!0,font_size:oe.font_size,source:oe.source||"manual"}));m(Z),v(null)},[n,l,i]),_.useEffect(()=>{const Z=re=>{const ae=P.current;if(!ae)return;const J=(re.clientX-ae.startX)/ae.pageW,te=(re.clientY-ae.startY)/ae.pageH;m(ce=>ce.map(ve=>ve.key!==ae.key?ve:ae.mode==="move"?{...ve,x:Ude(Math.min(ae.orig.x+J,1-ve.w)),y:Ude(Math.min(ae.orig.y+te,1-ve.h))}:{...ve,w:Math.min(Math.max(.04,ae.orig.w+J),1-ve.x),h:Math.min(Math.max(.015,ae.orig.h+te),1-ve.y)}))},oe=()=>{P.current=null};return window.addEventListener("pointermove",Z),window.addEventListener("pointerup",oe),()=>{window.removeEventListener("pointermove",Z),window.removeEventListener("pointerup",oe)}},[]);const I=(Z,oe,re)=>{Z.stopPropagation(),Z.preventDefault();const ae=E.current[oe.page_index];if(!ae)return;const J=ae.getBoundingClientRect();P.current={key:oe.key,mode:re,startX:Z.clientX,startY:Z.clientY,orig:oe,pageW:J.width,pageH:J.height},v(oe.key)},D=(Z,oe)=>{if(p==="select"){v(null);return}const re=E.current[oe];if(!re)return;const ae=re.getBoundingClientRect(),J=i3e[p],te=Ude((Z.clientX-ae.left)/ae.width-J.w/2),ce=Ude((Z.clientY-ae.top)/ae.height-J.h/2),ve={key:crypto.randomUUID(),page_index:oe,x:Math.min(te,1-J.w),y:Math.min(ce,1-J.h),w:J.w,h:J.h,field_kind:p,merge_key:null,static_value:null,signer_role:$Be.includes(p)?"buyer_1":null,label:null,is_required:!0,font_size:null};m(me=>[...me,ve]),v(ve.key),f("select")},F=h.find(Z=>Z.key===g)||null,q=Z=>{F&&m(oe=>oe.map(re=>re.key===F.key?{...re,...Z}:re))},G=async(Z=!1)=>{if(o){S(!0);try{const oe=await o.arrayBuffer(),re=await v6e({data:oe}).promise,ae=Math.min(re.numPages,F4t),J=[];for(let he=1;he<=ae;he++){const ge=await re.getPage(he),Ee=ge.getViewport({scale:1}),Ne=ge.getViewport({scale:Math.min(1e3/Ee.width,1.6)}),Pe=document.createElement("canvas");Pe.width=Math.floor(Ne.width),Pe.height=Math.floor(Ne.height);const Oe=Pe.getContext("2d");Oe&&(Oe.fillStyle="#ffffff",Oe.fillRect(0,0,Pe.width,Pe.height),await ge.render({canvasContext:Oe,viewport:Ne}).promise,J.push({index:he-1,image:Pe.toDataURL("image/jpeg",.7)}))}const{data:te,error:ce}=await U.functions.invoke("forms-autoplace",{body:{version_id:s.id,pages:J,force:Z}});if(ce)throw new Error(ce.message||"The field scan failed.");if(te!=null&&te.error)throw new Error(te.error);const ve=(te==null?void 0:te.fields)||[];if(!ve.length){ne.info("The scan did not find any blank fields on this form. Place them manually below.");return}const me=ve.map(he=>({key:crypto.randomUUID(),page_index:he.page_index,x:he.x,y:he.y,w:he.w,h:he.h,field_kind:he.field_kind,merge_key:null,static_value:null,signer_role:he.signer_role||"buyer_1",label:he.label,is_required:!0,font_size:null,source:"ai"}));m(he=>[...he,...me]),v(null),ne.success(`${me.length} field${me.length===1?"":"s"} placed${te!=null&&te.cached?" (from the earlier scan)":""}. Review, nudge, then save.`)}catch(oe){ne.error((oe==null?void 0:oe.message)||"Could not scan this document. You can still place fields manually.")}finally{S(!1)}}},V=async()=>{const Z=h.filter(oe=>$Be.includes(oe.field_kind));for(const oe of Z)if(!oe.signer_role){ne.error("Every signer field needs a role (Buyer 1, Seller 1, Agent…)");return}b(!0);try{const{error:oe}=await U.from("form_field_mappings").delete().eq("version_id",s.id).or("field_kind.neq.data,mapping_mode.eq.overlay");if(oe)throw oe;const re=h.map((ce,ve)=>({version_id:s.id,pdf_field_name:null,mapping_mode:(ce.field_kind==="data"&&ce.static_value&&!ce.merge_key,"overlay"),field_kind:ce.field_kind,merge_key:ce.field_kind==="data"?ce.merge_key:null,static_value:ce.field_kind==="data"?ce.static_value:null,signer_role:$Be.includes(ce.field_kind)?ce.signer_role:null,label:ce.label,is_required:ce.is_required,page_index:ce.page_index,pos_x:ce.x,pos_y:ce.y,width:ce.w,height:ce.h,coords_normalized:!0,font_size:ce.font_size,source:ce.source||"manual",sort_order:ve}));if(re.length){const{error:ce}=await U.from("form_field_mappings").insert(re);if(ce)throw ce}const J=h.some(ce=>ce.field_kind==="data"&&(ce.merge_key||ce.static_value))||i.some(ce=>ce.field_kind==="data"&&ce.mapping_mode!=="overlay"&&(ce.mapping_mode==="acroform"&&ce.merge_key||ce.mapping_mode==="static"))||Z.length?"mapped":s.has_acroform?"needs_mapping":"needs_placement",{error:te}=await U.from("form_template_versions").update({mapping_status:J}).eq("id",s.id);if(te)throw te;ne.success("Placement saved"),a.invalidateQueries({queryKey:["form-field-mappings",s.id]}),a.invalidateQueries({queryKey:["form-templates"]}),r(!1)}catch(oe){ne.error((oe==null?void 0:oe.message)||"Could not save placement")}finally{b(!1)}},H=[{tool:"select",label:"Select",icon:rJ},{tool:"data",label:"Merge field",icon:h6},{tool:"signature",label:"Signature",icon:Mm},{tool:"initials",label:"Initials",icon:yq},{tool:"date_signed",label:"Date signed",icon:gc},{tool:"printed_name",label:"Printed name",icon:Oo},{tool:"text",label:"Text input",icon:gq}],K=s.page_count||1;return e.jsx(Is,{open:n,onOpenChange:r,children:e.jsxs(Ls,{className:"flex h-[94vh] max-w-6xl flex-col overflow-hidden p-0",children:[e.jsxs(Os,{className:"border-b px-5 py-3 text-left",children:[e.jsxs(Rs,{className:"text-base",children:["Place fields — ",t," (v",s.version_number,")"]}),e.jsx("p",{className:"text-xs font-normal text-muted-foreground",children:"Pick a field type on the left, then click on the document where it belongs. Drag to move, pull the corner to resize."})]}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[e.jsxs("div",{className:"w-36 shrink-0 space-y-1 overflow-y-auto border-r p-3 sm:w-44",children:[e.jsxs(z,{size:"sm",variant:"secondary",className:"mb-2 h-auto w-full flex-col items-start gap-0.5 py-2 text-left",disabled:w||!o,onClick:()=>G(!!s.autoplace_ran_at),children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-semibold",children:[w?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(un,{className:"h-3.5 w-3.5"}),w?"Scanning…":s.autoplace_ran_at?"Re-scan with AI":"Find fields with AI"]}),e.jsx("span",{className:"text-[10px] font-normal opacity-70",children:s.autoplace_ran_at?"Runs a fresh scan":`Scan ${M} page${M===1?"":"s"}`})]}),H.map(Z=>e.jsxs("button",{onClick:()=>f(Z.tool),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-medium transition-colors ${p===Z.tool?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(Z.icon,{className:"h-3.5 w-3.5 shrink-0"}),Z.label]},Z.tool)),e.jsx("div",{className:"pt-3 text-[11px] leading-snug text-muted-foreground",children:"Merge fields fill automatically from the deal. Signature fields are assigned to a signer."})]}),e.jsxs("div",{className:"relative min-w-0 flex-1 overflow-auto bg-muted/40 p-4",children:[(l||!o)&&!d&&e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),d&&e.jsx("p",{className:"p-6 text-center text-sm text-destructive",children:d}),e.jsx("div",{ref:C,className:"space-y-4",onClickCapture:Z=>{const oe=Z.target.closest("[data-page-index]");oe&&D(Z,Number(oe.dataset.pageIndex))}})]}),e.jsxs("div",{className:"hidden w-64 shrink-0 flex-col border-l sm:flex",children:[e.jsx("div",{className:"border-b px-4 py-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:F?i3e[F.field_kind].label:"Field settings"}),e.jsx(Ki,{className:"flex-1 p-4",children:F?e.jsxs("div",{className:"space-y-4",children:[F.field_kind==="data"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Merge value"}),e.jsxs(ls,{value:F.merge_key||"",onValueChange:Z=>q({merge_key:Z||null,static_value:null}),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(cs,{placeholder:"Choose data…"})}),e.jsx(as,{children:["Deal","Contact","Agent","Other"].map(Z=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase text-muted-foreground",children:Z}),UG.filter(oe=>oe.group===Z).map(oe=>e.jsx(He,{value:oe.key,className:"text-xs",children:oe.label},oe.key))]},Z))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"…or fixed text"}),e.jsx(pe,{className:"h-8 text-xs",placeholder:"Printed exactly as typed",value:F.merge_key?"":F.static_value||"",disabled:!!F.merge_key,onChange:Z=>q({static_value:Z.target.value||null})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Who signs this?"}),e.jsxs(ls,{value:F.signer_role||"",onValueChange:Z=>q({signer_role:Z}),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(cs,{placeholder:"Choose signer…"})}),e.jsx(as,{children:fit.map(Z=>e.jsx(He,{value:Z.value,className:"text-xs",children:Z.label},Z.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Label shown to signer"}),e.jsx(pe,{className:"h-8 text-xs",placeholder:i3e[F.field_kind].label,value:F.label||"",onChange:Z=>q({label:Z.target.value||null})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Required"}),e.jsx(mn,{checked:F.is_required,onCheckedChange:Z=>q({is_required:Z})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Font size (optional)"}),e.jsx(pe,{className:"h-8 text-xs",type:"number",min:6,max:24,value:F.font_size??"",onChange:Z=>q({font_size:Z.target.value?Number(Z.target.value):null})})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[F.page_index+1{const Z={...F,key:crypto.randomUUID(),page_index:F.page_index+1};m(oe=>[...oe,Z]),v(Z.key)},children:[e.jsx(Sa,{className:"mr-1 h-3 w-3"})," Next page"]}),e.jsxs(z,{variant:"outline",size:"sm",className:"h-8 flex-1 text-xs text-destructive",onClick:()=>{m(Z=>Z.filter(oe=>oe.key!==F.key)),v(null)},children:[e.jsx(Cn,{className:"mr-1 h-3 w-3"})," Remove"]})]})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a box on the document to edit what it fills and who signs it."})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs(z,{className:"w-full",onClick:V,disabled:y,children:[y?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Bo,{className:"mr-2 h-4 w-4"}),"Save placement"]})})]})]}),e.jsx(Atr,{boxes:h,pageRefs:E,selectedKey:g,onSelect:v,onDragStart:I})]})})}function Atr({boxes:s,pageRefs:t,selectedKey:n,onSelect:r,onDragStart:a}){const[,i]=_.useState(0);return _.useEffect(()=>{const l=setTimeout(()=>i(o=>o+1),300);return()=>clearTimeout(l)},[s.length===0]),e.jsx(e.Fragment,{children:s.map(l=>{var c;const o=t.current[l.page_index];return o?e.jsx(Etr,{target:o,children:e.jsxs("div",{onPointerDown:d=>a(d,l,"move"),onClick:d=>d.stopPropagation(),className:`absolute cursor-move rounded-sm border-2 transition-shadow ${l.field_kind==="data"?"border-primary bg-primary/10 text-primary":Ctr[l.signer_role||""]||"border-muted-foreground bg-muted/40"} ${n===l.key?"ring-2 ring-ring shadow-md":""}`,style:{left:`${l.x*100}%`,top:`${l.y*100}%`,width:`${l.w*100}%`,height:`${l.h*100}%`},children:[e.jsx("span",{className:"pointer-events-none absolute left-0.5 top-0 max-w-full truncate text-[9px] font-semibold leading-tight",children:l.field_kind==="data"?l.merge_key?((c=UG.find(d=>d.key===l.merge_key))==null?void 0:c.label)||l.merge_key:l.static_value||"Data":`${l.label||i3e[l.field_kind].label} · ${fDe(l.signer_role)}`}),n===l.key&&e.jsx("span",{onPointerDown:d=>a(d,l,"resize"),className:"absolute -bottom-1.5 -right-1.5 h-3.5 w-3.5 cursor-nwse-resize rounded-full border-2 border-background bg-primary"})]})},l.key):null})})}function Etr({target:s,children:t}){return pv.createPortal(t,s)}function Ttr({templates:s}){const{data:t=[],isLoading:n}=Urs(),r=per(),a=fer(),[i,l]=_.useState(null),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState([]);_.useEffect(()=>{i&&(i==="new"?(c(""),u(""),m([])):(c(i.name),u(i.description||""),m([...i.items||[]].sort((y,b)=>y.sort_order-b.sort_order).map(y=>y.template_id))))},[i]);const p=s.filter(y=>{var b;return((b=Cx(y))==null?void 0:b.mapping_status)==="mapped"}),f=y=>m(b=>b.includes(y)?b.filter(w=>w!==y):[...b,y]),g=(y,b)=>m(w=>{const S=[...w],C=y+b;return C<0||C>=S.length?w:([S[y],S[C]]=[S[C],S[y]],S)}),v=async()=>{if(!o.trim())return ne.error("Give the packet a name");if(!h.length)return ne.error("Add at least one form to the packet");try{await r.mutateAsync({id:i==="new"?void 0:i.id,name:o.trim(),description:d.trim()||null,templateIds:h}),ne.success(i==="new"?"Packet created":"Packet updated"),l(null)}catch(y){ne.error((y==null?void 0:y.message)||"Could not save the packet")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold tracking-tight",children:[e.jsx(X4,{className:"h-4 w-4 text-primary"})," Form packets"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bundle the forms you always send together. Signers sign the whole packet in one session."})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>l("new"),disabled:p.length===0,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," New packet"]})]}),n?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{className:"p-6 text-center text-sm text-muted-foreground",children:p.length===0?"Once at least one template is ready to send, you can bundle templates into a packet.":"No packets yet — build a “New Buyer Packet” or “Listing Agreement Bundle” and send it in one click."})}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(y=>{const b=xit(y,s);return e.jsx(be,{children:e.jsxs(Le,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(X4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:y.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," form",b.length===1?"":"s"]})]})]}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-xs text-muted-foreground",children:b.map(w=>e.jsx("li",{className:"truncate",children:w.name},w.id))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Send from any deal"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>l(y),children:[e.jsx(Wa,{className:"mr-1 h-3 w-3"})," Edit"]}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:async()=>{await Qi(`Delete the "${y.name}" packet? The forms themselves are kept.`)&&(await a.mutateAsync(y.id),ne.success("Packet deleted"))},children:e.jsx(Cn,{className:"h-3 w-3"})})]})]})]})},y.id)})}),e.jsx(Is,{open:!!i,onOpenChange:y=>!y&&l(null),children:e.jsxs(Ls,{className:"flex max-h-[88vh] max-w-lg flex-col overflow-hidden",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:i==="new"?"New form packet":"Edit packet"}),e.jsx(_r,{children:"Pick the forms and the order signers see them in. Only templates that are ready to send can be added."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Packet name"}),e.jsx(pe,{value:o,onChange:y=>c(y.target.value),placeholder:"New Buyer Packet"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Description (optional)"}),e.jsx(Ps,{rows:2,value:d,onChange:y=>u(y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Forms in this packet"}),e.jsx(Ki,{className:"max-h-56 rounded-lg border",children:e.jsx("div",{className:"divide-y",children:p.map(y=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 p-2.5 text-sm hover:bg-muted/50",children:[e.jsx(za,{checked:h.includes(y.id),onCheckedChange:()=>f(y.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:y.name})]},y.id))})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Signing order"}),e.jsx("div",{className:"space-y-1 rounded-lg border p-2",children:h.map((y,b)=>{const w=s.find(S=>S.id===y);return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"w-4 text-muted-foreground",children:[b+1,"."]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:(w==null?void 0:w.name)||"Removed template"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>g(b,-1),children:e.jsx(ap,{className:"h-3 w-3"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>g(b,1),children:e.jsx(Vf,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(z,{onClick:v,disabled:r.isPending,children:[r.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save packet"]})]})]})})]})}function Mtr(s){const t=s.indexOf(",");if(t<0)return null;try{const n=atob(s.slice(t+1)),r=new Uint8Array(n.length);for(let a=0;ad.field_kind==null||d.field_kind==="data"),n=await Drs(s.templateBytes,t,s.values),r=n.bytes.buffer.slice(n.bytes.byteOffset,n.bytes.byteOffset+n.bytes.byteLength),a=await wC.load(r,{updateMetadata:!1}),i=await a.embedFont($G.Helvetica),l=a.getPages(),o=[...n.skipped];for(const d of s.signerBoxes){const u=s.entries[d.id],h=l[d.page_index??0];if(!h||d.pos_x==null||d.pos_y==null)continue;if(!u||!u.png&&!((c=u.text)!=null&&c.trim())){o.push(d.static_value||d.field_kind||"signature");continue}const{width:m,height:p}=h.getSize(),f=d.coords_normalized!==!1,g=Number(d.pos_x)*(f?m:1),v=Number(d.width??(f?.2:140))*(f?m:1),y=Number(d.height??(f?.04:24))*(f?p:1),b=Number(d.pos_y)*(f?p:1),w=f?p-b-y:b;if(u.png){const S=Mtr(u.png);if(!S){o.push("signature");continue}const C=await a.embedPng(S),E=Math.min(v/C.width,y/C.height),P=C.width*E,M=C.height*E;h.drawImage(C,{x:g+(v-P)/2,y:w+(y-M)/2,width:P,height:M})}else{const S=u.text.trim(),C=Math.min(11,Math.max(7,y*.6));h.drawText(S,{x:g+1,y:w+Math.max(2,(y-C)/2),size:C,font:i,color:zu(0,0,0),maxWidth:Math.max(10,v-2)})}}return{bytes:await a.save(),skipped:o}}const Xrs='"Segoe Script","Brush Script MT",cursive';function Ltr(s){const t=document.createElement("canvas");t.width=640,t.height=200;const n=t.getContext("2d");return n.clearRect(0,0,t.width,t.height),n.fillStyle="#12233f",n.textAlign="center",n.font=`72px ${Xrs}`,n.fillText(s,t.width/2,t.height/2+24),t.toDataURL("image/png")}function Itr({label:s,onAdopt:t}){const n=_.useRef(null),r=_.useRef(!1),[a,i]=_.useState(""),[l,o]=_.useState(!1),c=m=>{const p=n.current,f=p.getBoundingClientRect();return{x:(m.clientX-f.left)/f.width*p.width,y:(m.clientY-f.top)/f.height*p.height}},d=m=>{const p=n.current;if(!p)return;r.current=!0,p.setPointerCapture(m.pointerId);const f=p.getContext("2d");f.lineWidth=3,f.lineCap="round",f.strokeStyle="#12233f";const g=c(m);f.beginPath(),f.moveTo(g.x,g.y)},u=m=>{if(!r.current)return;const p=n.current.getContext("2d"),f=c(m);p.lineTo(f.x,f.y),p.stroke(),o(!0)},h=()=>{r.current=!1};return e.jsxs(Qr,{defaultValue:"draw",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsx(Wt,{value:"draw",children:"Draw"}),e.jsx(Wt,{value:"type",children:"Type"})]}),e.jsxs(Kt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:n,width:640,height:200,className:"h-36 w-full touch-none rounded-lg border bg-white",onPointerDown:d,onPointerMove:u,onPointerUp:h,onPointerLeave:h}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{var p;const m=n.current;(p=m==null?void 0:m.getContext("2d"))==null||p.clearRect(0,0,m.width,m.height),o(!1)},children:[e.jsx($U,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs(z,{type:"button",size:"sm",className:"flex-1",disabled:!l,onClick:()=>{const m=n.current;m&&t(m.toDataURL("image/png"))},children:["Use this ",s]})]})]}),e.jsxs(Kt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(pe,{value:a,onChange:m=>i(m.target.value),placeholder:"Type your name"}),e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:Xrs},children:a||" "})}),e.jsxs(z,{type:"button",size:"sm",className:"w-full",disabled:!a.trim(),onClick:()=>t(Ltr(a.trim())),children:["Use this ",s]})]})]})}const Dtr=["signature","initials","date_signed","printed_name","text"],Rtr={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function Ftr({open:s,onOpenChange:t,template:n,version:r}){const a=ha(),{data:i=[],isLoading:l}=_ie(s?r.id:void 0),{data:o=[]}=xK(),[c,d]=_.useState(""),{data:u}=pit(s&&c?c:void 0),[h,m]=_.useState({}),[p,f]=_.useState({}),[g,v]=_.useState(null),[y,b]=_.useState(!1),w=_.useMemo(()=>i.filter(I=>(I.field_kind==null||I.field_kind==="data")&&I.mapping_mode!=="blank"&&(I.merge_key||I.pdf_field_name||I.static_value)),[i]),S=_.useMemo(()=>i.filter(I=>I.field_kind&&Dtr.includes(I.field_kind)),[i]);_.useEffect(()=>{u&&m(I=>{const D={...I};for(const[F,q]of Object.entries(u.values))q&&!D[F]&&(D[F]=q);return D})},[u]),_.useEffect(()=>{s||(m({}),f({}),v(null),d(""))},[s]);const C=I=>I.merge_key||I.pdf_field_name||I.id,E=I=>{v(I),f(D=>{var q;const F={...D};for(const G of S)(G.field_kind==="signature"||G.field_kind==="initials")&&(F[G.id]={png:I}),G.field_kind==="date_signed"&&!((q=F[G.id])!=null&&q.text)&&(F[G.id]={text:new Date().toLocaleDateString("en-US")});return F}),ne.success("Signature applied to the document")},P=S.filter(I=>{var D,F,q;return((D=p[I.id])==null?void 0:D.png)||((q=(F=p[I.id])==null?void 0:F.text)==null?void 0:q.trim())}).length,M=async()=>{b(!0);try{const I=await pDe(r.storage_path),D={...h},{bytes:F}=await Ptr({templateBytes:I,mappings:i,values:D,signerBoxes:S,entries:p}),G=`${n.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - signed.pdf`,V=F.buffer.slice(F.byteOffset,F.byteOffset+F.byteLength),H=new Blob([V],{type:"application/pdf"}),K=URL.createObjectURL(H),Z=document.createElement("a");if(Z.href=K,Z.download=G,Z.click(),URL.revokeObjectURL(K),c&&a){const oe=`${a}/${c}/${crypto.randomUUID()}.pdf`,{error:re}=await U.storage.from("deal-files").upload(oe,H,{contentType:"application/pdf"});if(re)throw re;const{error:ae}=await U.from("deal_files").insert({deal_id:c,owner_user_id:a,file_name:G,file_size:H.size,file_type:"application/pdf",storage_path:oe});if(ae)throw ae;await U.from("deal_activities").insert({deal_id:c,activity_type:"document",title:`Filled and signed ${n.name}`,description:`${G} was completed in LevelUp (v${r.version_number}).`,metadata:{template_id:n.id,version_id:r.id}}),ne.success("Saved to the deal and downloaded")}else ne.success("Your signed PDF is downloading");t(!1)}catch(I){ne.error(dit(I))}finally{b(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"flex max-h-[90vh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:["Fill & sign — ",n.name]}),e.jsx(_r,{children:"Type in the details, sign once and download the completed PDF. Nothing is emailed to anyone."})]}),e.jsxs("div",{className:"space-y-5 overflow-y-auto pr-1",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Prefill from a deal (optional)"}),e.jsxs(ls,{value:c||"none",onValueChange:I=>d(I==="none"?"":I),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"No deal — I'll type everything"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No deal — I'll type everything"}),o.map(I=>e.jsx(He,{value:I.id,children:I.deal_name},I.id))]})]}),c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"The finished PDF is also saved to this deal's files."})]}),l?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Form details"}),w.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no data fields — just sign it below."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:w.map(I=>{var G;const D=C(I),F=I.merge_key?((G=zrs.get(I.merge_key))==null?void 0:G.label)||I.merge_key:I.pdf_field_name||"Field",q=I.mapping_mode==="static";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:F}),e.jsx(pe,{value:q?I.static_value||"":h[D]??"",disabled:q,onChange:V=>m(H=>({...H,[D]:V.target.value}))})]},I.id)})})]}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Mm,{className:"h-4 w-4"})," Your signature"]}),S.length>0&&e.jsxs(ze,{variant:P===S.length?"default":"outline",children:[P,"/",S.length," placed"]})]}),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No signature spots are placed on this form yet. Use “Place fields & signatures” first."}):e.jsxs(e.Fragment,{children:[g?e.jsxs("div",{className:"flex items-center gap-3 rounded-md border bg-white p-3",children:[e.jsx("img",{src:g,alt:"Your signature",className:"h-12 object-contain"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>v(null),children:"Redo"})]}):e.jsx(Itr,{label:"signature",onAdopt:E}),e.jsx("div",{className:"space-y-2",children:S.filter(I=>I.field_kind==="printed_name"||I.field_kind==="text"||I.field_kind==="date_signed").map(I=>{var D;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(ee,{className:"text-xs text-muted-foreground",children:[Rtr[I.field_kind||"text"]," · page ",(I.page_index??0)+1,I.signer_role?` · ${fDe(I.signer_role)}`:""]}),e.jsx(pe,{value:((D=p[I.id])==null?void 0:D.text)??"",onChange:F=>f(q=>({...q,[I.id]:{text:F.target.value}}))})]},I.id)})}),e.jsxs("p",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(Mr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"By signing you agree your electronic signature is legally binding on this document."]})]})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs(z,{onClick:M,disabled:y||l,children:[y?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ga,{className:"mr-2 h-4 w-4"}),"Finish & download"]})]})]})})}function Otr({status:s}){return s==="mapped"?e.jsx(ze,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(ze,{variant:"outline",children:"Needs field placement"}):e.jsx(ze,{variant:"secondary",children:"Needs mapping"})}function ztr(){var Z,oe;const{data:s=[],isLoading:t,error:n}=hit(),{data:r=[]}=xK(),a=Frs(),i=Ors(),l=eer(),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(""),[g,v]=_.useState(null),[y,b]=_.useState(""),[w,S]=_.useState(null),[C,E]=_.useState("generate"),[P,M]=_.useState(null),[I,D]=_.useState("all"),F=s.some(re=>re.scope==="brokerage"),q=s.filter(re=>re.name.toLowerCase().includes(p.trim().toLowerCase())).filter(re=>I==="all"||(re.scope||"mine")===I).sort((re,ae)=>(re.scope==="brokerage"?1:0)-(ae.scope==="brokerage"?1:0)),G=async re=>{try{await l.mutateAsync(re),ne.success(`"${re.name}" copied to your forms`)}catch(ae){ne.error((ae==null?void 0:ae.message)||"Could not copy that form")}},V=h?s.find(re=>re.id===h.id)||h:null,H=Cx(V),K=async re=>{if(await Qi(`Delete "${re.name}" and all of its versions? Forms already generated stay on their deals.`))try{await i.mutateAsync(re),(h==null?void 0:h.id)===re.id&&m(null),ne.success("Template deleted")}catch(ae){ne.error((ae==null?void 0:ae.message)||"Could not delete the template")}};return e.jsxs($s,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Forms Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload blank PDF forms you are permitted to use, map their fields once, then fill them from any deal."})]}),e.jsxs(z,{onClick:()=>c(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Upload template"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search templates…",value:p,onChange:re=>f(re.target.value)})]}),F&&e.jsx("div",{className:"flex gap-1 rounded-lg border p-1",children:[["all","All"],["mine","My forms"],["brokerage","Brokerage forms"]].map(([re,ae])=>e.jsx(z,{size:"sm",variant:I===re?"secondary":"ghost",className:"h-7 text-xs",onClick:()=>D(re),children:ae},re))})]}),t&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),n&&e.jsx(be,{children:e.jsx(Le,{className:"p-6 text-center text-sm text-destructive",children:"Could not load your templates. Please refresh and try again."})}),!t&&!n&&s.length===0&&e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx($r,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No form templates yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload a blank PDF form you are legally permitted to use. LevelUp reads its fillable fields so you can map them to your deal, contact and agent data."})]}),e.jsxs(z,{onClick:()=>c(!0),children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"})," Upload your first template"]})]})}),!t&&!n&&s.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[q.map(re=>{var te;const ae=Cx(re),J=re.scope==="brokerage";return e.jsx(be,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Le,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx($r,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>m(re),children:[e.jsx("p",{className:"truncate font-medium",children:re.name}),J&&e.jsxs(ze,{variant:"outline",className:"mt-1 gap-1 text-[10px]",children:[e.jsx(oi,{className:"h-3 w-3"})," Brokerage form"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(te=uit.find(ce=>ce.value===re.category))==null?void 0:te.label," · v",(ae==null?void 0:ae.version_number)??1,ae?` · ${ae.page_count} page${ae.page_count===1?"":"s"}`:""]})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsx(qd,{align:"end",children:J?e.jsxs(e.Fragment,{children:[e.jsx(ua,{onClick:()=>m(re),children:"View details"}),e.jsxs(ua,{disabled:l.isPending,onClick:()=>G(re),children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"})," Copy to my forms"]}),e.jsxs(ua,{disabled:(ae==null?void 0:ae.mapping_status)!=="mapped",onClick:()=>M(re),children:[e.jsx(Mm,{className:"mr-2 h-4 w-4"})," Fill & sign"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ua,{onClick:()=>m(re),children:"Open & map fields"}),e.jsxs(ua,{onClick:()=>S(re),children:[e.jsx(op,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ua,{disabled:(ae==null?void 0:ae.mapping_status)!=="mapped",onClick:()=>{E("sign"),v(re),b("")},children:[e.jsx(Mm,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(ua,{disabled:(ae==null?void 0:ae.mapping_status)!=="mapped",onClick:()=>M(re),children:[e.jsx(Mm,{className:"mr-2 h-4 w-4"})," Fill & sign myself"]}),e.jsxs(ua,{onClick:()=>u(re),children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"})," Upload new version"]}),e.jsxs(ua,{onClick:()=>a.mutate({id:re.id,patch:{is_archived:!0}}),children:[e.jsx(w0,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ua,{className:"text-destructive",onClick:()=>K(re),children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Delete"]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Otr,{status:ae==null?void 0:ae.mapping_status}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(z,{variant:"ghost",size:"sm",disabled:(ae==null?void 0:ae.mapping_status)!=="mapped",onClick:()=>M(re),children:[e.jsx(Mm,{className:"mr-1.5 h-4 w-4"})," Fill & sign"]}),e.jsxs(z,{variant:"ghost",size:"sm",disabled:(ae==null?void 0:ae.mapping_status)!=="mapped",onClick:()=>{E("sign"),v(re),b("")},children:[e.jsx(Mm,{className:"mr-1.5 h-4 w-4"})," Send"]}),e.jsxs(z,{variant:"ghost",size:"sm",disabled:(ae==null?void 0:ae.mapping_status)!=="mapped",onClick:()=>{E("generate"),v(re),b("")},children:[e.jsx(UU,{className:"mr-1.5 h-4 w-4"})," Use"]})]})]})]})},re.id)}),q.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No templates match that search."})]}),!t&&!n&&s.length>0&&e.jsx("div",{className:"border-t pt-6",children:e.jsx(Ttr,{templates:s})})]}),e.jsx(Wg,{open:!!V,onOpenChange:re=>!re&&m(null),children:e.jsxs(gg,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(Dy,{className:"space-y-1 text-left",children:[e.jsxs("button",{className:"flex items-center gap-1 text-xs text-muted-foreground sm:hidden",onClick:()=>m(null),children:[e.jsx(ka,{className:"h-3 w-3"})," Back"]}),e.jsx(Ry,{children:V==null?void 0:V.name}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",H.version_number," · ",H.file_name," · ",mit(H.file_size)," · uploaded ",Ys(new Date(H.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(V==null?void 0:V.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:V.description}),H?e.jsx(e.Fragment,{children:(V==null?void 0:V.scope)==="brokerage"?e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-4 text-sm text-muted-foreground",children:[e.jsxs("p",{className:"flex items-center gap-2 font-medium text-foreground",children:[e.jsx(oi,{className:"h-4 w-4"})," Managed by your brokerage"]}),e.jsx("p",{className:"mt-1",children:"Fields on this form are set up by your brokerage. You can fill it from any deal or send it for signature. Need your own version? Use “Copy to my forms”."}),e.jsxs(z,{variant:"outline",className:"mt-3 w-full",disabled:l.isPending,onClick:()=>V&&G(V),children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"})," Copy to my forms"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",className:"w-full",onClick:()=>V&&S(V),children:[e.jsx(op,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(Yrs,{version:H})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template has no uploaded version yet."})]})]})}),e.jsx(R6e,{open:o,onOpenChange:c}),e.jsx(R6e,{open:!!d,onOpenChange:re=>!re&&u(null),templateId:d==null?void 0:d.id,templateName:d==null?void 0:d.name}),e.jsx(Wg,{open:!!g&&!y,onOpenChange:re=>!re&&v(null),children:e.jsxs(gg,{side:"bottom",className:"space-y-4",children:[e.jsx(Dy,{className:"text-left",children:e.jsx(Ry,{children:"Choose a deal"})}),r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don’t have any deals yet."}):e.jsxs(ls,{value:y,onValueChange:b,children:[e.jsx(rs,{className:"max-w-md",children:e.jsx(cs,{placeholder:"Select a deal"})}),e.jsx(as,{children:r.map(re=>e.jsx(He,{value:re.id,children:re.deal_name},re.id))})]})]})}),g&&y&&C==="generate"&&e.jsx(Brs,{open:!0,onOpenChange:re=>{re||(v(null),b(""))},dealId:y,dealName:(Z=r.find(re=>re.id===y))==null?void 0:Z.deal_name,initialTemplateId:g.id}),g&&y&&C==="sign"&&e.jsx(qrs,{open:!0,onOpenChange:re=>{re||(v(null),b(""))},dealId:y,dealName:(oe=r.find(re=>re.id===y))==null?void 0:oe.deal_name,initialTemplateId:g.id}),w&&Cx(w)&&e.jsx(Zrs,{open:!0,onOpenChange:re=>!re&&S(null),version:Cx(w),templateName:w.name}),P&&Cx(P)&&e.jsx(Ftr,{open:!0,onOpenChange:re=>!re&&M(null),template:P,version:Cx(P)})]})}function Qrs({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var G;const i=Jer(),l=etr(),{data:o}=xK(),c=ha(),{data:d}=rt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:V,error:H}=await U.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(H)throw H;return V},enabled:!!c&&s}),[u,h]=_.useState(""),[m,p]=_.useState(""),[f,g]=_.useState("none"),[v,y]=_.useState("none"),[b,w]=_.useState("medium"),[S,C]=_.useState("todo"),[E,P]=_.useState(),[M,I]=_.useState(!1),[D,F]=_.useState(!1);_.useEffect(()=>{n?(h(n.title),p(n.description||""),g(n.deal_id||"none"),y(n.contact_id||"none"),w(n.priority),C(n.status),P(n.due_date?x0(n.due_date):void 0)):(h(""),p(""),g(r||"none"),y("none"),w("medium"),C("todo"),P(void 0))},[n,s,r]);const q=async()=>{if(!u.trim()){ne.error("Task title is required");return}try{const V={title:u.trim(),description:m.trim()||null,deal_id:f==="none"?null:f,contact_id:v==="none"?null:v,stage_id:a||null,priority:b,status:S,due_date:E?Ys(E,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...V}),ne.success("Task updated")):(await i.mutateAsync(V),ne.success("Task created")),t(!1)}catch{ne.error("Failed to save task")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[480px]",children:[e.jsx(Os,{children:e.jsx(Rs,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:u,onChange:V=>h(V.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:m,onChange:V=>p(V.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Priority"}),e.jsxs(ls,{value:b,onValueChange:V=>w(V),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"low",children:"🟢 Low"}),e.jsx(He,{value:"medium",children:"🟡 Medium"}),e.jsx(He,{value:"high",children:"🟠 High"}),e.jsx(He,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Status"}),e.jsxs(ls,{value:S,onValueChange:V=>C(V),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"todo",children:"To Do"}),e.jsx(He,{value:"in_progress",children:"In Progress"}),e.jsx(He,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Due Date"}),e.jsxs(hd,{children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:Ct("w-full justify-start text-left font-normal",!E&&"text-muted-foreground"),children:[e.jsx(ya,{className:"mr-2 h-4 w-4"}),E?Ys(E,"PPP"):"Pick a date"]})}),e.jsx(nd,{className:"w-auto p-0",align:"start",children:e.jsx(Oj,{mode:"single",selected:E,onSelect:P,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Link to Deal"}),e.jsxs(hd,{open:M,onOpenChange:I,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{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(oi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),f!=="none"?((G=o==null?void 0:o.find(V=>V.id===f))==null?void 0:G.deal_name)||"Select deal":"No Deal"]}),e.jsx(R_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search deals..."}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:"No deals found."}),e.jsxs(G_,{children:[e.jsxs(c1,{value:"no-deal",onSelect:()=>{g("none"),I(!1)},children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",f==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(V=>e.jsxs(c1,{value:V.deal_name,onSelect:()=>{g(V.id),I(!1)},children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",f===V.id?"opacity-100":"opacity-0")}),V.deal_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Link to Contact"}),e.jsxs(hd,{open:D,onOpenChange:F,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{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(Oo,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?(()=>{const V=d==null?void 0:d.find(H=>H.id===v);return V?`${V.first_name} ${V.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(R_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ij,{children:[e.jsx(Dj,{placeholder:"Search contacts..."}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:"No contacts found."}),e.jsxs(G_,{children:[e.jsxs(c1,{value:"no-contact",onSelect:()=>{y("none"),F(!1)},children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(V=>e.jsxs(c1,{value:`${V.first_name} ${V.last_name}`,onSelect:()=>{y(V.id),F(!1)},children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",v===V.id?"opacity-100":"opacity-0")}),V.first_name," ",V.last_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:q,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const Btr={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 $tr({tasks:s}){const t=xDe(),n=ttr(),r=zn(),[a,i]=_.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{ne.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ne.success("Task deleted")}catch{ne.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(Mr,{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(O4t,{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(oi,{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(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(yi,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx(O4t,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:p=>r(`/mission-control/pipeline?deal=${p}`)},m.id))]},u)),a&&e.jsx(Qrs,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function O4t({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&sC(x0(s.due_date))&&!b0(x0(s.due_date)),o=!i&&s.due_date&&b0(x0(s.due_date)),c=Btr[s.priority];return e.jsxs("div",{className:Ct("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(Mr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Gf,{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:Ct("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(Oo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(ze,{variant:"outline",className:Ct("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Ct("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(Zr,{className:"h-3 w-3"}),Ys(x0(s.due_date),"MMM d")]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>r(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(Cp,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>n(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const Utr=[{status:"todo",label:"To Do",icon:Gf,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:dm,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Mr,color:"border-t-emerald-500"}],qtr={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Vtr({tasks:s}){const t=xDe(),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{ne.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Utr.map(i=>e.jsxs("div",{className:Ct("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(Htr,{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 Htr({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&sC(x0(s.due_date))&&!b0(x0(s.due_date)),a=!n&&s.due_date&&b0(x0(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Ct("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:qtr[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ct("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(oi,{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(Oo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Ct("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(Zr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Ys(x0(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 z4t={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Gtr({tasks:s}){const[t,n]=_.useState(new Date),r=xDe(),a=om(t),i=b_(t),l=v1(a),o=TPe(i),c=V3s({start:l,end:o}),d=_.useMemo(()=>{const m=new Map;return s.forEach(p=>{if(!p.due_date)return;const f=p.due_date,g=m.get(f)||[];g.push(p),m.set(f,g)}),m},[s]),u=_.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const p=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:p})}catch{ne.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(z,{variant:"ghost",size:"icon",onClick:()=>n(_F(t,1)),children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Ys(t,"MMMM yyyy")}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>n(A0(t,1)),children:e.jsx(yi,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(m=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:m},m))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(m=>{const p=Ys(m,"yyyy-MM-dd"),f=d.get(p)||[],g=eae(m,t),v=b0(m);return e.jsxs("div",{className:Ct("border-r border-b min-h-[100px] p-1",!g&&"bg-muted/30",v&&"bg-primary/5"),children:[e.jsx("div",{className:Ct("text-xs font-medium mb-1 text-right px-1",!g&&"text-muted-foreground/40",v&&"text-primary font-bold"),children:Ys(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[f.slice(0,3).map(y=>e.jsxs("button",{onClick:()=>h(y),className:Ct("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",y.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[y.status==="done"?e.jsx(Mr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Gf,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[z4t[y.priority]," ",y.title]})]},y.id)),f.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",f.length-3," more"]})]})]},p)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:Ct("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",m.status==="done"&&"opacity-50 line-through"),children:[m.status==="done"?e.jsx(Mr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Gf,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[z4t[m.priority]," ",m.title]}),m.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",m.deal.deal_name]})]},m.id))})]})]})}const Wtr={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Ktr({open:s,onOpenChange:t,stages:n}){var y;const[r,a]=_.useState(((y=n[0])==null?void 0:y.id)||""),{data:i,isLoading:l}=ntr(r||void 0),o=rtr(),c=atr(),[d,u]=_.useState(""),[h,m]=_.useState("medium"),[p,f]=_.useState(""),g=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:p?parseInt(p):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),f(""),ne.success("Template added")}catch{ne.error("Failed to add template")}},v=async b=>{try{await c.mutateAsync(b),ne.success("Template deleted")}catch{ne.error("Failed to delete template")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[560px]",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(FQ,{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(ee,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(b=>!b.is_won_stage&&!b.is_lost_stage).map(b=>e.jsx("button",{onClick:()=>a(b.id),className:Ct("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===b.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:b.name},b.id))})]}),e.jsx(Ki,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,w)=>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:Wtr[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>v(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-destructive"})})]},b.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(ee,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Task title...",value:d,onChange:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&g()}),e.jsxs(ls,{value:h,onValueChange:b=>m(b),children:[e.jsx(rs,{className:"w-[100px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"low",children:"🟢 Low"}),e.jsx(He,{value:"medium",children:"🟡 Med"}),e.jsx(He,{value:"high",children:"🟠 High"}),e.jsx(He,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(pe,{type:"number",placeholder:"e.g., 7",value:p,onChange:b=>f(b.target.value)})]}),e.jsxs(z,{onClick:g,disabled:!d.trim()||o.isPending,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function Ytr(){const{data:s,isLoading:t}=Grs(),{data:n}=cie(),[r,a]=_.useState("list"),[i,l]=_.useState(""),[o,c]=_.useState("active"),[d,u]=_.useState("all"),[h,m]=_.useState("all"),[p,f]=_.useState(!1),[g,v]=_.useState(!1),y=_.useMemo(()=>{if(!s)return[];const S=new Map;return s.forEach(C=>{C.deal&&S.set(C.deal.id,C.deal.deal_name)}),Array.from(S,([C,E])=>({id:C,name:E}))},[s]),b=_.useMemo(()=>s?s.filter(S=>{var D,F,q,G;const C=i.toLowerCase(),E=!C||S.title.toLowerCase().includes(C)||((F=(D=S.deal)==null?void 0:D.deal_name)==null?void 0:F.toLowerCase().includes(C))||`${((q=S.contact)==null?void 0:q.first_name)||""} ${((G=S.contact)==null?void 0:G.last_name)||""}`.toLowerCase().includes(C),P=o==="all"||o==="active"&&S.status!=="done"||o==="todo"&&S.status==="todo"||o==="in_progress"&&S.status==="in_progress"||o==="done"&&S.status==="done"||o==="overdue"&&S.status!=="done"&&S.due_date&&sC(x0(S.due_date))&&!b0(x0(S.due_date)),M=d==="all"||S.priority===d,I=h==="all"||h==="no_deal"&&!S.deal_id||S.deal_id===h;return E&&P&&M&&I}):[],[s,i,o,d,h]),w=_.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const S=s.filter(C=>C.status!=="done");return{total:S.length,overdue:S.filter(C=>C.due_date&&sC(x0(C.due_date))&&!b0(x0(C.due_date))).length,dueToday:S.filter(C=>C.due_date&&b0(x0(C.due_date))).length,dueThisWeek:S.filter(C=>C.due_date&&$Es(x0(C.due_date))).length,completed:s.filter(C=>C.status==="done").length}},[s]);return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(F_,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(z,{size:"sm",onClick:()=>f(!0),children:[e.jsx(sn,{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(My,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(nl,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:w.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(Zr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(gc,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(Mr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search tasks...",value:i,onChange:S=>l(S.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"w-[130px]",children:e.jsx(cs,{placeholder:"Priority"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Priorities"}),e.jsx(He,{value:"urgent",children:"🔴 Urgent"}),e.jsx(He,{value:"high",children:"🟠 High"}),e.jsx(He,{value:"medium",children:"🟡 Medium"}),e.jsx(He,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(ls,{value:h,onValueChange:m,children:[e.jsx(rs,{className:"w-[160px]",children:e.jsx(cs,{placeholder:"Deal"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Deals"}),e.jsx(He,{value:"no_deal",children:"No Deal"}),y.map(S=>e.jsx(He,{value:S.id,children:S.name},S.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(My,{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(gj,{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(gc,{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($tr,{tasks:b}),r==="kanban"&&e.jsx(Vtr,{tasks:b}),r==="calendar"&&e.jsx(Gtr,{tasks:b})]}),e.jsx(Qrs,{open:p,onOpenChange:f}),e.jsx(Ktr,{open:g,onOpenChange:v,stages:n||[]})]})})}function Ztr(s){const t=_it(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function Xtr({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 qde({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:Ct("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 Qtr(){const s=zn(),{data:t,isLoading:n}=Ler(),r=xDe(),[a,i]=_.useState(""),[l,o]=_.useState(!1),[c,d]=_.useState("all"),u=_.useMemo(()=>{let b=t||[];c==="contract"&&(b=b.filter(S=>!!S.contract_date));const w=a.trim().toLowerCase();return w&&(b=b.filter(S=>{var C,E,P,M;return((C=S.deal_name)==null?void 0:C.toLowerCase().includes(w))||((E=S.property_address)==null?void 0:E.toLowerCase().includes(w))||`${((P=S.contact)==null?void 0:P.first_name)??""} ${((M=S.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(w)})),b},[t,a,c]),h=_.useMemo(()=>{const b=[];return(u||[]).forEach(w=>{uQ.forEach(S=>{const C=w[S.key],E=K5(C);C&&E!==null&&E<=30&&b.push({id:`${w.id}-${S.key}`,kind:"date",label:S.label,dealId:w.id,dealName:w.deal_name,date:C,days:E})}),w.tasks.filter(S=>S.status!=="done"&&S.due_date).forEach(S=>{const C=K5(S.due_date);C!==null&&C<=30&&b.push({id:S.id,kind:"task",label:S.title,dealId:w.id,dealName:w.deal_name,date:S.due_date,days:C,priority:S.priority})})}),b.sort((w,S)=>w.days-S.days)},[u]),m=_.useMemo(()=>({overdue:h.filter(b=>b.days<0),today:h.filter(b=>b.days===0),week:h.filter(b=>b.days>0&&b.days<=7),later:h.filter(b=>b.days>7)}),[h]),p=_.useMemo(()=>{const b=t||[],w=b.filter(E=>{const P=K5(E.target_close_date);return P!==null&&P>=0&&P<=7}).length,S=b.reduce((E,P)=>E+P.tasks.filter(M=>{const I=K5(M.due_date);return M.status!=="done"&&I!==null&&I<0}).length,0),C=b.reduce((E,P)=>E+(Number(P.expected_price)||0),0);return{active:b.length,closingSoon:w,overdueTasks:S,volume:C}},[t]),f=b=>b.tasks.length===0?0:b.tasks.filter(w=>w.status==="done").length/b.tasks.length*100,g=b=>s(`/mission-control/pipeline?deal=${b}`),v=async b=>{try{await r.mutateAsync({id:b,status:"done"}),ne.success("Task completed")}catch{ne.error("Could not update task")}},y=({title:b,items:w,tone:S})=>{if(w.length===0)return null;const C=S==="danger"?"bg-destructive":S==="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:Ct("h-1.5 w-1.5 rounded-full",C)}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:b}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",w.length,")"]})]}),w.slice(0,12).map(E=>e.jsxs("div",{className:Ct("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",S==="danger"&&"border-destructive/30 bg-destructive/5"),children:[E.kind==="task"?e.jsx(za,{className:"shrink-0",onCheckedChange:()=>v(E.id),"aria-label":`Complete ${E.label}`}):e.jsx(Ud,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>g(E.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:E.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[E.dealName," · ",Ztr(E.date)]})]}),e.jsx("span",{className:Ct("text-[11px] font-semibold shrink-0 tabular-nums",E.days<0?"text-destructive":E.days<=3?"text-amber-600":"text-muted-foreground"),children:E.days<0?`${Math.abs(E.days)}d late`:E.days===0?"Today":`${E.days}d`})]},E.id))]})};return e.jsxs($s,{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(z,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(ip,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(qde,{icon:Wf,label:"Active transactions",value:p.active}),e.jsx(qde,{icon:vu,label:"Closing within 7 days",value:p.closingSoon,tone:"warn"}),e.jsx(qde,{icon:nl,label:"Overdue tasks",value:p.overdueTasks,tone:p.overdueTasks>0?"danger":"good"}),e.jsx(qde,{icon:kl,label:"Pipeline volume",value:p.volume>=1e6?`$${(p.volume/1e6).toFixed(1)}M`:`$${Math.round(p.volume/1e3)}K`,tone:"good"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search transactions, addresses, or clients...",value:a,onChange:b=>i(b.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx(z,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx(z,{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(bt,{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(Ud,{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(Mr,{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(y,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(y,{title:"Today",items:m.today,tone:"warn"}),e.jsx(y,{title:"This week",items:m.week,tone:"warn"}),e.jsx(y,{title:"Coming up",items:m.later,tone:"default"})]})]})}),e.jsx("div",{className:"lg:col-span-3 space-y-3",children:u.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed p-12 text-center",children:[e.jsx(sa,{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(z,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(b=>{const w=f(b),S=K5(b.target_close_date),C=b.tasks.filter(M=>M.status!=="done"),E=C.filter(M=>{const I=K5(M.due_date);return I!==null&&I<0}),P=C.filter(M=>M.due_date).sort((M,I)=>(K5(M.due_date)??0)-(K5(I.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>g(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(Xtr,{value:w}),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:b.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[b.property_address||"Address TBD",b.contact&&` · ${b.contact.first_name} ${b.contact.last_name}`]})]}),e.jsx(yi,{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:[b.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${b.stage.color}1f`,color:b.stage.color},children:b.stage.name}),e.jsx(ze,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),S!==null&&e.jsx(ze,{variant:"secondary",className:Ct("text-[10px]",S<0&&"bg-destructive/10 text-destructive",S>=0&&S<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:S<0?`Closing ${Math.abs(S)}d overdue`:`Closes in ${S}d`}),E.length>0&&e.jsxs(ze,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[E.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(Di,{value:w,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:[b.tasks.filter(M=>M.status==="done").length," of"," ",b.tasks.length," steps complete"]}),P&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",P.title]})]})]}),b.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."})]})]})},b.id)})})]})]}),e.jsx(Hrs,{open:l,onOpenChange:o})]})}function Jrs(){const s=ha();return rt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function Jtr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function esr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const tsr=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),UBe=[{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"}],ssr={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function eas(){const{data:s=[],isLoading:t}=Jrs(),n=Jtr(),r=esr(),[a,i]=_.useState("all"),[l,o]=_.useState({}),c=_.useMemo(()=>a==="all"?s:s.filter(p=>p.status===a),[s,a]),d=_.useMemo(()=>({total:s.length,new:s.filter(p=>p.status==="new").length,converted:s.filter(p=>p.status==="converted").length}),[s]),u=(p,f)=>{n.mutate({id:p.id,status:f}),ne.success("Status updated")},h=p=>{const f=l[p.id];n.mutate({id:p.id,agent_notes:f}),o(g=>{const{[p.id]:v,...y}=g;return y}),ne.success("Notes saved")},m=async p=>{await Qi(`Delete referral for ${p.friend_name}?`)&&r.mutate(p.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(dl,{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(Ko,{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"},...UBe.map(p=>({v:p.value,l:p.label}))].map(p=>e.jsx("button",{onClick:()=>i(p.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===p.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:p.l},p.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Ko,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(p=>{var y,b;const f=UBe.find(w=>w.value===p.status),g=(y=p.client_portals)==null?void 0:y.slug,v=p.referrer_name||((b=p.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:p.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(ya,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:v})," ·"," ",tsr(p.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"outline",className:f==null?void 0:f.className,children:(f==null?void 0:f.label)||p.status}),e.jsxs(ls,{value:p.status,onValueChange:w=>u(p,w),children:[e.jsx(rs,{className:"h-8 w-[130px] text-xs",children:e.jsx(cs,{})}),e.jsx(as,{children:UBe.map(w=>e.jsx(He,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]})]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.friend_interest&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:ssr[p.friend_interest]||p.friend_interest}),p.friend_email&&e.jsxs("a",{href:`mailto:${p.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(on,{className:"h-3 w-3"}),p.friend_email]}),p.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(va,{className:"h-3 w-3"}),p.friend_phone]}),e.jsxs("a",{href:`sms:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Bu,{className:"h-3 w-3"}),"Text"]})]})]}),p.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',p.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[p.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ps,{value:l[p.id],onChange:w=>o(S=>({...S,[p.id]:w.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{size:"sm",onClick:()=>h(p),children:"Save"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>o(w=>{const{[p.id]:S,...C}=w;return C}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(w=>({...w,[p.id]:p.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:p.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[g&&e.jsxs("a",{href:`/portal/${g}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(mr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>m(p),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})]},p.id)})})]})}function tas({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=_W.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(be,{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(Hl,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Ia,{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(va,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(on,{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(Wo,{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(ya,{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(Ha,{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(z,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(xa,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(Yf,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(z,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(Cp,{className:"w-3.5 h-3.5"})}),n&&e.jsx(z,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Cn,{className:"w-3.5 h-3.5"})})]})]})}function sas({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=EFs(),[c,d]=_.useState({}),[u,h]=_.useState(!1),m=_.useRef(null),p=async v=>{if(!v.type.startsWith("image/")){ne.error("Please select an image");return}if(v.size>5*1024*1024){ne.error("Image must be under 5MB");return}h(!0);try{const y=v.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${y}`,{error:w}=await U.storage.from("vendor-logos").upload(b,v,{upsert:!0,contentType:v.type});if(w)throw w;const{data:S}=U.storage.from("vendor-logos").getPublicUrl(b);d(C=>({...C,logo_url:S.publicUrl})),ne.success("Logo uploaded")}catch(y){ne.error(y.message||"Upload failed")}finally{h(!1)}};_.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 f=(v,y)=>d(b=>({...b,[v]:y})),g=async()=>{var v;if(!((v=c.name)!=null&&v.trim())){ne.error("Name is required");return}try{await o.mutateAsync(c),ne.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(y){ne.error(y.message||"Failed to save vendor")}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{children:"Contact Name *"}),e.jsx(pe,{value:c.name||"",onChange:v=>f("name",v.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Company"}),e.jsx(pe,{value:c.company||"",onChange:v=>f("company",v.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ls,{value:c.category,onValueChange:v=>f("category",v),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:_W.map(v=>e.jsx(He,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:c.phone||"",onChange:v=>f("phone",v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:c.email||"",onChange:v=>f("email",v.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:c.website||"",onChange:v=>f("website",v.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var b;const y=(b=v.target.files)==null?void 0:b[0];y&&p(y),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:()=>f("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(er,{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(Ra,{className:"h-5 w-5"})}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=m.current)==null?void 0:v.click()},disabled:u,children:[u?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Address"}),e.jsx(pe,{value:c.address||"",onChange:v=>f("address",v.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{rows:3,value:c.description||"",onChange:v=>f("description",v.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Primary Action"}),e.jsxs(ls,{value:c.action_type,onValueChange:v=>f("action_type",v),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:SFs.map(v=>e.jsx(He,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Booking URL (Calendly etc.)"}),e.jsx(pe,{value:c.booking_url||"",onChange:v=>f("booking_url",v.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Compliance Disclosure (optional)"}),e.jsx(Ps,{rows:2,value:c.disclosure_text||"",onChange:v=>f("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(ee,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(mn,{checked:!!c.is_active,onCheckedChange:v=>f("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(ee,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(mn,{checked:!!c.is_featured,onCheckedChange:v=>f("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(mn,{checked:!!c.is_required,onCheckedChange:v=>f("is_required",v)})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:g,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function nas({embedded:s=!1}={}){const t=ha(),{brokerageId:n}=hs(),{data:r,isLoading:a}=AFs(),{data:i={}}=w9t("agent",t),l=b9t(),o=TFs(),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,g]=_.useState("all"),v=(r==null?void 0:r.vendors)||[],y=(r==null?void 0:r.selections)||[],b=_.useMemo(()=>{const D=new Map;return y.forEach(F=>D.set(F.vendor_id,F.is_visible)),D},[y]),w=_.useMemo(()=>v.filter(D=>!(f!=="all"&&D.category!==f||m&&!`${D.name} ${D.company||""}`.toLowerCase().includes(m.toLowerCase()))),[v,m,f]),S=w.filter(D=>D.owner_type==="agent"),C=w.filter(D=>D.owner_type==="brokerage"),E=async D=>{if(await Qi("Delete this vendor?"))try{await l.mutateAsync(D),ne.success("Vendor deleted")}catch(F){ne.error(F.message)}},P=async(D,F)=>{try{await o.mutateAsync({vendorId:D,isVisible:F})}catch(q){ne.error(q.message)}},M=D=>D.is_required?!0:b.get(D.id)??D.owner_type==="agent",I=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(Px,{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(z,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{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(Rr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:D=>p(D.target.value)})]}),e.jsxs("select",{value:f,onChange:D=>g(D.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),_W.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(Qr,{defaultValue:n?"all":"personal",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"all",children:["All (",w.length,")"]}),n&&e.jsxs(Wt,{value:"brokerage",children:["From Brokerage (",C.length,")"]}),e.jsxs(Wt,{value:"personal",children:["My Personal (",S.length,")"]})]}),e.jsx(Kt,{value:"all",className:"mt-4",children:e.jsx(qBe,{vendors:w,isVisibleInPortals:M,onToggle:P,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})}),n&&e.jsx(Kt,{value:"brokerage",className:"mt-4",children:C.length===0?e.jsx(B4t,{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(qBe,{vendors:C,isVisibleInPortals:M,onToggle:P,userId:t,clicks:i})}),e.jsx(Kt,{value:"personal",className:"mt-4",children:S.length===0?e.jsx(B4t,{icon:e.jsx(Px,{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(z,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(qBe,{vendors:S,isVisibleInPortals:M,onToggle:P,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})})]}),e.jsx(sas,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?I:e.jsx($s,{children:I})}function qBe({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(tas,{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 B4t({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 nsr(s){return rt({queryKey:["brokerage-form-folders",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_form_folders").select("*").eq("brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function rsr(s){const t=$t(),n=()=>{t.invalidateQueries({queryKey:["brokerage-form-folders",s]}),t.invalidateQueries({queryKey:["form-templates"]})},r=mt({mutationFn:async o=>{var h;const{data:c}=await U.auth.getUser(),{data:d,error:u}=await U.from("brokerage_form_folders").insert({brokerage_id:s,name:o,created_by:((h=c.user)==null?void 0:h.id)??null}).select().single();if(u)throw u;return d},onSuccess:n}),a=mt({mutationFn:async({id:o,name:c})=>{const{error:d}=await U.from("brokerage_form_folders").update({name:c}).eq("id",o);if(d)throw d},onSuccess:n}),i=mt({mutationFn:async o=>{const{error:c}=await U.from("brokerage_form_folders").delete().eq("id",o);if(c)throw c},onSuccess:n}),l=mt({mutationFn:async({templateId:o,folderId:c})=>{const{error:d}=await U.from("form_templates").update({folder_id:c}).eq("id",o);if(d)throw d},onSuccess:n});return{createFolder:r,renameFolder:a,deleteFolder:i,moveTemplate:l}}function asr({status:s}){return s==="mapped"?e.jsx(ze,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(ze,{variant:"outline",children:"Needs field placement"}):e.jsx(ze,{variant:"secondary",children:"Needs mapping"})}function isr(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=hs(),{data:a=[],isLoading:i}=QJn(s),l=Frs(),o=Ors(),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(null),[f,g]=_.useState(null),[v,y]=_.useState(""),[b,w]=_.useState("all"),{data:S=[]}=nsr(s),{createFolder:C,deleteFolder:E,moveTemplate:P}=rsr(s),M=async()=>{var H;const V=(H=window.prompt("Folder name (for example: Onboarding, Listing paperwork)"))==null?void 0:H.trim();if(V)try{const K=await C.mutateAsync(V);w(K.id),ne.success("Folder created")}catch(K){ne.error((K==null?void 0:K.message)||"Could not create the folder")}};if(r)return e.jsx($s,{children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t&&!n)return e.jsx($s,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const I=a.filter(V=>V.name.toLowerCase().includes(v.trim().toLowerCase())).filter(V=>b==="all"?!0:b==="unfiled"?!V.folder_id:V.folder_id===b),D=m?a.find(V=>V.id===m.id)||m:null,F=Cx(D),q=async(V,H)=>{const K=Cx(V);if(H&&(K==null?void 0:K.mapping_status)!=="mapped"){ne.error("Map and place the fields before publishing this form to your agents.");return}try{await l.mutateAsync({id:V.id,patch:{is_published:H}}),ne.success(H?"Published to your agents":"Unpublished — agents can no longer use it")}catch(Z){ne.error((Z==null?void 0:Z.message)||"Could not update the form")}},G=async V=>{if(await Qi(`Delete "${V.name}"? Agents will lose access. Forms already generated stay on their deals.`))try{await o.mutateAsync(V),(m==null?void 0:m.id)===V.id&&p(null),ne.success("Form deleted")}catch(H){ne.error((H==null?void 0:H.message)||"Could not delete the form")}};return e.jsxs($s,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Brokerage Forms"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Build the official set of forms your agents can pick from. Map the fields once, publish, and every agent can fill them straight from a deal."})]}),e.jsxs(z,{onClick:()=>d(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Upload form"]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search forms…",value:v,onChange:V=>y(V.target.value)})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:M,children:[e.jsx($Q,{className:"mr-2 h-4 w-4"})," New folder"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{size:"sm",variant:b==="all"?"default":"outline",onClick:()=>w("all"),children:"All forms"}),S.map(V=>e.jsxs("div",{className:"flex items-center",children:[e.jsxs(z,{size:"sm",variant:b===V.id?"default":"outline",className:"rounded-r-none",onClick:()=>w(V.id),children:[e.jsx(VU,{className:"mr-2 h-4 w-4"}),V.name]}),e.jsx(z,{size:"sm",variant:b===V.id?"default":"outline",className:"rounded-l-none border-l-0 px-2","aria-label":`Delete ${V.name} folder`,onClick:async()=>{await Qi(`Delete the "${V.name}" folder? The forms inside stay in your library.`)&&(await E.mutateAsync(V.id),b===V.id&&w("all"))},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]},V.id)),S.length>0&&e.jsx(z,{size:"sm",variant:b==="unfiled"?"default":"outline",onClick:()=>w("unfiled"),children:"Unfiled"})]}),i&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!i&&a.length===0&&e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(oi,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No brokerage forms yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload the blank PDFs your office uses. Once you map their fields and publish, your agents can pick them from their Forms library and Deal → Forms tab."})]}),e.jsxs(z,{onClick:()=>d(!0),children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"})," Upload your first form"]})]})}),!i&&a.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[I.map(V=>{var K;const H=Cx(V);return e.jsx(be,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Le,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx($r,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>p(V),children:[e.jsx("p",{className:"truncate font-medium",children:V.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(K=uit.find(Z=>Z.value===V.category))==null?void 0:K.label," · v",(H==null?void 0:H.version_number)??1,H?` · ${H.page_count} page${H.page_count===1?"":"s"}`:""]})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[e.jsx(ua,{onClick:()=>p(V),children:"Open & map fields"}),e.jsxs(ua,{onClick:()=>g(V),children:[e.jsx(op,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ua,{onClick:()=>h(V),children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"})," Upload new version"]}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Iy,{}),e.jsx(qP,{className:"text-xs font-normal text-muted-foreground",children:"Move to folder"}),S.map(Z=>e.jsxs(ua,{disabled:V.folder_id===Z.id,onClick:()=>P.mutate({templateId:V.id,folderId:Z.id}),children:[e.jsx(VU,{className:"mr-2 h-4 w-4"})," ",Z.name]},Z.id)),V.folder_id&&e.jsx(ua,{onClick:()=>P.mutate({templateId:V.id,folderId:null}),children:"Remove from folder"}),e.jsx(Iy,{})]}),e.jsxs(ua,{onClick:()=>l.mutate({id:V.id,patch:{is_archived:!0,is_published:!1}}),children:[e.jsx(w0,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ua,{className:"text-destructive",onClick:()=>G(V),children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(asr,{status:H==null?void 0:H.mapping_status}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[V.is_published?"Published":"Draft",e.jsx(mn,{checked:!!V.is_published,onCheckedChange:Z=>q(V,Z)})]})]})]})},V.id)}),I.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No forms match that search."})]})]}),e.jsx(Wg,{open:!!D,onOpenChange:V=>!V&&p(null),children:e.jsxs(gg,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(Dy,{className:"space-y-1 text-left",children:[e.jsx(Ry,{children:D==null?void 0:D.name}),F&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",F.version_number," · ",F.file_name," ·"," ",mit(F.file_size)," · uploaded"," ",Ys(new Date(F.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(D==null?void 0:D.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description}),F?e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",className:"w-full",onClick:()=>D&&g(D),children:[e.jsx(op,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(Yrs,{version:F})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no uploaded version yet."})]})]})}),e.jsx(R6e,{open:c,onOpenChange:d,brokerageId:s}),e.jsx(R6e,{open:!!u,onOpenChange:V=>!V&&h(null),templateId:u==null?void 0:u.id,templateName:u==null?void 0:u.name,brokerageId:s}),f&&Cx(f)&&e.jsx(Zrs,{open:!0,onOpenChange:V=>!V&&g(null),version:Cx(f),templateName:f.name})]})}function osr(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=hs(),{data:a=[],isLoading:i}=CFs(s),{data:l={}}=w9t("brokerage",s),o=b9t(),[c,d]=_.useState(null),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,g]=_.useState("all");if(r)return e.jsx($s,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx($s,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const v=a.filter(b=>!(f!=="all"&&b.category!==f||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),y=async b=>{if(await Qi("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),ne.success("Vendor deleted")}catch(w){ne.error(w.message)}};return e.jsx($s,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(oi,{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(z,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{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(Rr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:b=>p(b.target.value)})]}),e.jsxs("select",{value:f,onChange:b=>g(b.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),_W.map(b=>e.jsx("option",{value:b.value,children:b.label},b.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(oi,{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(z,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{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(b=>e.jsx(tas,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>y(b.id),clickCount:l[b.id]},b.id))}),e.jsx(sas,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}function ras({portalId:s,portalSlug:t,clientName:n,agentName:r}){const{data:a,isLoading:i}=k9t(s),l=S9t(),o=LFs(),[c,d]=_.useState(""),u=_.useRef(null),h=(a||[]).filter(p=>p.sender_type==="client"&&!p.read_at).length;_.useEffect(()=>{h>0&&o.mutate(s)},[h,s]),_.useEffect(()=>{var p;(p=u.current)==null||p.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const m=async()=>{const p=c.trim();if(p)try{await l.mutateAsync({portalId:s,senderType:"agent",senderName:r||null,body:p,portalUrl:t?`https://clients.relevelup.com/${t}`:void 0}),d(""),ne.success("Message sent — your client was emailed")}catch(f){ne.error((f==null?void 0:f.message)||"Could not send message")}};return e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-semibold",children:["Conversation with ",n||"your client"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Both sides get an email for every message"})]}),e.jsxs("div",{className:"space-y-3 max-h-[420px] overflow-y-auto pr-1",children:[i&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(bt,{className:"w-4 h-4 animate-spin text-muted-foreground"})}),!i&&(!a||a.length===0)&&e.jsxs("div",{className:"text-center py-10 border-2 border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"No messages yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Start the conversation — your client can reply right inside their portal."})]}),a==null?void 0:a.map(p=>{const f=p.sender_type==="agent";return e.jsx("div",{className:`flex ${f?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-lg px-3 py-2 border ${f?"bg-primary/10 border-primary/20":"bg-muted border-border"}`,children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground mb-1",children:[f?r||"You":p.sender_name||n||"Client"," ·"," ",Ys(new Date(p.created_at),"MMM d, h:mm a")]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:p.body})]})},p.id)}),e.jsx("div",{ref:u})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(Ps,{value:c,onChange:p=>d(p.target.value),rows:3,placeholder:`Reply to ${n||"your client"}...`}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:m,disabled:l.isPending||!c.trim(),size:"sm",children:[l.isPending?e.jsx(bt,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx(Fr,{className:"w-4 h-4 mr-1.5"}),"Send & notify"]})})]})]})})}function lsr({selectedPortalId:s,onSelectPortal:t}){const{data:n,isLoading:r}=C9t(),[a,i]=_.useState(""),[l,o]=_.useState(!1),[c,d]=_.useState(s??null);_.useEffect(()=>{s&&d(s)},[s]);const u=_.useMemo(()=>{const f=a.trim().toLowerCase();return(n||[]).filter(g=>l&&g.unreadCount===0?!1:f?(g.clientName||"").toLowerCase().includes(f)||(g.clientEmail||"").toLowerCase().includes(f):!0)},[n,a,l]),h=_.useRef(!1);_.useEffect(()=>{if(h.current||c||u.length===0)return;h.current=!0;const f=u.find(g=>g.messageCount>0)||u[0];d(f.portalId)},[u,c]);const m=f=>{h.current=!0,d(f),t==null||t(f)},p=(n||[]).find(f=>f.portalId===c)||null;return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(bt,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):!n||n.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"p-10 text-center",children:[e.jsx(qi,{className:"w-6 h-6 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"font-medium",children:"No client portals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create a portal from a deal and your conversations will appear here."})]})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-[320px_1fr]",children:[e.jsx("div",{className:`${p?"hidden md:block":"block"}`,children:e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 space-y-2 border-b",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"w-4 h-4 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{value:a,onChange:f=>i(f.target.value),placeholder:"Search clients",className:"pl-8"})]}),e.jsx(z,{variant:l?"default":"outline",size:"sm",onClick:()=>o(f=>!f),children:"Unread only"})]}),e.jsxs("div",{className:"max-h-[560px] overflow-y-auto divide-y",children:[u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"No conversations match."}),u.map(f=>{const g=f.portalId===c;return e.jsxs("button",{onClick:()=>m(f.portalId),className:`w-full text-left p-3 transition-colors hover:bg-muted/60 ${g?"bg-muted":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:f.clientName||"Unnamed client"}),f.unreadCount>0&&e.jsx(ze,{className:"shrink-0",children:f.unreadCount})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:f.lastMessage?`${f.lastMessage.sender_type==="agent"?"You: ":""}${f.lastMessage.body}`:"No messages yet"}),f.lastMessage&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:Md(new Date(f.lastMessage.created_at),{addSuffix:!0})})]},f.portalId)})]})]})}),e.jsx("div",{className:`${p?"block":"hidden md:block"}`,children:p?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"md:hidden",onClick:()=>m(null),children:[e.jsx(ka,{className:"w-4 h-4 mr-1.5"}),"All conversations"]}),e.jsx(ras,{portalId:p.portalId,portalSlug:p.slug,clientName:p.clientName})]}):e.jsx(be,{children:e.jsx(Le,{className:"p-10 text-center text-sm text-muted-foreground",children:"Pick a client to see the conversation."})})})]})}const csr=[{value:"overview",label:"Portals",icon:op},{value:"messages",label:"Messages",icon:qi},{value:"vendors",label:"Vendors",icon:jv},{value:"referrals",label:"Referrals",icon:Ko},{value:"branding",label:"Branding",icon:yc},{value:"questions",label:"Onboarding",icon:k0}];function dsr(){const[s,t]=Gl(),n=s.get("tab")||"overview",[r,a]=_.useState(n),[i,l]=_.useState(!1),[o,c]=_.useState(!1),d=s.get("portal"),{data:u}=C9t(),h=(u||[]).reduce((m,p)=>m+p.unreadCount,0);return _.useEffect(()=>{t(m=>{const p=new URLSearchParams(m);return p.set("tab",r),r!=="messages"&&p.delete("portal"),p},{replace:!0})},[r,t]),e.jsxs($s,{children:[e.jsx(dl,{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(j7,{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(z,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(or,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(Qr,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(Jr,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:csr.map(m=>e.jsxs(Wt,{value:m.value,className:"gap-2",children:[e.jsx(m.icon,{className:"w-4 h-4"}),m.label,m.value==="messages"&&h>0&&e.jsx(ze,{className:"ml-1 h-5 px-1.5",children:h})]},m.value))}),e.jsx(Kt,{value:"overview",className:"mt-6",children:e.jsx(Krs,{})}),e.jsx(Kt,{value:"messages",className:"mt-6",children:e.jsx(lsr,{selectedPortalId:d,onSelectPortal:m=>t(p=>{const f=new URLSearchParams(p);return f.set("tab","messages"),m?f.set("portal",m):f.delete("portal"),f},{replace:!0})})}),e.jsx(Kt,{value:"vendors",className:"mt-6",children:e.jsx(usr,{})}),e.jsx(Kt,{value:"referrals",className:"mt-6",children:e.jsx(hsr,{})}),e.jsx(Kt,{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(yc,{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(z,{onClick:()=>l(!0),children:[e.jsx(Gc,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(Kt,{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(k0,{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(z,{onClick:()=>c(!0),children:[e.jsx(Gc,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(Wrs,{open:i,onOpenChange:l}),e.jsx(Vrs,{open:o,onOpenChange:c})]})}function usr(){return e.jsx(nas,{embedded:!0})}function hsr(){return e.jsx(eas,{})}const o$=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function msr(s){return rt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 U.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 U.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 psr(){const{portalId:s}=Mi(),t=zn(),n=ha(),{data:r,isLoading:a}=msr(s),{data:i=[]}=KOn(s),{data:l=[]}=Jrs(),o=QW(),c=MZt(),d=PZt(),u=LZt(),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[g,v]=_.useState(!1),[y,b]=_.useState(!1),w=(r==null?void 0:r.portal)??null,S=(r==null?void 0:r.deal)??null,C=_.useMemo(()=>w?l.filter(K=>K.portal_id===w.id):[],[l,w==null?void 0:w.id]);if(a)return e.jsx($s,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!w)return e.jsx($s,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(z,{asChild:!0,variant:"outline",children:e.jsxs(or,{to:"/mission-control/client-portals",children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const E=SS(w.slug),P=(S==null?void 0:S.deal_name)||"Untitled deal",M=S==null?void 0:S.contact,I=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",D=!!w.archived_at,F=()=>{navigator.clipboard.writeText(E),ne.success("Portal link copied!")},q=async K=>{try{await o.mutateAsync({id:w.id,is_enabled:K}),ne.success(K?"Portal enabled":"Portal disabled")}catch{ne.error("Failed to update")}},G=async()=>{try{await c.mutateAsync(w.id),ne.success("Portal archived")}catch{ne.error("Failed to archive")}},V=async()=>{try{await d.mutateAsync(w.id),ne.success("Portal restored")}catch{ne.error("Failed to restore")}},H=async()=>{try{await u.mutateAsync({id:w.id,dealId:w.deal_id}),ne.success("Portal deleted"),t("/mission-control/client-portals")}catch{ne.error("Failed to delete")}};return e.jsxs($s,{children:[e.jsx(dl,{children:e.jsxs("title",{children:[P," — 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(z,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(or,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(ka,{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:P}),e.jsx(ze,{variant:"outline",className:D?"bg-muted text-muted-foreground":w.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:D?"Archived":w.is_enabled?"Active":"Disabled"}),e.jsx(ze,{variant:"outline",className:"capitalize text-xs",children:w.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Oo,{className:"w-3.5 h-3.5"}),w.client_name||I||"No client name set",(M==null?void 0:M.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(on,{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(va,{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:E})})]}),!D&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(mn,{checked:w.is_enabled,onCheckedChange:q})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(z,{onClick:F,variant:"outline",size:"sm",children:[e.jsx(Sa,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(z,{onClick:()=>window.open(E,"_blank"),variant:"outline",size:"sm",children:[e.jsx(mr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(z,{onClick:()=>v(!0),size:"sm",children:[e.jsx(Fr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(z,{onClick:()=>f(!0),variant:"outline",size:"sm",children:[e.jsx(I4,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(z,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(Gc,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[D?e.jsxs(z,{onClick:V,variant:"outline",size:"sm",children:[e.jsx(eP,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(z,{onClick:G,variant:"ghost",size:"sm",children:[e.jsx(w0,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(z,{onClick:()=>b(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Vde,{icon:I4,label:"Updates Posted",value:i.length}),e.jsx(Vde,{icon:Ko,label:"Referrals",value:C.length}),e.jsx(Vde,{icon:ya,label:"Inspection",value:w.inspection_date?o$(w.inspection_date):"—"}),e.jsx(Vde,{icon:ya,label:"Appraisal",value:w.appraisal_date?o$(w.appraisal_date):"—"})]}),e.jsxs(Qr,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsx(Wt,{value:"messages",children:"Messages"}),e.jsxs(Wt,{value:"referrals",children:["Referrals (",C.length,")"]}),e.jsx(Wt,{value:"branding",children:"Branding"}),e.jsx(Wt,{value:"details",children:"Details"})]}),e.jsx(Kt,{value:"messages",className:"mt-4",children:e.jsx(ras,{portalId:w.id,portalSlug:w.slug,clientName:w.client_name})}),e.jsx(Kt,{value:"updates",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Le,{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(z,{size:"sm",onClick:()=>f(!0),children:[e.jsx(I4,{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(I4,{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(K=>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:K.title}),K.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:o$(K.created_at)}),K.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:K.content}),K.video_url&&e.jsxs("a",{href:K.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(Xr,{className:"w-3 h-3"})," View video"]})]})})},K.id))})]})})}),e.jsx(Kt,{value:"referrals",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),C.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Ko,{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:C.map(K=>e.jsx(or,{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:K.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[K.friend_email||K.friend_phone||"No contact info"," · ",o$(K.created_at)]})]}),e.jsx(ze,{variant:"outline",className:"text-xs capitalize",children:K.status})]})},K.id))})]})})}),e.jsx(Kt,{value:"branding",className:"mt-4",children:e.jsx(be,{children:e.jsx(Le,{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(yc,{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(z,{onClick:()=>m(!0),children:[e.jsx(Gc,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(Kt,{value:"details",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Le,{className:"p-6 space-y-4",children:[e.jsx(BT,{label:"Visibility",value:w.visibility}),e.jsx(BT,{label:"Onboarding Required",value:w.require_onboarding?"Yes":"No"}),e.jsx(BT,{label:"Allow Spouse",value:w.allow_spouse?"Yes":"No"}),e.jsx(BT,{label:"Notify Client on Updates",value:w.notify_client?"Yes":"No"}),e.jsx(BT,{label:"Show Post-Close Tips",value:w.show_post_close_tips?"Yes":"No"}),e.jsx(BT,{label:"Slug",value:w.slug,mono:!0}),e.jsx(BT,{label:"Created",value:o$(w.created_at)}),e.jsx(BT,{label:"Last Updated",value:o$(w.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(z,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(Gc,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(yit,{open:h,onOpenChange:m,portal:w,dealOwnerId:n||""}),e.jsx(vit,{open:p,onOpenChange:f,portalId:w.id,portalSlug:w.slug,notifyClient:w.notify_client}),e.jsx(bit,{open:g,onOpenChange:v,portal:w,dealName:P}),e.jsx(Ql,{open:y,onOpenChange:b,children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Permanently delete this portal?"}),e.jsx(ql,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:H,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Vde({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 BT({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 gZe=[{value:"video_intro",label:"Video Intro",icon:Xr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:XA,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Ip,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:Oc,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:sd,description:"Links to your social profiles"}],fsr=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],xsr={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function aas({cardId:s}){const{data:t,isLoading:n}=XMs(s),r=QMs(),a=JMs(),i=ePs(),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ln,{className:"h-16 w-full"}),e.jsx(ln,{className:"h-16 w-full"})]});const m=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:xsr[c]||{}},{onSuccess:()=>{o(!1),d("")}})},p=b=>{a.mutate({id:b.id,is_visible:!b.is_visible})},f=(b,w)=>{if(!t)return;const S=t.findIndex(P=>P.id===b.id),C=w==="up"?S-1:S+1;if(C<0||C>=t.length)return;const E=t[C];a.mutate({id:b.id,sort_order:E.sort_order}),a.mutate({id:E.id,sort_order:b.sort_order})},g=async b=>{await Qi("Remove this block from this card?")&&i.mutate(b.id)},v=(b,w)=>{a.mutate({id:b.id,config:w},{onSuccess:()=>h(null)})},y=b=>gZe.find(w=>w.value===b);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(z,{size:"sm",onClick:()=>o(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,w)=>{const S=y(b.block_type),C=(S==null?void 0:S.icon)||Ip;return e.jsx(be,{className:b.is_visible?"":"opacity-50",children:e.jsx(Le,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zf,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(C,{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:(S==null?void 0:S.label)||b.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:gsr(b)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b,"up"),disabled:w===0,children:e.jsx(ap,{className:"h-3 w-3"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b,"down"),disabled:w===t.length-1,children:e.jsx(Vf,{className:"h-3 w-3"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>p(b),children:b.is_visible?e.jsx(xa,{className:"h-3 w-3"}):e.jsx(Yf,{className:"h-3 w-3"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(b),children:"Edit"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>g(b),children:e.jsx(Cn,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:gZe.map(b=>{const w=b.icon;return e.jsxs("button",{onClick:()=>d(b.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===b.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(w,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.description})]})]},b.value)})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(z,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(ysr,{block:u,onSave:b=>v(u,b),onClose:()=>h(null)})]})}function gsr(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 ysr({block:s,onSave:t,onClose:n}){const[r,a]=_.useState(s.config),i=gZe.find(l=>l.value===s.block_type);return e.jsx(Is,{open:!0,onOpenChange:n,children:e.jsxs(Ls,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(vsr,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(bsr,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(_sr,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(wsr,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(jsr,{config:r,onChange:a}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(z,{onClick:()=>t(r),children:"Save"})]})]})})}function vsr({config:s,onChange:t,cardId:n}){var p,f;const[r,a]=_.useState(""),[i,l]=_.useState((p=s.video_url)!=null&&p.includes("youtube")||(f=s.video_url)!=null&&f.includes("youtu.be")?"youtube":"library"),{data:o}=rt({queryKey:["card-owner",n],queryFn:async()=>{const{data:g}=await U.from("agent_cards").select("user_id").eq("id",n).single();return g==null?void 0:g.user_id},enabled:!!n}),{data:c,isLoading:d}=rt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:g,error:v}=await U.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(v)throw v;return g||[]},enabled:!!o}),u=(c==null?void 0:c.filter(g=>!r||(g.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,m=g=>{var w;const v=(w=g.playback_url)==null?void 0:w.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${v?v[1]:"570924"}/${g.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:b,bunny_video_id:g.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(Qr,{value:i,onValueChange:l,children:[e.jsxs(Jr,{className:"w-full",children:[e.jsx(Wt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Wt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Kt,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:r,onChange:g=>a(g.target.value),className:"pl-9"})]}),e.jsx(Ki,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ln,{className:"h-14 w-full"}),e.jsx(ln,{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(g=>e.jsxs("button",{onClick:()=>m(g),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===g.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[g.thumbnail_url?e.jsx("img",{src:g.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:v=>{var y;v.currentTarget.style.display="none",(y=v.currentTarget.nextElementSibling)==null||y.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${g.thumbnail_url?"hidden":""}`,children:e.jsx(Xr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:g.title||"Untitled Video"}),h===g.bunny_video_id&&e.jsx(Wr,{className:"h-4 w-4 text-primary flex-shrink-0"})]},g.id))})})]}),e.jsx(Kt,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(ee,{children:"YouTube URL"}),e.jsx(pe,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:g=>t({...s,video_url:g.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 bsr({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(be,{children:e.jsxs(Le,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Cn,{className:"h-3 w-3"})})]}),e.jsx(pe,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(pe,{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(z,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function _sr({config:s,onChange:t}){const n=s.tags||[],[r,a]=_.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(ee,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:fsr.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(ee,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(z,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(ee,{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 wsr({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(pe,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(pe,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(Cn,{className:"h-3 w-3"})})]},o)),e.jsxs(z,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const $4t=[{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 jsr({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=$4t.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=gVe[c],u=$4t.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(pe,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(ee,{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=gVe[c.value];return e.jsxs("button",{onClick:()=>r(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}function Nsr({slug:s,agentName:t}){const n=_.useRef(null),r=`https://cards.relevelup.com/${s}`,a=_.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const m=document.createElement("a");m.download=`${s}-qr-code.png`,m.href=l.toDataURL("image/png"),m.click(),ne.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(ee,{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(LN,{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(z,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function VBe(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 ksr(){const{user:s}=hs(),{data:t,isLoading:n}=KMs(s==null?void 0:s.id),r=XW(),[a,i]=_.useState(null),l=_.useMemo(()=>a||(t?VBe(t):null),[a,t]);if(n)return e.jsx($s,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(ln,{className:"h-8 w-48"}),e.jsx(ln,{className:"h-32 w-full"}),e.jsx(ln,{className:"h-32 w-full"})]})});if(!t)return e.jsx($s,{children:e.jsx(Csr,{userId:s==null?void 0:s.id})});const o=l||VBe(t),c=d=>{i(u=>{const h=u||VBe(t);return typeof d=="function"?d(h):d})};return e.jsx($s,{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(Asr,{card:t}),e.jsx(Psr,{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(yN,{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(Ssr,{card:t,form:o})})]})})]})})}function Ssr({card:s,form:t}){const{data:n}=rt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await U.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=_.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(BJe,{card:r})})}function Csr({userId:s}){var c;const[t,n]=_.useState(""),r=hOt(),{data:a}=rt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await U.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){ne.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ne.success("Your digital card has been created!")})},o=[{icon:Wo,title:"Shareable Link",desc:"One link that works everywhere"},{icon:cf,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Om,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:yc,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(be,{className:"shadow-lg border-2",children:[e.jsxs(_t,{className:"text-center pb-2",children:[e.jsx(Nt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(En,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Le,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(z,{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 Asr({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ne.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(Wo,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(z,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(mr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function Esr({userId:s}){const t=$t(),n=_.useRef(null),[r,a]=_.useState(!1),[i,l]=_.useState(""),{data:o,isLoading:c}=rt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:F}=await U.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let q=(F==null?void 0:F.avatar_url)||null;if(!q){const{data:G}=await U.storage.from("avatars").list(`${s}`);if(G&&G.length>0){const{data:V}=U.storage.from("avatars").getPublicUrl(`${s}/${G[0].name}`);q=`${V.publicUrl}?t=${Date.now()}`,await U.from("profiles").update({avatar_url:q}).eq("id",s)}}return{...F,avatar_url:q}}}),[d,u]=_.useState(null),[h,m]=_.useState(null),[p,f]=_.useState(null),[g,v]=_.useState(!1),y=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",w=p??(o==null?void 0:o.email)??"",S=o==null?void 0:o.avatar_url,C=((o==null?void 0:o.name)||"A").split(" ").map(F=>F[0]).join("").toUpperCase().slice(0,2),E=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),P=mt({mutationFn:async F=>{const{error:q}=await U.from("profiles").update(F).eq("id",s);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ne.success("Profile updated!")},onError:()=>ne.error("Failed to update profile")}),M=()=>{const F={};if(d!==null&&d!==(o==null?void 0:o.name)&&(F.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(F.phone=h||null),p!==null&&p!==(o==null?void 0:o.email)&&(F.email=p),Object.keys(F).length===0){ne.info("No changes to save");return}P.mutate(F)},I=F=>{var V;const q=(V=F.target.files)==null?void 0:V[0];if(!q)return;if(!q.type.startsWith("image/")){ne.error("Please select an image file");return}const G=new FileReader;G.onloadend=()=>{l(G.result),a(!0)},G.readAsDataURL(q),F.target.value=""},D=async F=>{v(!0);try{const{data:q}=await U.storage.from("avatars").list(`${s}`);q&&q.length>0&&await U.storage.from("avatars").remove(q.map(Z=>`${s}/${Z.name}`));const G=`${s}/avatar.jpg`,{error:V}=await U.storage.from("avatars").upload(G,F,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:H}=U.storage.from("avatars").getPublicUrl(G),K=H.publicUrl+"?t="+Date.now();await U.from("profiles").update({avatar_url:K}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ne.success("Photo updated!")}catch{ne.error("Failed to upload photo")}finally{v(!1)}};return c?e.jsx(ln,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:E?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Le,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Profile Info"}),E&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Ho,{className:"h-3 w-3"}),"Missing info — complete below so your card looks great"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-3",children:"This info shows on your digital card and updates your profile everywhere."}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative group cursor-pointer",onClick:()=>{var F;return(F=n.current)==null?void 0:F.click()},children:[e.jsxs(ja,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(xi,{src:S||void 0,alt:y}),e.jsx(Na,{className:"text-lg font-semibold bg-primary/10 text-primary",children:C})]}),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(Lx,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:I})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:g?"Uploading...":S?"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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(pe,{value:y,onChange:F=>u(F.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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(pe,{value:b,onChange:F=>m(F.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(pe,{value:w,onChange:F=>f(F.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(z,{variant:"outline",size:"sm",onClick:M,disabled:P.isPending,className:"w-full",children:P.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(Ltt,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:D,aspectRatio:1})]})}function Tsr({form:s,setForm:t,userId:n}){const[r,a]=_.useState(null),[i,l]=_.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=_.useState(s.team_logo_url?"logo":"name"),d=p=>{l(p),t(p==="name"?f=>({...f,brokerage_logo_url:""}):f=>({...f,brokerage_display_name:""}))},u=p=>{c(p),t(p==="name"?f=>({...f,team_logo_url:""}):f=>({...f,team_name:""}))},h=async(p,f)=>{var v;const g=(v=p.target.files)==null?void 0:v[0];if(g){if(!g.type.startsWith("image/")){ne.error("Please select an image file");return}a(f);try{const y=g.name.split(".").pop()||"png",w=`${n}/${f==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${y}`,{error:S}=await U.storage.from("card-logos").upload(w,g,{upsert:!0});if(S)throw S;const{data:C}=U.storage.from("card-logos").getPublicUrl(w),E=C.publicUrl+"?t="+Date.now();t(f==="brokerage_logo_url"?P=>({...P,[f]:E,brokerage_display_name:""}):P=>({...P,[f]:E,team_name:""})),ne.success("Logo uploaded!")}catch{ne.error("Failed to upload logo")}finally{a(null),p.target.value=""}}},m=p=>{t(f=>({...f,[p]:""}))};return e.jsx(be,{children:e.jsxs(Le,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{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(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(z,{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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(pe,{value:s.brokerage_display_name,onChange:p=>t(f=>({...f,brokerage_display_name:p.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>m("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Lx,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p=>h(p,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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(Mx,{value:[s.brokerage_logo_size||56],onValueChange:([p])=>t(f=>({...f,brokerage_logo_size:p})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx(z,{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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(pe,{value:s.team_name,onChange:p=>t(f=>({...f,team_name:p.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Team Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.team_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.team_logo_url,alt:"Team logo",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>m("team_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Lx,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p=>h(p,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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(Mx,{value:[s.team_logo_size||56],onValueChange:([p])=>t(f=>({...f,team_logo_size:p})),min:24,max:120,step:4})]})]})]})]})})}function Msr({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(ee,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(yc,{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(z,{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(pe,{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 Psr({card:s,form:t,setForm:n}){var g;const r=mOt(),a=$t(),{data:i}=pOt(s.id),[l,o]=_.useState(s.slug),[c,d]=_.useState(!1),[u,h]=_.useState("idle"),m=_.useRef(JSON.stringify(t)),p=_.useRef(null);_.useEffect(()=>{const v=JSON.stringify(t);if(v!==m.current)return p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{m.current=v,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{p.current&&clearTimeout(p.current)}},[t]);const f=async()=>{const v=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!v){ne.error("Please enter a valid URL");return}if(v===s.slug){ne.info("No changes to save");return}d(!0);try{const{data:y}=await U.from("agent_cards").select("id").eq("slug",v).neq("id",s.id).maybeSingle();if(y){ne.error("This URL is already taken. Try another one.");return}const{error:b}=await U.from("agent_cards").update({slug:v}).eq("id",s.id);if(b)throw b;o(v),a.invalidateQueries({queryKey:["agent-card"]}),ne.success("Card address updated!")}catch{ne.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Qr,{defaultValue:"content",children:[e.jsxs(Jr,{className:"w-full h-11 p-1",children:[e.jsxs(Wt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(j0,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Wt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(xa,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Wt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(cf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Wt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(lf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Wt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Gh,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Kt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(Esr,{userId:s.user_id}),e.jsx(Tsr,{form:t,setForm:n,userId:s.user_id}),e.jsx(be,{children:e.jsxs(Le,{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(ee,{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(mn,{checked:t.is_published,onCheckedChange:v=>n(y=>({...y,is_published:v}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{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(pe,{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(z,{variant:"outline",size:"sm",onClick:f,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(ee,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(pe,{value:t.display_email,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(ls,{value:t.theme,onValueChange:v=>n(y=>({...y,theme:v})),children:[e.jsx(rs,{className:"h-11",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(He,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(He,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(He,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(Msr,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(pe,{value:t.title,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(pe,{value:t.positioning_statement,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ps,{value:t.bio,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(pe,{value:t.review_snippet,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(pe,{value:t.review_source_url,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(pe,{value:t.booking_url,onChange:v=>n(y=>({...y,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(ee,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(pe,{value:t.custom_cta_label,onChange:v=>n(y=>({...y,custom_cta_label:v.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(Kt,{value:"sections",className:"mt-4",children:e.jsx(be,{children:e.jsx(Le,{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:y,desc:b})=>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(ee,{className:"text-sm font-medium",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(mn,{checked:t[v],onCheckedChange:w=>n(S=>({...S,[v]:w}))})]},v))})})}),e.jsx(Kt,{value:"blocks",className:"mt-4",children:e.jsx(aas,{cardId:s.id})}),e.jsx(Kt,{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:xa,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:Gh,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((g=i==null?void 0:i.leads)==null?void 0:g.length)??0,icon:Pl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(v=>e.jsx(be,{className:"overflow-hidden",children:e.jsxs(Le,{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(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"Recent Leads"})}),e.jsx(Le,{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(be,{children:e.jsxs(Le,{className:"p-8 text-center",children:[e.jsx(Gh,{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(Kt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(be,{children:e.jsx(Le,{className:"p-6",children:e.jsx(Nsr,{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 Lsr(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(null),[g,v]=_.useState(null),[y,b]=_.useState(0),[w,S]=_.useState(""),[C,E]=_.useState(!1),{data:P,isLoading:M}=rt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:re,error:ae}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ae)throw ae;return re}}),I=mt({mutationFn:async re=>{const{data:ae,error:J}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:re}});if(J)throw J;if(ae!=null&&ae.error)throw new Error(ae.error);return ae},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ne.success("BoldTrail connected successfully!")},onError:re=>{ne.error(re.message||"Failed to connect BoldTrail")}}),D=mt({mutationFn:async()=>{const{data:re,error:ae}=await U.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ae)throw ae;return re},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ne.success("BoldTrail disconnected")},onError:()=>ne.error("Failed to disconnect")}),F=mt({mutationFn:async re=>{const{data:ae,error:J}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:re}});if(J)throw J;if(ae!=null&&ae.error)throw new Error(ae.error);return ae},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ne.success("Sync direction saved")},onError:re=>{ne.error(re.message||"Failed to save sync direction")}}),q=mt({mutationFn:async()=>{const{data:re,error:ae}=await U.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ae)throw ae;if(re!=null&&re.error)throw new Error(re.error);return re},onSuccess:re=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),re.kvcore_user_id){const ae=re.detected_name||re.detected_email||`ID ${re.kvcore_user_id}`;ne.success(`Detected your BoldTrail account: ${ae}`)}else if(re.candidates&&re.candidates.length>0){const ae=re.candidates.slice(0,5).map(J=>`${J.id} (${J.count} contacts)`).join(", ");ne.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ae}. Pick yours and enter it below.`,{duration:12e3}),E(!0)}else ne.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),E(!0)},onError:re=>ne.error(re.message||"Detection failed")}),G=mt({mutationFn:async re=>{const{data:ae,error:J}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...re}});if(J)throw J;if(ae!=null&&ae.error)throw new Error(ae.error);return ae},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ne.success("Settings saved"),E(!1)},onError:re=>ne.error(re.message||"Failed to save settings")}),V=mt({mutationFn:async()=>{const{data:re,error:ae}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ae)throw ae;if(re!=null&&re.error)throw new Error(re.error);return re},onSuccess:re=>{f(null),c(re),a(!0)},onError:re=>{ne.error(re.message||"Failed to generate sync preview")}}),H=mt({mutationFn:async()=>{v("Initializing sync..."),b(5);const{data:re,error:ae}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:oe}});if(ae)throw ae;if(re!=null&&re.error)throw new Error(re.error);const J=re;let te=J.sync_log_id,ce=J.next_phase,ve=J.next_offset,me=J.push_total||0,he=J.pull_total||0,ge=0,Ee=0;for(;ce!=="finalize";){const Oe=me+he;ce==="fetch_bt"?v("Fetching BoldTrail contacts..."):ce==="analyze"?(v("Analyzing contacts..."),b(15)):ce==="push"?(v(`Pushing contacts to BoldTrail... (${ge}/${me})`),b(Oe>0?ge/Oe*100:0)):ce==="pull"&&(v(`Pulling contacts from BoldTrail... (${Ee}/${he})`),b(Oe>0?(me+Ee)/Oe*100:0));const{data:ke,error:Ve}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ce,offset:ve,sync_log_id:te,sync_direction:oe}});if(Ve)throw Ve;if(ke!=null&&ke.error)throw new Error(ke.error);const _e=ke;ge+=_e.chunk_pushed||0,Ee+=_e.chunk_pulled||0,_e.push_total!==void 0&&(me=_e.push_total||0),_e.pull_total!==void 0&&(he=_e.pull_total||0),_e.progress&&v(_e.progress),ce==="pull"&&he>0?b(Math.min(95,Ee/he*100)):ce==="push"&&me>0&&b(Math.min(95,ge/me*100)),ce=_e.next_phase,ve=_e.next_offset}v("Finalizing sync..."),b(95);const{data:Ne,error:Pe}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:te,sync_direction:oe}});if(Pe)throw Pe;return b(100),Ne},onSuccess:re=>{v(null),b(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"]}),ne.success(`Sync complete! Pushed ${re.contacts_pushed||0}, pulled ${re.contacts_pulled||0}, skipped ${re.contacts_skipped||0} duplicates.`)},onError:re=>{v(null),b(0),ne.error(re.message||"Sync failed")}}),K=P==null?void 0:P.connected,Z=(P==null?void 0:P.sync_direction)||"bidirectional",oe=p??Z;return e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(_t,{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(Og,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",K&&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(dm,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(En,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Le,{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(Xl,{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(Xl,{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(Xl,{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"})]}),K?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"}),(P==null?void 0:P.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(P.last_sync_at).toLocaleString(),P.last_sync_status&&e.jsx(ze,{variant:P.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:P.last_sync_status})]}),(P==null?void 0:P.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[P.boldtrail_contact_count," contacts in BoldTrail"]}),(P==null?void 0:P.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:P.last_sync_message})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect BoldTrail?"}),e.jsx(ql,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>D.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(jj,{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:"Include contacts without an email address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Phone or name-only leads come across too. Turn this off to sync only contacts that have an email address."})]}),e.jsx(mn,{checked:(P==null?void 0:P.sync_include_no_email)!==!1,onCheckedChange:re=>G.mutate({sync_include_no_email:re}),disabled:G.isPending})]})}),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(jj,{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(mn,{checked:!!(P!=null&&P.sync_only_owned),onCheckedChange:re=>G.mutate({sync_only_owned:re}),disabled:G.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Your BoldTrail Agent ID"}),C?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",placeholder:"e.g. 12345",value:w,onChange:re=>S(re.target.value),className:"h-8 text-sm"}),e.jsx(z,{size:"sm",onClick:()=>{const re=w.trim()===""?null:Number(w);G.mutate({kvcore_user_id:re})},disabled:G.isPending,children:"Save"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>E(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(P==null?void 0:P.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>q.mutate(),disabled:q.isPending,children:[q.isPending?e.jsx(Gi,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>{var re;S(((re=P==null?void 0:P.kvcore_user_id)==null?void 0:re.toString())??""),E(!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(YTe,{value:Z,onChange:re=>F.mutate(re)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(z,{onClick:()=>V.mutate(),disabled:V.isPending||H.isPending,variant:"outline",className:"gap-2",children:[V.isPending?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(xa,{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(pe,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:re=>n(re.target.value),className:"flex-1"}),e.jsxs(z,{onClick:()=>I.mutate(t),disabled:!t||t.length<10||I.isPending,children:[I.isPending?e.jsx(Gi,{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(Is,{open:r,onOpenChange:re=>{H.isPending||a(re)},children:e.jsxs(Ls,{className:"sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Og,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(_r,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const re=oe==="pull_only"?0:o.to_push,ae=oe==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(YTe,{value:oe,onChange:f,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(jj,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Owner filter is on. Only contacts assigned to your BoldTrail account",o.kvcore_user_id?` (ID ${o.kvcore_user_id})`:""," will be synced.",o.boldtrail_total_brokerage!=null&&e.jsxs(e.Fragment,{children:[" Brokerage total: ",e.jsx("strong",{children:o.boldtrail_total_brokerage.toLocaleString()}),"."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${oe==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:re}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${oe==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:ae}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Vf,{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(On,{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"]}),H.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Di,{value:y||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:g||"Sync in progress..."})]}),re>0&&e.jsxs(f1,{open:d,onOpenChange:u,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3 text-emerald-600"}),re," contacts to push to BoldTrail"]}),e.jsx(cl,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(g1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((J,te)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:J.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:J.email})]},te)),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"]})]})})]}),ae>0&&e.jsxs(f1,{open:h,onOpenChange:m,children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vf,{className:"h-3 w-3 text-blue-600"}),ae," contacts to pull from BoldTrail"]}),e.jsx(cl,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(g1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((J,te)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:J.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:J.email})]},te)),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"]})]})})]}),re===0&&ae===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(z,{variant:"outline",onClick:()=>a(!1),disabled:H.isPending,children:"Cancel"}),e.jsxs(z,{onClick:()=>H.mutate(),disabled:H.isPending||re===0&&ae===0,className:"gap-2",children:[H.isPending?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(Og,{className:"h-4 w-4"}),H.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Os,{className:"p-6 pb-0",children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Og,{className:"h-5 w-5 text-emerald-600"}),"How BoldTrail Sync Works"]})}),e.jsx("div",{className:"px-6 pb-6",children:e.jsx("video",{src:"/videos/BoldTrailIntegration.mp4",controls:!0,autoPlay:!0,className:"w-full rounded-lg",controlsList:"nodownload"})})]})})]})}const l$=async s=>{const{data:t,error:n}=await U.functions.invoke("lofty-sync",{body:s});if(n)throw new Error(n.message);if(t!=null&&t.error)throw new Error(typeof t.error=="string"?t.error:JSON.stringify(t.error));return t};function Isr(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),[d,u]=_.useState(null),[h,m]=_.useState(null),{data:p,isLoading:f}=rt({queryKey:["lofty-status"],queryFn:async()=>await l$({action:"status"})}),g=()=>s.invalidateQueries({queryKey:["lofty-status"]}),v=mt({mutationFn:async()=>l$({action:"save_token",api_token:t.trim()}),onSuccess:E=>{ne.success(E!=null&&E.contact_count?`Connected to Lofty — ${E.contact_count} contacts found`:"Connected to Lofty"),n(""),g()},onError:E=>ne.error(E.message)}),y=mt({mutationFn:async()=>l$({action:"disconnect"}),onSuccess:()=>{ne.success("Lofty disconnected"),g()},onError:E=>ne.error(E.message)}),b=mt({mutationFn:async E=>l$({action:"save_settings",...E}),onSuccess:()=>g(),onError:E=>ne.error(E.message)}),w=mt({mutationFn:async()=>l$({action:"detect_owner"}),onSuccess:E=>{const P=(E==null?void 0:E.candidates)||[];m(P),P.length===0?ne.info("No assigned-agent IDs found on your Lofty contacts."):P.length===1?(b.mutate({lofty_user_id:P[0].id}),ne.success(`Using Lofty agent ID ${P[0].id}`)):ne.success("Pick which Lofty agent ID is yours below.")},onError:E=>ne.error(E.message)}),S=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let E="start",P=0,M=null,I=0;for(;E&&I<400;){I++;const D=await l$({action:"sync",phase:E,offset:P,sync_log_id:M});M=D.sync_log_id||M,D.progress&&u(D.progress),c(F=>Math.min(95,F+4)),E=D.next_phase,P=D.next_offset||0,E||(c(100),u(D.message||"Sync complete"),ne.success(D.message||"Lofty sync complete"))}}catch(E){ne.error(E.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),g()}},C=!!(p!=null&&p.connected);return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:["Lofty",C?e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Xl,{className:"h-3 w-3"})," Connected"]}):e.jsx(ze,{variant:"outline",children:"Not connected"})]}),e.jsx(En,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),C&&e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Lofty?"}),e.jsx(ql,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>y.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Le,{className:"space-y-5",children:f?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):C?e.jsxs("div",{className:"space-y-5",children:[e.jsx(YTe,{value:(p==null?void 0:p.sync_direction)||"pull_only",onChange:E=>b.mutate({sync_direction:E}),size:"sm"}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Only my contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip team/brokerage contacts assigned to other Lofty agents."})]}),e.jsx(mn,{checked:!!(p!=null&&p.sync_only_owned),onCheckedChange:E=>b.mutate({sync_only_owned:E})})]}),(p==null?void 0:p.sync_only_owned)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>w.mutate(),disabled:w.isPending,children:[w.isPending?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(On,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(p==null?void 0:p.lofty_user_id)&&e.jsxs(ze,{variant:"secondary",children:["Agent ID ",p.lofty_user_id]})]}),h&&h.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(E=>e.jsxs(z,{size:"sm",variant:(p==null?void 0:p.lofty_user_id)===E.id?"default":"outline",onClick:()=>b.mutate({lofty_user_id:E.id}),children:[E.id," · ",E.count," contacts"]},E.id))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Import notes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pull each contact's Lofty notes into their Agent OS notes (deduped)."})]}),e.jsx(mn,{checked:!!(p!=null&&p.import_notes),onCheckedChange:E=>b.mutate({import_notes:E})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"lofty-tags",placeholder:((p==null?void 0:p.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:E=>a(E.target.value)}),e.jsx(z,{variant:"outline",onClick:()=>b.mutate({pull_tag_filter:r.split(",").map(E=>E.trim()).filter(Boolean)}),children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to import every contact. Comma-separated Lofty tags."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(z,{onClick:S,disabled:i,children:[i?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4"}),i?"Syncing…":"Sync Now"]}),(p==null?void 0:p.last_sync_at)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last sync ",new Date(p.last_sync_at).toLocaleString("en-US",{timeZone:"America/New_York"})]})]}),(i||o>0)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Di,{value:o}),d&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),(p==null?void 0:p.last_sync_message)&&!i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.last_sync_message})]}),((p==null?void 0:p.logs)||[]).length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:"Recent syncs"}),e.jsx("div",{className:"space-y-1",children:p.logs.map(E=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(E.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[E.contacts_pulled," imported · ",E.contacts_pushed," pushed ·"," ",E.contacts_skipped," skipped"]}),e.jsx(ze,{variant:E.status==="completed"?"secondary":"destructive",children:E.status})]},E.id))})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(pe,{id:"lofty-key",type:"password",placeholder:"Paste your Lofty API key",value:t,onChange:E=>n(E.target.value),autoComplete:"off"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["In Lofty go to ",e.jsx("strong",{children:"Settings → Integrations → API Key Management"})," and create a key with contact access."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{onClick:()=>v.mutate(),disabled:t.trim().length<10||v.isPending,children:[v.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(_j,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"https://developer.lofty.com/",target:"_blank",rel:"noreferrer",children:["Lofty API docs ",e.jsx(mr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function Dsr(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(!1),[i,l]=_.useState(0),[o,c]=_.useState(null),{data:d,isLoading:u}=rt({queryKey:["fub-status"],queryFn:async()=>{const{data:g,error:v}=await U.functions.invoke("followupboss-sync",{body:{action:"status"}});if(v)throw v;return g}}),h=mt({mutationFn:async g=>{const{data:v,error:y}=await U.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:g}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ne.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:g=>ne.error(g.message)}),m=mt({mutationFn:async()=>{const{error:g}=await U.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(g)throw g},onSuccess:()=>{ne.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),p=mt({mutationFn:async g=>{const{error:v}=await U.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:g}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),f=async()=>{a(!0),l(0),c("Pulling from FUB…");let g=0,v=0,y=0,b=0;try{for(;;){const{data:E,error:P}=await U.functions.invoke("followupboss-sync",{body:{action:"sync",offset:g}});if(P)throw P;if(E!=null&&E.error)throw new Error(E.error);v+=E.chunk_created||0,y+=E.chunk_updated||0,b+=E.chunk_skipped||0,g=E.next_offset;const M=E.total?Math.min(100,Math.round(g/E.total*100)):100;if(l(M),c(`Pulling · ${g} / ${E.total||"?"}`),E.done)break;await new Promise(I=>setTimeout(I,400))}let w=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to FUB…");;){const{data:P,error:M}=await U.functions.invoke("followupboss-sync",{body:{action:"push",offset:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);w+=P.chunk_pushed||0,S+=P.chunk_failed||0,E=P.next_offset;const I=P.total?Math.min(100,Math.round(E/P.total*100)):100;if(l(I),c(`Pushing · ${E} / ${P.total||"?"}`),P.done)break;await new Promise(D=>setTimeout(D,400))}}const C=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";ne.success(`Sync complete · ${v} new, ${y} updated${b?`, ${b} skipped`:""}${C}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(w){ne.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(_j,{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(Xl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(En,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Le,{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(mn,{checked:d.sync_direction==="bidirectional",onCheckedChange:g=>p.mutate(g?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Di,{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(z,{onClick:f,disabled:r,children:[e.jsx(Gi,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{variant:"outline",disabled:r,children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Follow Up Boss?"}),e.jsx(ql,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(pe,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:g=>n(g.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(mr,{className:"h-3 w-3"})]})]})]}),e.jsx(z,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Rsr(){var V;const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState(0),[d,u]=_.useState(null),[h,m]=_.useState(!1),[p,f]=_.useState(null),[g,v]=_.useState(!1),[y,b]=_.useState(new Set),{data:w,isLoading:S}=rt({queryKey:["cloze-status"],queryFn:async()=>{const{data:H,error:K}=await U.functions.invoke("cloze-sync",{body:{action:"status"}});if(K)throw K;return H}}),C=mt({mutationFn:async()=>{const{data:H,error:K}=await U.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(K)throw K;if(H!=null&&H.error)throw new Error(H.error);return H},onSuccess:()=>{ne.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:H=>ne.error(H.message)}),E=mt({mutationFn:async()=>{const{error:H}=await U.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(H)throw H},onSuccess:()=>{ne.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),P=mt({mutationFn:async H=>{const{error:K}=await U.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:H}});if(K)throw K},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=mt({mutationFn:async H=>{const{error:K}=await U.functions.invoke("cloze-sync",{body:{action:"set_scope",...H}});if(K)throw K},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),I=async()=>{v(!0);try{const{data:H,error:K}=await U.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(K)throw K;if(H!=null&&H.error)throw new Error(H.error);f(H.segments||[]),b(new Set((w==null?void 0:w.selected_segments)||[])),m(!0)}catch(H){ne.error(H.message||"Failed to load segments")}finally{v(!1)}},D=async()=>{const H=Array.from(y);await M.mutateAsync({sync_scope:"segments",selected_segments:H}),ne.success(`Saved · ${H.length} segment(s) selected`),m(!1)},F=async()=>{const H=(w==null?void 0:w.sync_direction)||"pull_only";l(!0),c(0);try{if(H==="pull_only"||H==="bidirectional"){u("Pulling from Cloze…");let K=0,Z=0,oe=0;for(;;){const{data:re,error:ae}=await U.functions.invoke("cloze-sync",{body:{action:"sync",offset:K}});if(ae)throw ae;if(re!=null&&re.error)throw new Error(re.error);if(Z+=re.chunk_created||0,oe+=re.chunk_updated||0,K=re.next_offset,u(`Pulling · ${Z+oe} contacts processed`),c(re.done?100:Math.min(95,(Z+oe)%200/2)),re.done)break;await new Promise(J=>setTimeout(J,300))}ne.success(`Pulled · ${Z} new, ${oe} updated`)}if(H==="push_only"||H==="bidirectional"){c(0),u("Pushing to Cloze…");let K=0,Z=0,oe=0;for(;;){const{data:re,error:ae}=await U.functions.invoke("cloze-sync",{body:{action:"push",offset:K}});if(ae)throw ae;if(re!=null&&re.error)throw new Error(re.error);Z+=re.chunk_pushed||0,oe+=re.chunk_failed||0,K=re.next_offset;const J=re.total?Math.min(100,Math.round(K/re.total*100)):100;if(c(J),u(`Pushing · ${K} / ${re.total||"?"}`),re.done)break;await new Promise(te=>setTimeout(te,300))}ne.success(`Pushed · ${Z}${oe?`, ${oe} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(K){ne.error(K.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},q=(w==null?void 0:w.sync_scope)||"all",G=((V=w==null?void 0:w.selected_segments)==null?void 0:V.length)||0;return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(_j,{className:"h-5 w-5 text-primary"}),"Cloze",(w==null?void 0:w.connected)&&e.jsxs(ze,{variant:"default",className:"ml-1",children:[e.jsx(Xl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(En,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Le,{className:"space-y-4",children:S?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):w!=null&&w.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:w.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:w.last_sync_at?new Date(w.last_sync_at).toLocaleString():"Never"})]})]}),w.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:w.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(ls,{value:w.sync_direction||"pull_only",onValueChange:H=>P.mutate(H),disabled:i||P.isPending,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(He,{value:"push_only",children:"Push to Cloze"}),e.jsx(He,{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:q==="all"?"All Cloze contacts.":`${G} segment${G===1?"":"s"} selected.`})]}),e.jsxs(ls,{value:q,onValueChange:H=>{H==="all"?M.mutate({sync_scope:"all",selected_segments:[]}):(M.mutate({sync_scope:"segments",selected_segments:w.selected_segments||[]}),I())},disabled:i||M.isPending,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All contacts"}),e.jsx(He,{value:"segments",children:"Selected segments"})]})]})]}),q==="segments"&&e.jsxs("div",{children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:I,disabled:g,children:[e.jsx(gJ,{className:"h-4 w-4 mr-2"}),g?"Loading segments…":"Choose segments"]}),h&&p&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[p.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),p.map(H=>{const K=y.has(H.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(za,{checked:K,onCheckedChange:Z=>{const oe=new Set(y);Z?oe.add(H.id):oe.delete(H.id),b(oe)}}),e.jsx("span",{className:"flex-1 text-sm",children:H.name}),H.count!=null&&e.jsx(ze,{variant:"secondary",className:"text-xs",children:H.count})]},H.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{size:"sm",onClick:D,disabled:M.isPending,children:["Save selection (",y.size,")"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Di,{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(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{disabled:i,children:[e.jsx(Gi,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Preview sync"}),e.jsx(ql,{asChild:!0,children:e.jsx(Fsr,{segments:p})})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:F,children:"Start Sync"})]})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{variant:"outline",disabled:i,children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Cloze?"}),e.jsx(ql,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>E.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(pe,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:H=>a(H.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(pe,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:H=>n(H.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(mr,{className:"h-3 w-3"})]})]})]}),e.jsx(z,{onClick:()=>C.mutate(),disabled:!t.trim()||!r.trim()||C.isPending,children:C.isPending?"Connecting…":"Connect Cloze"})]})})]})}function Fsr({segments:s}){var h;const[t,n]=_.useState(!0),[r,a]=_.useState(null),[i,l]=_.useState(null);if(_.useEffect(()=>{(async()=>{try{const{data:m,error:p}=await U.functions.invoke("cloze-sync",{body:{action:"preview"}});if(p)throw p;if(m!=null&&m.error)throw new Error(m.error);a(m)}catch(m){l(m.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(m=>[m.id,m.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(m.id)||m.id}),e.jsx("span",{className:"text-muted-foreground",children:m.total})]},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function Osr(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(!1),[i,l]=_.useState(0),[o,c]=_.useState(null),{data:d,isLoading:u}=rt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:g,error:v}=await U.functions.invoke("boomtown-sync",{body:{action:"status"}});if(v)throw v;return g}}),h=mt({mutationFn:async g=>{const{data:v,error:y}=await U.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:g}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ne.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:g=>ne.error(g.message)}),m=mt({mutationFn:async()=>{const{error:g}=await U.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(g)throw g},onSuccess:()=>{ne.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),p=mt({mutationFn:async g=>{const{error:v}=await U.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:g}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),f=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let g=0,v=0,y=0,b=0;try{for(;;){const{data:E,error:P}=await U.functions.invoke("boomtown-sync",{body:{action:"sync",offset:g}});if(P)throw P;if(E!=null&&E.error)throw new Error(E.error);v+=E.chunk_created||0,y+=E.chunk_updated||0,b+=E.chunk_skipped||0,g=E.next_offset;const M=E.total?Math.min(100,Math.round(g/E.total*100)):100;if(l(M),c(`Pulling · ${g} / ${E.total||"?"}`),E.done)break;await new Promise(I=>setTimeout(I,400))}let w=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to Boomtown…");;){const{data:P,error:M}=await U.functions.invoke("boomtown-sync",{body:{action:"push",offset:E}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);w+=P.chunk_pushed||0,S+=P.chunk_failed||0,E=P.next_offset;const I=P.total?Math.min(100,Math.round(E/P.total*100)):100;if(l(I),c(`Pushing · ${E} / ${P.total||"?"}`),P.done)break;await new Promise(D=>setTimeout(D,400))}}const C=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";ne.success(`Sync complete · ${v} new, ${y} updated${b?`, ${b} skipped`:""}${C}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(w){ne.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(_j,{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(Xl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(En,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Le,{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(mn,{checked:d.sync_direction==="bidirectional",onCheckedChange:g=>p.mutate(g?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Di,{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(z,{onClick:f,disabled:r,children:[e.jsx(Gi,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{variant:"outline",disabled:r,children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Boomtown?"}),e.jsx(ql,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(pe,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:g=>n(g.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(mr,{className:"h-3 w-3"})]})]}),e.jsx(z,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function ias(){const s=zn(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState("Test from ReLevelUp"),[o,c]=_.useState(!1),{data:d,isLoading:u}=rt({queryKey:["ses-config"],queryFn:async()=>{const p=await jse();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){ne.error("Please fill in From and To email addresses");return}c(!0);try{const p=await jse(),g=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();g.success?ne.success(`Test email sent! Message ID: ${g.messageId}`):ne.error(g.error||"Failed to send test email")}catch(p){ne.error(p.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(be,{children:[e.jsx(_t,{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(on,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(En,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(ze,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xl,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(Le,{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(ee,{className:"text-xs",children:"From Email"}),e.jsx(pe,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:p=>a(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"To Email"}),e.jsx(pe,{placeholder:"your@email.com",value:t,onChange:p=>n(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:i,onChange:p=>l(p.target.value),className:"text-sm"})]})]}),e.jsxs(z,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(z,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(Nh,{className:"h-4 w-4 mr-2"})," Launch Campaign Composer"]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Region:"})," ",d==null?void 0:d.region]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Domain:"})," send.relevelup.com (verified)"]})]})]}),!m&&!u&&e.jsx(Le,{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 HBe(s){const t=await jse(),n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function zsr({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(Mr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(ze,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Not started"]})}function oas({brokerageId:s,onVerifiedSelect:t}){const n=$t(),[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),{data:p,isLoading:f}=rt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:b,error:w}=await U.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(w)throw w;return b||[]}}),g=mt({mutationFn:async()=>HBe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ne.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>ne.error(b.message)}),v=async b=>{var w,S;u(b.id);try{const C=await HBe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((w=C.sender)==null?void 0:w.status)==="verified"?ne.success(`${b.email} is verified! 🎉`):ne.info(`Status: ${((S=C.sender)==null?void 0:S.status)||"unknown"}`)}catch(C){ne.error(C.message)}finally{u(null)}},y=mt({mutationFn:async b=>HBe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ne.success("Sender removed"),m(null)},onError:b=>ne.error(b.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."})]}),f?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(b=>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(on,{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:b.email}),e.jsx(zsr,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx(z,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})]})]},b.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(ee,{className:"text-xs",children:"Email Address *"}),e.jsx(pe,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(pe,{value:i,onChange:b=>l(b.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(z,{size:"sm",onClick:()=>g.mutate(),disabled:!r.trim()||g.isPending,children:[g.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Ql,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Remove this sender?"}),e.jsxs(ql,{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($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>h&&y.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function GBe(s){const t=await jse(),n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function Bsr({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(Mr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(ze,{variant:"secondary",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(ze,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Not started"]})}function $sr({userId:s,onVerifiedSelect:t}){const n=$t(),[r,a]=_.useState(""),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(null),{data:p,isLoading:f}=rt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:b,error:w}=await U.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(w)throw w;return b||[]}}),g=mt({mutationFn:async()=>GBe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:b=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ne.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),b!=null&&b.domain_warning&&ne.warning("Heads up about this address",{description:b.domain_warning,duration:15e3}),a(""),l(""),c(!1)},onError:b=>ne.error(b.message)}),v=async b=>{var w,S;u(b.id);try{const C=await GBe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((w=C.sender)==null?void 0:w.status)==="verified"?ne.success(`${b.email} is verified! 🎉`):ne.info(`Status: ${((S=C.sender)==null?void 0:S.status)||"unknown"}`)}catch(C){ne.error(C.message)}finally{u(null)}},y=mt({mutationFn:async b=>GBe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ne.success("Sender removed"),m(null)},onError:b=>ne.error(b.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."]})]}),f?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(b=>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(on,{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:b.email}),e.jsx(Bsr,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx(z,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})]})]},b.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(ee,{className:"text-xs",children:"Email Address *"}),e.jsx(pe,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(pe,{value:i,onChange:b=>l(b.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(z,{size:"sm",onClick:()=>g.mutate(),disabled:!r.trim()||g.isPending,children:[g.isPending?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Ql,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Remove this sender?"}),e.jsxs(ql,{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($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>h&&y.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Usr(){var S,C,E,P,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=hs(),i=a||((S=r==null?void 0:r[0])==null?void 0:S.id)||null,l=(t||n)&&!!i,o=$t(),[c,d]=_.useState(!1),[u,h]=_.useState(""),[m,p]=_.useState(""),{data:f}=rt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:D}=await U.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(D)throw D;return I}}),{data:g}=rt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:D}=await U.from("profiles").select("email, name").eq("id",s.id).single();if(D)throw D;return I}}),v=((C=f==null?void 0:f.reply_to_email)==null?void 0:C.trim())||((E=g==null?void 0:g.email)==null?void 0:E.trim())||"",y=((P=f==null?void 0:f.display_name)==null?void 0:P.trim())||((M=g==null?void 0:g.name)==null?void 0:M.trim())||"";_.useEffect(()=>{c||(h(v),p(y))},[c,v,y]);const b=mt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const I={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(f){const{error:D}=await U.from("mass_email_settings").update(I).eq("user_id",s.id);if(D)throw D}else{const{error:D}=await U.from("mass_email_settings").insert({user_id:s.id,...I});if(D)throw D}},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]}),ne.success("Reply-to email saved!"),d(!1)},onError:I=>ne.error(I.message)}),w=!!v;return e.jsxs(be,{children:[e.jsx(_t,{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(Fr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:["Mass Email",w?e.jsxs(ze,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Xl,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(ze,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(En,{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(Le,{className:"space-y-3",children:[w&&!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:y||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Wa,{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(ee,{className:"text-xs",children:"Display Name"}),e.jsx(pe,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:I=>p(I.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(ee,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(pe,{type:"email",placeholder:"your@email.com",value:u,onChange:I=>h(I.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{size:"sm",onClick:()=>b.mutate(),disabled:b.isPending||!u.trim(),children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(v),p(y)},children:[e.jsx(er,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(fc,{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(Ch,{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($sr,{userId:s.id,onVerifiedSelect:I=>{h(I),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(fc,{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(Ch,{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(oas,{brokerageId:i})]})]})]})]})}function las(){var p,f,g,v,y,b;const{user:s,isAdmin:t}=hs(),n=$t(),r=Xtt(),a=Tqt(),i=Mqt(),[l,o]=_.useState(!1),c=!!((p=r.data)!=null&&p.connected),d=rt({queryKey:["canva-imports",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:w,error:S}=await U.from("canva_imports").select("id, workflow, design_title, format, pages, bucket, storage_paths, created_at").order("created_at",{ascending:!1}).limit(24);if(S)throw S;return w||[]}}),u=rt({queryKey:["canva-import-thumbs",(f=d.data)==null?void 0:f.map(w=>w.id).join()],enabled:!!((g=d.data)!=null&&g.length),queryFn:async()=>{const w={};return await Promise.all((d.data||[]).map(async S=>{if(S.format==="pdf"||!S.storage_paths[0]){w[S.id]=null;return}const{data:C}=await U.storage.from(S.bucket).createSignedUrl(S.storage_paths[0],3600,{transform:{width:400,resize:"contain"}});w[S.id]=(C==null?void 0:C.signedUrl)??null})),w}}),h=async w=>{for(const S of w.storage_paths){const{data:C}=await U.storage.from(w.bucket).createSignedUrl(S,300,{download:!0});C!=null&&C.signedUrl&&window.open(C.signedUrl,"_blank","noopener")}},m=mt({mutationFn:async w=>{w.workflow==="library"&&await U.storage.from(w.bucket).remove(w.storage_paths);const{error:S}=await U.from("canva_imports").delete().eq("id",w.id);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-imports"]}),ne.success("Removed from your Canva library")},onError:()=>ne.error("Couldn't remove that design")});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(be,{className:"border-primary/25 shadow-sm",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2 font-display text-xl",children:[e.jsx(yc,{className:"h-5 w-5 text-primary"}),"Canva"]}),e.jsx(En,{children:"Connect your own Canva account to bring finished designs into LevelUp. LevelUp can only view and export your designs — it can't change or delete anything in Canva. Editing happens in Canva."})]}),e.jsx(Le,{className:"space-y-3",children:r.isLoading?e.jsx(bt,{className:"h-5 w-5 animate-spin"}):r.data&&!r.data.configured?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Canva isn't set up for LevelUp yet. An admin needs to finish the Canva app setup."}):c?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ze,{variant:"secondary",children:["Connected",(v=r.data)!=null&&v.display_name?` as ${r.data.display_name}`:""]}),e.jsxs(z,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Ga,{className:"mr-1.5 h-4 w-4"}),"Import from Canva"]}),e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:"https://www.canva.com/",target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-1.5 h-4 w-4"}),"Design with Canva"]})}),t&&e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(or,{to:"/mission-control/direct-mail",children:[e.jsx(on,{className:"mr-1.5 h-4 w-4"}),"Mail Studio"]})}),t&&e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>a.mutate({client:"public"}),disabled:a.isPending,title:"Try the new Canva app connection — replaces only your own connection if you approve it",children:[a.isPending?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Z4,{className:"mr-1.5 h-4 w-4"}),"Test public Canva app"]}),e.jsxs(z,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>i.mutate(),disabled:i.isPending,children:[e.jsx(rE,{className:"mr-1.5 h-4 w-4"}),"Disconnect"]})]}):e.jsxs("div",{className:"space-y-2",children:[((y=r.data)==null?void 0:y.needs_reconnect)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Canva connection needs to be renewed."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(z,{onClick:()=>a.mutate({}),disabled:a.isPending,children:[a.isPending?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Oc,{className:"mr-1.5 h-4 w-4"}),"Connect Canva"]}),t&&e.jsxs(z,{variant:"outline",onClick:()=>a.mutate({client:"public"}),disabled:a.isPending,children:[a.isPending?e.jsx(bt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Z4,{className:"mr-1.5 h-4 w-4"}),"Test public Canva app"]})]}),t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Admins: "Test public Canva app" tries the new Canva app connection without affecting your current one.'})]})})]}),!!((b=d.data)!=null&&b.length)&&e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Designs saved from Canva"}),e.jsx(En,{children:"Permanent copies kept in LevelUp, even if you later change or delete them in Canva."})]}),e.jsx(Le,{className:"grid gap-3 sm:grid-cols-3",children:d.data.map(w=>{var S;return e.jsxs("div",{className:"overflow-hidden rounded-lg border",children:[(S=u.data)!=null&&S[w.id]?e.jsx("img",{src:u.data[w.id],alt:w.design_title||"Canva design",className:"h-28 w-full bg-muted object-contain"}):e.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-muted text-xs uppercase text-muted-foreground",children:w.format}),e.jsxs("div",{className:"space-y-1 p-2",children:[e.jsx("p",{className:"truncate text-xs font-medium",children:w.design_title||"Untitled design"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[w.workflow==="mail_studio"?"Mail Studio":"Library"," · ",w.pages.length," page",w.pages.length===1?"":"s"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{size:"sm",variant:"ghost",className:"h-7 px-2",onClick:()=>h(w),children:e.jsx(Ga,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"sm",variant:"ghost",className:"h-7 px-2 text-destructive",onClick:()=>m.mutate(w),disabled:m.isPending,children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})]},w.id)})})]}),e.jsx(Pqt,{open:l,onOpenChange:o,mode:"library",workflow:"library",onImported:w=>{ne.success(`Saved ${w.files.length} page${w.files.length===1?"":"s"} to LevelUp`)}})]})}function qsr({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}}const Vsr=[{id:"all",label:"All tools",icon:op},{id:"crm",label:"Real estate CRMs",icon:vy},{id:"social",label:"Social media",icon:sd},{id:"communication",label:"Communication",icon:on},{id:"marketing",label:"AI & marketing",icon:un}],Hsr={gmail:"Gmail","mass-email":"Mass Email",facebook:"Facebook",instagram:"Instagram",linkedin:"LinkedIn","google-business":"Google Business",boldtrail:"BoldTrail",lofty:"Lofty",followupboss:"Follow Up Boss",cloze:"Cloze",boomtown:"BoomTown",chatgpt:"ChatGPT",canva:"Canva",ses:"Amazon SES"};function Gsr({connected:s,label:t}){return s?e.jsxs(ze,{className:"border-0 bg-success/10 text-success hover:bg-success/10",children:[e.jsx("span",{className:"mr-1.5 h-1.5 w-1.5 rounded-full bg-success"}),"Connected"]}):e.jsx(ze,{variant:"outline",className:"text-muted-foreground",children:t||"Available"})}function a_({title:s,description:t,icon:n,connected:r,statusLabel:a,selected:i,onClick:l,badge:o}){return e.jsxs("button",{type:"button",onClick:l,className:`group flex min-h-36 w-full flex-col justify-between rounded-lg border bg-card p-4 text-left shadow-sm transition-[border-color,box-shadow,transform] duration-200 hover:-translate-y-0.5 hover:border-primary/45 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${i?"border-primary ring-1 ring-primary/20":"border-border"}`,children:[e.jsxs("div",{className:"flex w-full items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-md bg-primary/10 text-primary",children:n}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-1.5",children:[o&&e.jsx(ze,{variant:"secondary",className:"text-[10px] uppercase",children:o}),e.jsx(Gsr,{connected:r,label:a})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"font-display text-base font-semibold text-foreground",children:s}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground transition-transform duration-200 group-hover:translate-x-0.5 group-hover:text-primary"})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-sm leading-5 text-muted-foreground",children:t})]})]})}function Wsr(){const s=zn(),{isAdmin:t,user:n}=hs(),{actingAsAgent:r,effectiveUserId:a}=qre(),i=$t(),[l,o]=_.useState(!1),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState("all"),[v,y]=_.useState(null),{data:b}=Xtt(),{scopeUserId:w,isDelegated:S}=qsr({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:C,isLoading:E}=rt({queryKey:["gmail-integration",w],enabled:!!w&&!S,queryFn:async()=>{const{data:_e,error:Ae}=await U.from("gmail_integrations").select("*").eq("user_id",w).maybeSingle();if(Ae)throw Ae;return _e}}),{data:P}=rt({queryKey:["social-accounts",w],enabled:!!w&&!S,queryFn:async()=>{const{data:_e,error:Ae}=await U.from("social_accounts").select("*").eq("user_id",w).order("created_at",{ascending:!1});if(Ae)throw Ae;return _e}}),{data:M}=rt({queryKey:["google-business-status",w],enabled:!!w&&!S,queryFn:async()=>{const{data:_e,error:Ae}=await U.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(Ae)throw Ae;return _e}}),I=mt({mutationFn:async _e=>{const{error:Ae}=await U.functions.invoke("google-business-oauth",{body:{action:"set_primary_location",locationId:_e}});if(Ae)throw Ae},onSuccess:()=>{ne.success("Business updated"),i.invalidateQueries({queryKey:["google-business-status",w]}),i.invalidateQueries({queryKey:["social-accounts",w]})},onError:()=>ne.error("Could not update your business selection")}),D=mt({mutationFn:async()=>{const{error:_e}=await U.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(_e)throw _e},onSuccess:()=>{i.invalidateQueries({queryKey:["google-business-status",w]}),i.invalidateQueries({queryKey:["social-accounts",w]}),ne.success("Google Business disconnected")},onError:()=>ne.error("Could not disconnect Google Business")}),F=mt({mutationFn:async()=>{const{data:_e,error:Ae}=await U.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(Ae)throw Ae;return _e},onSuccess:_e=>{i.invalidateQueries({queryKey:["google-business-status",w]}),_e!=null&&_e.success&&_e.locationsCount?ne.success(_e.message??"Locations updated"):ne.error((_e==null?void 0:_e.message)??"No business locations were found on this Google account.")},onError:()=>ne.error("Could not check Google for your business")}),q=async()=>{if(S){ne.error("Account connections must be made by the agent from their own login.");return}p(!0);try{const{data:_e,error:Ae}=await U.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/mission-control/integrations"}});if(Ae)throw Ae;if(_e!=null&&_e.authUrl)window.location.href=_e.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(_e){console.error("Google Business OAuth error:",_e),ne.error("Failed to start Google connection. Please try again."),p(!1)}},G=async()=>{if(S){ne.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:_e,error:Ae}=await U.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(Ae)throw Ae;if(_e!=null&&_e.authUrl)window.location.href=_e.authUrl;else throw new Error("Failed to get authorization URL")}catch(_e){console.error("Gmail OAuth error:",_e),ne.error("Failed to start Gmail connection"),o(!1)}},V=async _e=>{if(S){ne.error("Account connections must be made by the agent from their own login.");return}d(!0);try{sessionStorage.setItem("social-connect-return-to",window.location.pathname);const{data:Ae,error:Se}=await U.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:_e}});if(Se)throw Se;if(Ae!=null&&Ae.authUrl)window.location.href=Ae.authUrl;else throw new Error("Failed to get authorization URL")}catch(Ae){console.error("Meta OAuth error:",Ae),ne.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},H=async()=>{if(S){ne.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:_e,error:Ae}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(Ae)throw Ae;if(_e!=null&&_e.authUrl)window.location.href=_e.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(_e){console.error("LinkedIn OAuth error:",_e),ne.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},K=mt({mutationFn:async _e=>{const{error:Ae}=await U.from("gmail_integrations").delete().eq("id",_e).eq("user_id",w);if(Ae)throw Ae},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",w]}),ne.success("Gmail disconnected")},onError:()=>{ne.error("Failed to disconnect Gmail")}}),Z=mt({mutationFn:async _e=>{const{error:Ae}=await U.from("social_accounts").delete().eq("id",_e).eq("user_id",w);if(Ae)throw Ae},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",w]}),ne.success("Account disconnected")},onError:()=>{ne.error("Failed to disconnect account")}}),oe=!S&&!!(C!=null&&C.is_active),re=(P==null?void 0:P.filter(_e=>_e.platform==="facebook"))||[],ae=(P==null?void 0:P.filter(_e=>_e.platform==="instagram"))||[],J=(P==null?void 0:P.filter(_e=>_e.platform==="linkedin"))||[],te=(P==null?void 0:P.filter(_e=>_e.platform==="google_business"))||[],{data:ce}=rt({queryKey:["mass-email-settings",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:_e,error:Ae}=await U.from("mass_email_settings").select("reply_to_email").eq("user_id",n==null?void 0:n.id).maybeSingle();if(Ae)throw Ae;return _e}}),ve=(_e,Ae)=>({queryKey:[_e],queryFn:async()=>{const{data:Se,error:We}=await U.functions.invoke(Ae,{body:{action:"status"}});if(We)throw We;return Se},staleTime:6e4}),{data:me}=rt(ve("boldtrail-status","boldtrail-sync")),{data:he}=rt(ve("lofty-status","lofty-sync")),{data:ge}=rt(ve("fub-status","followupboss-sync")),{data:Ee}=rt(ve("cloze-status","cloze-sync")),{data:Ne}=rt(ve("boomtown-status","boomtown-sync")),Pe=[oe,!!(ce!=null&&ce.reply_to_email),re.length>0,ae.length>0,J.length>0,!!(me!=null&&me.connected),!!(he!=null&&he.connected),!!(ge!=null&&ge.connected),!!(Ee!=null&&Ee.connected),!!(Ne!=null&&Ne.connected)].filter(Boolean).length,Oe=_e=>{y(Ae=>Ae===_e?null:_e)},ke=_e=>{const Ae=_e==="facebook"?re:_e==="instagram"?ae:J,Se=_e==="facebook"?of:_e==="instagram"?Fm:fg,We=_e==="facebook"?"Facebook":_e==="instagram"?"Instagram":"LinkedIn",qe=_e==="linkedin"?H:()=>V(_e),Be=_e==="linkedin"?u:c;return e.jsxs(be,{className:"border-primary/25 shadow-sm",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"font-display text-xl",children:["Manage ",We]}),e.jsx(En,{children:_e==="instagram"?"Connect a Business or Creator account. Personal Instagram accounts are not supported.":`Manage the ${We} account used for publishing LevelUp content.`})]}),e.jsxs(Le,{className:"space-y-3",children:[Ae.map(Ze=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(ja,{className:"h-9 w-9",children:[e.jsx(xi,{src:Ze.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Se,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Ze.page_name||Ze.platform_username||`${We} account`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":`Disconnect ${We}`,children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsxs(Ul,{children:["Disconnect ",We,"?"]}),e.jsx(ql,{children:"You will need to reconnect this account before publishing again."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>Z.mutate(Ze.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},Ze.id)),e.jsxs(z,{variant:"outline",onClick:qe,disabled:Be||S,children:[Be?e.jsx(Gi,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(sn,{className:"mr-2 h-4 w-4"}),Ae.length?`Add another ${We} account`:`Connect ${We}`]})]})]})},Ve=(()=>{var _e,Ae,Se;switch(v){case"gmail":return e.jsxs(be,{className:"border-primary/25 shadow-sm",children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"font-display text-xl",children:"Manage Gmail"}),e.jsx(En,{children:"Send personalized emails from contact pages and automatically record the activity."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:["Send from your Gmail account","Log email touchpoints","Compose from any contact"].map(Be=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-muted/25 p-3 text-sm",children:[e.jsx(Wr,{className:"mt-0.5 h-4 w-4 shrink-0 text-success"}),Be]},Be))}),oe?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:C.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"text-destructive",children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"}),"Disconnect"]})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Gmail?"}),e.jsx(ql,{children:"You will need to reconnect before sending emails from Gmail."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>K.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(z,{onClick:G,disabled:l||E||S,children:[l?e.jsx(Gi,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(on,{className:"mr-2 h-4 w-4"}),"Connect Gmail"]})]})]});case"mass-email":return e.jsx(Usr,{});case"canva":return e.jsx(las,{});case"facebook":return ke("facebook");case"instagram":return ke("instagram");case"linkedin":return ke("linkedin");case"google-business":const We=(M==null?void 0:M.connected)===!0,qe=((_e=M==null?void 0:M.locations)==null?void 0:_e.find(Be=>Be.is_primary))??((Ae=M==null?void 0:M.locations)==null?void 0:Ae[0]);return e.jsxs(be,{className:"border-primary/25 shadow-sm",children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"font-display text-xl",children:"Google Business Profile"}),e.jsx(En,{children:"Post updates and manage reviews from your Google Business Profile."})]}),e.jsxs(Le,{className:"space-y-3",children:[(M==null?void 0:M.needsReconnect)&&We&&e.jsx("div",{className:"rounded-md border border-warning/40 bg-warning/10 p-3 text-sm",children:"We upgraded our Google connection. Please reconnect once so posting and reviews keep working."}),We&&e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/20 p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:(qe==null?void 0:qe.location_name)||(M==null?void 0:M.email)||"Google Business"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":"Disconnect Google Business",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Google Business?"}),e.jsx(ql,{children:"You will need to reconnect before posting or syncing reviews again."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>D.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),(((Se=M==null?void 0:M.locations)==null?void 0:Se.length)??0)>1&&e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which business should we use?"}),M.locations.map(Be=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-sm",children:Be.location_name||Be.location_id}),Be.is_primary?e.jsx(ze,{className:"shrink-0 text-xs",children:"Active"}):e.jsx(z,{size:"sm",variant:"outline",className:"shrink-0",disabled:I.isPending,onClick:()=>I.mutate(Be.location_id),children:"Use this"})]},Be.id))]}),We&&(M==null?void 0:M.missingBusinessScope)&&e.jsxs("div",{className:"rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800",children:["Google signed you in, but didn't give LevelUp access to your Business Profile. Click Reconnect below and make sure the",e.jsx("strong",{children:" Business Profile "})," checkbox is ticked on Google's permission screen."]}),We&&!(M!=null&&M.missingBusinessScope)&&(M==null?void 0:M.apiAccessPending)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800",children:[e.jsxs("p",{children:["We couldn't find a business listing on ",(M==null?void 0:M.email)||"this Google account",". Make sure you signed in with the Google account that manages your Business Profile, then check again."]}),e.jsxs(z,{size:"sm",variant:"outline",disabled:F.isPending,onClick:()=>F.mutate(),children:[F.isPending?e.jsx(Gi,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Gi,{className:"mr-2 h-4 w-4"}),"Check again"]})]}),e.jsxs(z,{variant:We&&!(M!=null&&M.needsReconnect)?"outline":"default",onClick:q,disabled:m||S,children:[m?e.jsx(Gi,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(sn,{className:"mr-2 h-4 w-4"}),We?"Reconnect Google Business":"Connect Google Business"]})]})]});case"boldtrail":return e.jsx(Lsr,{});case"lofty":return e.jsx(Isr,{});case"followupboss":return e.jsx(Dsr,{});case"cloze":return e.jsx(Rsr,{});case"boomtown":return e.jsx(Osr,{});case"chatgpt":return e.jsxs(be,{className:"border-primary/25 shadow-sm",children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"font-display text-xl",children:"ChatGPT"}),e.jsx(En,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]}),e.jsx(Le,{children:e.jsxs(z,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Da,{className:"ml-2 h-4 w-4"})]})})]});case"ses":return t?e.jsx(ias,{}):null;default:return null}})();return e.jsx($s,{children:e.jsxs("div",{className:"integrations-hub mx-auto max-w-7xl animate-fade-in px-4 py-5 sm:px-6 lg:px-8",children:[e.jsxs("header",{className:"flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase text-primary",children:"Connected workspace"}),e.jsx("h1",{className:"font-display text-3xl font-semibold text-foreground sm:text-4xl",children:"Integrations"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm text-muted-foreground sm:text-base",children:"Connect the services that power your communication, marketing, and contact workflows."})]}),e.jsxs(ze,{variant:"outline",className:"w-fit gap-2 border-primary/25 bg-card px-3 py-1.5 text-sm text-foreground",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-success"}),Pe," services active"]})]}),S&&e.jsx(be,{className:"mt-5 border-warning/40 bg-warning/5",children:e.jsxs(_t,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(Hl,{className:"mt-0.5 h-5 w-5 text-warning"}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(En,{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("div",{className:"mt-6 grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)]",children:[e.jsx("nav",{"aria-label":"Integration categories",className:"min-w-0",children:e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2 lg:sticky lg:top-5 lg:flex-col lg:overflow-visible",children:Vsr.map(_e=>{const Ae=_e.icon,Se=f===_e.id;return e.jsxs(z,{variant:Se?"secondary":"ghost",className:`shrink-0 justify-start gap-2 ${Se?"text-primary":"text-muted-foreground"}`,onClick:()=>{g(_e.id),y(null)},children:[e.jsx(Ae,{className:"h-4 w-4"}),_e.label]},_e.id)})})}),e.jsxs("main",{className:"min-w-0 space-y-8",children:[(f==="all"||f==="communication")&&e.jsxs("section",{"aria-labelledby":"email-connections",children:[e.jsxs("div",{className:"mb-3 flex items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"email-connections",className:"font-display text-xl font-semibold",children:"Email connections"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Your highest-priority tools for individual and campaign email."})]}),e.jsxs(ze,{variant:"secondary",className:"hidden sm:flex",children:[e.jsx(Nh,{className:"mr-1.5 h-3.5 w-3.5"}),"Priority"]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(a_,{title:"Gmail",description:"Send personal emails and automatically log each touchpoint.",icon:e.jsx(on,{className:"h-5 w-5"}),connected:oe,selected:v==="gmail",onClick:()=>Oe("gmail"),badge:"Priority"}),e.jsx(a_,{title:"Mass Email",description:"Send polished campaigns from a verified sender address.",icon:e.jsx(Fr,{className:"h-5 w-5"}),connected:!!(ce!=null&&ce.reply_to_email),statusLabel:"Setup required",selected:v==="mass-email",onClick:()=>Oe("mass-email"),badge:"Priority"})]})]}),(f==="all"||f==="crm")&&e.jsxs("section",{"aria-labelledby":"crm-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"crm-connections",className:"font-display text-xl font-semibold",children:"Real estate CRMs"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Bring contacts into LevelUp and control how they stay synchronized."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(a_,{title:"BoldTrail",description:"Sync contacts, ownership, tags, notes, and lead details.",icon:e.jsx(vy,{className:"h-5 w-5"}),connected:me==null?void 0:me.connected,selected:v==="boldtrail",onClick:()=>Oe("boldtrail")}),e.jsx(a_,{title:"Lofty",description:"Connect Lofty contacts and control sync direction.",icon:e.jsx(vy,{className:"h-5 w-5"}),connected:he==null?void 0:he.connected,selected:v==="lofty",onClick:()=>Oe("lofty")}),e.jsx(a_,{title:"Follow Up Boss",description:"Keep Follow Up Boss contacts aligned with LevelUp.",icon:e.jsx(vy,{className:"h-5 w-5"}),connected:ge==null?void 0:ge.connected,selected:v==="followupboss",onClick:()=>Oe("followupboss")}),e.jsx(a_,{title:"Cloze",description:"Sync contacts from your Cloze account or selected segments.",icon:e.jsx(vy,{className:"h-5 w-5"}),connected:Ee==null?void 0:Ee.connected,selected:v==="cloze",onClick:()=>Oe("cloze")}),e.jsx(a_,{title:"BoomTown",description:"Import and synchronize your BoomTown contact database.",icon:e.jsx(vy,{className:"h-5 w-5"}),connected:Ne==null?void 0:Ne.connected,selected:v==="boomtown",onClick:()=>Oe("boomtown")})]})]}),(f==="all"||f==="social")&&e.jsxs("section",{"aria-labelledby":"social-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"social-connections",className:"font-display text-xl font-semibold",children:"Social media"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Connect the profiles and pages used by Social Studio."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(a_,{title:"Facebook",description:"Publish to your connected Facebook Pages.",icon:e.jsx(of,{className:"h-5 w-5"}),connected:re.length>0,selected:v==="facebook",onClick:()=>Oe("facebook")}),e.jsx(a_,{title:"Instagram",description:"Schedule content to a Business or Creator account.",icon:e.jsx(Fm,{className:"h-5 w-5"}),connected:ae.length>0,selected:v==="instagram",onClick:()=>Oe("instagram")}),e.jsx(a_,{title:"LinkedIn",description:"Share content with your professional network.",icon:e.jsx(fg,{className:"h-5 w-5"}),connected:J.length>0,selected:v==="linkedin",onClick:()=>Oe("linkedin")}),e.jsx(a_,{title:"Google Business",description:"Post updates and manage reviews on your Google Business Profile.",icon:e.jsx(oi,{className:"h-5 w-5"}),connected:te.length>0&&!(M!=null&&M.needsReconnect),statusLabel:M!=null&&M.needsReconnect?"Reconnect":void 0,selected:v==="google-business",onClick:()=>Oe("google-business")})]})]}),(f==="all"||f==="marketing")&&e.jsxs("section",{"aria-labelledby":"marketing-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"marketing-connections",className:"font-display text-xl font-semibold",children:"AI & marketing"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Extend LevelUp with AI tools and managed delivery services."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(a_,{title:"Canva",description:"Bring your own Canva designs into Mail Studio and your LevelUp library.",icon:e.jsx(yc,{className:"h-5 w-5"}),connected:!!(b!=null&&b.connected),statusLabel:b!=null&&b.needs_reconnect?"Reconnect":void 0,selected:v==="canva",onClick:()=>Oe("canva")}),e.jsx(a_,{title:"ChatGPT",description:"Use your LevelUp tools directly from ChatGPT.",icon:e.jsx(K4,{className:"h-5 w-5"}),statusLabel:"View setup",selected:v==="chatgpt",onClick:()=>Oe("chatgpt")}),t&&e.jsx(a_,{title:"Amazon SES",description:"Manage the platform-level mass email delivery service.",icon:e.jsx(vS,{className:"h-5 w-5"}),statusLabel:"Admin only",badge:"Admin",selected:v==="ses",onClick:()=>Oe("ses")})]})]})]})]}),e.jsx(Wg,{open:v!==null,onOpenChange:_e=>{_e||y(null)},children:e.jsxs(gg,{side:"right",className:"integrations-hub w-full overflow-y-auto border-l bg-background p-0 sm:max-w-2xl lg:max-w-3xl [&>button]:z-20",children:[e.jsxs(Dy,{className:"sticky top-0 z-10 border-b bg-background px-5 py-5 pr-12 text-left sm:px-7",children:[e.jsxs(Ry,{className:"font-display text-xl",children:[v?Hsr[v]:"Integration"," settings"]}),e.jsx(Z9,{children:"Review the connection and update its settings here."})]}),e.jsx("div",{className:"p-4 sm:p-7",children:Ve})]})})]})})}const Ksr="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function Ysr(){const[s,t]=_.useState(null),[n,r]=_.useState(!1),[a,i]=_.useState(0),[l,o]=_.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 y=new Uint8Array(await v.slice(0,4).arrayBuffer());return y[0]===80&&y[1]===75&&y[2]===3&&y[3]===4||y[0]===80&&y[1]===75&&y[2]===5&&y[3]===6||y[0]===80&&y[1]===75&&y[2]===7&&y[3]===8},m=v=>{const y=document.createElement("a");y.href=v,y.download="levelup-extension.zip",y.rel="noopener noreferrer",y.target="_blank",document.body.appendChild(y),y.click(),y.remove()},p=async()=>{o(!0);try{if(u){m(`${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 y=await v.blob();if(!await h(y)){m(`${d}?v=${Date.now()}`);return}const b=new Blob([y],{type:"application/zip"}),w=URL.createObjectURL(b),S=document.createElement("a");S.href=w,S.download="levelup-extension.zip",document.body.appendChild(S),S.click(),S.remove(),setTimeout(()=>URL.revokeObjectURL(w),1e3)}catch(v){ne.error(v.message||"Download failed")}finally{o(!1)}},f=async()=>{r(!0);try{await U.auth.refreshSession();const{data:v}=await U.auth.getSession();if(!v.session){ne.error("Your session has expired. Please sign in again.");return}const{data:y,error:b}=await U.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${v.session.access_token}`}});if(b)throw b;t(y.code),i(y.expires_in||300);const w=setInterval(()=>{i(S=>S<=1?(clearInterval(w),t(null),0):S-1)},1e3)}catch(v){console.error("generateCode error",v),ne.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)}},g=()=>{s&&(navigator.clipboard.writeText(s),ne.success("Copied"))};return e.jsx($s,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(dl,{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(t7,{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(be,{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(z,{size:"lg",className:"w-full",onClick:()=>window.open(Ksr,"_blank","noopener,noreferrer"),children:[e.jsx(t7,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(mr,{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(be,{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(z,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(Sa,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(z,{onClick:f,variant:"outline",className:"flex-1",children:[e.jsx(Gi,{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(Wr,{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(z,{onClick:f,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Gi,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(be,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sh,{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(z,{variant:"link",className:"h-auto p-0 text-sm",onClick:p,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function Zsr(){const[s]=Gl(),t=zn(),[n,r]=_.useState("loading"),[a,i]=_.useState("Connecting your Gmail account...");return _.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"),ne.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ne.error("No authorization code received");return}try{const{data:h,error:m}=await U.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),ne.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"),ne.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(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{className:"text-center",children:[n==="loading"&&e.jsx(bt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Xl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Bd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Nt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(En,{children:a})]}),e.jsx(Le,{className:"flex justify-center",children:n!=="loading"&&e.jsx(z,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function Xsr(){const s=zn();return _.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 Qsr(){const[s]=Gl(),t=zn(),[n,r]=_.useState("loading"),a=_.useRef(!1),[i,l]=_.useState("Processing your connection...");return _.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var m;const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),ne.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ne.error("No authorization code received");return}try{const{data:p,error:f}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(f){let g=f.message||"Failed to connect accounts";try{const v=f.context;if(v&&typeof v.json=="function"){const y=await v.json();y!=null&&y.error&&(g=y.error)}}catch{}throw new Error(g)}if(p!=null&&p.success)r("success"),l(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),ne.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),l(p instanceof Error?p.message:"Failed to connect accounts"),ne.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(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{className:"text-center",children:[n==="loading"&&e.jsx(bt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Xl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Bd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Nt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(En,{children:i})]}),e.jsx(Le,{className:"flex justify-center",children:n!=="loading"&&e.jsx(z,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const cas=new Date().getFullYear(),Jsr=Array.from({length:5},(s,t)=>cas-t);function enr(){const[s,t]=_.useState(cas),n=zn(),{data:r,isLoading:a}=YUs();return a?e.jsx($s,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(ln,{className:"h-24"},i))}),e.jsx(ln,{className:"h-96"})]})}):e.jsx($s,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(ls,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(rs,{className:"w-[120px]",children:e.jsx(cs,{})}),e.jsx(as,{children:Jsr.map(i=>e.jsx(He,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(On,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Agents with Scorecards"}),e.jsx(En,{children:"Click to view individual agent scorecards"})]}),e.jsx(Le,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(wl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:r.map(i=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:i.name}),e.jsx(yt,{className:"text-muted-foreground",children:i.email}),e.jsx(yt,{className:"text-right",children:e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const tnr="00000000-0000-0000-0000-000000000000",snr=s=>{if(!s)return"—";const[t,n,r]=s.split(/[-/T]/);return`${n}/${r}/${t}`};function nnr(s){if(s.total_agents===0)return{label:"Empty",className:"bg-muted text-muted-foreground"};const t=s.active_90d/s.total_agents;return t>=.4?{label:"Healthy",className:"bg-emerald-100 text-emerald-800"}:t>=.15?{label:"At risk",className:"bg-amber-100 text-amber-800"}:{label:"Dormant",className:"bg-red-100 text-red-800"}}const rnr={never_started:"Never started",signed_in_empty:"Signed in, empty",started:"Started, gone quiet",active:"Active"};function anr(){const s=$t(),[t,n]=_.useState(null),[r,a]=_.useState(""),[i,l]=_.useState(null),{data:o=[]}=rt({queryKey:["agent-activation-settings"],queryFn:async()=>{const{data:S,error:C}=await U.from("agent_activation_settings").select("*");if(C)throw C;return S}}),{data:c=[],isLoading:d}=rt({queryKey:["brokerage-adoption-stats"],queryFn:async()=>{const{data:S,error:C}=await U.rpc("get_brokerage_adoption_stats");if(C)throw C;return S}}),{data:u}=rt({queryKey:["agent-activation-metrics"],refetchInterval:6e4,queryFn:async()=>{const S=async D=>{const{count:F}=await D(U.from("agent_activation_sends").select("id",{count:"exact",head:!0}));return F??0},[C,E,P]=await Promise.all([S(D=>D.eq("status","sent")),S(D=>D.not("opened_at","is",null)),S(D=>D.not("clicked_at","is",null))]),{count:M}=await U.from("agent_activation_state").select("user_id",{count:"exact",head:!0}),{count:I}=await U.from("agent_activation_state").select("user_id",{count:"exact",head:!0}).eq("exit_reason","active");return{sent:C,opened:E,clicked:P,inSequence:M??0,activated:I??0}}}),h=o.find(S=>S.brokerage_id===null),m=!!(h!=null&&h.enabled),p=S=>o.find(C=>C.brokerage_id===S),f=mt({mutationFn:async({brokerageId:S,enabled:C})=>{const{data:E}=await U.from("agent_activation_settings").select("id").eq("brokerage_id",S??tnr).maybeSingle();let P=E;if(S===null){const{data:M}=await U.from("agent_activation_settings").select("id").is("brokerage_id",null).maybeSingle();P=M}if(P){const{error:M}=await U.from("agent_activation_settings").update({enabled:C,updated_at:new Date().toISOString()}).eq("id",P.id);if(M)throw M}else{const{error:M}=await U.from("agent_activation_settings").insert({brokerage_id:S,enabled:C});if(M)throw M}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-activation-settings"]}),ne.success("Setting saved")},onError:()=>ne.error("Could not save setting")}),g=mt({mutationFn:async S=>{const{data:C,error:E}=await U.functions.invoke("agent-activation-run",{body:{action:"preview",step:S,brokerage_name:t==null?void 0:t.brokerage_name}});if(E)throw E;return C},onSuccess:l,onError:()=>ne.error("Preview failed")}),v=mt({mutationFn:async S=>{const{data:C,error:E}=await U.functions.invoke("agent-activation-run",{body:{action:"test_send",step:S,brokerage_name:t==null?void 0:t.brokerage_name}});if(E)throw E;if(C!=null&&C.error)throw new Error(C.error);return C},onSuccess:S=>ne.success(`Test email sent to ${S.sent_to}`),onError:S=>ne.error(S.message||"Test send failed")}),y=c.filter(S=>S.brokerage_name.toLowerCase().includes(r.toLowerCase())),b=u!=null&&u.sent?Math.round(u.opened/u.sent*100):0,w=u!=null&&u.sent?Math.round(u.clicked/u.sent*100):0;return e.jsx($s,{title:"Agent Activation",children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6 max-w-7xl",children:[t?e.jsxs("div",{className:"space-y-4",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",onClick:()=>n(null),children:[e.jsx(Wc,{className:"h-4 w-4"}),"Back to all brokerages"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:t.brokerage_name}),e.jsx("p",{className:"text-muted-foreground",children:"Agent Activation · manage this brokerage's agents and sequence."})]})]}):e.jsx(Xh,{title:"Agent Activation",description:"Find dormant agents and walk them into the product with a branded email sequence. Nothing sends until you turn it on."}),e.jsx("div",{className:"grid gap-4 grid-cols-2 lg:grid-cols-5",children:[{label:"Emails sent",value:(u==null?void 0:u.sent)??0,hint:"across all brokerages"},{label:"Opened",value:(u==null?void 0:u.opened)??0,hint:`${b}% open rate`},{label:"Clicked",value:(u==null?void 0:u.clicked)??0,hint:`${w}% click rate`},{label:"Agents in sequence",value:(u==null?void 0:u.inSequence)??0,hint:"currently receiving"},{label:"Activated",value:(u==null?void 0:u.activated)??0,hint:"signed in and working"}].map(S=>e.jsx(be,{children:e.jsxs(Le,{className:"pt-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:S.label}),e.jsx("div",{className:"text-2xl font-bold",children:S.value.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.hint})]})},S.label))}),e.jsx(be,{className:m?"border-emerald-300":"border-amber-300",children:e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(pm,{className:"h-5 w-5"}),"Master switch"]}),e.jsx(En,{children:m?"Activation emails are LIVE for brokerages you enable below.":"OFF worldwide. No activation emails can be sent to anyone."})]}),e.jsx(mn,{checked:m,onCheckedChange:S=>f.mutate({brokerageId:null,enabled:S})})]})})}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"text-lg flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"})," The sequence"]}),e.jsx(En,{children:"Five emails, all sent from LevelUp. Preview any step or send a test to yourself."})]}),e.jsx(Le,{className:"flex flex-wrap gap-2",children:[1,2,3,4,5].map(S=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>g.mutate(S),disabled:g.isPending,children:[e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"})," Step ",S]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>v.mutate(S),disabled:v.isPending,title:"Send test to my email",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})})]},S))})]}),t?e.jsx(inr,{brokerage:t,settings:p(t.brokerage_id),masterOn:m,onBack:()=>n(null),onToggle:S=>f.mutate({brokerageId:t.brokerage_id,enabled:S})}):e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Brokerage adoption"}),e.jsx(En,{children:"Select a brokerage to manage agents and enable the sequence."})]}),e.jsx(pe,{placeholder:"Search brokerages…",value:r,onChange:S=>a(S.target.value),className:"max-w-xs"})]})}),e.jsx(Le,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Health"}),e.jsx(Tt,{className:"text-right",children:"Agents"}),e.jsx(Tt,{className:"text-right",children:"Never in"}),e.jsx(Tt,{className:"text-right",children:"Active 90d"}),e.jsx(Tt,{className:"text-right",children:"With data"}),e.jsx(Tt,{className:"text-right",children:"Activation"})]})}),e.jsx(Qa,{children:y.map(S=>{var P;const C=nnr(S),E=!!((P=p(S.brokerage_id))!=null&&P.enabled);return e.jsxs(fn,{className:"cursor-pointer",onClick:()=>n(S),children:[e.jsx(yt,{className:"font-medium",children:S.brokerage_name}),e.jsx(yt,{children:e.jsx(ze,{variant:"secondary",className:C.className,children:C.label})}),e.jsx(yt,{className:"text-right",children:S.total_agents}),e.jsx(yt,{className:"text-right",children:S.never_logged_in}),e.jsx(yt,{className:"text-right",children:S.active_90d}),e.jsx(yt,{className:"text-right",children:S.with_contacts+S.with_deals>0?`${S.with_contacts}`:0}),e.jsx(yt,{className:"text-right",children:e.jsx(ze,{variant:E?"default":"outline",children:E?"On":"Off"})})]},S.brokerage_id)})})]})})]}),e.jsx(Is,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:i==null?void 0:i.subject}),e.jsx(_r,{children:"Exactly as the agent will receive it."})]}),i&&e.jsx("iframe",{title:"Email preview",sandbox:"",srcDoc:i.html,className:"w-full h-[560px] rounded-md border"})]})})]})})}function inr({brokerage:s,settings:t,masterOn:n,onBack:r,onToggle:a}){const i=$t(),[l,o]=_.useState(""),{data:c=[],isLoading:d}=rt({queryKey:["brokerage-agent-activation",s.brokerage_id],queryFn:async()=>{const{data:g,error:v}=await U.rpc("get_brokerage_agent_activation",{_brokerage_id:s.brokerage_id});if(v)throw v;return g}}),u=mt({mutationFn:async({userId:g,skip:v})=>{if(v){const{error:y}=await U.from("agent_activation_state").upsert({user_id:g,brokerage_id:s.brokerage_id,exited_at:new Date().toISOString(),exit_reason:"manual_skip",updated_at:new Date().toISOString()},{onConflict:"user_id"});if(y)throw y}else{const{error:y}=await U.from("agent_activation_state").update({exited_at:null,exit_reason:null,updated_at:new Date().toISOString()}).eq("user_id",g);if(y)throw y}},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),ne.success("Agent updated")},onError:()=>ne.error("Update failed")}),h=mt({mutationFn:async g=>{const{data:v,error:y}=await U.functions.invoke("agent-activation-run",{body:{action:"send_now",user_id:g,brokerage_id:s.brokerage_id}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),ne.success("Email sent")},onError:g=>ne.error(g.message||"Send failed")}),m=!!(t!=null&&t.enabled),p=m&&n,f=c.filter(g=>(g.name||"").toLowerCase().includes(l.toLowerCase())||(g.email||"").toLowerCase().includes(l.toLowerCase()));return e.jsxs(be,{children:[e.jsxs(_t,{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(z,{variant:"ghost",size:"sm",onClick:r,children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:s.brokerage_name}),e.jsxs(En,{children:[s.total_agents," agents · ",s.never_logged_in," never logged in ·"," ",s.active_90d," active in 90 days"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:p?"Sequence LIVE for this brokerage":n?"Off for this brokerage":"Master switch is off"}),e.jsx(mn,{checked:m,onCheckedChange:a})]})]}),e.jsx("div",{className:"pt-2",children:e.jsx(pe,{placeholder:"Search agents…",value:l,onChange:g=>o(g.target.value),className:"max-w-xs"})})]}),e.jsx(Le,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Stage"}),e.jsx(Tt,{className:"text-right",children:"Logins"}),e.jsx(Tt,{children:"Last login"}),e.jsx(Tt,{className:"text-right",children:"Contacts"}),e.jsx(Tt,{className:"text-right",children:"Deals"}),e.jsx(Tt,{className:"text-right",children:"Step"}),e.jsx(Tt,{className:"text-right",children:"Emails"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:f.map(g=>{const v=g.exit_reason==="manual_skip";return e.jsxs(fn,{children:[e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:g.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]}),e.jsx(yt,{children:e.jsx(ze,{variant:g.stage==="active"?"default":"secondary",children:v?"Skipped":rnr[g.stage]})}),e.jsx(yt,{className:"text-right",children:g.login_count}),e.jsx(yt,{children:snr(g.last_login)}),e.jsx(yt,{className:"text-right",children:g.contact_count}),e.jsx(yt,{className:"text-right",children:g.deal_count}),e.jsxs(yt,{className:"text-right",children:[g.step,"/5"]}),e.jsx(yt,{className:"text-right",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[g.last_opened_at?e.jsx(l7,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(on,{className:"h-3.5 w-3.5 text-muted-foreground"}),g.emails_sent]})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"sm",disabled:!p||!!g.exited_at||h.isPending,onClick:()=>h.mutate(g.user_id),title:"Send the next step now",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>u.mutate({userId:g.user_id,skip:!v}),title:v?"Include in sequence":"Skip this agent",children:e.jsx(_q,{className:`h-3.5 w-3.5 ${v?"text-red-500":""}`})})]})})]},g.user_id)})})]})})]})}const das=new Date().getFullYear(),onr=Array.from({length:10},(s,t)=>das-t);function U4t(){var g;const{userId:s}=Mi(),t=zn(),r=Pd().pathname.startsWith("/mission-control"),[a,i]=_.useState(das),{data:l,isLoading:o}=rt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:v,error:y}=await U.from("profiles").select("id, name, email").eq("id",s).single();if(y)throw y;return v},enabled:!!s}),{data:c,isLoading:d}=Ket(a,s),{yearStats:u,lifetimeStats:h,isLoading:m,showCommission:p}=kBt(a,s),{data:f}=NBt(a,s);return o?e.jsx($s,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(v=>e.jsx(ln,{className:"h-24"},v))})]})}):e.jsx($s,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(ka,{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(ls,{value:String(a),onValueChange:v=>i(Number(v)),children:[e.jsx(rs,{className:"w-[120px]",children:e.jsx(cs,{})}),e.jsx(as,{children:onr.map(v=>e.jsx(He,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(sa,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(On,{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(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lm(u.totalVolume,!0)})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{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:lm(u.averagePrice,!0)})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Kh,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((g=u.topLeadSource)==null?void 0:g.name)||"-"})]})})]}),f&&e.jsx(Nss,{goals:f,stats:u,year:a,showCommission:p}),e.jsxs(Qr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"transactions",children:"Transactions"}),e.jsx(Wt,{value:"charts",children:"Charts"}),e.jsxs(Wt,{value:"map",children:[e.jsx(Ha,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Kt,{value:"transactions",children:e.jsx(Tat,{transactions:c||[],showCommission:p,isLoading:d})}),e.jsx(Kt,{value:"charts",children:e.jsx(Mat,{stats:u,year:a})}),e.jsx(Kt,{value:"map",children:e.jsx(Pat,{transactions:c||[],isLoading:d})})]})]})})}function lnr(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState("all"),[i,l]=_.useState(null);Wre();const{data:o,refetch:c}=rt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:I}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(I==null?void 0:I.enabled)??!1}}),{data:d,isLoading:u}=rt({queryKey:["admin-listings"],queryFn:async()=>{const{data:I,error:D}=await U.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(D)throw D;return I}}),{data:h}=rt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:I}=await U.from("listings").select("id, is_approved, status"),{data:D}=await U.from("listing_shares").select("id"),{data:F}=await U.from("listing_views").select("id"),{count:q}=await U.from("listing_leads").select("id",{count:"exact",head:!0}),G=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:V}=await U.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",G);return{total:(I==null?void 0:I.length)||0,pending:(I==null?void 0:I.filter(H=>!H.is_approved).length)||0,active:(I==null?void 0:I.filter(H=>H.status==="active").length)||0,totalShares:(D==null?void 0:D.length)||0,totalViews:(F==null?void 0:F.length)||0,totalLeads:q||0,leadsLast7:V||0}}}),{data:m}=rt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const I={};let D=0;const F=1e3;for(;;){const{data:q,error:G}=await U.from("listing_leads").select("listing_id").range(D,D+F-1);if(G)throw G;if(!q||q.length===0)break;for(const V of q)V.listing_id&&(I[V.listing_id]=(I[V.listing_id]||0)+1);if(q.length{const{data:I,error:D}=await U.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(D)throw D;return I}}),g=async(I,D,F="submit_url")=>{try{const{data:{session:q}}=await U.auth.getSession();if(!q)return;const{data:G,error:V}=await U.functions.invoke("google-indexing",{body:{action:F,listing_id:I,listing_slug:D}});if(V)throw V;if((G==null?void 0:G.configured)===!1)return;G!=null&&G.success&&ne.success("Submitted to Google for indexing")}catch(q){console.error("Google indexing submission failed:",q)}},v=mt({mutationFn:async()=>{const{data:{session:I}}=await U.auth.getSession();if(!I)throw new Error("Not authenticated");const{data:D,error:F}=await U.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(F)throw F;return D},onSuccess:I=>{if((I==null?void 0:I.configured)===!1){ne.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ne.success(`Submitted ${(I==null?void 0:I.succeeded)||0} URLs to Google (${(I==null?void 0:I.failed)||0} failed)`)},onError:I=>{ne.error("Failed to submit to Google"),console.error(I)}}),y=mt({mutationFn:async({id:I,approved:D,slug:F})=>{const{error:q}=await U.from("listings").update({is_approved:D}).eq("id",I);if(q)throw q;return{id:I,approved:D,slug:F}},onSuccess:I=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ne.success(I.approved?"Listing approved":"Listing unapproved"),I.approved?g(I.id,I.slug||null,"submit_url"):g(I.id,I.slug||null,"remove_url")}}),b=mt({mutationFn:async({id:I,featured:D})=>{const{error:F}=await U.from("listings").update({is_featured:D}).eq("id",I);if(F)throw F},onSuccess:(I,{featured:D})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ne.success(D?"Listing featured":"Listing unfeatured")}}),w=mt({mutationFn:async I=>{const{error:D}=await U.from("listings").delete().eq("id",I);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ne.success("Listing deleted")}}),S=mt({mutationFn:async I=>{const{error:D}=await U.from("feature_flags").update({enabled:I}).eq("key","listing_exchange_enabled");if(D)throw D},onSuccess:()=>{c(),ne.success("Feature flag updated")}}),C=o??!1,E=d==null?void 0:d.filter(I=>{var q,G,V,H;const D=((q=I.city)==null?void 0:q.toLowerCase().includes(t.toLowerCase()))||((V=(G=I.agent)==null?void 0:G.name)==null?void 0:V.toLowerCase().includes(t.toLowerCase()))||((H=I.property_address)==null?void 0:H.toLowerCase().includes(t.toLowerCase())),F=r==="all"||r==="pending"&&!I.is_approved||r==="approved"&&I.is_approved;return D&&F}),P=I=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(I),M=I=>{const D={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 D[I]||D.active};return e.jsxs($s,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending,className:"gap-2",children:[v.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wo,{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(mn,{checked:C,onCheckedChange:I=>S.mutate(I)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oi,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kl,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sd,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(h==null?void 0:h.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(be,{children:e.jsx(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by city, address, or agent...",value:t,onChange:I=>n(I.target.value),className:"pl-9"})]}),e.jsx(Qr,{value:r,onValueChange:I=>a(I),children:e.jsxs(Jr,{children:[e.jsx(Wt,{value:"all",children:"All"}),e.jsx(Wt,{value:"pending",children:"Pending"}),e.jsx(Wt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{children:["Listings (",(E==null?void 0:E.length)||0,")"]})}),e.jsx(Le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Price"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-center",children:"Approved"}),e.jsx(Tt,{className:"text-center",children:"Featured"}),e.jsx(Tt,{children:"Views"}),e.jsx(Tt,{children:"Shares"}),e.jsx(Tt,{children:"Leads"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{})]})}),e.jsx(Qa,{children:u?e.jsx(fn,{children:e.jsx(yt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(E==null?void 0:E.length)===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):E==null?void 0:E.map(I=>{var D,F,q,G,V;return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(F=(D=I.photos)==null?void 0:D[0])!=null&&F.photo_url?e.jsx("img",{src:I.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(oi,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:I.property_address||`${I.city}, ${I.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(q=I.property_type)==null?void 0:q.replace("_"," ")})]})]})}),e.jsx(yt,{children:e.jsx("p",{className:"text-sm",children:((G=I.agent)==null?void 0:G.name)||"Unknown"})}),e.jsx(yt,{className:"font-medium",children:P(I.price)}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",className:M(I.status),children:(V=I.status)==null?void 0:V.replace("_"," ")})}),e.jsx(yt,{className:"text-center",children:e.jsx(mn,{checked:I.is_approved??!1,onCheckedChange:H=>y.mutate({id:I.id,approved:H,slug:I.slug})})}),e.jsx(yt,{className:"text-center",children:e.jsx(mn,{checked:I.is_featured??!1,onCheckedChange:H=>b.mutate({id:I.id,featured:H})})}),e.jsx(yt,{children:I.view_count||0}),e.jsx(yt,{children:I.share_count||0}),e.jsx(yt,{children:((m==null?void 0:m[I.id])??0)>0?e.jsx(z,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:I.id,label:I.property_address||`${I.city}, ${I.state}`}),children:m==null?void 0:m[I.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Ys(new Date(I.created_at),"MMM d, yyyy")}),e.jsx(yt,{children:e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",children:e.jsx(lb,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onClick:()=>window.open(`/mission-control/listings/${I.id}`,"_blank"),children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(ua,{onClick:()=>b.mutate({id:I.id,featured:!I.is_featured}),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),I.is_featured?"Unfeature":"Feature"]}),e.jsxs(ua,{className:"text-destructive",onClick:async()=>{await Qi("Are you sure you want to delete this listing?")&&w.mutate(I.id)},children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},I.id)})})]})})})]})]}),e.jsx(Is,{open:!!i,onOpenChange:I=>!I&&l(null),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Leads from listing"}),e.jsx(_r,{children:i==null?void 0:i.label})]}),f?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(bt,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!p||p.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Captured"})]})}),e.jsx(Qa,{children:p.map(I=>{var D;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:[I.first_name,I.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(yt,{children:I.email}),e.jsx(yt,{children:I.phone||"—"}),e.jsx(yt,{children:e.jsx(ze,{variant:"outline",children:(D=I.lead_type)==null?void 0:D.replace("_"," ")})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:Ys(new Date(I.created_at),"MMM d, yyyy h:mm a")})]},I.id)})})]})]})})]})}function cnr(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function dnr(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),{data:l,isLoading:o}=rt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const p=1e3;for(;;){const{data:f,error:g}=await U.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(m,m+p-1);if(g)throw g;if(!f||f.length===0||(h.push(...f),f.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(p=>{var g,v,y,b,w,S;return h&&new Date(p.created_at).getTime(){const h=c.length,m=c.filter(g=>g.lead_type==="showing_request").length,p=new Set(c.map(g=>g.agent_id)).size,f=new Set(c.map(g=>g.listing_id)).size;return{total:h,showings:m,uniqueAgents:p,uniqueListings:f}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(v=>{var y,b,w,S,C,E;return[Ys(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||""}`:"",((y=v.listing)==null?void 0:y.property_address)||"",((b=v.listing)==null?void 0:b.city)||"",(w=v.listing)!=null&&w.price?String(v.listing.price):"",((S=v.agent)==null?void 0:S.name)||"",((C=v.agent)==null?void 0:C.email)||"",((E=v.referrer)==null?void 0:E.name)||"",(v.message||"").replace(/[\r\n]+/g," ")]})].map(v=>v.map(y=>`"${String(y).replace(/"/g,'""')}"`).join(",")).join(` `),p=new Blob([m],{type:"text/csv"}),f=URL.createObjectURL(p),g=document.createElement("a");g.href=f,g.download=`listing-leads-${Ys(new Date,"yyyy-MM-dd")}.csv`,g.click(),URL.revokeObjectURL(f)};return e.jsx($s,{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(z,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(Ga,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.total})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{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(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Agents w/ Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueAgents})]})})]}),e.jsx(be,{children:e.jsx(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:a,onValueChange:h=>i(h),children:[e.jsx(rs,{className:"w-full sm:w-48",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Types"}),e.jsx(He,{value:"info_request",children:"Info Request"}),e.jsx(He,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(ls,{value:n,onValueChange:h=>r(h),children:[e.jsx(rs,{className:"w-full sm:w-40",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Time"}),e.jsx(He,{value:"7",children:"Last 7 days"}),e.jsx(He,{value:"30",children:"Last 30 days"}),e.jsx(He,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{children:["Leads (",c.length,")"]})}),e.jsx(Le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Lead"}),e.jsx(Tt,{children:"Contact"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Assigned To"}),e.jsx(Tt,{children:"Referred By"}),e.jsx(Tt,{children:"Message"})]})}),e.jsx(Qa,{children:o?e.jsx(fn,{children:e.jsx(yt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,p;return e.jsxs(fn,{children:[e.jsxs(yt,{className:"whitespace-nowrap text-sm",children:[Ys(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(h.created_at),"h:mm a")})]}),e.jsx(yt,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(yt,{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(on,{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(va,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(yt,{children:h.listing?e.jsxs(or,{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(mr,{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(", ")," · ",cnr(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(yt,{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(yt,{children:[e.jsx("div",{className:"text-sm font-medium",children:((m=h.agent)==null?void 0:m.name)||"—"}),((p=h.agent)==null?void 0:p.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(yt,{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(yt,{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(qi,{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 c$={new_listing_alerts:{label:"New Listing Alerts",icon:$g,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:o7,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:Fo,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Rr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:ip,color:"bg-emerald-100 text-emerald-800"}},q4t=[{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 V4t(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function unr(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState("30d"),[l,o]=_.useState("all"),[c,d]=_.useState("");_.useEffect(()=>{let p=!1;return(async()=>{r(!0);let f=U.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const g=q4t.find(b=>b.key===a);if(g&&g.days>0){const b=new Date(Date.now()-g.days*864e5).toISOString();f=f.gte("created_at",b)}const{data:v,error:y}=await f;p||(y?(console.error(y),t([])):t(v||[]),r(!1))})(),()=>{p=!0}},[a]);const u=_.useMemo(()=>s.filter(p=>{if(l!=="all"&&p.lead_type!==l)return!1;if(c){const f=c.toLowerCase();if(![p.email,p.first_name,p.last_name,p.phone,p.source_page,p.referrer].filter(Boolean).join(" ").toLowerCase().includes(f))return!1}return!0}),[s,l,c]),h=_.useMemo(()=>{const p=u.length,f=new Set(u.map(v=>v.email.toLowerCase())).size,g={};return u.forEach(v=>{g[v.lead_type]=(g[v.lead_type]||0)+1}),{total:p,uniqueEmails:f,byType:g}},[u]),m=()=>{const f=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var S;const w=[V4t(b.created_at),((S=c$[b.lead_type])==null?void 0:S.label)||b.lead_type,b.email,b.first_name||"",b.last_name||"",b.phone||"",b.listing_id||"",b.source_page||"",b.referrer||"",b.criteria?JSON.stringify(b.criteria):""].map(C=>`"${String(C).replace(/"/g,'""')}"`);f.push(w.join(","))});const g=new Blob([f.join(` `)],{type:"text/csv"}),v=URL.createObjectURL(g),y=document.createElement("a");y.href=v,y.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,y.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(dl,{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(or,{to:"/admin",children:e.jsxs(z,{variant:"ghost",size:"sm",children:[e.jsx(ka,{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(z,{onClick:m,variant:"outline",size:"sm",children:[e.jsx(Ga,{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(be,{children:e.jsxs(Le,{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(c$).map(p=>{const f=c$[p],g=f.icon;return e.jsx(be,{children:e.jsxs(Le,{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(g,{className:"h-3.5 w-3.5"}),f.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[p]||0})]})},p)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ls,{value:a,onValueChange:p=>i(p),children:[e.jsx(rs,{className:"w-[160px] bg-white",children:e.jsx(cs,{})}),e.jsx(as,{children:q4t.map(p=>e.jsx(He,{value:p.key,children:p.label},p.key))})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-[200px] bg-white",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All lead types"}),Object.keys(c$).map(p=>e.jsx(He,{value:p,children:c$[p].label},p))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(pe,{placeholder:"Search name, email, phone…",value:c,onChange:p=>d(p.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(be,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(p=>{const f=c$[p.lead_type],g=f==null?void 0:f.icon,v=[p.first_name,p.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:V4t(p.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(ze,{className:`${(f==null?void 0:f.color)||""} font-normal`,variant:"secondary",children:[g?e.jsx(g,{className:"h-3 w-3 mr-1"}):null,(f==null?void 0:f.label)||p.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:${p.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),p.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:p.phone?e.jsxs("a",{href:`tel:${p.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),p.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[p.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[p.listing_id.slice(0,8),"…"]})]}),p.criteria&&Object.keys(p.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(p.criteria).map(([y,b])=>`${y}: ${b}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[p.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(mr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p.source_page})]}),p.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",p.referrer]})]})]},p.id)})})]})})})]})]})}const hnr=()=>{var h,m;const[s,t]=_.useState(""),[n,r]=_.useState(null),{data:a,isLoading:i}=rt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:p,error:f}=await U.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(f)throw f;const g=(p==null?void 0:p.map(b=>b.user_id))||[],{data:v}=await U.from("profiles").select("id, name, email").in("id",g);return p==null?void 0:p.map(b=>({...b,profiles:(v==null?void 0:v.find(w=>w.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(p=>{var g,v,y,b,w;const f=s.toLowerCase();return((v=(g=p.profiles)==null?void 0:g.name)==null?void 0:v.toLowerCase().includes(f))||((b=(y=p.profiles)==null?void 0:y.email)==null?void 0:b.toLowerCase().includes(f))||((w=p.review_text)==null?void 0:w.toLowerCase().includes(f))}),o=a!=null&&a.length?(a.reduce((p,f)=>p+f.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((p,f)=>(p[f.rating]=(p[f.rating]||0)+1,p),{}),d=(a==null?void 0:a.filter(p=>p.posted_to_google).length)||0,u=p=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(f=>e.jsx(Ia,{className:Ct("h-4 w-4",p>=f?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},f))});return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Total Reviews"}),e.jsx(Nt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Average Rating"}),e.jsxs(Nt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Ia,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"5-Star Reviews"}),e.jsx(Nt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(be,{children:e.jsxs(_t,{className:"pb-2",children:[e.jsx(En,{children:"Posted to Google"}),e.jsxs(Nt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(mr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or review...",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Rating"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Tt,{children:"Google"}),e.jsx(Tt,{children:"Date"})]})}),e.jsx(Qa,{children:i?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(p=>{var f,g;return e.jsxs(fn,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(p),children:[e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((f=p.profiles)==null?void 0:f.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(g=p.profiles)==null?void 0:g.email})]})}),e.jsx(yt,{children:u(p.rating)}),e.jsx(yt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:p.review_text||"-"})}),e.jsx(yt,{children:p.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(yt,{className:"text-sm text-muted-foreground",children:Ys(new Date(p.created_at),"MMM d, yyyy")})]},p.id)})})]})})}),e.jsx(Is,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(on,{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(ya,{className:"h-4 w-4"}),Ys(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(mr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(ze,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},H4t={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},mnr={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 pnr(){const[s,t]=_.useState(""),[n,r]=_.useState("all"),[a,i]=_.useState("all"),[l,o]=_.useState("7"),{data:c,isLoading:d}=rt({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:p,error:f}=await U.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(f)throw f;return p||[]}}),u=_.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(p=>n!=="all"&&p.source!==n||a!=="all"&&p.status!==a?!1:m?[p.agent_name,p.agent_email,p.lead_name,p.lead_email,p.lead_phone,p.subject].some(f=>(f||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=_.useMemo(()=>{const m=u.length,p=u.filter(v=>v.status==="sent"||v.status==="backfilled").length,f=u.filter(v=>v.status==="failed").length,g=new Set(u.map(v=>v.agent_user_id).filter(Boolean)).size;return{total:m,sent:p,failed:f,agents:g}},[u]);return e.jsx($s,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Xh,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:n,onValueChange:r,children:[e.jsx(rs,{className:"w-full md:w-48",children:e.jsx(cs,{placeholder:"Source"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Sources"}),Object.entries(H4t).map(([m,p])=>e.jsx(He,{value:m,children:p},m))]})]}),e.jsxs(ls,{value:a,onValueChange:i,children:[e.jsx(rs,{className:"w-full md:w-40",children:e.jsx(cs,{placeholder:"Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Statuses"}),e.jsx(He,{value:"sent",children:"Sent"}),e.jsx(He,{value:"backfilled",children:"Backfilled"}),e.jsx(He,{value:"failed",children:"Failed"})]})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-full md:w-36",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"1",children:"Last 24h"}),e.jsx(He,{value:"7",children:"Last 7 days"}),e.jsx(He,{value:"14",children:"Last 14 days"}),e.jsx(He,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"When"}),e.jsx(Tt,{children:"Source"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Lead"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(Qa,{children:d?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(m=>e.jsxs(fn,{children:[e.jsx(yt,{className:"whitespace-nowrap text-sm",children:Ys(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(yt,{children:e.jsx(ze,{variant:"secondary",children:H4t[m.source]||m.source})}),e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:m.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.agent_email||"—"})]}),e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:m.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[m.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(yt,{children:[e.jsx(ze,{className:mnr[m.status]||"",children:m.status}),m.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:m.error_message,children:m.error_message})]})]},m.id))})]})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Historical entries (before this feature was enabled) are marked as ",e.jsx("em",{children:"backfilled"})," and reconstructed from the underlying lead records. New leads are logged automatically going forward."]})]})})}const fnr=[{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"}],xnr=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 gnr(){const s=$t(),{user:t}=hs(),[n,r]=_.useState(!1),[a,i]=_.useState(!1),[l,o]=_.useState(!1),{data:c,isLoading:d}=rt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:I}=await U.from("weekly_digest_settings").select("*").single();if(I)throw I;return M}}),{data:u,isLoading:h}=rt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:I}=await U.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(I)throw I;return M}}),{data:m}=rt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:I}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(I)throw I;return M||0}}),{data:p,refetch:f}=rt({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[I,D,F,q]=await Promise.all([U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",M.toISOString())]);return{pending:I.count||0,processing:D.count||0,sent:F.count||0,failed:q.count||0,total:(I.count||0)+(D.count||0)+(F.count||0)+(q.count||0)}},refetchInterval:5e3});_.useEffect(()=>{if(p&&(p.pending>0||p.processing>0)){const M=setInterval(()=>{f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(M)}},[p,f,s]);const{data:g=0}=rt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:I,error:D}=await U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString());if(D)throw D;return I||0}}),v=mt({mutationFn:async M=>{const{error:I}=await U.from("weekly_digest_settings").update(M).eq("id",c==null?void 0:c.id);if(I)throw I},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ne.success("Settings updated")},onError:M=>{ne.error("Failed to update settings: "+M.message)}}),y=async()=>{r(!0);try{const{data:M,error:I}=await U.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(I)throw I;M.queued?ne.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&ne.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){ne.error("Failed to send digest: "+M.message)}finally{r(!1)}},b=async()=>{var M,I,D,F,q,G;if(!(t!=null&&t.email)){ne.error("No email found for your account");return}i(!0);try{const{data:V,error:H}=await U.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(H)throw H;const K=V==null?void 0:V.resendId,Z=V==null?void 0:V.resendDetails,oe=Z==null?void 0:Z.status,re=((M=Z==null?void 0:Z.body)==null?void 0:M.status)||((D=(I=Z==null?void 0:Z.body)==null?void 0:I.data)==null?void 0:D.status),ae=((q=(F=Z==null?void 0:Z.body)==null?void 0:F.error)==null?void 0:q.message)||((G=Z==null?void 0:Z.body)==null?void 0:G.message);ne.success(K?`Preview accepted by email provider (id: ${K})${oe?`, status check: ${oe}`:""}${re?`, provider: ${re}`:""}${ae?` (${ae})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(V){ne.error("Failed to send preview: "+V.message)}finally{i(!1)}},w=async()=>{o(!0);try{const{data:M,error:I}=await U.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(I)throw I;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?ne.info("No failed emails to retry"):M.queued?ne.success(`${M.queued} emails queued for retry!`):ne.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),f(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){ne.error("Failed to retry: "+M.message)}finally{o(!1)}},S=p!=null&&p.total?Math.round((p.sent+p.failed)/p.total*100):0,C=((p==null?void 0:p.pending)||0)>0||((p==null?void 0:p.processing)||0)>0,{data:E}=rt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var G,V;const M=new Date;M.setUTCHours(0,0,0,0);const[I,D,F,q]=await Promise.all([U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),U.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:I.count||0,totalFailed:D.count||0,agentOsEngaged:F.count||0,lastSent:((V=(G=q.data)==null?void 0:G[0])==null?void 0:V.sent_at)||null}},refetchInterval:C?5e3:!1}),P={totalSent:(E==null?void 0:E.totalSent)||0,totalFailed:(E==null?void 0:E.totalFailed)||0,lastSent:E==null?void 0:E.lastSent,agentOsEngaged:(E==null?void 0:E.agentOsEngaged)||0};return d?e.jsx($s,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):e.jsx($s,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(Qr,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Gc,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Wt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Kt,{value:"settings",className:"space-y-6",children:[C&&p&&e.jsx(be,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(bt,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[p.sent.toLocaleString()," sent, ",p.pending.toLocaleString()," pending",p.failed>0&&`, ${p.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[S,"%"]})]}),e.jsx(Di,{value:S,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(p.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsx(Le,{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(On,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(be,{children:e.jsx(Le,{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(Mr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(be,{children:e.jsx(Le,{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(Bd,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(be,{children:e.jsx(Le,{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(Zr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.lastSent?Ys(new Date(P.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(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(En,{children:"Configure when the digest is sent"})]}),e.jsxs(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(mn,{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(ee,{children:"Cron Frequency"}),e.jsxs(ls,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>v.mutate({cron_frequency:M}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(He,{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(ee,{children:"Day of Week"}),e.jsxs(ls,{value:String(c==null?void 0:c.send_day),onValueChange:M=>v.mutate({send_day:parseInt(M)}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:fnr.map(M=>e.jsx(He,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Time (UTC)"}),e.jsxs(ls,{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(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:xnr.map(M=>e.jsx(He,{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(z,{onClick:b,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(xa,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(z,{onClick:y,disabled:n,className:"flex-1",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),g>0&&e.jsxs(z,{onClick:w,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Gi,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${g} Failed`]})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(En,{children:"Choose what to include in the digest"})]}),e.jsxs(Le,{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($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"New Resources"})]}),e.jsx(mn,{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(On,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Community Highlights"})]}),e.jsx(mn,{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(wl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Agent OS Stats"})]}),e.jsx(mn,{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(ya,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Upcoming Events"})]}),e.jsx(mn,{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(bu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Goals Progress"})]}),e.jsx(mn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>v.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Custom Introduction"}),e.jsx(En,{children:"Personalize the intro message (optional)"})]}),e.jsx(Le,{children:e.jsx(Ps,{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(Kt,{value:"stats",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(En,{children:"Recent digest emails sent to members"})]}),e.jsx(Le,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Sent At"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Agent OS"})]})}),e.jsx(Qa,{children:u.map(M=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:M.email_sent_to}),e.jsx(yt,{children:Ys(new Date(M.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(yt,{children:e.jsx(ze,{variant:M.delivery_status==="sent"?"default":"destructive",children:M.delivery_status})}),e.jsx(yt,{children:M.resources_count}),e.jsx(yt,{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(on,{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 ynr={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 vnr(){var te,ce,ve;const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(null),[i,l]=_.useState(!1),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(!0),[g,v]=_.useState(!1),[y,b]=_.useState(""),[w,S]=_.useState(null),{data:C,isLoading:E}=rt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:me,error:he}=await U.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(he)throw he;const ge=(me==null?void 0:me.map(Pe=>Pe.user_id))||[],{data:Ee}=await U.from("profiles").select("id, name, email").in("id",ge),Ne=new Map((Ee==null?void 0:Ee.map(Pe=>[Pe.id,{name:Pe.name,email:Pe.email}]))||[]);return me==null?void 0:me.map(Pe=>({...Pe,profile:Ne.get(Pe.user_id)||null}))}}),{data:P}=rt({queryKey:["all-profiles-for-points",C],queryFn:async()=>{const he=[];let ge=0;for(;;){const{data:Ee,error:Ne}=await U.from("profiles").select("id, name, email").order("name").range(ge,ge+1e3-1);if(Ne)throw Ne;if(he.push(...Ee),!Ee||Ee.length<1e3)break;ge+=1e3}return he}}),I=((P==null?void 0:P.filter(me=>!(C!=null&&C.some(he=>he.user_id===me.id))))||[]).filter(me=>{var ge,Ee;if(!y)return!0;const he=y.toLowerCase();return((ge=me.name)==null?void 0:ge.toLowerCase().includes(he))||((Ee=me.email)==null?void 0:Ee.toLowerCase().includes(he))}),{data:D,isLoading:F}=rt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:me,error:he}=await U.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(he)throw he;return me},enabled:!!(r!=null&&r.user_id)&&o}),{data:q}=rt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:me,error:he}=await U.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(he)throw he;return me},enabled:!!(r!=null&&r.user_id)}),G=mt({mutationFn:async({userId:me,points:he,reason:ge})=>{const{error:Ee}=await U.from("agent_points").insert({user_id:me,points:he,reason:ge});if(Ee)throw Ee;const{data:Ne}=await U.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",me).maybeSingle(),Pe=((Ne==null?void 0:Ne.total_points)||0)+he,Oe=((Ne==null?void 0:Ne.spendable_points)||0)+he,{error:ke}=await U.from("agent_attendance_stats").upsert({user_id:me,total_points:Math.max(0,Pe),spendable_points:Math.max(0,Oe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ke)throw ke},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),ne.success(p?"Points awarded successfully!":"Points deducted successfully!")},onError:me=>{console.error("Error modifying points:",me),ne.error("Failed to modify points")}}),V=()=>{if(!r||!d||!h){ne.error("Please fill in all fields");return}const me=parseInt(d);if(isNaN(me)||me<=0){ne.error("Please enter a valid positive number");return}G.mutate({userId:r.user_id,points:p?me:-me,reason:h})},H=()=>{if(!w||!d||!h){ne.error("Please fill in all fields");return}const me=parseInt(d);if(isNaN(me)||me<=0){ne.error("Please enter a valid positive number");return}G.mutate({userId:w.id,points:me,reason:h},{onSuccess:()=>{v(!1),S(null),b("")}})},K=(me,he)=>{a(me),f(he),l(!0)},Z=me=>{a(me),c(!0)},oe=C==null?void 0:C.filter(me=>{var Ne,Pe,Oe,ke;const he=((Pe=(Ne=me.profile)==null?void 0:Ne.name)==null?void 0:Pe.toLowerCase())||"",ge=((ke=(Oe=me.profile)==null?void 0:Oe.email)==null?void 0:ke.toLowerCase())||"",Ee=t.toLowerCase();return he.includes(Ee)||ge.includes(Ee)}),re=(C==null?void 0:C.reduce((me,he)=>me+he.total_points,0))||0,ae=(C==null?void 0:C.length)||0,J=ae>0?Math.round(re/ae):0;return E?e.jsx($s,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(me=>e.jsx(ln,{className:"h-24"},me))}),e.jsx(ln,{className:"h-96"})]})}):e.jsx($s,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(On,{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:ae}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(jl,{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:re.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{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:J}),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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:t,onChange:me=>n(me.target.value),className:"pl-10"})]}),e.jsxs(z,{onClick:()=>v(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Agent Leaderboard"}),e.jsx(En,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Le,{children:!oe||oe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(jl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Total Points"}),e.jsx(Tt,{className:"text-center",children:"Spendable"}),e.jsx(Tt,{className:"text-center",children:"Events"}),e.jsx(Tt,{className:"text-center",children:"Streak"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:oe.map((me,he)=>{var ge,Ee,Ne,Pe;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:he<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${he===0?"bg-yellow-100 text-yellow-700":he===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:he+1}):e.jsx("span",{className:"text-muted-foreground",children:he+1})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{children:((Ee=(ge=me.profile)==null?void 0:ge.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ne=me.profile)==null?void 0:Ne.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Pe=me.profile)==null?void 0:Pe.email})]})]})}),e.jsx(yt,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1"}),me.total_points]})}),e.jsx(yt,{className:"text-center",children:e.jsxs(ze,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Ko,{className:"h-3 w-3 mr-1"}),me.spendable_points||0]})}),e.jsx(yt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3 text-muted-foreground"}),me.total_events_attended]})}),e.jsx(yt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(vu,{className:"h-3 w-3 text-orange-500"}),me.current_streak]})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>K(me,!0),title:"Award points",children:e.jsx(sn,{className:"h-4 w-4 text-green-600"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>K(me,!1),title:"Deduct points",children:e.jsx(gN,{className:"h-4 w-4 text-red-600"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>Z(me),title:"View history",children:e.jsx(O_,{className:"h-4 w-4"})})]})})]},me.user_id)})})]})})]}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:p?"Award Points":"Deduct Points"}),e.jsxs(_r,{children:[p?"Award":"Deduct"," points ",p?"to":"from"," ",((te=r==null?void 0:r.profile)==null?void 0:te.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"points",children:"Points Amount"}),e.jsx(pe,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:me=>u(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"reason",children:"Reason"}),e.jsx(Ps,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:me=>m(me.target.value)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(z,{onClick:V,disabled:G.isPending,className:p?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:G.isPending?"Saving...":p?"Award Points":"Deduct Points"})]})]})}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:["Point History: ",(ce=r==null?void 0:r.profile)==null?void 0:ce.name]}),e.jsx(_r,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(Qr,{defaultValue:"history",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-2",children:[e.jsx(Wt,{value:"history",children:"Point History"}),e.jsx(Wt,{value:"badges",children:"Badges"})]}),e.jsx(Kt,{value:"history",className:"mt-4",children:F?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(me=>e.jsx(ln,{className:"h-12"},me))}):!D||D.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(O_,{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:D.map(me=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:me.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ys(new Date(me.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ze,{variant:me.points>=0?"default":"destructive",className:me.points>=0?"bg-green-100 text-green-800":"",children:[me.points>=0?"+":"",me.points]})]},me.id))})}),e.jsx(Kt,{value:"badges",className:"mt-4",children:!q||q.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Kh,{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:q.map(me=>e.jsxs("div",{className:`p-3 rounded-lg ${ynr[me.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kh,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:me.badge_name})]}),me.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:me.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Ys(new Date(me.earned_at),"MMM d, yyyy")]})]},me.id))})})]})]})}),e.jsx(Is,{open:g,onOpenChange:me=>{v(me),me||(S(null),b(""),u(""),m(""))},children:e.jsxs(Ls,{className:"max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Award Points to New Agent"}),e.jsx(_r,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(ja,{className:"h-10 w-10",children:e.jsx(Na,{children:((ve=w.name)==null?void 0:ve.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:w.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:w.email})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>S(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(pe,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:me=>u(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ps,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:me=>m(me.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:y,onChange:me=>b(me.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:I.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(On,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:y?"No matching agents found":"All agents already have points"})]}):I.slice(0,20).map(me=>{var he;return e.jsxs("button",{onClick:()=>S(me),className:"w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 text-left",children:[e.jsx(ja,{className:"h-8 w-8",children:e.jsx(Na,{children:((he=me.name)==null?void 0:he.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:me.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:me.email})]})]},me.id)})})]})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),w&&e.jsxs(z,{onClick:H,disabled:G.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function bnr(){const{data:s,isLoading:t}=WMs(),[n,r]=_.useState(null),[a,i]=_.useState(!1),[l,o]=_.useState(""),[c,d]=_.useState("all"),[u,h]=_.useState("newest"),[m,p]=_.useState("table"),f=_.useMemo(()=>(s==null?void 0:s.map(w=>w.user_id))||[],[s]),g=_.useMemo(()=>(s==null?void 0:s.map(w=>w.id))||[],[s]),{data:v}=rt({queryKey:["card-profiles-lookup",f],queryFn:async()=>{if(f.length===0)return{};const{data:w}=await U.from("profiles").select("id, name, email").in("id",f),S={};return w==null||w.forEach(C=>{S[C.id]={name:C.name||"",email:C.email||""}}),S},enabled:f.length>0}),{data:y}=rt({queryKey:["card-stats-all",g],queryFn:async()=>{if(g.length===0)return{};const w={};g.forEach(E=>{w[E]={views:0,leads:0}});const{data:S}=await U.from("agent_card_interactions").select("card_id").in("card_id",g).eq("interaction_type","card_view");S==null||S.forEach(E=>{w[E.card_id]&&w[E.card_id].views++});const{data:C}=await U.from("agent_card_leads").select("card_id").in("card_id",g);return C==null||C.forEach(E=>{w[E.card_id]&&w[E.card_id].leads++}),w},enabled:g.length>0}),b=_.useMemo(()=>{if(!s)return[];let w=[...s];if(c==="live"?w=w.filter(S=>S.is_published):c==="draft"&&(w=w.filter(S=>!S.is_published)),l.trim()){const S=l.toLowerCase();w=w.filter(C=>{var P,M;const E=v==null?void 0:v[C.user_id];return C.slug.toLowerCase().includes(S)||((P=E==null?void 0:E.name)==null?void 0:P.toLowerCase().includes(S))||((M=E==null?void 0:E.email)==null?void 0:M.toLowerCase().includes(S))})}return u==="newest"?w.sort((S,C)=>new Date(C.created_at).getTime()-new Date(S.created_at).getTime()):u==="oldest"?w.sort((S,C)=>new Date(S.created_at).getTime()-new Date(C.created_at).getTime()):u==="name"?w.sort((S,C)=>{var E,P;return(((E=v==null?void 0:v[S.user_id])==null?void 0:E.name)||"").localeCompare(((P=v==null?void 0:v[C.user_id])==null?void 0:P.name)||"")}):u==="slug"?w.sort((S,C)=>S.slug.localeCompare(C.slug)):u==="views_desc"?w.sort((S,C)=>{var E,P;return(((E=y==null?void 0:y[C.id])==null?void 0:E.views)||0)-(((P=y==null?void 0:y[S.id])==null?void 0:P.views)||0)}):u==="views_asc"?w.sort((S,C)=>{var E,P;return(((E=y==null?void 0:y[S.id])==null?void 0:E.views)||0)-(((P=y==null?void 0:y[C.id])==null?void 0:P.views)||0)}):u==="leads_desc"?w.sort((S,C)=>{var E,P;return(((E=y==null?void 0:y[C.id])==null?void 0:E.leads)||0)-(((P=y==null?void 0:y[S.id])==null?void 0:P.leads)||0)}):u==="leads_asc"&&w.sort((S,C)=>{var E,P;return(((E=y==null?void 0:y[S.id])==null?void 0:E.leads)||0)-(((P=y==null?void 0:y[C.id])==null?void 0:P.leads)||0)}),w},[s,c,l,u,v]);return e.jsxs($s,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(z,{onClick:()=>i(!0),children:[e.jsx(sn,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or slug...",value:l,onChange:w=>o(w.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:c,onValueChange:d,children:[e.jsx(rs,{className:"w-full sm:w-36",children:e.jsx(cs,{placeholder:"Status"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All Status"}),e.jsx(He,{value:"live",children:"Live"}),e.jsx(He,{value:"draft",children:"Draft"})]})]}),e.jsxs(ls,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"w-full sm:w-44",children:e.jsx(cs,{placeholder:"Sort by"})}),e.jsxs(as,{children:[e.jsx(He,{value:"newest",children:"Newest First"}),e.jsx(He,{value:"oldest",children:"Oldest First"}),e.jsx(He,{value:"name",children:"Name A–Z"}),e.jsx(He,{value:"slug",children:"Slug A–Z"}),e.jsx(He,{value:"views_desc",children:"Most Views"}),e.jsx(He,{value:"views_asc",children:"Fewest Views"}),e.jsx(He,{value:"leads_desc",children:"Most Leads"}),e.jsx(He,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(z,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>p("table"),className:"rounded-r-none",children:e.jsx(pq,{className:"h-4 w-4"})}),e.jsx(z,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>p("grid"),className:"rounded-l-none",children:e.jsx(op,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",b.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(w=>e.jsx(ln,{className:"h-48"},w))}):b.length>0?m==="table"?e.jsx(_nr,{cards:b,cardProfiles:v,cardStats:y,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:b.map(w=>e.jsx(wnr,{card:w,onEdit:()=>r(w),stats:y==null?void 0:y[w.id]},w.id))}):s&&s.length>0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Rr,{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(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(On,{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(z,{onClick:()=>i(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(jnr,{open:a,onOpenChange:i}),n&&e.jsx(Nnr,{card:n,open:!!n,onOpenChange:w=>!w&&r(null)})]})}function _nr({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(Vf,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(ap,{className:"h-3 w-3"}):e.jsx(Og,{className:"h-3 w-3 opacity-40"});return e.jsx(be,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:e.jsxs("button",{onClick:()=>{i(a==="name"?"newest":"name")},className:"flex items-center gap-1 hover:text-foreground text-muted-foreground",children:["Agent ",a==="name"&&e.jsx(ap,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],u=n==null?void 0:n[c.id],h=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(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(z,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),ne.success("Link copied!")},children:e.jsx(Sa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{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(mr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function wnr({card:s,onEdit:t,stats:n}){const[r,a]=_.useState(null);_.useEffect(()=>{(async()=>{const{data:c}=await U.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await U.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=U.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),ne.success("Link copied!")};return e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(Na,{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(xa,{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(On,{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(z,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(z,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Sa,{className:"h-3 w-3"})}),e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(mr,{className:"h-3 w-3"})})})]})]})})}function jnr({open:s,onOpenChange:t}){const[n,r]=_.useState(""),[a,i]=_.useState(""),[l,o]=_.useState(""),[c,d]=_.useState(!1),u=hOt(),h=l.trim(),{data:m}=rt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let b=U.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(b=b.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:w}=await b;return w||[]},enabled:s}),[p,f]=_.useState(null),g=(m==null?void 0:m.find(b=>b.id===n))||p,v=()=>{if(!n||!a.trim()){ne.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("")}})},y=b=>{var S;r(b),d(!1);const w=m==null?void 0:m.find(C=>C.id===b);w&&(f(w),i(((S=w.name)==null?void 0:S.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create Agent Card"}),e.jsx(_r,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Agent"}),e.jsxs(hd,{open:c,onOpenChange:d,children:[e.jsx(md,{asChild:!0,children:e.jsxs(z,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[g?`${g.name} (${g.email})`:"Search for an agent...",e.jsx(R_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(nd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Ij,{shouldFilter:!1,children:[e.jsx(Dj,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(Rj,{children:[e.jsx(Fj,{children:"No agents found."}),e.jsx(G_,{children:(m||[]).map(b=>e.jsxs(c1,{value:b.id,onSelect:y,children:[e.jsx(Wr,{className:Ct("mr-2 h-4 w-4",n===b.id?"opacity-100":"opacity-0")}),b.name," (",b.email,")"]},b.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:a,onChange:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx(z,{onClick:v,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function Nnr({card:s,open:t,onOpenChange:n}){const r=mOt(),{data:a}=pOt(s.id),i=$t(),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(!1),[m,p]=_.useState(""),[f,g]=_.useState(s.slug),[v,y]=_.useState(!1),[b,w]=_.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});_.useEffect(()=>{t&&(async()=>{try{const{data:D}=await U.storage.from("avatars").list(`${s.user_id}`);if(D&&D.length>0){const{data:F}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${D[0].name}`);o(`${F.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const S=I=>{var q;const D=(q=I.target.files)==null?void 0:q[0];if(!D)return;if(!D.type.startsWith("image/")){ne.error("Please select an image file");return}if(D.size>5*1024*1024){ne.error("Image must be under 5MB");return}const F=new FileReader;F.onloadend=()=>{p(F.result),h(!0)},F.readAsDataURL(D),I.target.value=""},C=async I=>{d(!0);try{const{data:D}=await U.storage.from("avatars").list(`${s.user_id}`);D&&D.length>0&&await U.storage.from("avatars").remove(D.map(H=>`${s.user_id}/${H.name}`));const F=`${s.user_id}/avatar.jpg`,{error:q}=await U.storage.from("avatars").upload(F,I,{upsert:!0,contentType:"image/jpeg"});if(q)throw q;const{data:G}=U.storage.from("avatars").getPublicUrl(F),V=`${G.publicUrl}?t=${Date.now()}`;o(V),await U.from("profiles").update({avatar_url:V}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ne.success("Photo updated!")}catch(D){ne.error(D.message||"Upload failed")}finally{d(!1)}},E=async()=>{const I=f.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!I){ne.error("Please enter a valid URL");return}if(I===s.slug){ne.info("No changes to save");return}y(!0);try{const{data:D}=await U.from("agent_cards").select("id").eq("slug",I).neq("id",s.id).maybeSingle();if(D){ne.error("This URL is already taken. Try another one.");return}const{error:F}=await U.from("agent_cards").update({slug:I}).eq("id",s.id);if(F)throw F;g(I),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ne.success("Card address updated!")}catch{ne.error("Failed to update card address")}finally{y(!1)}},P=async(I,D)=>{var q;const F=(q=I.target.files)==null?void 0:q[0];if(F){if(!F.type.startsWith("image/")){ne.error("Please select an image file");return}try{const G=F.name.split(".").pop()||"png",V=D==="brokerage_logo_url"?"brokerage-logo":"team-logo",H=`${s.user_id}/${V}.${G}`,{error:K}=await U.storage.from("card-logos").upload(H,F,{upsert:!0});if(K)throw K;const{data:Z}=U.storage.from("card-logos").getPublicUrl(H),oe=Z.publicUrl+"?t="+Date.now();w(D==="brokerage_logo_url"?re=>({...re,[D]:oe,brokerage_display_name:""}):re=>({...re,[D]:oe,team_name:""})),ne.success("Logo uploaded!")}catch{ne.error("Failed to upload logo")}finally{I.target.value=""}}},M=()=>{r.mutate({id:s.id,...b,title:b.title||null,positioning_statement:b.positioning_statement||null,bio:b.bio||null,review_snippet:b.review_snippet||null,review_source_url:b.review_source_url||null,booking_url:b.booking_url||null,custom_cta_label:b.custom_cta_label||null,custom_cta_url:b.custom_cta_url||null,brokerage_display_name:b.brokerage_display_name||null,brokerage_logo_url:b.brokerage_logo_url||null,brokerage_logo_size:b.brokerage_logo_size,team_name:b.team_name||null,team_logo_url:b.team_logo_url||null,team_logo_size:b.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(Is,{open:t,onOpenChange:n,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Edit Agent Card"}),e.jsxs(_r,{children:["/card/",s.slug]})]}),e.jsxs(Qr,{defaultValue:"content",children:[e.jsxs(Jr,{className:"w-full",children:[e.jsx(Wt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Wt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Wt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Wt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Kt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Published"}),e.jsx(mn,{checked:b.is_published,onCheckedChange:I=>w(D=>({...D,is_published:I}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(ja,{className:"h-16 w-16",children:[e.jsx(xi,{src:l||void 0}),e.jsx(Na,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S,disabled:c}),e.jsx(z,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:f,onChange:I=>g(I.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(z,{variant:"outline",size:"sm",onClick:E,disabled:v||f===s.slug,className:"shrink-0",children:v?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Theme"}),e.jsxs(ls,{value:b.theme,onValueChange:I=>w(D=>({...D,theme:I})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(He,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(He,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(He,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Title / Tagline"}),e.jsx(pe,{value:b.title,onChange:I=>w(D=>({...D,title:I.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(ee,{children:"Positioning Statement"}),e.jsx(pe,{value:b.positioning_statement,onChange:I=>w(D=>({...D,positioning_statement:I.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Bio"}),e.jsx(Ps,{value:b.bio,onChange:I=>w(D=>({...D,bio:I.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review Snippet"}),e.jsx(pe,{value:b.review_snippet,onChange:I=>w(D=>({...D,review_snippet:I.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review Source URL"}),e.jsx(pe,{value:b.review_source_url,onChange:I=>w(D=>({...D,review_source_url:I.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(pe,{value:b.booking_url,onChange:I=>w(D=>({...D,booking_url:I.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Custom CTA Label (optional)"}),e.jsx(pe,{value:b.custom_cta_label,onChange:I=>w(D=>({...D,custom_cta_label:I.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Custom CTA URL (optional)"}),e.jsx(pe,{value:b.custom_cta_url,onChange:I=>w(D=>({...D,custom_cta_url:I.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(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{value:b.brokerage_display_name,onChange:I=>w(D=>({...D,brokerage_display_name:I.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!b.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${b.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>w(I=>({...I,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(Ra,{className:"h-3.5 w-3.5"}),b.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"brokerage_logo_url")})]})]}),b.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.brokerage_logo_size||56,"px"]})]}),e.jsx(Mx,{value:[b.brokerage_logo_size||56],onValueChange:([I])=>w(D=>({...D,brokerage_logo_size:I})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{value:b.team_name,onChange:I=>w(D=>({...D,team_name:I.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!b.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.team_logo_url,alt:"Team logo",style:{height:`${b.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>w(I=>({...I,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(Ra,{className:"h-3.5 w-3.5"}),b.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"team_logo_url")})]})]}),b.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.team_logo_size||56,"px"]})]}),e.jsx(Mx,{value:[b.team_logo_size||56],onValueChange:([I])=>w(D=>({...D,team_logo_size:I})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Kt,{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:I,label:D,hint:F})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:D}),F&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[F," ",I==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(mn,{checked:b[I],onCheckedChange:q=>w(G=>({...G,[I]:q}))})]},I))}),e.jsx(Kt,{value:"blocks",className:"mt-4",children:e.jsx(aas,{cardId:s.id})}),e.jsx(Kt,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(be,{children:e.jsxs(Le,{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(I=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:I.name}),I.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",I.phone]}),I.intent&&e.jsx(ze,{variant:"secondary",className:"ml-2 text-xs",children:I.intent})]},I.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(z,{onClick:M,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(Ltt,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:C,aspectRatio:1})]})}const rV={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"},wit={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 jit(s=!0){return rt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=U.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function knr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ne.success("Category created successfully")},onError:t=>{ne.error("Failed to create category: "+t.message)}})}function Snr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ne.success("Category updated successfully")},onError:t=>{ne.error("Failed to update category: "+t.message)}})}function Cnr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ne.success("Category deleted successfully")},onError:t=>{ne.error("Failed to delete category: "+t.message)}})}function uas(s,t=!0){return rt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=U.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(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 Anr(s){return rt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await U.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Enr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ne.success("Product created successfully")},onError:t=>{ne.error("Failed to create product: "+t.message)}})}function Tnr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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]}),ne.success("Product updated successfully")},onError:t=>{ne.error("Failed to update product: "+t.message)}})}function Mnr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ne.success("Product deleted successfully")},onError:t=>{ne.error("Failed to delete product: "+t.message)}})}function Pnr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 Lnr(){const s=$t();return mt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await U.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]}),ne.success("Image deleted successfully")},onError:t=>{ne.error("Failed to delete image: "+t.message)}})}function Inr(){const s=$t();return mt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await U.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await U.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]}),ne.success("Primary image updated")},onError:t=>{ne.error("Failed to set primary image: "+t.message)}})}function Dnr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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]}),ne.success("Variant added successfully")}})}function Rnr(){const s=$t();return mt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await U.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]}),ne.success("Variant deleted successfully")}})}function Fnr(){const s=$t();return mt({mutationFn:async({productId:t,videoUrl:n})=>{await U.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await U.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]}),ne.success("Video updated successfully")}})}function Onr(s){const{isAdmin:t}=hs();return rt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=U.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 U.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 znr(){const{user:s}=hs();return rt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function Bnr(s){return rt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await U.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 $nr(){const s=$t(),{user:t}=hs();return mt({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 U.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await U.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 U.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(m){console.error("Failed to send notification email:",m)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ne.success("Order status updated")},onError:n=>{ne.error("Failed to update order: "+n.message)}})}function Unr(){const s=$t();return mt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await U.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await U.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await U.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ne.success("Proof uploaded & customer notified")}})}function qnr(){const s=$t();return mt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await U.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"]}),ne.success("Proof approved")}})}function Vnr(){const s=$t();return mt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await U.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"]}),ne.success("Proof rejected - please upload a new proof")}})}function Hnr(){const{data:s,isLoading:t}=jit(!1),n=knr(),r=Snr(),a=Cnr(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},m=g=>{c(g),u({name:g.name,description:g.description||"",image_url:g.image_url||"",sort_order:g.sort_order,is_active:g.is_active}),l(!0)},p=async g=>{g.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},f=async g=>{await Qi("Are you sure you want to delete this category?")&&await a.mutateAsync(g)};return t?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(ln,{className:"h-8 w-48"})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(g=>e.jsx(ln,{className:"h-12 w-full"},g))})})]}):e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{children:"Categories"}),e.jsxs(Is,{open:i,onOpenChange:g=>{l(g),g||h()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:d.name,onChange:g=>u({...d,name:g.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",value:d.description,onChange:g=>u({...d,description:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"image_url",children:"Image URL"}),e.jsx(pe,{id:"image_url",value:d.image_url,onChange:g=>u({...d,image_url:g.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(pe,{id:"sort_order",type:"number",value:d.sort_order,onChange:g=>u({...d,sort_order:parseInt(g.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"is_active",checked:d.is_active,onCheckedChange:g=>u({...d,is_active:g})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]}),e.jsx(z,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Le,{children:s&&s.length>0?e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Sort Order"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(g=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:g.name}),e.jsx(yt,{className:"max-w-xs truncate",children:g.description}),e.jsx(yt,{children:g.sort_order}),e.jsx(yt,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${g.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:g.is_active?"Active":"Inactive"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>m(g),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>f(g.id),disabled:a.isPending,children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function Gnr(){var J,te;const{data:s,isLoading:t}=uas(void 0,!1),{data:n}=jit(!1),r=Enr(),a=Tnr(),i=Mnr(),l=Pnr(),o=Lnr(),c=Inr(),d=Dnr(),u=Rnr(),h=Fnr(),[m,p]=_.useState(!1),[f,g]=_.useState(!1),[v,y]=_.useState(!1),[b,w]=_.useState(null),[S,C]=_.useState(null),[E,P]=_.useState(!1),[M,I]=_.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}),[D,F]=_.useState({name:"",price_adjustment:0}),[q,G]=_.useState(""),V=()=>{I({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),w(null)},H=ce=>{w(ce),I({name:ce.name,description:ce.description||"",base_price:Number(ce.base_price),shipping_fee:Number(ce.shipping_fee),category_id:ce.category_id||"",allow_artwork_upload:ce.allow_artwork_upload,requires_proof_approval:ce.requires_proof_approval,is_active:ce.is_active,sort_order:ce.sort_order}),p(!0)},K=async ce=>{ce.preventDefault();const ve={...M,category_id:M.category_id||null};b?await a.mutateAsync({id:b.id,...ve}):await r.mutateAsync(ve),p(!1),V()},Z=async ce=>{await Qi("Are you sure you want to delete this product?")&&await i.mutateAsync(ce)},oe=async ce=>{if(!S||!ce.target.files||ce.target.files.length===0)return;P(!0);const ve=ce.target.files[0],me=ve.name.split(".").pop(),he=`products/${S.id}/${Date.now()}.${me}`;try{const{error:ge}=await U.storage.from("marketplace").upload(he,ve);if(ge)throw ge;const{data:{publicUrl:Ee}}=U.storage.from("marketplace").getPublicUrl(he);await l.mutateAsync({product_id:S.id,image_url:Ee,is_primary:!S.images||S.images.length===0}),ne.success("Image uploaded successfully")}catch(ge){ne.error("Failed to upload image: "+ge.message)}finally{P(!1)}},re=async ce=>{ce.preventDefault(),S&&(await d.mutateAsync({product_id:S.id,name:D.name,price_adjustment:D.price_adjustment}),F({name:"",price_adjustment:0}))},ae=async()=>{!S||!q||(await h.mutateAsync({productId:S.id,videoUrl:q}),G(""))};return t?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(ln,{className:"h-8 w-48"})}),e.jsx(Le,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ce=>e.jsx(ln,{className:"h-64 w-full"},ce))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{children:"Products"}),e.jsxs(Is,{open:m,onOpenChange:ce=>{p(ce),ce||V()},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:K,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(ee,{htmlFor:"name",children:"Product Name"}),e.jsx(pe,{id:"name",value:M.name,onChange:ce=>I({...M,name:ce.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"category",children:"Category"}),e.jsxs(ls,{value:M.category_id,onValueChange:ce=>I({...M,category_id:ce}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select category"})}),e.jsx(as,{children:n==null?void 0:n.map(ce=>e.jsx(He,{value:ce.id,children:ce.name},ce.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ps,{id:"description",value:M.description,onChange:ce=>I({...M,description:ce.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(ee,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(pe,{id:"base_price",type:"number",step:"0.01",min:"0",value:M.base_price,onChange:ce=>I({...M,base_price:parseFloat(ce.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(pe,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:M.shipping_fee,onChange:ce=>I({...M,shipping_fee:parseFloat(ce.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(pe,{id:"sort_order",type:"number",value:M.sort_order,onChange:ce=>I({...M,sort_order:parseInt(ce.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:ce=>I({...M,allow_artwork_upload:ce})}),e.jsx(ee,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:ce=>I({...M,requires_proof_approval:ce})}),e.jsx(ee,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"is_active",checked:M.is_active,onCheckedChange:ce=>I({...M,is_active:ce})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(z,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:b?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Le,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(ce=>{var ve,me;return e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ce.images&&ce.images.length>0?e.jsx("img",{src:((ve=ce.images.find(he=>he.is_primary))==null?void 0:ve.image_url)||ce.images[0].image_url,alt:ce.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"}),!ce.is_active&&e.jsx(ze,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Le,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ce.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((me=ce.category)==null?void 0:me.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ce.base_price).toFixed(2)]}),Number(ce.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ce.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ce.allow_artwork_upload&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ce.requires_proof_approval&&e.jsx(ze,{variant:"outline",className:"text-xs",children:"Proof Required"}),ce.variants&&ce.variants.length>0&&e.jsxs(ze,{variant:"outline",className:"text-xs",children:[ce.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>H(ce),children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>{C(ce),g(!0)},children:[e.jsx(N0,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>{C(ce),y(!0)},children:[e.jsx(Ip,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>Z(ce.id),children:e.jsx(Cn,{className:"h-3 w-3 text-destructive"})})]})]})]},ce.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(Is,{open:f,onOpenChange:g,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Manage Images - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(J=S==null?void 0:S.images)==null?void 0:J.map(ce=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ce.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ce.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:[!ce.is_primary&&e.jsx(z,{variant:"secondary",size:"icon",onClick:async()=>{var ve;await c.mutateAsync({imageId:ce.id,productId:S.id}),C({...S,images:(ve=S.images)==null?void 0:ve.map(me=>({...me,is_primary:me.id===ce.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(z,{variant:"destructive",size:"icon",onClick:async()=>{var me;await o.mutateAsync({id:ce.id,productId:S.id});const ve=s==null?void 0:s.find(he=>he.id===S.id);ve&&C({...ve,images:(me=ve.images)==null?void 0:me.filter(he=>he.id!==ce.id)})},disabled:o.isPending,children:e.jsx(Cn,{className:"h-4 w-4"})})]})]},ce.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:oe,className:"hidden",id:"image-upload",disabled:E}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(N0,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(ee,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(pe,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:q,onChange:ce=>G(ce.target.value)}),e.jsxs(z,{onClick:ae,disabled:!q,children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(S==null?void 0:S.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",S.video.video_url]})]})]})]})}),e.jsx(Is,{open:v,onOpenChange:y,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Manage Variants - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:re,className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Variant name (e.g., 500 count)",value:D.name,onChange:ce=>F({...D,name:ce.target.value}),required:!0}),e.jsx(pe,{type:"number",step:"0.01",placeholder:"Price adj.",value:D.price_adjustment,onChange:ce=>F({...D,price_adjustment:parseFloat(ce.target.value)||0}),className:"w-32"}),e.jsx(z,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(te=S==null?void 0:S.variants)==null?void 0:te.map(ce=>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:ce.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(ce.price_adjustment)>=0?"+":"","$",Number(ce.price_adjustment).toFixed(2)]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:ce.id,productId:S.id}),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]},ce.id)),(!(S!=null&&S.variants)||S.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 Wnr=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function Knr(){var g,v,y;const{data:s,isLoading:t}=Onr(),n=$nr(),r=Unr(),[a,i]=_.useState(null),[l,o]=_.useState(!1),[c,d]=_.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=_.useState(!1),m=b=>{i(b),d({status:b.status,notes:"",trackingNumber:b.tracking_number||"",trackingUrl:b.tracking_url||""}),o(!0)},p=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},f=async(b,w)=>{if(!a||!b.target.files||b.target.files.length===0)return;h(!0);const S=b.target.files[0],C=S.name.split(".").pop(),E=`proofs/${a.id}/${w}/${Date.now()}.${C}`;try{const{error:P}=await U.storage.from("marketplace").upload(E,S);if(P)throw P;const{data:{publicUrl:M}}=U.storage.from("marketplace").getPublicUrl(E);await r.mutateAsync({itemId:w,proofUrl:M,orderId:a.id}),ne.success("Proof uploaded successfully")}catch(P){ne.error("Failed to upload proof: "+P.message)}finally{h(!1)}};return t?e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(ln,{className:"h-8 w-48"})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(ln,{className:"h-16 w-full"},b))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Orders"})}),e.jsx(Le,{children:s&&s.length>0?e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Order #"}),e.jsx(Tt,{children:"Customer"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Total"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:s.map(b=>{var w,S;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-mono",children:b.order_number}),e.jsx(yt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((w=b.user)==null?void 0:w.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(S=b.user)==null?void 0:S.email})]})}),e.jsx(yt,{children:Ys(new Date(b.created_at),"MMM d, yyyy")}),e.jsxs(yt,{className:"font-bold",children:["$",Number(b.total).toFixed(2)]}),e.jsx(yt,{children:e.jsx(ze,{className:wit[b.status],children:rV[b.status]})}),e.jsx(yt,{className:"text-right",children:e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(xa,{className:"h-4 w-4 mr-1"}),"View"]})})]},b.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(Is,{open:l,onOpenChange:o,children:e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Rs,{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:(g=a.user)==null?void 0:g.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:(y=a.items)==null?void 0:y.map(b=>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:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(b.unit_price).toFixed(2)," x ",b.quantity]})]}),b.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:b.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:b.proof_status==="approved"?"default":"secondary",children:b.proof_status||"No proof yet"})]}),b.proof_url?e.jsx("a",{href:b.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:w=>f(w,b.id),className:"hidden",id:`proof-${b.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${b.id}`,children:e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Ra,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},b.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(ee,{children:"Status"}),e.jsxs(ls,{value:c.status,onValueChange:b=>d({...c,status:b}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Wnr.map(b=>e.jsx(He,{value:b,children:rV[b]},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tracking Number"}),e.jsx(pe,{value:c.trackingNumber,onChange:b=>d({...c,trackingNumber:b.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tracking URL"}),e.jsx(pe,{value:c.trackingUrl,onChange:b=>d({...c,trackingUrl:b.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Ps,{value:c.notes,onChange:b=>d({...c,notes:b.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(z,{onClick:p,disabled:n.isPending,className:"w-full",children:[e.jsx(Sh,{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(b=>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:rV[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Ys(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function Ynr(){const[s,t]=_.useState("products"),n=zn();return e.jsx($s,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(z,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(Qr,{value:s,onValueChange:t,children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Wt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Sh,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Wt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(wv,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Wt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(bS,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Kt,{value:"products",children:e.jsx(Gnr,{})}),e.jsx(Kt,{value:"categories",children:e.jsx(Hnr,{})}),e.jsx(Kt,{value:"orders",children:e.jsx(Knr,{})})]})]})})}function has(){return rt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function Znr(s){return rt({queryKey:["reward-items",s],queryFn:async()=>{let t=U.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function Xnr(s){return rt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=U.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function Qnr(s){return rt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 Jnr(){return rt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await U.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 err(s){return rt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await U.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 trr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 srr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function nrr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function rrr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function arr(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 irr(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 orr(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.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 lrr(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function WBe(s,t){const n=lrr(s);if(n)try{const{data:r,error:a}=await U.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ne.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),ne.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),ne.error("Failed to download file")}}function mas(){return rt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await U.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function crr(){const s=$t();return mt({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 U.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function drr(){const{user:s}=hs(),[t,n]=_.useState("items"),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(null),[g,v]=_.useState(!1),[y,b]=_.useState(null),[w,S]=_.useState(""),[C,E]=_.useState(""),[P,M]=_.useState(null),[I,D]=_.useState(""),[F,q]=_.useState("file"),[G,V]=_.useState(""),[H,K]=_.useState(""),[Z,oe]=_.useState(""),[re,ae]=_.useState(!0),[J,te]=_.useState(null),[ce,ve]=_.useState(!1),[me,he]=_.useState(!1),ge=_.useRef(null),Ee=_.useRef(null),{data:Ne,isLoading:Pe}=has(),{data:Oe,isLoading:ke}=Znr(),{data:Ve,isLoading:_e}=Jnr(),{data:Ae,isLoading:Se}=mas(),We=srr(),qe=nrr(),Be=rrr(),Ze=arr(),$e=irr(),Xe=orr(),nt=crr(),[Ge,Je]=_.useState({}),ut=wt=>{wt?(l(wt),c(wt.name),u(wt.description||""),m(wt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},lt=async()=>{if(!o.trim()){ne.error("Please enter a category name");return}try{i?(await qe.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ne.success("Category updated successfully")):(await We.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Ne==null?void 0:Ne.length)||0)+1}),ne.success("Category created successfully")),a(!1)}catch(wt){console.error("Error saving category:",wt),ne.error("Failed to save category")}},qt=async()=>{if(p)try{await Be.mutateAsync(p),ne.success("Category deleted successfully"),f(null)}catch(wt){console.error("Error deleting category:",wt),ne.error("Failed to delete category")}},zt=wt=>{var Us;wt?(b(wt),S(wt.name),E(wt.description||""),M(wt.category_id),D(wt.points_cost.toString()),q(wt.item_type),V(wt.file_url||""),K(wt.preview_image_url||""),oe(((Us=wt.max_quantity)==null?void 0:Us.toString())||""),ae(wt.is_active)):(b(null),S(""),E(""),M(null),D(""),q("file"),V(""),K(""),oe(""),ae(!0)),v(!0)},Zt=async(wt,Us)=>{Us==="file"?ve(!0):he(!0);try{const Es=wt.name.split(".").pop(),kn=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Es}`,Sn=`${Us==="file"?"items":"previews"}/${kn}`,{error:bn}=await U.storage.from("reward-store").upload(Sn,wt);if(bn)throw bn;const{data:{publicUrl:cr}}=U.storage.from("reward-store").getPublicUrl(Sn);Us==="file"?V(cr):K(cr),ne.success("File uploaded successfully")}catch(Es){console.error("Error uploading file:",Es),ne.error("Failed to upload file")}finally{Us==="file"?ve(!1):he(!1)}},ms=async()=>{if(!w.trim()){ne.error("Please enter an item name");return}if(!I||parseInt(I)<0){ne.error("Please enter a valid points cost");return}try{const wt={name:w,description:C||null,category_id:P,points_cost:parseInt(I),item_type:F,file_url:G||null,preview_image_url:H||null,max_quantity:Z?parseInt(Z):null,current_quantity:Z?parseInt(Z):null,is_active:re,created_by:s==null?void 0:s.id};y?(await $e.mutateAsync({id:y.id,...wt,current_quantity:y.max_quantity!==(Z?parseInt(Z):null)?Z?parseInt(Z):null:y.current_quantity}),ne.success("Item updated successfully")):(await Ze.mutateAsync(wt),ne.success("Item created successfully")),v(!1)}catch(wt){console.error("Error saving item:",wt),ne.error("Failed to save item")}},Dt=async()=>{if(J)try{await Xe.mutateAsync(J),ne.success("Item deleted successfully"),te(null)}catch(wt){console.error("Error deleting item:",wt),ne.error("Failed to delete item")}},It=async(wt,Us)=>{const Es=Ge[wt];if(Es===void 0||Es===Us.toString())return;const kn=parseInt(Es);if(isNaN(kn)||kn<0){ne.error("Please enter a valid positive number");return}try{await nt.mutateAsync({id:wt,points:kn}),ne.success("Points updated successfully"),Je(Sn=>{const bn={...Sn};return delete bn[wt],bn})}catch(Sn){console.error("Error updating points:",Sn),ne.error("Failed to update points")}};return Pe||ke||_e||Se?e.jsx($s,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-8 w-64"}),e.jsx(ln,{className:"h-96"})]})}):e.jsxs($s,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Sh,{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:(Oe==null?void 0:Oe.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Oe==null?void 0:Oe.filter(wt=>wt.is_active).length)||0," active"]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wv,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Ne==null?void 0:Ne.length)||0})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ia,{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:[Oe&&Oe.length>0?Math.round(Oe.reduce((wt,Us)=>wt+Us.points_cost,0)/Oe.length):0," pts"]})]})})]}),e.jsxs(Qr,{value:t,onValueChange:n,children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"items",children:"Items"}),e.jsx(Wt,{value:"categories",children:"Categories"}),e.jsx(Wt,{value:"purchases",children:"Purchases"}),e.jsx(Wt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Kt,{value:"items",className:"mt-4",children:e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Store Items"}),e.jsx(En,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(z,{onClick:()=>zt(),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Le,{children:!Oe||Oe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ko,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No items yet. Add your first reward item!"})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{className:"text-center",children:"Cost"}),e.jsx(Tt,{className:"text-center",children:"Type"}),e.jsx(Tt,{className:"text-center",children:"Quantity"}),e.jsx(Tt,{className:"text-center",children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:Oe.map(wt=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[wt.preview_image_url?e.jsx("img",{src:wt.preview_image_url,alt:wt.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(Ko,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:wt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:wt.description||"No description"})]})]})}),e.jsx(yt,{children:wt.category?e.jsx(ze,{variant:"outline",children:wt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(yt,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1"}),wt.points_cost]})}),e.jsx(yt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[wt.item_type==="file"?e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Kc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:wt.item_type})]})}),e.jsx(yt,{className:"text-center",children:wt.max_quantity!==null?e.jsxs("span",{className:wt.current_quantity===0?"text-red-500":"",children:[wt.current_quantity,"/",wt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(yt,{className:"text-center",children:e.jsx(ze,{variant:wt.is_active?"default":"secondary",children:wt.is_active?"Active":"Inactive"})}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>zt(wt),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>te(wt.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},wt.id))})]})})]})}),e.jsx(Kt,{value:"categories",className:"mt-4",children:e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Categories"}),e.jsx(En,{children:"Organize your store items into categories"})]}),e.jsxs(z,{onClick:()=>ut(),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Le,{children:!Ne||Ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(wv,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center",children:"Items"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(Qa,{children:Ne.map(wt=>e.jsxs(fn,{children:[e.jsxs(yt,{className:"font-medium",children:[wt.icon&&e.jsx("span",{className:"mr-2",children:wt.icon}),wt.name]}),e.jsx(yt,{className:"text-muted-foreground",children:wt.description||"—"}),e.jsx(yt,{className:"text-center",children:(Oe==null?void 0:Oe.filter(Us=>Us.category_id===wt.id).length)||0}),e.jsx(yt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>ut(wt),children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>f(wt.id),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})})]},wt.id))})]})})]})}),e.jsx(Kt,{value:"purchases",className:"mt-4",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(bS,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(En,{children:"View all reward redemptions by agents"})]}),e.jsx(Le,{children:!Ve||Ve.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(bS,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(Qa,{children:Ve.map(wt=>{var Us,Es,kn,Sn;return e.jsxs(fn,{children:[e.jsx(yt,{className:"text-muted-foreground",children:Ys(new Date(wt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(yt,{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(Oo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Us=wt.user)==null?void 0:Us.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Es=wt.user)==null?void 0:Es.email)||"—"})]})]})}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(kn=wt.item)!=null&&kn.preview_image_url?e.jsx("img",{src:wt.item.preview_image_url,alt:wt.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(Ko,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Sn=wt.item)==null?void 0:Sn.name)||"Deleted item"})]})}),e.jsx(yt,{className:"text-center",children:e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1"}),wt.points_spent]})})]},wt.id)})})]})})]})})]})]}),e.jsx(Is,{open:r,onOpenChange:a,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:i?"Edit Category":"Add Category"}),e.jsx(_r,{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(ee,{htmlFor:"categoryName",children:"Name"}),e.jsx(pe,{id:"categoryName",value:o,onChange:wt=>c(wt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ps,{id:"categoryDescription",value:d,onChange:wt=>u(wt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(pe,{id:"categoryIcon",value:h,onChange:wt=>m(wt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(z,{onClick:lt,disabled:We.isPending||qe.isPending,children:We.isPending||qe.isPending?"Saving...":"Save"})]})]})}),e.jsx(Is,{open:g,onOpenChange:v,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:y?"Edit Item":"Add Item"}),e.jsx(_r,{children:y?"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(ee,{htmlFor:"itemName",children:"Name *"}),e.jsx(pe,{id:"itemName",value:w,onChange:wt=>S(wt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ps,{id:"itemDescription",value:C,onChange:wt=>E(wt.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(ee,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(ls,{value:P||"none",onValueChange:wt=>M(wt==="none"?null:wt),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select category"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No category"}),Ne==null?void 0:Ne.map(wt=>e.jsxs(He,{value:wt.id,children:[wt.icon&&`${wt.icon} `,wt.name]},wt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(pe,{id:"itemPointsCost",type:"number",min:"0",value:I,onChange:wt=>D(wt.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(ee,{htmlFor:"itemType",children:"Type"}),e.jsxs(ls,{value:F,onValueChange:q,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"file",children:"File Download"}),e.jsx(He,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(pe,{id:"itemMaxQuantity",type:"number",min:"1",value:Z,onChange:wt=>oe(wt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:G,onChange:wt=>V(wt.target.value),placeholder:F==="file"?"Upload a file or paste URL":"Paste external link"}),F==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:()=>{var wt;return(wt=ge.current)==null?void 0:wt.click()},disabled:ce,children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx("input",{ref:ge,type:"file",className:"hidden",onChange:wt=>{var Es;const Us=(Es=wt.target.files)==null?void 0:Es[0];Us&&Zt(Us,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:H,onChange:wt=>K(wt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:()=>{var wt;return(wt=Ee.current)==null?void 0:wt.click()},disabled:me,children:e.jsx(nc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",accept:"image/*",className:"hidden",onChange:wt=>{var Es;const Us=(Es=wt.target.files)==null?void 0:Es[0];Us&&Zt(Us,"preview")}})]}),H&&e.jsx("img",{src:H,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{id:"itemIsActive",checked:re,onCheckedChange:ae}),e.jsx(ee,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(z,{onClick:ms,disabled:Ze.isPending||$e.isPending,children:Ze.isPending||$e.isPending?"Saving...":"Save"})]})]})}),e.jsx(Ql,{open:!!p,onOpenChange:()=>f(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Category"}),e.jsx(ql,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:qt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Ql,{open:!!J,onOpenChange:()=>te(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete Item"}),e.jsx(ql,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:Dt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(be,{className:"mt-4",children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gc,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Nt,{children:"Point Reward Settings"}),e.jsx(En,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Le,{children:!Ae||Ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Gc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center w-32",children:"Points"}),e.jsx(Tt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(Qa,{children:Ae.map(wt=>e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsx("p",{className:"font-medium",children:wt.action_name})}),e.jsx(yt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:wt.description})}),e.jsx(yt,{className:"text-center",children:e.jsx(pe,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ge[wt.id]??wt.points.toString(),onChange:Us=>Je(Es=>({...Es,[wt.id]:Us.target.value}))})}),e.jsx(yt,{className:"text-right",children:e.jsx(z,{size:"sm",variant:"outline",disabled:Ge[wt.id]===void 0||Ge[wt.id]===wt.points.toString()||nt.isPending,onClick:()=>It(wt.id,wt.points),children:e.jsx(Bo,{className:"h-4 w-4"})})})]},wt.id))})]})})]})]})}function urr(){const s=zn();return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Xh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(be,{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(sd,{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(z,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(Da,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(las,{}),e.jsx(ias,{})]})})}const G4t=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(of,{className:t}):s==="instagram"?e.jsx(Fm,{className:t}):s==="linkedin"?e.jsx(fg,{className:t}):s==="google"?e.jsx(on,{className:t}):null},hrr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function mrr(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState(""),[l,o]=_.useState("all");_.useEffect(()=>{(async()=>{r(!0);const{data:m,error:p}=await U.rpc("admin_get_social_connections");if(p){ne.error(p.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=_.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(p=>l!=="all"&&p.platform!==l?!1:m?(p.user_name||"").toLowerCase().includes(m)||(p.user_email||"").toLowerCase().includes(m)||(p.page_name||"").toLowerCase().includes(m)||(p.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=_.useMemo(()=>{const m=new Map;return s.forEach(p=>{const f=m.get(p.user_id)||{name:p.user_name,email:p.user_email,platforms:new Set,count:0};f.platforms.add(p.platform),f.count+=1,m.set(p.user_id,f)}),Array.from(m.entries()).map(([p,f])=>({user_id:p,...f}))},[s]),u=_.useMemo(()=>{const m=new Map;return s.forEach(p=>m.set(p.platform,(m.get(p.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(m.entries())}},[s,d]),h=m=>m&&new Date(m).getTime()e.jsxs(be,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[G4t(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:p})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(pe,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"md:w-48",children:e.jsx(cs,{placeholder:"All platforms"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All platforms"}),e.jsx(He,{value:"facebook",children:"Facebook"}),e.jsx(He,{value:"instagram",children:"Instagram"}),e.jsx(He,{value:"linkedin",children:"LinkedIn"}),e.jsx(He,{value:"google",children:"Google"})]})]})]}),e.jsx(be,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Platform"}),e.jsx(Tt,{children:"Page / Account"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Connected"})]})}),e.jsx(Qa,{children:c.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const p=h(m.token_expires_at);return e.jsxs(fn,{children:[e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:m.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.user_email})]}),e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[G4t(m.platform)," ",m.platform]})}),e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:m.page_name||m.platform_username||"—"}),m.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",m.instagram_business_id]})]}),e.jsx(yt,{children:m.is_active?p?e.jsxs(ze,{variant:"destructive",className:"gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"})," Expired"]}):e.jsx(ze,{children:"Active"}):e.jsx(ze,{variant:"secondary",children:"Inactive"})}),e.jsx(yt,{className:"text-sm text-muted-foreground",children:hrr(m.created_at)})]},m.id)})})]})})]})})}const prr={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 VZ(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function frr(){var F,q,G,V,H;const s=$t(),[t,n]=_.useState("Test Push"),[r,a]=_.useState("Testing web push notification"),[i,l]=_.useState("/community"),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[p,f]=_.useState(null),[g,v]=_.useState(null),{data:y,isLoading:b}=rt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:K,error:Z}=await U.from("push_notification_settings").select("*").order("setting_key");if(Z)throw Z;return K}}),{data:w,isLoading:S}=rt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:K,error:Z}=await U.from("push_subscriptions").select("*",{count:"exact",head:!0});if(Z)throw Z;return{totalSubscriptions:K||0}}}),C=mt({mutationFn:async({settingKey:K,isEnabled:Z})=>{const{error:oe}=await U.from("push_notification_settings").update({is_enabled:Z}).eq("setting_key",K);if(oe)throw oe},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ne.success("Notification setting updated")},onError:K=>{ne.error("Failed to update setting: "+K.message)}}),E=_.useMemo(()=>{var K,Z;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((K=h.serviceWorker)==null?void 0:K.activeState)??"unknown"} · sub=${(Z=h.subscription)!=null&&Z.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);_.useEffect(()=>{let K=!0;const Z=async()=>{var J,te,ce,ve,me,he,ge;const re="serviceWorker"in navigator&&"PushManager"in window,ae={isSupported:re,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((J=navigator.serviceWorker)!=null&&J.controller)};if(!re){K&&m(ae);return}try{const{data:Ee,error:Ne}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(Ne)throw Ne;ae.vapidPublicKey=Ee==null?void 0:Ee.vapidPublicKey;const Oe=(await navigator.serviceWorker.getRegistrations()).find(ke=>{var _e,Ae,Se;return(((_e=ke.active)==null?void 0:_e.scriptURL)||((Ae=ke.waiting)==null?void 0:Ae.scriptURL)||((Se=ke.installing)==null?void 0:Se.scriptURL)||"").includes("/sw.js")});if(Oe){ae.pushWorkerScriptUrl=((te=Oe.active)==null?void 0:te.scriptURL)||((ce=Oe.waiting)==null?void 0:ce.scriptURL)||((ve=Oe.installing)==null?void 0:ve.scriptURL),ae.serviceWorker={scope:Oe.scope,activeState:(me=Oe.active)==null?void 0:me.state};const ke=await Oe.pushManager.getSubscription();if(ke){const Ve=ke.toJSON();ae.subscription={endpoint:Ve.endpoint,p256dh:(he=Ve.keys)==null?void 0:he.p256dh,auth:(ge=Ve.keys)==null?void 0:ge.auth}}}}catch(Ee){ae.error=(Ee==null?void 0:Ee.message)||String(Ee)}K&&m(ae)};Z();const oe=window.setInterval(Z,4e3);return()=>{K=!1,window.clearInterval(oe)}},[]);const P=async()=>{if(typeof Notification>"u"){ne.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ne.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ne.success("Triggered a local notification (not push).")}catch(K){ne.error(`Local notification failed: ${(K==null?void 0:K.message)||String(K)}`)}},M=async()=>{c(!0),f(null);try{const{data:K,error:Z}=await U.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(Z)throw Z;f({sent:K==null?void 0:K.sent,failed:K==null?void 0:K.failed,expiredCleaned:K==null?void 0:K.expiredCleaned,vapidPublicKey:K==null?void 0:K.vapidPublicKey}),(K==null?void 0:K.sent)>0?ne.success(`Test notification sent to ${K.sent} subscriber(s)`):(K==null?void 0:K.failed)>0?ne.warning(`Notification failed for ${K.failed} subscriber(s). ${K.expired||0} expired subscriptions cleaned up.`):ne.info("No active subscriptions to send to")}catch(K){console.error("Error sending test notification:",K),f({error:(K==null?void 0:K.message)||String(K)}),ne.error("Failed to send test notification: "+(K.message||"Unknown error"))}finally{c(!1)}},I=async()=>{u(!0),v(null);try{const{data:K,error:Z}=await U.functions.invoke("generate-vapid-keys",{body:{}});if(Z)throw Z;const oe=K==null?void 0:K.publicKey,re=K==null?void 0:K.privateKey;if(!oe||!re)throw new Error("generate-vapid-keys did not return keys");v({publicKey:oe,privateKey:re}),ne.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(K){console.error("Error generating VAPID keys:",K),ne.error("Failed to generate VAPID keys: "+((K==null?void 0:K.message)||"Unknown error"))}finally{u(!1)}},D=mt({mutationFn:async()=>{const{error:K}=await U.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(K)throw K},onSuccess:()=>{ne.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:K=>{ne.error("Failed to clear subscriptions: "+K.message)}});return e.jsx($s,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(On,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(En,{children:"Current active push notification subscriptions"})]}),e.jsx(Le,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:S?"...":(w==null?void 0:w.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Gc,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(En,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Le,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:y==null?void 0:y.map(K=>{const Z=prr[K.setting_key]||{label:K.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:Z.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Z.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:K.description})]})]}),e.jsx(mn,{checked:K.is_enabled,onCheckedChange:oe=>C.mutate({settingKey:K.setting_key,isEnabled:oe}),disabled:C.isPending})]},K.id)})})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx($g,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(En,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Le,{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:E}),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?VZ(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: ",(F=h.serviceWorker)!=null&&F.scope?VZ(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((q=h.serviceWorker)==null?void 0:q.activeState)??"none"]})]})]}),e.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Current browser subscription"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["endpoint: ",(G=h.subscription)!=null&&G.endpoint?VZ(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(V=h.subscription)!=null&&V.p256dh?VZ(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(H=h.subscription)!=null&&H.auth?VZ(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(z,{variant:"outline",onClick:P,children:"Local notification test"}),e.jsx(z,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(pe,{id:"test-title",value:t,onChange:K=>n(K.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ps,{id:"test-body",value:r,onChange:K=>a(K.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(pe,{id:"test-url",value:i,onChange:K=>l(K.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(z,{onClick:M,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),p&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),p.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",p.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",p.sent??0," sent, ",p.failed??0," failed, ",p.expiredCleaned??0," expired cleaned"]}),p.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:p.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Cn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(En,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Le,{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(z,{variant:"destructive",onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),D.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(z,{variant:"outline",onClick:I,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),g&&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:g.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:g.privateKey})]})]})]})]})]})]})})}function xrr(){const{toast:s}=_i(),[t,n]=_.useState([]),[r,a]=_.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=_.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=Mae("presentation_count","desc"),h=u(t,{name:f=>{var g;return((g=f.name)==null?void 0:g.toLowerCase())||""},presentations:f=>f.presentation_count,views:f=>f.total_views,leads:f=>f.total_leads,cta_clicks:f=>f.total_cta_clicks,conversion:f=>f.total_views>0?f.total_leads/f.total_views*100:0});_.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:f,error:g}=await U.rpc("get_admin_presentation_stats");if(g)throw g;if(!f||f.length===0){l(!1);return}const v=f.map(C=>C.owner_user_id),{data:y,error:b}=await U.from("profiles").select("id, name, email, avatar_url").in("id",v);if(b)throw b;const w=new Map((y==null?void 0:y.map(C=>[C.id,C]))||[]),S=f.map(C=>{const E=w.get(C.owner_user_id);return{owner_user_id:C.owner_user_id,name:(E==null?void 0:E.name)||"Unknown",email:(E==null?void 0:E.email)||"",avatar_url:(E==null?void 0:E.avatar_url)||null,presentation_count:Number(C.presentation_count),total_views:Number(C.total_views),total_leads:Number(C.total_leads),total_cta_clicks:Number(C.total_cta_clicks)}});n(S),n(S),a({totalPresentations:S.reduce((C,E)=>C+E.presentation_count,0),totalViews:S.reduce((C,E)=>C+E.total_views,0),totalLeads:S.reduce((C,E)=>C+E.total_leads,0),totalCtaClicks:S.reduce((C,E)=>C+E.total_cta_clicks,0),agentsUsing:S.length})}catch(f){console.error("Error loading presentation stats:",f),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},p=[{label:"Agents Using",value:r.agentsUsing,icon:On,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:C0,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:xa,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Pl,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:Gh,color:"text-rose-600"}];return e.jsx($s,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:p.map(f=>e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:f.label}),e.jsx(f.icon,{className:`h-4 w-4 ${f.color}`})]}),e.jsx(Le,{children:i?e.jsx(ln,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:f.value.toLocaleString()})})]},f.label))}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Le,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((f,g)=>e.jsx(ln,{className:"h-12 w-full"},g))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Hh,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Hh,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Hh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Hh,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Hh,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Hh,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(Qa,{children:h.map(f=>{var v,y;const g=f.total_views>0?(f.total_leads/f.total_views*100).toFixed(1):"0.0";return e.jsxs(fn,{children:[e.jsx(yt,{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:f.avatar_url?e.jsx("img",{src:f.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((y=(v=f.name)==null?void 0:v.charAt(0))==null?void 0:y.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:f.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:f.email})]})]})}),e.jsx(yt,{className:"text-center font-medium",children:f.presentation_count}),e.jsx(yt,{className:"text-center",children:f.total_views.toLocaleString()}),e.jsx(yt,{className:"text-center",children:f.total_leads>0?e.jsx(ze,{variant:"secondary",children:f.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(yt,{className:"text-center",children:f.total_cta_clicks}),e.jsx(yt,{className:"text-center",children:e.jsxs("span",{className:Number(g)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[g,"%"]})})]},f.owner_user_id)})})]})})]})]})})}const KBe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",grr=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function yrr(){const{toast:s}=_i(),[t,n]=_.useState(!0),[r,a]=_.useState([]),[i,l]=_.useState({}),[o,c]=_.useState("");_.useEffect(()=>{(async()=>{try{n(!0);const v=[],y=1e3;for(let S=0;;S+=y){const{data:C,error:E}=await U.from("listing_presentations").select("id, owner_user_id, title, status, property_address_line1, city, state, list_price, template_id, last_generated_at, created_at, updated_at").order("created_at",{ascending:!1}).range(S,S+y-1);if(E)throw E;if(v.push(...C??[]),!C||C.lengthS.owner_user_id))),w={};for(let S=0;S{w[E.id]={name:E.name??"Unknown",email:E.email??""}})}l(w)}catch(v){console.error(v),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=_.useMemo(()=>{const g=Date.now(),v=g-7*24*60*60*1e3,y=g-30*24*60*60*1e3;return{total:r.length,generated:r.filter(b=>!!b.last_generated_at).length,agents:new Set(r.map(b=>b.owner_user_id)).size,thisWeek:r.filter(b=>new Date(b.created_at).getTime()>=v).length,thisMonth:r.filter(b=>new Date(b.created_at).getTime()>=y).length}},[r]),u=_.useMemo(()=>{const g=new Map;return r.forEach(v=>{const y=i[v.owner_user_id],b=g.get(v.owner_user_id)??{user_id:v.owner_user_id,name:(y==null?void 0:y.name)??"Unknown",email:(y==null?void 0:y.email)??"",total:0,generated:0,last_activity:v.updated_at};b.total+=1,v.last_generated_at&&(b.generated+=1),new Date(v.updated_at)>new Date(b.last_activity)&&(b.last_activity=v.updated_at),g.set(v.owner_user_id,b)}),Array.from(g.values()).sort((v,y)=>y.total-v.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(g=>g.name.toLowerCase().includes(h)||g.email.toLowerCase().includes(h)):u,p=h?r.filter(g=>{const v=i[g.owner_user_id];return(g.title??"").toLowerCase().includes(h)||(g.property_address_line1??"").toLowerCase().includes(h)||(g.city??"").toLowerCase().includes(h)||((v==null?void 0:v.name)??"").toLowerCase().includes(h)||((v==null?void 0:v.email)??"").toLowerCase().includes(h)}):r,f=[{label:"Total presentations",value:d.total,icon:$r,sub:"All time"},{label:"Agents using it",value:d.agents,icon:On,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:un,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:Ud,sub:`${d.thisWeek} in last 7 days`}];return e.jsx($s,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{title:"Listing Presentation Studio",description:"Adoption and usage of the Listing Presentation Studio across all agents"}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(g=>e.jsx(ln,{className:"h-28 w-full"},g))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:f.map(g=>e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g.sub})]})]},g.label))}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:g=>c(g.target.value)})]}),e.jsxs(Qr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Wt,{value:"all",children:["All presentations (",p.length,")"]})]}),e.jsx(Kt,{value:"agents",children:e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-right",children:"Presentations"}),e.jsx(Tt,{className:"text-right",children:"Generated"}),e.jsx(Tt,{children:"Last activity"})]})}),e.jsxs(Qa,{children:[m.map(g=>e.jsxs(fn,{children:[e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]}),e.jsx(yt,{className:"text-right font-semibold",children:g.total}),e.jsx(yt,{className:"text-right",children:g.generated}),e.jsx(yt,{children:KBe(g.last_activity)})]},g.user_id)),!t&&m.length===0&&e.jsx(fn,{children:e.jsx(yt,{colSpan:4,className:"py-10 text-center text-muted-foreground",children:"No agents have created a listing presentation yet."})})]})]})})})}),e.jsx(Kt,{value:"all",children:e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Presentation"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Price"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Last generated"})]})}),e.jsxs(Qa,{children:[p.slice(0,300).map(g=>{var v,y;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:g.title||"Untitled"}),e.jsxs(yt,{children:[e.jsx("div",{children:((v=i[g.owner_user_id])==null?void 0:v.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((y=i[g.owner_user_id])==null?void 0:y.email)??""})]}),e.jsx(yt,{className:"text-sm",children:[g.property_address_line1,g.city,g.state].filter(Boolean).join(", ")||"—"}),e.jsx(yt,{children:grr(g.list_price)}),e.jsx(yt,{children:e.jsx(ze,{variant:g.last_generated_at?"default":"secondary",children:g.last_generated_at?"Generated":g.status||"Draft"})}),e.jsx(yt,{children:KBe(g.created_at)}),e.jsx(yt,{children:KBe(g.last_generated_at)})]},g.id)}),!t&&p.length===0&&e.jsx(fn,{children:e.jsx(yt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const Tee="listing_revival";function vrr(){const{user:s,loading:t,isAdmin:n}=hs(),{data:r}=rt({queryKey:["feature-entitlement",Tee,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",Tee).maybeSingle();if(i)throw i;return{tier:(a==null?void 0:a.tier)??null}}});return{hasAccess:!0,tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t}}const brr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function _rr(){var u,h;const{user:s}=hs(),t=$t(),[n,r]=_.useState(""),a=rt({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:p}=await U.rpc("get_admin_listing_revival_stats");if(p)throw p;return m??[]}}),i=rt({queryKey:["lr-admin-members",n],queryFn:async()=>{let m=U.from("profiles").select("id, name, email").order("name").limit(200);if(n.trim()){const b=`%${n.trim()}%`;m=m.or(`email.ilike.${b},name.ilike.${b}`)}const{data:p,error:f}=await m;if(f)throw f;const g=(p??[]).map(b=>b.id),{data:v}=await U.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",Tee).in("user_id",g.length?g:["00000000-0000-0000-0000-000000000000"]),y=new Map((v??[]).map(b=>[b.user_id,b]));return(p??[]).map(b=>{var w;return{user_id:b.id,name:b.name,email:b.email,enabled:!!((w=y.get(b.id))!=null&&w.enabled)}})}}),l=mt({mutationFn:async({userId:m,enabled:p})=>{const{error:f}=await U.from("feature_entitlements").upsert({user_id:m,feature_key:Tee,enabled:p,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(f)throw f;await U.from("feature_entitlement_audit").insert({feature_key:Tee,target_user_id:m,action:p?"grant":"revoke",performed_by:s.id})},onSuccess:(m,p)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),ne.success(p.enabled?"Access granted":"Access revoked")},onError:m=>ne.error(m.message)}),o=rt({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(f=>f.owner_user_id),{data:p}=await U.from("profiles").select("id, name, email").in("id",m);return new Map((p??[]).map(f=>[f.id,f]))}}),c=_.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((p,f)=>p+Number(f.campaign_count),0),leads:m.reduce((p,f)=>p+Number(f.lead_count),0),hot:m.reduce((p,f)=>p+Number(f.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:On},{label:"Campaigns built",value:c.campaigns,icon:un},{label:"Seller leads",value:c.leads,icon:Xf},{label:"Hot leads",value:c.hot,icon:vu}];return e.jsxs($s,{title:"Listing Revival Admin",children:[e.jsx(Xh,{title:"Listing Revival",description:"Track adoption, campaign output and seller leads — and control who gets access."}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4 mt-6",children:d.map(m=>e.jsx(be,{children:e.jsxs(Le,{className:"p-5 flex items-center gap-4",children:[e.jsx("div",{className:"rounded-xl bg-amber-500/15 text-amber-600 p-3",children:e.jsx(m.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:a.isLoading?"—":m.value}),e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wider",children:m.label})]})]})},m.label))}),e.jsxs(Qr,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"usage",children:"Agent usage"}),e.jsx(Wt,{value:"access",children:"Access"})]}),e.jsx(Kt,{value:"usage",className:"mt-4",children:e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Usage by agent"})}),e.jsx(Le,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(ln,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-right",children:"Campaigns"}),e.jsx(Tt,{className:"text-right",children:"Live pages"}),e.jsx(Tt,{className:"text-right",children:"Leads"}),e.jsx(Tt,{className:"text-right",children:"Hot"}),e.jsx(Tt,{className:"text-right",children:"Engagement"}),e.jsx(Tt,{className:"text-right",children:"Last activity"})]})}),e.jsx(Qa,{children:[...a.data].sort((m,p)=>Number(p.campaign_count)-Number(m.campaign_count)).map(m=>{var f;const p=(f=o.data)==null?void 0:f.get(m.owner_user_id);return e.jsxs(fn,{children:[e.jsxs(yt,{children:[e.jsx("div",{className:"font-medium",children:(p==null?void 0:p.name)??"Agent"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(p==null?void 0:p.email)??m.owner_user_id.slice(0,8)})]}),e.jsx(yt,{className:"text-right tabular-nums",children:m.campaign_count}),e.jsx(yt,{className:"text-right tabular-nums",children:m.published_count}),e.jsx(yt,{className:"text-right tabular-nums",children:m.lead_count}),e.jsx(yt,{className:"text-right",children:Number(m.hot_lead_count)>0?e.jsx(ze,{className:"bg-red-500/15 text-red-600 hover:bg-red-500/15",children:m.hot_lead_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(yt,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(yt,{className:"text-right text-sm text-muted-foreground",children:brr(m.last_activity)})]},m.owner_user_id)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-6",children:"No campaigns have been created yet."})})]})}),e.jsx(Kt,{value:"access",className:"mt-4",children:e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Rr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search agents by name or email",value:n,onChange:m=>r(m.target.value)})]}),i.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(ln,{className:"h-10 w-full"},m))}):e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{className:"text-right",children:"Access"})]})}),e.jsx(Qa,{children:(i.data??[]).map(m=>e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium",children:m.name??"—"}),e.jsx(yt,{className:"text-muted-foreground",children:m.email??"—"}),e.jsx(yt,{className:"text-right",children:e.jsx(mn,{checked:m.enabled,onCheckedChange:p=>l.mutate({userId:m.user_id,enabled:p})})})]},m.user_id))})]})]})]})})]})]})}function wrr(){const{toast:s}=_i(),[t,n]=_.useState([]),[r,a]=_.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=_.useState(!0);_.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await U.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(v=>v.agent_id),{data:m,error:p}=await U.from("profiles").select("id, name, email, avatar_url").in("id",h);if(p)throw p;const f=new Map((m==null?void 0:m.map(v=>[v.id,v]))||[]),g=d.map(v=>{const y=f.get(v.agent_id);return{agent_id:v.agent_id,name:(y==null?void 0:y.name)||"Unknown",email:(y==null?void 0:y.email)||"",avatar_url:(y==null?void 0:y.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)}});g.sort((v,y)=>y.total_visitors-v.total_visitors),n(g),a({totalOpenHouses:g.reduce((v,y)=>v+y.open_house_count,0),totalVisitors:g.reduce((v,y)=>v+y.total_visitors,0),totalLeads:g.reduce((v,y)=>v+y.total_leads,0),activeOpenHouses:g.reduce((v,y)=>v+y.active_count,0),agentsUsing:g.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:On,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:sa,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Xl,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:xa,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Pl,color:"text-rose-600"}];return e.jsx($s,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Nt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Le,{children:i?e.jsx(ln,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Le,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(ln,{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(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Open Houses"}),e.jsx(Tt,{className:"text-center",children:"Active"}),e.jsx(Tt,{className:"text-center",children:"Visitors"}),e.jsx(Tt,{className:"text-center",children:"Leads"}),e.jsx(Tt,{className:"text-center",children:"Conversion"})]})}),e.jsx(Qa,{children:t.map(d=>{var h,m;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(fn,{children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((m=(h=d.name)==null?void 0:h.charAt(0))==null?void 0:m.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email})]})]})}),e.jsx(yt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(yt,{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(yt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(yt,{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(yt,{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 jrr(){const[s]=Gl(),t=zn(),[n,r]=_.useState("loading"),a=_.useRef(!1),[i,l]=_.useState("Processing connection...");return _.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),ne.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ne.error("Failed to connect: No authorization code");return}try{const{data:m,error:p}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(p){let f=p.message||"Failed to connect accounts";try{const g=p.context;if(g&&typeof g.json=="function"){const v=await g.json();v!=null&&v.error&&(f=v.error)}}catch{}throw new Error(f)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),ne.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),r("error"),l(m.message||"Failed to complete connection"),ne.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(bt,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Xl,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Bd,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Nt,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(En,{children:i})]}),e.jsx(Le,{className:"flex justify-center",children:e.jsx(z,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Nrr(){const s=$t(),[t,n]=_.useState(""),[r,a]=_.useState(""),[i,l]=_.useState([]),o=_.useRef(null),{data:c,isLoading:d}=rt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:w}=await U.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(w)throw w;return b}}),u=(c==null?void 0:c.filter(b=>b.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(b=>b.status==="sent").length)||0,converted:(c==null?void 0:c.filter(b=>b.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=mt({mutationFn:async b=>{const{data:w,error:S}=await U.functions.invoke("send-prospect-email",{body:{emails:b}});if(S)throw S;return w},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ne.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{ne.error("Failed to send: "+b.message)}}),p=mt({mutationFn:async()=>{var C,E;const{data:{user:b}}=await U.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:w,error:S}=await U.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(E=(C=b.user_metadata)==null?void 0:C.name)==null?void 0:E.split(" ")[0]}],test_mode:!0}});if(S)throw S;return w},onSuccess:()=>{ne.success("Test email sent to your inbox!")},onError:b=>{ne.error("Failed to send test: "+b.message)}}),f=mt({mutationFn:async()=>{const{data:b,error:w}=await U.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(w)throw w;return b},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ne.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{ne.error("Failed to send live lead invites: "+b.message)}}),g=()=>{if(!t.trim()){ne.error("Please enter an email address");return}if(c==null?void 0:c.find(w=>w.email.toLowerCase()===t.trim().toLowerCase())){ne.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},v=b=>{var C;const w=(C=b.target.files)==null?void 0:C[0];if(!w)return;const S=new FileReader;S.onload=E=>{var F,q;const M=((F=E.target)==null?void 0:F.result).split(` `).filter(G=>G.trim()),I=[],D=(q=M[0])!=null&&q.toLowerCase().includes("email")?1:0;for(let G=D;GZ.trim().replace(/"/g,"")),H=V[0],K=V[1];H&&H.includes("@")&&I.push({email:H,first_name:K||void 0})}l(I),ne.success(`${I.length} entries loaded from CSV`)},S.readAsText(w),o.current&&(o.current.value="")},y=()=>{if(i.length===0){ne.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(S=>S.email.toLowerCase()))||[]),w=i.filter(S=>!b.has(S.email.toLowerCase()));if(w.length===0){ne.error("All emails have already been prospected");return}w.length0&&e.jsxs(be,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Nv,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(ze,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(En,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Le,{children:e.jsxs(z,{onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2",children:[f.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(bu,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(En,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(bt,{className:"h-3 w-3 animate-spin"}):e.jsx(on,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Le,{children:e.jsxs(Qr,{defaultValue:"single",children:[e.jsxs(Jr,{className:"mb-4",children:[e.jsxs(Wt,{value:"single",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Wt,{value:"bulk",children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Kt,{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(ee,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(pe,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>n(b.target.value),onKeyDown:b=>b.key==="Enter"&&g()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(ee,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(pe,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&g()})]}),e.jsxs(z,{onClick:g,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Kt,{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(z,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx($r,{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(On,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(er,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((b,w)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},w)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(z,{onClick:y,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(En,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Le,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,w)=>e.jsx(ln,{className:"h-12 w-full"},w))}):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:"Source"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(b=>{var w;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:b.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Ys(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(ze,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Mr,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.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(Nv,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:(w=b.utm_source)!=null&&w.startsWith("toolbox:")?e.jsxs(ze,{variant:"outline",className:"gap-1 font-normal",children:[e.jsx($r,{className:"h-3 w-3"}),b.utm_source.replace("toolbox:","")]}):b.utm_source||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?Ys(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id)})})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(bu,{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 Lz(s){const t=$t(),{toast:n}=_i(),r=rt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=rt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:m,error:p}=await U.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(p)throw p;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=mt({mutationFn:async c=>{const{data:{user:d}}=await U.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:m}=await U.from("recruit_prospects").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=mt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await U.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=mt({mutationFn:async c=>{const{error:d}=await U.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function krr(s){const t=$t(),{toast:n}=_i(),r=rt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await U.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=mt({mutationFn:async i=>{const{data:{user:l}}=await U.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await U.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const W4t=(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 Nit({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=_.useState(W4t(r,n)),c=u=>h=>o(m=>({...m,[u]:h.target.value})),d=u=>{u.preventDefault(),a({...l,experience_years:l.experience_years?parseInt(l.experience_years):null,last_year_transactions:l.last_year_transactions?parseInt(l.last_year_transactions):null,stage_id:l.stage_id||null}),o(W4t(r,n)),t(!1)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(Qr,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-4",children:[e.jsx(Wt,{value:"basic",children:"Basic Info"}),e.jsx(Wt,{value:"production",children:"Production"}),e.jsx(Wt,{value:"social",children:"Social & Web"}),e.jsx(Wt,{value:"personal",children:"Personal"})]}),e.jsxs(Kt,{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(ee,{children:"First Name *"}),e.jsx(pe,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{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(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{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(ee,{children:"License #"}),e.jsx(pe,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Experience (years)"}),e.jsx(pe,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Address"}),e.jsx(pe,{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(ee,{children:"City"}),e.jsx(pe,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Zip"}),e.jsx(pe,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Pipeline Stage"}),e.jsxs(ls,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:n.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Referred By"}),e.jsx(pe,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(Kt,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Annual Production Volume"}),e.jsx(pe,{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(ee,{children:"Last Year Volume"}),e.jsx(pe,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Year Transactions"}),e.jsx(pe,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Avg Sale Price"}),e.jsx(pe,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Specialties / Niche"}),e.jsx(pe,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(Kt,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"LinkedIn URL"}),e.jsx(pe,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website URL"}),e.jsx(pe,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Instagram Handle"}),e.jsx(pe,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Facebook URL"}),e.jsx(pe,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(Kt,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Birthday"}),e.jsx(pe,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Spouse / Partner Name"}),e.jsx(pe,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Interests / Hobbies"}),e.jsx(pe,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ps,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function gDe(){const{user:s}=hs();return rt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([U.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),U.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function kit({value:s,onChange:t}){const{data:n,isLoading:r}=gDe();return e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Send from"}),e.jsxs(ls,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(He,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(i7,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(He,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(on,{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 pas({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState("default"),[g,v]=_.useState(!1),y=$t(),{data:b}=gDe();_.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),f(b!=null&&b.massEmail?"mass_email":b!=null&&b.gmail?"gmail":"default"))},[s,c,o,b==null?void 0:b.massEmail,b==null?void 0:b.gmail]);const w=async()=>{var S,C;if(!i){ne.error("This prospect has no email address on file.");return}v(!0);try{const{data:E,error:P}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:p}});if(P)throw P;if(((E==null?void 0:E.sent)??0)>0)ne.success(`Email sent to ${i}`),y.invalidateQueries({queryKey:["recruit-videos"]}),y.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const I=((C=(S=E==null?void 0:E.results)==null?void 0:S[0])==null?void 0:C.error)||"Failed to send";ne.error(I)}}catch(E){ne.error((E==null?void 0:E.message)||"Failed to send email")}finally{v(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsx(pe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(kit,{value:p,onChange:f}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:d,onChange:S=>u(S.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ps,{value:h,onChange:S=>m(S.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(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs(z,{onClick:w,disabled:g||!i,children:[g?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function $4(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const yZe=[{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 Srr(s){return rt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Crr(s){return rt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function fas(){const s=$t(),{toast:t}=_i();return mt({mutationFn:async n=>{const{data:{user:r}}=await U.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await U.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 xas(){const s=$t();return mt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await U.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 gas(s){return rt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 Arr(){const s=$t(),{toast:t}=_i();return mt({mutationFn:async n=>{const{data:{user:r}}=await U.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await U.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 Err(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function Trr({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var H;const{data:a=[],isLoading:i}=Crr(s),{data:l=[]}=gas(r),o=fas(),c=RC();xas();const[d,u]=_.useState("idle"),[h,m]=_.useState(0),[p,f]=_.useState(0),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState(!1),[C,E]=_.useState(null),[P,M]=_.useState(null),[I,D]=_.useState(null),F=((H=l.find(K=>K.id===g))==null?void 0:H.script_text)||"",q=()=>{u("idle"),m(0),f(0),v(""),b("")},G=_.useCallback(async(K,Z)=>{u("uploading");try{const oe=`Recruiting: ${t}`,{videoId:re,libraryId:ae}=await qL(oe),{uploadUrl:J,apiKey:te}=await VL(re),ce=new XMLHttpRequest;ce.upload.onprogress=Oe=>{Oe.lengthComputable&&m(Oe.loaded/Oe.total*100)},await new Promise((Oe,ke)=>{ce.onload=()=>ce.status>=200&&ce.status<300?Oe():ke(new Error("Upload failed")),ce.onerror=()=>ke(new Error("Upload failed")),ce.open("PUT",J),ce.setRequestHeader("AccessKey",te),ce.send(K)}),u("processing");let ve=0;const me=Date.now(),he=9e4,ge=`https://iframe.mediadelivery.net/embed/${ae}/${re}`;for(;ve<4&&(await new Promise(ke=>setTimeout(ke,3e3)),!(Date.now()-me>he));){const Oe=await DN(re);if(ve=Oe.status,f(Oe.encodeProgress||0),ve===5||ve===6)throw new Error("Video processing failed")}const Ee=await DN(re),Ne=(Ee.storageSize||K.size)/(1024*1024),Pe=await c.mutateAsync({bunny_video_id:re,playback_url:Ee.directPlayUrl||ge,thumbnail_url:Ee.thumbnailUrl,preview_url:Ee.previewUrl||null,duration_seconds:Ee.length||Z,file_size_mb:Ne,title:oe,status:ve>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Pe.id,brokerage_id:r,message:y||void 0}),u("done"),ne.success("Video recorded and linked to prospect!"),setTimeout(()=>{S(!1),q()},1500)}catch(oe){ne.error(oe.message||"Failed to upload video"),u("record")}},[s,t,r,y,c,o]),V=K=>{K&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${K}`),ne.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(Xr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(Is,{open:w,onOpenChange:K=>{!K&&(d==="uploading"||d==="processing")||(S(K),K||q())},children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsxs(Rs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(ls,{value:g,onValueChange:v,children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{placeholder:"No script — speak freely"})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No script"}),l.map(K=>{var Z;return e.jsx(He,{value:K.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[K.title,e.jsx(ze,{variant:"outline",className:"text-[9px] ml-1",children:(Z=yZe.find(oe=>oe.value===K.category))==null?void 0:Z.label})]})},K.id)})]})]}),F&&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:F})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ps,{value:y,onChange:K=>b(K.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(z,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(YE,{maxDurationSeconds:600,onRecordingComplete:G,teleprompterContent:F||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(Di,{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(Di,{value:p,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(p),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(su,{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(K=>{var Z;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:$4(K.video)?e.jsx("img",{src:$4(K.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(Xr,{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:((Z=K.video)==null?void 0:Z.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[K.view_count>0?e.jsxs(ze,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(xa,{className:"h-2.5 w-2.5 mr-0.5"}),K.view_count]}):K.sent_at?e.jsxs(ze,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Fr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(ze,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(K.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>V(K.share_token),title:"Copy link",children:e.jsx(Sa,{className:"h-3 w-3"})}),e.jsxs(z,{variant:K.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var oe;E(K.id),M(((oe=K.video)==null?void 0:oe.title)||null),D(K.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(on,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:K.sent_at?"Resend":"Email"})]})]})]},K.id)})}),C&&e.jsx(pas,{open:!!C,onOpenChange:K=>{K||E(null)},recruitVideoId:C,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:P,defaultMessage:I})]})}function Mrr({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=rt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=U.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx($r,{className:"h-4 w-4"}),"Use Template",e.jsx(cl,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(qd,{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(bt,{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(Iy,{}),e.jsx(qP,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(ua,{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 Prr({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=hs(),o=(a||"").split(" ")[0]||"there",[c,d]=_.useState(""),[u,h]=_.useState(""),[m,p]=_.useState("default"),[f,g]=_.useState(!1),[v,y]=_.useState(null),[b,w]=_.useState(!1),S=$t(),{data:C}=gDe();_.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const F=C!=null&&C.massEmail?"mass_email":C!=null&&C.gmail?"gmail":"default";p(F),y(null),w(!1)}},[s,o,C==null?void 0:C.massEmail,C==null?void 0:C.gmail]);const{data:E=[],isLoading:P}=rt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:F,error:q}=await U.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(q)throw q;return F??[]},enabled:s&&!!(l!=null&&l.id)}),M=E.find(F=>F.id===v)||null,I=async()=>{var F,q;if(!i){ne.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ne.error("Subject and message are required.");return}g(!0);try{if(v){const{data:G}=await U.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",v).maybeSingle();let V=G==null?void 0:G.id;if(!V){const{data:oe,error:re}=await U.from("recruit_videos").insert({prospect_id:n,video_id:v,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(re)throw re;V=oe.id}const{data:H,error:K}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[V],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(K)throw K;if(((H==null?void 0:H.sent)??0)>0)ne.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-videos"]}),S.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const oe=((q=(F=H==null?void 0:H.results)==null?void 0:F[0])==null?void 0:q.error)||"Failed to send";ne.error(oe)}}else{const{data:G,error:V}=await U.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(V)throw V;G!=null&&G.success?(ne.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ne.error((G==null?void 0:G.error)||"Failed to send")}}catch(G){ne.error((G==null?void 0:G.message)||"Failed to send email")}finally{g(!1)}},D=F=>{const q=G=>G.replace(/\[First Name\]/gi,o);d(q(F.subject)),h(q(F.body)),ne.success(`Loaded "${F.title}"`)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsx(pe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(kit,{value:m,onChange:p}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(Mrr,{brokerageId:r,onSelect:D})]}),e.jsx(pe,{value:c,onChange:F=>d(F.target.value)}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Message"}),e.jsx(Ps,{value:u,onChange:F=>h(F.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(ee,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Include a video"]}),M?e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{y(null),w(!1)},children:[e.jsx(er,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(z,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>w(F=>!F),children:b?"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:$4(M)?e.jsx("img",{src:$4(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(Xr,{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&&b&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:P?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):E.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."}):E.map(F=>e.jsxs("button",{type:"button",onClick:()=>{y(F.id),w(!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:$4(F)?e.jsx("img",{src:$4(F),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Xr,{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:F.title||"Untitled video"}),F.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(F.duration_seconds/60),":",String(Math.floor(F.duration_seconds%60)).padStart(2,"0")]})]})]},F.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(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>t(!1),disabled:f,children:"Cancel"}),e.jsxs(z,{onClick:I,disabled:f||!i,children:[f?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Lrr(s){return rt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const K4t=[{value:"call",label:"Phone Call",icon:va},{value:"email",label:"Email",icon:on},{value:"text",label:"Text Message",icon:qi},{value:"meeting",label:"Meeting",icon:ya},{value:"note",label:"Note",icon:$r},{value:"campaign_email",label:"Campaign Email",icon:Fr}];function Sw({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 Hde({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(mr,{className:"h-3 w-3 opacity-50"})]}):null}function jp({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:s}),e.jsx(pe,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Sit({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=krr((s==null?void 0:s.id)||null),{data:d=[]}=Lrr((s==null?void 0:s.id)||null),[u,h]=_.useState({type:"note",title:"",description:""}),[m,p]=_.useState(!1),[f,g]=_.useState(!1),[v,y]=_.useState({}),[b,w]=_.useState(!1);if(!s)return null;const S=()=>{var V,H;y({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:((V=s.experience_years)==null?void 0:V.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:((H=s.last_year_transactions)==null?void 0:H.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||""}),g(!0)},C=()=>{const V={id:s.id};for(const[H,K]of Object.entries(v))H==="experience_years"||H==="last_year_transactions"?V[H]=K?parseInt(K):null:V[H]=K||null;i(V),g(!1)},E=()=>g(!1),P=V=>H=>y(K=>({...K,[V]:H})),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:""}),p(!1))},I=t.find(V=>V.id===s.stage_id),D=s.address||s.city||s.state,F=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,q=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,G=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(Wg,{open:r,onOpenChange:V=>{V||g(!1),a(V)},children:[e.jsx(gg,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Ki,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(Dy,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ry,{className:"text-xl",children:[s.first_name," ",s.last_name]}),I&&e.jsx(ze,{variant:"outline",style:{borderColor:I.color,color:I.color},className:"mt-1",children:I.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[f?e.jsxs(e.Fragment,{children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:E,children:e.jsx(er,{className:"h-4 w-4"})}),e.jsx(z,{variant:"default",size:"icon",onClick:C,children:e.jsx(Bo,{className:"h-4 w-4"})})]}):e.jsx(z,{variant:"ghost",size:"icon",onClick:S,title:"Edit prospect",children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Delete prospect?"}),e.jsx(ql,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!f&&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(on,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(z,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>w(!0),children:[e.jsx(on,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(va,{className:"h-3.5 w-3.5"})," ",s.phone]}),D&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ha,{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(ee,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(ls,{value:s.stage_id||"",onValueChange:V=>i({id:s.id,stage_id:V}),children:[e.jsx(rs,{className:"mt-1",children:e.jsx(cs,{})}),e.jsx(as,{children:t.map(V=>e.jsx(He,{value:V.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:V.color}}),V.name]})},V.id))})]})]}),e.jsxs(Qr,{defaultValue:"details",className:"w-full",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Wt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Wt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Wt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Wt,{value:"personal",className:"text-xs",children:"Personal"})]}),f?e.jsxs(e.Fragment,{children:[e.jsxs(Kt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jp,{label:"First Name",value:v.first_name,onChange:P("first_name")}),e.jsx(jp,{label:"Last Name",value:v.last_name,onChange:P("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jp,{label:"Email",value:v.email,onChange:P("email"),type:"email"}),e.jsx(jp,{label:"Phone",value:v.phone,onChange:P("phone")})]}),e.jsx(jp,{label:"Current Brokerage",value:v.current_brokerage,onChange:P("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jp,{label:"License #",value:v.license_number,onChange:P("license_number")}),e.jsx(jp,{label:"Experience (years)",value:v.experience_years,onChange:P("experience_years"),type:"number"})]}),e.jsx(jp,{label:"Address",value:v.address,onChange:P("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(jp,{label:"City",value:v.city,onChange:P("city")}),e.jsx(jp,{label:"State",value:v.state,onChange:P("state")}),e.jsx(jp,{label:"Zip",value:v.zip_code,onChange:P("zip_code")})]}),e.jsx(jp,{label:"Source",value:v.source,onChange:P("source")}),e.jsx(jp,{label:"Referred By",value:v.referred_by,onChange:P("referred_by")}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Notes"}),e.jsx(Ps,{value:v.notes,onChange:V=>y(H=>({...H,notes:V.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Kt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(jp,{label:"Annual Production",value:v.annual_production,onChange:P("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(jp,{label:"Last Year Volume",value:v.last_year_volume,onChange:P("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(jp,{label:"Last Year Transactions",value:v.last_year_transactions,onChange:P("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(jp,{label:"Avg Sale Price",value:v.avg_sale_price,onChange:P("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(jp,{label:"Specialties / Niche",value:v.specialties,onChange:P("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Kt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(jp,{label:"LinkedIn URL",value:v.linkedin_url,onChange:P("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(jp,{label:"Website URL",value:v.website_url,onChange:P("website_url"),type:"url",placeholder:"https://..."}),e.jsx(jp,{label:"Instagram Handle",value:v.instagram_handle,onChange:P("instagram_handle"),placeholder:"@handle"}),e.jsx(jp,{label:"Facebook URL",value:v.facebook_url,onChange:P("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Kt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(jp,{label:"Birthday",value:v.birthday,onChange:P("birthday"),type:"date"}),e.jsx(jp,{label:"Spouse / Partner",value:v.spouse_name,onChange:P("spouse_name")}),e.jsx(jp,{label:"Interests / Hobbies",value:v.interests,onChange:P("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Kt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Sw,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(Sw,{label:"License #",value:s.license_number}),e.jsx(Sw,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(Sw,{label:"Referred By",value:s.referred_by}),e.jsx(Sw,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(Kt,{value:"production",className:"mt-3",children:F?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Sw,{label:"Annual Production",value:s.annual_production}),e.jsx(Sw,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(Sw,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(Sw,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(Sw,{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(Kt,{value:"social",className:"mt-3",children:q?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Hde,{label:"LinkedIn",url:s.linkedin_url,icon:fg}),e.jsx(Hde,{label:"Website",url:s.website_url,icon:Wo}),s.instagram_handle&&e.jsx(Hde,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Fm}),e.jsx(Hde,{label:"Facebook",url:s.facebook_url,icon:of})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Kt,{value:"personal",className:"mt-3",children:G?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Sw,{label:"Birthday",value:s.birthday?Ys(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Ko}),e.jsx(Sw,{label:"Spouse / Partner",value:s.spouse_name,icon:Fo}),e.jsx("div",{className:"col-span-2",children:e.jsx(Sw,{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(Trr,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(fc,{}),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(z,{size:"sm",variant:"outline",onClick:()=>p(!m),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),m&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(ls,{value:u.type,onValueChange:V=>h(H=>({...H,type:V})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:K4t.map(V=>e.jsx(He,{value:V.value,children:V.label},V.value))})]}),e.jsx(pe,{placeholder:"Subject / Title",value:u.title,onChange:V=>h(H=>({...H,title:V.target.value}))}),e.jsx(Ps,{placeholder:"Details (optional)",value:u.description,onChange:V=>h(H=>({...H,description:V.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(z,{size:"sm",onClick:M,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const V=[...o.map(H=>({type:"manual",data:H,date:H.created_at})),...d.map(H=>({type:"campaign_email",data:H,date:H.sent_at||H.created_at}))].sort((H,K)=>new Date(K.date).getTime()-new Date(H.date).getTime());return V.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):V.map(H=>{if(H.type==="manual"){const Z=H.data,oe=K4t.find(ae=>ae.value===Z.activity_type),re=(oe==null?void 0:oe.icon)||$r;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(re,{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:Z.title}),Z.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Z.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ys(new Date(Z.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${Z.id}`)}const K=H.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(Fr,{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 #",K.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:K.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[K.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(Fr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),K.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(xa,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Ys(new Date(K.opened_at),"MMM d, h:mm a")]}):K.status!=="failed"?e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,K.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(wy,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Ys(new Date(K.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ys(new Date(K.sent_at||K.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${K.id}`)})})()})]})]})})}),e.jsx(Prr,{open:b,onOpenChange:w,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const Irr=["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 Cit({open:s,onOpenChange:t,brokerageId:n,stages:r}){var D;const{toast:a}=_i(),i=$t(),l=_.useRef(null),[o,c]=_.useState([]),[d,u]=_.useState([]),[h,m]=_.useState({}),[p,f]=_.useState(((D=r[0])==null?void 0:D.id)||""),[g,v]=_.useState(!1),[y,b]=_.useState("upload"),[w,S]=_.useState(0),C=()=>{c([]),u([]),m({}),b("upload"),S(0)},E=F=>{var V;const q=(V=F.target.files)==null?void 0:V[0];if(!q)return;const G=new FileReader;G.onload=H=>{var te;const Z=((te=H.target)==null?void 0:te.result).split(/\r?\n/).filter(ce=>ce.trim());if(Z.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const oe=P(Z[0]);u(oe);const re={},ae=new Set;oe.forEach((ce,ve)=>{const me=ce.toLowerCase().replace(/[^a-z0-9]/g,"");let he=null;/^firstname$/.test(me)||me==="first"?he="first_name":/^lastname$/.test(me)||me==="last"?he="last_name":/^email$/.test(me)||me==="emailaddress"?he="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(me)?he="phone":/officename|currentbrokerage|brokerage|company/.test(me)?he="current_brokerage":/membernumber|licensenumber|license/.test(me)?he="license_number":/experienceyears|yearsexperience/.test(me)?he="experience_years":/^totalvolume$|annualproduction/.test(me)?he="annual_production":/^address$/.test(me)?he="address":/^city$/.test(me)?he="city":/^state$/.test(me)?he="state":/^postalcode$|^zip$|^zipcode$/.test(me)?he="zip_code":/listsidevolume|lastyearvolume/.test(me)?he="last_year_volume":/^totalcount$|lastyeartransactions/.test(me)?he="last_year_transactions":/avgsaleprice|averageprice/.test(me)?he="avg_sale_price":/linkedin/.test(me)?he="linkedin_url":/website/.test(me)?he="website_url":/specialt/.test(me)?he="specialties":/referr/.test(me)?he="referred_by":/^notes$|^note$/.test(me)&&(he="notes"),he&&!ae.has(he)&&(re[String(ve)]=he,ae.add(he))}),m(re);const J=Z.slice(1).map(ce=>{const ve=P(ce),me={};return oe.forEach((he,ge)=>{me[String(ge)]=ve[ge]||""}),me});c(J),b("map")},G.readAsText(q)},P=F=>{const q=[];let G="",V=!1;for(const H of F)H==='"'?V=!V:H===","&&!V?(q.push(G.trim()),G=""):G+=H;return q.push(G.trim()),q},M=async()=>{v(!0);try{const{data:{user:F}}=await U.auth.getUser();if(!F)throw new Error("Not authenticated");const q=o.map(V=>{const H={brokerage_id:n,created_by:F.id,stage_id:p,source:"csv_import",first_name:"Unknown"},K=H;return Object.entries(h).forEach(([Z,oe])=>{var ae;const re=(ae=V[Z])==null?void 0:ae.trim();re&&(oe==="experience_years"||oe==="last_year_transactions"?K[oe]=parseInt(re.replace(/[^0-9.-]/g,""))||null:oe==="annual_production"||oe==="last_year_volume"||oe==="avg_sale_price"?K[oe]=re.replace(/[^0-9.$,.-]/g,""):K[oe]=re)}),H});let G=0;for(let V=0;V{const F=`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`,q=new Blob([F],{type:"text/csv"}),G=URL.createObjectURL(q),V=document.createElement("a");V.href=G,V.download="recruit-prospects-template.csv",V.click(),URL.revokeObjectURL(G)};return e.jsx(Is,{open:s,onOpenChange:F=>{F||C(),t(F)},children:e.jsxs(Ls,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Import Prospects from CSV"})}),y==="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(xN,{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:E}),e.jsxs(z,{onClick:()=>{var F;return(F=l.current)==null?void 0:F.click()},children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(z,{variant:"link",className:"text-xs",onClick:I,children:"Download CSV template"})]}),y==="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(ls,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{})}),e.jsx(as,{children:r.map(F=>e.jsx(He,{value:F.id,children:F.name},F.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Tt,{className:"w-[160px]",children:"Map To"}),e.jsx(Tt,{children:"Preview"})]})}),e.jsx(Qa,{children:d.map((F,q)=>{var G;return e.jsxs(fn,{children:[e.jsx(yt,{className:"font-medium text-xs",children:F}),e.jsx(yt,{children:e.jsxs(ls,{value:h[String(q)]||"skip",onValueChange:V=>m(H=>({...H,[String(q)]:V==="skip"?"":V})),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"skip",children:"— Skip —"}),Irr.map(V=>e.jsx(He,{value:V,children:V.replace(/_/g," ")},V))]})]})}),e.jsx(yt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((G=o[0])==null?void 0:G[String(q)])||"—"})]},q)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>{C()},children:"Back"}),e.jsx(z,{onClick:M,disabled:g||!Object.values(h).includes("first_name"),children:g?"Importing...":`Import ${o.length} Prospects`})]})]}),y==="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(Wr,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[w," prospects imported successfully!"]}),e.jsx(z,{onClick:()=>{C(),t(!1)},children:"Close"})]})]})})}function yas({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=Lz(s),[o,c]=_.useState(!1),[d,u]=_.useState(),[h,m]=_.useState(null),[p,f]=_.useState(!1),[g,v]=_.useState(!1),[y,b]=_.useState(null),[w,S]=_.useState(""),[C,E]=_.useState("all");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 P=[...new Set(n.map(H=>H.source).filter(H=>!!H))].sort(),M=n.filter(H=>{const K=w.trim().toLowerCase();return(!K||`${H.first_name} ${H.last_name||""} ${H.current_brokerage||""} ${H.email||""}`.toLowerCase().includes(K))&&(C==="all"||H.source===C)}),I=H=>M.filter(K=>K.stage_id===H),D=(H,K)=>{b(K),H.dataTransfer.effectAllowed="move"},F=H=>{H.preventDefault(),H.dataTransfer.dropEffect="move"},q=(H,K)=>{H.preventDefault(),y&&(i.mutate({id:y,stage_id:K}),b(null))},G=H=>{u(H),c(!0)},V=H=>{m(H),f(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-md border bg-card p-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2 sm:flex-row",children:[e.jsxs("div",{className:"relative min-w-0 flex-1 sm:max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"h-9 pl-9",value:w,onChange:H=>S(H.target.value),placeholder:"Search pipeline…"})]}),e.jsxs(ls,{value:C,onValueChange:E,children:[e.jsxs(rs,{className:"h-9 w-full sm:w-[190px]",children:[e.jsx(F_,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(cs,{})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All sources"}),P.map(H=>e.jsx(He,{value:H,children:H.replace(/_/g," ")},H))]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(z,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",M.length," of ",n.length," prospects"]}),(w||C!=="all")&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{S(""),E("all")},children:"Clear filters"})]}),e.jsxs(Ki,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(H=>{const K=I(H.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:F,onDrop:Z=>q(Z,H.id),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between border-b pb-2 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:H.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:H.name}),e.jsx(ze,{variant:"secondary",className:"text-xs h-5 px-1.5",children:K.length})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>G(H.id),children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"min-h-[220px] space-y-2 rounded-md border border-dashed bg-muted/20 p-2",children:K.map(Z=>e.jsx(be,{className:"group cursor-pointer rounded-md border-l-4 p-3 shadow-xs transition-all hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md motion-reduce:hover:translate-y-0",style:{borderLeftColor:H.color},draggable:!0,onDragStart:oe=>D(oe,Z.id),onClick:()=>V(Z),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Zf,{className:"mt-0.5 h-4 w-4 cursor-grab text-muted-foreground/40 opacity-40 transition-opacity group-hover:opacity-100"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"truncate text-sm font-semibold",children:[Z.first_name," ",Z.last_name]}),Z.source&&e.jsx(ze,{variant:"secondary",className:"h-5 shrink-0 px-1.5 text-[9px] capitalize",children:Z.source.replace(/_/g," ")})]}),Z.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(oi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:Z.current_brokerage})]}),(Z.annual_production||Z.last_year_volume||Z.specialties)&&e.jsx("p",{className:"truncate text-[11px] font-medium text-primary",children:Z.last_year_volume||Z.annual_production||Z.specialties}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Z.email&&e.jsx(on,{className:"h-3 w-3 text-muted-foreground"}),Z.phone&&e.jsx(va,{className:"h-3 w-3 text-muted-foreground"}),!Z.email&&!Z.phone&&e.jsx("span",{className:"text-[10px] text-amber-700",children:"Contact info needed"})]}),Z.experience_years!=null&&e.jsxs(ze,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[Z.experience_years,"yr"]})]})]})]})},Z.id))})]},H.id)})}),e.jsx(Zre,{orientation:"horizontal"})]}),e.jsx(Nit,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:H=>a.mutate(H),isSubmitting:a.isPending}),e.jsx(Sit,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:f,onUpdate:H=>{i.mutate(H),m(K=>K?{...K,...H}:null)},onDelete:H=>l.mutate(H)}),e.jsx(Cit,{open:g,onOpenChange:v,brokerageId:s,stages:t})]})}function vZe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=Lz(s),{user:o}=hs(),c=$t(),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(!1),[g,v]=_.useState(!1),[y,b]=_.useState(""),[w,S]=_.useState("all"),[C,E]=_.useState("all"),[P,M]=_.useState("all"),[I,D]=_.useState(null),[F,q]=_.useState("asc"),[G,V]=_.useState(new Set),[H,K]=_.useState(!1),[Z,oe]=_.useState(""),re=_.useMemo(()=>{const ke=new Set;return n.forEach(Ve=>{Ve.current_brokerage&&ke.add(Ve.current_brokerage)}),Array.from(ke).sort()},[n]),{data:ae=[]}=rt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Ve)throw Ve;return ke}}),{data:J=[]}=rt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ve=[],_e=0;for(;;){const{data:Ae,error:Se}=await U.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(_e,_e+1e3-1);if(Se)throw Se;if(Ve=Ve.concat(Ae??[]),!Ae||Ae.length<1e3)break;_e+=1e3}return Ve}}),te=_.useMemo(()=>{const ke=new Map;return J.forEach(Ve=>{ke.has(Ve.prospect_id)||ke.set(Ve.prospect_id,new Set),ke.get(Ve.prospect_id).add(Ve.campaign_id)}),ke},[J]),ce=ke=>{I===ke?q(Ve=>Ve==="asc"?"desc":"asc"):(D(ke),q("asc"))},ve=({column:ke})=>I!==ke?e.jsx(Og,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):F==="asc"?e.jsx(ap,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(Vf,{className:"h-3.5 w-3.5 ml-1 text-primary"}),me=ke=>t.find(Ve=>Ve.id===ke),he=_.useMemo(()=>{let ke=n.filter(Ve=>{var qe,Be,Ze;const _e=!y||`${Ve.first_name} ${Ve.last_name}`.toLowerCase().includes(y.toLowerCase())||((qe=Ve.email)==null?void 0:qe.toLowerCase().includes(y.toLowerCase()))||((Be=Ve.current_brokerage)==null?void 0:Be.toLowerCase().includes(y.toLowerCase())),Ae=w==="all"||Ve.stage_id===w,Se=C==="all"||Ve.current_brokerage===C;let We=!0;return P==="in_campaign"?We=te.has(Ve.id):P==="not_in_campaign"?We=!te.has(Ve.id):P!=="all"&&(We=((Ze=te.get(Ve.id))==null?void 0:Ze.has(P))??!1),_e&&Ae&&Se&&We});return I&&(ke=[...ke].sort((Ve,_e)=>{var qe,Be;let Ae=null,Se=null;switch(I){case"name":Ae=`${Ve.first_name} ${Ve.last_name||""}`.toLowerCase(),Se=`${_e.first_name} ${_e.last_name||""}`.toLowerCase();break;case"stage":Ae=((qe=me(Ve.stage_id))==null?void 0:qe.sort_order)??999,Se=((Be=me(_e.stage_id))==null?void 0:Be.sort_order)??999;break;case"brokerage":Ae=(Ve.current_brokerage||"").toLowerCase(),Se=(_e.current_brokerage||"").toLowerCase();break;case"experience":Ae=Ve.experience_years??-1,Se=_e.experience_years??-1;break;case"production":Ae=(Ve.annual_production||"").toLowerCase(),Se=(_e.annual_production||"").toLowerCase();break;case"source":Ae=(Ve.source||"").toLowerCase(),Se=(_e.source||"").toLowerCase();break;default:return 0}if(Ae===Se)return 0;if(Ae==null)return 1;if(Se==null)return-1;const We=Ae0&&he.every(ke=>G.has(ke.id)),Ee=he.some(ke=>G.has(ke.id)),Ne=()=>{V(ge?new Set:new Set(he.map(ke=>ke.id)))},Pe=ke=>{V(Ve=>{const _e=new Set(Ve);return _e.has(ke)?_e.delete(ke):_e.add(ke),_e})},Oe=mt({mutationFn:async()=>{if(!Z||!(o!=null&&o.id))throw new Error("Select a campaign");const ke=new Set(J.filter(Ae=>Ae.campaign_id===Z).map(Ae=>Ae.prospect_id)),Ve=Array.from(G).filter(Ae=>!ke.has(Ae)).map(Ae=>({prospect_id:Ae,campaign_id:Z,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Ve.length===0)throw new Error("All selected prospects are already in this campaign");const{error:_e}=await U.from("recruit_campaign_assignments").insert(Ve);if(_e)throw _e;return Ve.length},onSuccess:ke=>{ne.success(`${ke} prospect(s) added to campaign`),K(!1),V(new Set),oe(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ke=>ne.error(ke.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(Rr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search prospects...",value:y,onChange:ke=>b(ke.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[G.size>0&&e.jsxs(z,{variant:"secondary",onClick:()=>K(!0),className:"gap-1.5",children:[e.jsx(Fr,{className:"h-4 w-4"})," Add ",G.size," to Campaign"]}),e.jsxs(z,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(z,{onClick:()=>u(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(F_,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(ls,{value:w,onValueChange:S,children:[e.jsx(rs,{className:"w-[160px] h-8 text-xs",children:e.jsx(cs,{placeholder:"All stages"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),t.map(ke=>e.jsx(He,{value:ke.id,children:ke.name},ke.id))]})]}),e.jsxs(ls,{value:C,onValueChange:E,children:[e.jsxs(rs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(oi,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(cs,{placeholder:"All brokerages"})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All brokerages"}),re.map(ke=>e.jsx(He,{value:ke,children:ke},ke))]})]}),e.jsxs(ls,{value:P,onValueChange:M,children:[e.jsxs(rs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(cs,{placeholder:"Campaign status"})]}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All contacts"}),e.jsx(He,{value:"in_campaign",children:"In any campaign"}),e.jsx(He,{value:"not_in_campaign",children:"Not in any campaign"}),ae.map(ke=>e.jsxs(He,{value:ke.id,children:["In: ",ke.name]},ke.id))]})]}),(w!=="all"||C!=="all"||P!=="all")&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{S("all"),E("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(za,{checked:ge,onCheckedChange:Ne,"aria-label":"Select all",...Ee&&!ge?{"data-state":"indeterminate"}:{}})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>ce("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(ve,{column:"name"})]})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>ce("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(ve,{column:"stage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>ce("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(ve,{column:"brokerage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ce("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(ve,{column:"experience"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ce("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(ve,{column:"production"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(Qa,{children:he.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):he.map(ke=>{const Ve=me(ke.stage_id),_e=te.get(ke.id),Ae=(_e==null?void 0:_e.size)??0;return e.jsxs(fn,{className:"cursor-pointer",onClick:()=>{m(ke),f(!0)},children:[e.jsx(yt,{onClick:Se=>Se.stopPropagation(),children:e.jsx(za,{checked:G.has(ke.id),onCheckedChange:()=>Pe(ke.id),"aria-label":`Select ${ke.first_name}`})}),e.jsxs(yt,{className:"font-medium",children:[ke.first_name," ",ke.last_name]}),e.jsx(yt,{children:Ve?e.jsxs(ze,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Ve.color,color:Ve.color,backgroundColor:`${Ve.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Ve.color}}),Ve.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(yt,{className:"hidden md:table-cell",children:ke.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(oi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ke.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(yt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ke.email&&e.jsx(on,{className:"h-3.5 w-3.5 text-muted-foreground"}),ke.phone&&e.jsx(va,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ke.email&&!ke.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(yt,{className:"hidden lg:table-cell",children:ke.experience_years!=null?`${ke.experience_years} yr`:"—"}),e.jsx(yt,{className:"hidden lg:table-cell",children:ke.annual_production||"—"}),e.jsx(yt,{className:"hidden lg:table-cell",children:Ae>0?e.jsxs(ze,{variant:"secondary",className:"text-xs",children:[Ae," campaign",Ae>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(yt,{children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Se=>{Se.stopPropagation(),l.mutate(ke.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})})]},ke.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[G.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[G.size," selected · "]}),he.length," of ",n.length," prospects"]}),e.jsx(Is,{open:H,onOpenChange:K,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:G.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Campaign"}),e.jsxs(ls,{value:Z,onValueChange:oe,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Select a campaign..."})}),e.jsx(as,{children:ae.map(ke=>e.jsxs(He,{value:ke.id,children:[ke.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ke.warmth_level,")"]})]},ke.id))})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>K(!1),children:"Cancel"}),e.jsx(z,{onClick:()=>Oe.mutate(),disabled:!Z||Oe.isPending,children:Oe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(Nit,{open:d,onOpenChange:u,stages:t,onSubmit:ke=>a.mutate(ke),isSubmitting:a.isPending}),e.jsx(Sit,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:f,onUpdate:ke=>{i.mutate(ke),m(Ve=>Ve?{...Ve,...ke}:null)},onDelete:ke=>l.mutate(ke)}),e.jsx(Cit,{open:g,onOpenChange:v,brokerageId:s,stages:t})]})}function vas({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=Lz(s),a=_.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(y=>y.name==="Signed"),o=t.find(y=>y.name==="Onboarded"),c=n.filter(y=>y.stage_id===(l==null?void 0:l.id)||y.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((y,b)=>y+PN(u,new Date(b.created_at)),0)/i):0,m=t.map(y=>({...y,count:n.filter(b=>b.stage_id===y.id).length})),p={};n.forEach(y=>{const b=y.source||"unknown";p[b]=(p[b]||0)+1});const f=Object.entries(p).sort((y,b)=>b[1]-y[1]),g=new Date;g.setDate(g.getDate()-30);const v=n.filter(y=>new Date(y.created_at)>=g).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:f,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(be,{children:e.jsx(Le,{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(On,{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(be,{children:e.jsx(Le,{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(kl,{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(be,{children:e.jsx(Le,{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(Zr,{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(be,{children:e.jsx(Le,{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(bu,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Le,{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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Le,{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 Drr=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function bas({brokerageId:s}){const{toast:t}=_i(),{user:n}=hs(),r=$t(),[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(!1),[u,h]=_.useState(null),{data:m=[],isLoading:p}=rt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:S,error:C}=await U.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(C)throw C;return S}}),f=mt({mutationFn:async S=>{if(S.id){const{error:C}=await U.from("recruit_email_templates").update({category:S.category,title:S.title,subject:S.subject,body:S.body}).eq("id",S.id);if(C)throw C}else{const{error:C}=await U.from("recruit_email_templates").insert({brokerage_id:s,category:S.category||"Outreach",title:S.title,subject:S.subject,body:S.body,created_by:n==null?void 0:n.id,sort_order:100});if(C)throw C}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:S=>t({title:"Save failed",description:S.message,variant:"destructive"})}),g=mt({mutationFn:async S=>{const{error:C}=await U.from("recruit_email_templates").delete().eq("id",S);if(C)throw C},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:S=>t({title:"Delete failed",description:S.message,variant:"destructive"})}),v=(S,C)=>{navigator.clipboard.writeText(S),i(C),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},y=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},b=S=>{h(S),d(!0)},w=Array.from(new Set(m.map(S=>S.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(z,{onClick:y,size:"sm",className:"gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"})," New Template"]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):w.map(S=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," ",S]}),m.filter(C=>C.category===S).map(C=>{const E=C.brokerage_id!==null;return e.jsxs(be,{className:`transition-all ${l===C.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(_t,{className:"pb-2 cursor-pointer",onClick:()=>o(l===C.id?null:C.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Nt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:C.title}),!E&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),E&&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: ",C.subject]})]}),e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:C.category})]})}),l===C.id&&e.jsxs(Le,{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:C.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:C.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>v(C.subject,C.id+"-s"),children:[a===C.id+"-s"?e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>v(C.body,C.id+"-b"),children:[a===C.id+"-b"?e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),E&&e.jsxs(e.Fragment,{children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>b(C),children:[e.jsx(Wa,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(z,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await Qi("Delete this template?")&&g.mutate(C.id)},children:[e.jsx(Cn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},C.id)})]},S)),e.jsx(Is,{open:c,onOpenChange:d,children:e.jsxs(Ls,{className:"max-w-2xl",children:[e.jsx(Os,{children:e.jsx(Rs,{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(ee,{className:"text-xs",children:"Title"}),e.jsx(pe,{value:(u==null?void 0:u.title)||"",onChange:S=>h(C=>({...C,title:S.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:S=>h(C=>({...C,category:S.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:Drr.map(S=>e.jsx("option",{value:S,children:S},S))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:(u==null?void 0:u.subject)||"",onChange:S=>h(C=>({...C,subject:S.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Body"}),e.jsx(Ps,{value:(u==null?void 0:u.body)||"",onChange:S=>h(C=>({...C,body:S.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(hr,{children:[e.jsx(z,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>f.mutate(u||{}),disabled:f.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[f.isPending&&e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const Y4t={call:va,email:on,text:qi,meeting:ya,note:$r};function _as({brokerageId:s}){const{data:t,isLoading:n}=rt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await U.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(p=>p.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await U.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(p=>p.created_by),...(l||[]).map(p=>p.created_by)])],{data:d}=await U.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(p=>[p.id,p])),h=L4e(new Date,30);return{recruiters:c.map(p=>{var b,w;const f=(l||[]).filter(S=>S.created_by===p),g=f.filter(S=>new Date(S.created_at)>=h),v={};g.forEach(S=>{v[S.activity_type]=(v[S.activity_type]||0)+1});const y=r.filter(S=>S.created_by===p).length;return{id:p,name:((b=u[p])==null?void 0:b.name)||"Unknown",email:((w=u[p])==null?void 0:w.email)||"",totalActivities:f.length,recentActivities:g.length,byType:v,prospectsCreated:y}}).sort((p,f)=>f.recentActivities-p.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Le,{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(Oo,{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=Y4t[i]||$r;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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Recent Activity"})}),e.jsx(Le,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=Y4t[r.activity_type]||$r;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:r.title}),r.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:Ys(new Date(r.created_at),"MMM d, h:mm a")})]})]},r.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function was({brokerageId:s}){const{toast:t}=_i(),n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=rt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:v,error:y}=await U.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(y)throw y;return v}}),d=[...new Set(o.map(v=>v.referred_by))],{data:u=[]}=rt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:v}=await U.from("profiles").select("id, name, email").in("id",d);return v||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(v=>[v.id,v])),m=mt({mutationFn:async v=>{const{data:{user:y}}=await U.auth.getUser();if(!y)throw new Error("Not authenticated");const{error:b}=await U.from("recruit_referrals").insert({brokerage_id:s,referred_by:y.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(b)throw b},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"})}),p=mt({mutationFn:async({id:v,status:y,incentive_status:b})=>{const w={updated_at:new Date().toISOString()};y&&(w.status=y),b&&(w.incentive_status=b);const{error:S}=await U.from("recruit_referrals").update(w).eq("id",v);if(S)throw S},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),f=v=>v==="approved"||v==="signed"?e.jsx(Wr,{className:"h-3 w-3"}):v==="rejected"?e.jsx(Bd,{className:"h-3 w-3"}):e.jsx(Zr,{className:"h-3 w-3"}),g=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(z,{onClick:()=>a(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(be,{className:"py-12 text-center",children:[e.jsx(Pl,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(v=>{var y;return e.jsx(be,{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:g(v.status),children:[f(v.status)," ",v.status]}),v.incentive_status&&e.jsxs(ze,{variant:"outline",className:g(v.incentive_status),children:[e.jsx(Ko,{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: ",((y=h[v.referred_by])==null?void 0:y.name)||"Unknown"," • ",Ys(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(ls,{value:v.status,onValueChange:b=>p.mutate({id:v.id,status:b}),children:[e.jsx(rs,{className:"h-7 text-xs w-[110px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"pending",children:"Pending"}),e.jsx(He,{value:"contacted",children:"Contacted"}),e.jsx(He,{value:"approved",children:"Approved"}),e.jsx(He,{value:"signed",children:"Signed"}),e.jsx(He,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(ls,{value:v.incentive_status||"pending",onValueChange:b=>p.mutate({id:v.id,incentive_status:b}),children:[e.jsx(rs,{className:"h-7 text-xs w-[100px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"pending",children:"Unpaid"}),e.jsx(He,{value:"paid",children:"Paid"}),e.jsx(He,{value:"n/a",children:"N/A"})]})]})]})]})},v.id)})}),e.jsx(Is,{open:r,onOpenChange:a,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),m.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"First Name *"}),e.jsx(pe,{required:!0,value:i.first_name,onChange:v=>l(y=>({...y,first_name:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{value:i.last_name,onChange:v=>l(y=>({...y,last_name:v.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:i.email,onChange:v=>l(y=>({...y,email:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:i.phone,onChange:v=>l(y=>({...y,phone:v.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{value:i.current_brokerage,onChange:v=>l(y=>({...y,current_brokerage:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ps,{value:i.notes,onChange:v=>l(y=>({...y,notes:v.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function jas({brokerageId:s}){const{toast:t}=_i(),n=$t(),[r,a]=_.useState(!1),{data:i}=rt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:p}=await U.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(p)throw p;return m}}),{data:l=[]}=rt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:p}=await U.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(p)throw p;return m}}),o=mt({mutationFn:async m=>{const{error:p}=await U.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=mt({mutationFn:async({id:m,status:p})=>{const{error:f}=await U.from("recruit_interest_submissions").update({status:p}).eq("id",m);if(f)throw f},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=m=>m==="contacted"||m==="converted"?"bg-green-500/10 text-green-600":m==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:m=>o.mutate(m)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx(z,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(Wr,{className:"h-3.5 w-3.5"}):e.jsx(Sa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(mr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Le,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Pl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(m=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[m.first_name," ",m.last_name]}),e.jsx(ze,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),m.phone]}),m.current_brokerage&&e.jsxs("span",{children:["From: ",m.current_brokerage]}),m.experience_years&&e.jsxs("span",{children:[m.experience_years,"yr exp"]})]}),m.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',m.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:Ys(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ls,{value:m.status,onValueChange:p=>c.mutate({id:m.id,status:p}),children:[e.jsx(rs,{className:"h-7 text-xs w-[110px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"new",children:"New"}),e.jsx(He,{value:"contacted",children:"Contacted"}),e.jsx(He,{value:"converted",children:"Converted"}),e.jsx(He,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function Nas({brokerageId:s}){const{toast:t}=_i(),n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState({prospect_id:"",title:"",description:"",due_date:Ys(Uh(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=_.useState("pending"),{data:d=[]}=rt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:C,error:E}=await U.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(E)throw E;return C}}),{data:u=[],isLoading:h}=rt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const C=d.map(M=>M.id);if(!C.length)return[];const{data:E,error:P}=await U.from("recruit_follow_ups").select("*").in("prospect_id",C).order("due_date");if(P)throw P;return E},enabled:d.length>0}),m=Object.fromEntries(d.map(C=>[C.id,C])),p=mt({mutationFn:async C=>{const{data:{user:E}}=await U.auth.getUser();if(!E)throw new Error("Not authenticated");const{error:P}=await U.from("recruit_follow_ups").insert({prospect_id:C.prospect_id,assigned_to:E.id,title:C.title,description:C.description||null,due_date:new Date(C.due_date).toISOString()});if(P)throw P},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Ys(Uh(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:C=>t({title:"Error",description:C.message,variant:"destructive"})}),f=mt({mutationFn:async({id:C,completed:E})=>{const{error:P}=await U.from("recruit_follow_ups").update({completed_at:E?new Date().toISOString():null}).eq("id",C);if(P)throw P},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),g=u.filter(C=>o==="pending"?!C.completed_at:o==="completed"?!!C.completed_at:!0),v=g.filter(C=>!C.completed_at&&sC(new Date(C.due_date))&&!b0(new Date(C.due_date))),y=g.filter(C=>!C.completed_at&&b0(new Date(C.due_date))),b=g.filter(C=>!C.completed_at&&!sC(new Date(C.due_date))&&!b0(new Date(C.due_date))),w=g.filter(C=>!!C.completed_at),S=C=>{const E=m[C.prospect_id],P=!C.completed_at&&sC(new Date(C.due_date))&&!b0(new Date(C.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(za,{checked:!!C.completed_at,onCheckedChange:M=>f.mutate({id:C.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 ${C.completed_at?"line-through text-muted-foreground":""}`,children:C.title}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[E&&e.jsxs(ze,{variant:"secondary",className:"text-[10px]",children:[E.first_name," ",E.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${P?"text-destructive font-medium":""}`,children:[P?e.jsx(Ho,{className:"h-3 w-3"}):e.jsx(ya,{className:"h-3 w-3"}),Ys(new Date(C.due_date),"MMM d, h:mm a")]}),C.is_automated&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},C.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(C=>e.jsxs(z,{size:"sm",variant:o===C?"default":"outline",onClick:()=>c(C),className:"capitalize text-xs",children:[C," ",C==="pending"&&v.length+y.length+b.length>0&&`(${v.length+y.length+b.length})`]},C))}),e.jsxs(z,{size:"sm",onClick:()=>a(!0),children:[e.jsx(sn,{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(Ho,{className:"h-3.5 w-3.5"})," Overdue (",v.length,")"]}),v.map(S)]}),o!=="completed"&&y.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(Zr,{className:"h-3.5 w-3.5"})," Today (",y.length,")"]}),y.map(S)]}),o!=="completed"&&b.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(ya,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(S)]}),o!=="pending"&&w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Completed (",w.length,")"]}),w.map(S)]}),g.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(Is,{open:r,onOpenChange:a,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:C=>{C.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{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:C=>l(E=>({...E,prospect_id:C.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(C=>e.jsxs("option",{value:C.id,children:[C.first_name," ",C.last_name]},C.id))]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Task *"}),e.jsx(pe,{required:!0,value:i.title,onChange:C=>l(E=>({...E,title:C.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Details"}),e.jsx(Ps,{value:i.description,onChange:C=>l(E=>({...E,description:C.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Due Date *"}),e.jsx(pe,{type:"datetime-local",required:!0,value:i.due_date,onChange:C=>l(E=>({...E,due_date:C.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:p.isPending,children:"Schedule"})]})]})]})})]})}const Rrr=[{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 kas({brokerageId:s}){const{toast:t}=_i(),n=$t(),[r,a]=_.useState(null),{data:i,isLoading:l}=rt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:v,error:y}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(y)throw y;return v}}),[o,c]=_.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:Rrr,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});_.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=mt({mutationFn:async()=>{const 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:y}=await U.from("recruit_landing_page_settings").update(v).eq("id",o.id);if(y)throw y}else{const{error:y}=await U.from("recruit_landing_page_settings").insert(v);if(y)throw y}},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,y)=>{const b=v.name.split(".").pop(),w=`${s}/${y}-${Date.now()}.${b}`,{error:S}=await U.storage.from("recruit-landing").upload(w,v);if(S)throw S;const{data:{publicUrl:C}}=U.storage.from("recruit-landing").getPublicUrl(w);return C},h=async(v,y)=>{var w;const b=(w=v.target.files)==null?void 0:w[0];if(b){a(y);try{const S=await u(b,y);c(C=>({...C,[y]:S})),t({title:"Image uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},m=async v=>{var b;const y=(b=v.target.files)==null?void 0:b[0];if(y){a("gallery");try{const w=await u(y,"gallery");c(S=>({...S,gallery_images:[...S.gallery_images,w]})),t({title:"Gallery image added!"})}catch(w){t({title:"Upload failed",description:w.message,variant:"destructive"})}finally{a(null)}}},p=async(v,y)=>{var w;const b=(w=v.target.files)==null?void 0:w[0];if(b){a(`testimonial-${y}`);try{const S=await u(b,`testimonial-${y}`);c(C=>{const E=[...C.testimonials];return E[y]={...E[y],photo_url:S},{...C,testimonials:E}})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},{data:f}=rt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:v,error:y}=await U.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(y)throw y;return v}}),g=`https://bestbrokerage.relevelup.com/join-brokerage/${(f==null?void 0:f.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:[(f==null?void 0:f.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:g}),e.jsx(z,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:g,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Branding"})}),e.jsx(Le,{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(ee,{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(z,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(Ra,{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(ee,{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(y=>({...y,primary_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.primary_color,onChange:v=>c(y=>({...y,primary_color:v.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(y=>({...y,accent_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.accent_color,onChange:v=>c(y=>({...y,accent_color:v.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:o.hero_headline,onChange:v=>c(y=>({...y,hero_headline:v.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Subtext"}),e.jsx(Ps,{value:o.hero_subtext,onChange:v=>c(y=>({...y,hero_subtext:v.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(ee,{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(z,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Ra,{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(z,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,hero_image_url:null})),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,benefits:[...v.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Le,{className:"space-y-3",children:[o.benefits.map((v,y)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Zf,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(pe,{value:v.icon,onChange:b=>{const w=[...o.benefits];w[y]={...v,icon:b.target.value},c(S=>({...S,benefits:w}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(pe,{value:v.title,onChange:b=>{const w=[...o.benefits];w[y]={...v,title:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Benefit title"}),e.jsx(pe,{value:v.description,onChange:b=>{const w=[...o.benefits];w[y]={...v,description:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Short description"})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((w,S)=>S!==y)})),children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-destructive"})})]},y)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{className:"text-base",children:"Testimonials"}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,testimonials:[...v.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Le,{className:"space-y-3",children:[o.testimonials.map((v,y)=>{var b;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:((b=v.name)==null?void 0:b[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${y}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:w=>p(w,y)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{value:v.name,onChange:w=>{const S=[...o.testimonials];S[y]={...v,name:w.target.value},c(C=>({...C,testimonials:S}))},placeholder:"Name"}),e.jsx(pe,{value:v.role,onChange:w=>{const S=[...o.testimonials];S[y]={...v,role:w.target.value},c(C=>({...C,testimonials:S}))},placeholder:"Role / Title"})]}),e.jsx(Ps,{value:v.quote,onChange:w=>{const S=[...o.testimonials];S[y]={...v,quote:w.target.value},c(C=>({...C,testimonials:S}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>c(w=>({...w,testimonials:w.testimonials.filter((S,C)=>C!==y)})),children:e.jsx(Cn,{className:"h-3.5 w-3.5 text-destructive"})})]},y)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(z,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(nc,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:m})]})]}),e.jsx(Le,{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,y)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v,alt:`Gallery ${y+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(z,{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(b=>({...b,gallery_images:b.gallery_images.filter((w,S)=>S!==y)})),children:e.jsx(Cn,{className:"h-3 w-3"})})]},y))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Application Form Style"}),e.jsxs(ls,{value:o.form_style,onValueChange:v=>c(y=>({...y,form_style:v})),children:[e.jsx(rs,{className:"mt-1.5",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(He,{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(Hl,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(ee,{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(mn,{checked:o.confidential_messaging,onCheckedChange:v=>c(y=>({...y,confidential_messaging:v}))})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(pj,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(mn,{checked:o.calculator_enabled,onCheckedChange:v=>c(y=>({...y,calculator_enabled:v}))})]}),o.calculator_enabled&&e.jsxs(Le,{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(ee,{className:"text-xs",children:"Calculator Headline"}),e.jsx(pe,{value:o.calculator_config.headline||"",onChange:v=>c(y=>({...y,calculator_config:{...y.calculator_config,headline:v.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subtext"}),e.jsx(pe,{value:o.calculator_config.subtext||"",onChange:v=>c(y=>({...y,calculator_config:{...y.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(ee,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(pe,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:v=>c(y=>({...y,calculator_config:{...y.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(ee,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:v=>c(y=>({...y,calculator_config:{...y.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(ee,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(pe,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:v=>c(y=>({...y,calculator_config:{...y.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(ee,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:v=>c(y=>({...y,calculator_config:{...y.calculator_config,monthly_fee:parseFloat(v.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:v=>c(y=>({...y,calculator_config:{...y.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(ee,{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(mn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:v=>c(y=>({...y,calculator_config:{...y.calculator_config,show_email_capture:v}}))})]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(xj,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(mn,{checked:o.lead_magnet_enabled,onCheckedChange:v=>c(y=>({...y,lead_magnet_enabled:v}))})]}),o.lead_magnet_enabled&&e.jsxs(Le,{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(ee,{className:"text-xs",children:"Title"}),e.jsx(pe,{value:o.lead_magnet_config.title||"",onChange:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,title:v.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Description"}),e.jsx(Ps,{rows:2,value:o.lead_magnet_config.description||"",onChange:v=>c(y=>({...y,lead_magnet_config:{...y.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(ee,{className:"text-xs",children:"Button Text"}),e.jsx(pe,{value:o.lead_magnet_config.button_text||"",onChange:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,button_text:v.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(pe,{value:o.lead_magnet_config.pdf_url||"",onChange:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,pdf_url:v.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(z,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(Ra,{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 b;const y=(b=v.target.files)==null?void 0:b[0];if(y){a("lead_magnet_pdf");try{const w=await u(y,"lead-magnet");c(S=>({...S,lead_magnet_config:{...S.lead_magnet_config,pdf_url:w}})),t({title:"PDF uploaded!"})}catch(w){t({title:"Upload failed",description:w.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Frr,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Bo,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function Frr({brokerageId:s}){const{data:t=[]}=rt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await U.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(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(n=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[n.first_name||"—"," · ",n.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[Ys(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function Sas({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=_.useState(!1),o=r??i,c=a??l,[d,u]=_.useState("pick-recipients"),[h,m]=_.useState(new Set(n?[n]:[])),[p,f]=_.useState("all"),[g,v]=_.useState(""),[y,b]=_.useState(null),[w,S]=_.useState(""),[C,E]=_.useState(0),[P,M]=_.useState(0),[I,D]=_.useState(""),[F,q]=_.useState(""),{data:G}=gDe(),[V,H]=_.useState("default");_.useEffect(()=>{H(G!=null&&G.massEmail?"mass_email":G!=null&&G.gmail?"gmail":"default")},[G==null?void 0:G.massEmail,G==null?void 0:G.gmail]);const[K,Z]=_.useState(null),{prospects:oe,stages:re}=Lz(s),ae=fas(),J=RC(),{data:te=[]}=rt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ke,error:Ve}=await U.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Ve)throw Ve;return ke??[]},enabled:o&&d==="pick-video"}),ce=_.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),f("all"),v(""),b(null),S(""),E(0),M(0),D(""),q(""),H("default"),Z(null)},[n]),ve=ke=>{!ke&&(d==="uploading"||d==="processing"||d==="sending")||(c(ke),ke||setTimeout(ce,200))},me=_.useMemo(()=>oe.filter(ke=>{if(!ke.email||p!=="all"&&ke.stage_id!==p)return!1;if(g){const Ve=g.toLowerCase();if(!`${ke.first_name} ${ke.last_name??""}`.toLowerCase().includes(Ve)&&!ke.email.toLowerCase().includes(Ve))return!1}return!0}),[oe,p,g]),he=ke=>{m(Ve=>{const _e=new Set(Ve);return _e.has(ke)?_e.delete(ke):_e.add(ke),_e})},ge=()=>{h.size===me.length?m(new Set):m(new Set(me.map(ke=>ke.id)))},Ee=_.useCallback(async(ke,Ve)=>{u("uploading");try{const _e=`Recruiting blast (${h.size} recipients)`,{videoId:Ae,libraryId:Se}=await qL(_e),{uploadUrl:We,apiKey:qe}=await VL(Ae),Be=new XMLHttpRequest;Be.upload.onprogress=lt=>{lt.lengthComputable&&E(lt.loaded/lt.total*100)},await new Promise((lt,qt)=>{Be.onload=()=>Be.status>=200&&Be.status<300?lt():qt(new Error("Upload failed")),Be.onerror=()=>qt(new Error("Upload failed")),Be.open("PUT",We),Be.setRequestHeader("AccessKey",qe),Be.send(ke)}),u("processing");const Ze=`https://iframe.mediadelivery.net/embed/${Se}/${Ae}`;let $e=0;const Xe=Date.now(),nt=9e4;for(;$e<4&&(await new Promise(qt=>setTimeout(qt,3e3)),!(Date.now()-Xe>nt));){const lt=await DN(Ae);if($e=lt.status,M(lt.encodeProgress||0),$e===5||$e===6)throw new Error("Video processing failed")}const Ge=await DN(Ae),Je=(Ge.storageSize||ke.size)/(1024*1024),ut=await J.mutateAsync({bunny_video_id:Ae,playback_url:Ge.directPlayUrl||Ze,thumbnail_url:Ge.thumbnailUrl,preview_url:Ge.previewUrl||null,duration_seconds:Ge.length||Ve,file_size_mb:Je,title:_e,status:$e>=4?"ready":"processing",touch_type:"recruiting"});b(ut.id),S(_e),u("compose")}catch(_e){ne.error((_e==null?void 0:_e.message)||"Failed to upload video"),u("pick-video")}},[h.size,J]),Ne=_.useCallback(async()=>{if(!(!y||h.size===0)){u("sending");try{const ke=[];for(const Ae of h){const Se=await ae.mutateAsync({prospect_id:Ae,video_id:y,brokerage_id:s,message:F||void 0});ke.push(Se.id)}const{data:Ve,error:_e}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ke,brokerage_id:s,subject_override:I||void 0,message_override:F||void 0,send_via:V}});if(_e)throw new Error(_e.message);Z({sent:(Ve==null?void 0:Ve.sent)??0,total:(Ve==null?void 0:Ve.total)??ke.length}),u("done"),ne.success(`Sent ${(Ve==null?void 0:Ve.sent)??0} of ${(Ve==null?void 0:Ve.total)??ke.length} videos`)}catch(ke){ne.error((ke==null?void 0:ke.message)||"Failed to send"),u("compose")}}},[y,h,s,F,I,V,ae]),Pe=h.size,Oe=oe.filter(ke=>!ke.email).length;return e.jsxs(Is,{open:o,onOpenChange:ve,children:[t&&e.jsx(rl,{asChild:!0,children:t}),e.jsxs(Ls,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Os,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Pe>0&&e.jsxs(ze,{variant:"secondary",className:"ml-2",children:[e.jsx(On,{className:"h-3 w-3 mr-1"}),Pe," ",Pe===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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search prospects...",value:g,onChange:ke=>v(ke.target.value),className:"pl-9"})]}),e.jsxs(ls,{value:p,onValueChange:f,children:[e.jsx(rs,{className:"w-48",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),re.map(ke=>e.jsx(He,{value:ke.id,children:ke.name},ke.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:ge,className:"hover:underline",children:[h.size===me.length&&me.length>0?"Deselect all":"Select all"," ","(",me.length,")"]}),Oe>0&&e.jsxs("span",{children:[Oe," prospect(s) hidden — no email on file"]})]}),e.jsx(Ki,{className:"flex-1 border rounded-md",children:me.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No prospects match. Make sure prospects have email addresses."}):e.jsx("div",{className:"divide-y",children:me.map(ke=>{const Ve=h.has(ke.id),_e=re.find(Ae=>Ae.id===ke.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(za,{checked:Ve,onCheckedChange:()=>he(ke.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:[ke.first_name," ",ke.last_name]}),_e&&e.jsx(ze,{variant:"outline",className:"text-[10px]",style:{borderColor:_e.color,color:_e.color},children:_e.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email," ",ke.current_brokerage&&`· ${ke.current_brokerage}`]})]})]},ke.id)})})}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx(z,{disabled:Pe===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(Qr,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Jr,{className:"self-start",children:[e.jsxs(Wt,{value:"record",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Wt,{value:"library",children:[e.jsx(vj,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Kt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Yh,{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 ",Pe," ",Pe===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(z,{onClick:()=>u("record"),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Kt,{value:"library",className:"flex-1 overflow-auto",children:te.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:te.map(ke=>e.jsxs("button",{onClick:()=>{b(ke.id),S(ke.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:$4(ke)?e.jsx("img",{src:$4(ke),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(Xr,{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:ke.title||"Untitled"})})]},ke.id))})})]}),e.jsx(hr,{children:e.jsx(z,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(YE,{maxDurationSeconds:600,onRecordingComplete:Ee}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(z,{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(bt,{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(Di,{value:d==="uploading"?C:P,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?C:P),"%"]})]}),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(Mr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:w})," selected · sending to ",e.jsx("strong",{children:Pe})," recipient",Pe===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(pe,{value:I,onChange:ke=>D(ke.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(ee,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ps,{value:F,onChange:ke=>q(ke.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(kit,{value:V,onChange:H}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(z,{onClick:Ne,disabled:!y||Pe===0,children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"})," Send to ",Pe," ",Pe===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(bt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Pe," recipient",Pe===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&K&&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 ${K.sent===K.total?"bg-primary/10":"bg-muted"}`,children:K.sent===K.total?e.jsx(Mr,{className:"h-8 w-8 text-primary"}):e.jsx(Ho,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[K.sent," of ",K.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(z,{onClick:()=>ve(!1),children:"Done"})]})]})]})}function Orr(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function zrr({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(xa,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(ze,{variant:"secondary",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(ze,{variant:"outline",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function Cas({brokerageId:s}){var w,S,C,E;const{data:t=[],isLoading:n}=Srr(s),{data:r=[]}=gas(s),a=Arr(),i=Err(),l=xas(),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState({title:"",script_text:"",category:"general"}),[p,f]=_.useState(null),g=t.filter(P=>{var I,D,F,q;return o?`${((I=P.prospect)==null?void 0:I.first_name)||""} ${((D=P.prospect)==null?void 0:D.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((q=(F=P.video)==null?void 0:F.title)==null?void 0:q.toLowerCase().includes(o.toLowerCase())):!0}),v={total:t.length,sent:t.filter(P=>P.sent_at).length,viewed:t.filter(P=>P.view_count>0).length,ctaClicked:t.filter(P=>P.cta_clicked_at).length},y=_.useCallback(P=>{if(!P)return;const M=`${window.location.origin}/recruit-video/${P}`;navigator.clipboard.writeText(M),ne.success("Share link copied")},[]);_.useCallback((P,M)=>{l.mutate({id:P,sent_via:M})},[l]);const b=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{m({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:v.total,icon:Xr,color:"text-primary"},{label:"Sent",value:v.sent,icon:Fr,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:xa,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:Mr,color:"text-emerald-500"}].map(P=>e.jsx(be,{children:e.jsxs(Le,{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 ${P.color}`,children:e.jsx(P.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P.label})]})]})},P.label))}),e.jsxs(Qr,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"videos",children:[e.jsx(Xr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Wt,{value:"scripts",children:[e.jsx($r,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Wt,{value:"analytics",children:[e.jsx(wl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Kt,{value:"videos",children:e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Nt,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or title...",value:o,onChange:P=>c(P.target.value),className:"pl-9"})]}),e.jsx(Sas,{brokerageId:s,trigger:e.jsxs(z,{size:"sm",className:"gap-1.5",children:[e.jsx(on,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Le,{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"})}):g.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Xr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No video outreach yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Record a personalized video from any prospect's profile card"})]}):e.jsx("div",{className:"space-y-3",children:g.map(P=>{var M,I,D,F,q,G,V;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:[$4(P.video)?e.jsx("img",{src:$4(P.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(Xr,{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:Orr(((M=P.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:[(I=P.prospect)==null?void 0:I.first_name," ",(D=P.prospect)==null?void 0:D.last_name]}),e.jsx(zrr,{video:P})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((F=P.video)==null?void 0:F.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ys(new Date(P.created_at),"MMM d, yyyy"),((q=P.prospect)==null?void 0:q.current_brokerage)&&` · ${P.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>y(P.share_token),title:"Copy share link",children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsxs(z,{variant:P.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>f(P),disabled:!((G=P.prospect)!=null&&G.email),title:(V=P.prospect)!=null&&V.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(on,{className:"h-4 w-4"}),P.sent_at?"Resend":"Email"]}),P.share_token&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${P.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(mr,{className:"h-4 w-4"})})]})]},P.id)})})})]})}),e.jsx(Kt,{value:"scripts",children:e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Nt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(Is,{open:d,onOpenChange:u,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{size:"sm",children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:h.title,onChange:P=>m(M=>({...M,title:P.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ls,{value:h.category,onValueChange:P=>m(M=>({...M,category:P})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:yZe.map(P=>e.jsx(He,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Script"}),e.jsx(Ps,{value:h.script_text,onChange:P=>m(M=>({...M,script_text:P.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(z,{onClick:b,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Le,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx($r,{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(P=>{var I;const M=((I=yZe.find(D=>D.value===P.category))==null?void 0:I.label)||P.category;return e.jsx(be,{className:"relative group",children:e.jsxs(Le,{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:P.title})]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(P.id),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:P.script_text}),P.is_global&&e.jsx(ze,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},P.id)})})})]})}),e.jsx(Kt,{value:"analytics",children:e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Le,{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(P=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:P.label}),e.jsxs("span",{className:"font-medium",children:[P.count," (",P.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${P.color} rounded-full transition-all`,style:{width:`${P.pct}%`}})})]},P.label))}),t.filter(P=>P.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(P=>P.view_count>0).sort((P,M)=>M.view_count-P.view_count).slice(0,5).map(P=>{var M,I;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=P.prospect)==null?void 0:M.first_name," ",(I=P.prospect)==null?void 0:I.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(xa,{className:"h-3.5 w-3.5"})," ",P.view_count]}),P.cta_clicked_at&&e.jsx(Mr,{className:"h-4 w-4 text-emerald-500"})]})]},P.id)})})]})]})]})})]}),p&&e.jsx(pas,{open:!!p,onOpenChange:P=>{P||f(null)},recruitVideoId:p.id,brokerageId:s,prospectName:`${((w=p.prospect)==null?void 0:w.first_name)||""} ${((S=p.prospect)==null?void 0:S.last_name)||""}`.trim(),prospectEmail:(C=p.prospect)==null?void 0:C.email,videoTitle:(E=p.video)==null?void 0:E.title,defaultMessage:p.message})]})}function Aas({brokerageId:s}){const{toast:t}=_i(),n=$t(),{stages:r,prospects:a}=Lz(s),[i,l]=_.useState(!1),[o,c]=_.useState({title:"",target_count:"10",target_stage_id:"",period_start:Ys(new Date,"yyyy-MM-dd"),period_end:Ys(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=rt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:f,error:g}=await U.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(g)throw g;return f}}),h=mt({mutationFn:async f=>{const{data:{user:g}}=await U.auth.getUser();if(!g)throw new Error("Not authenticated");const{error:v}=await U.from("recruit_goals").insert({brokerage_id:s,title:f.title,target_count:parseInt(f.target_count),target_stage_id:f.target_stage_id||null,period_start:f.period_start,period_end:f.period_end,created_by:g.id});if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:f=>t({title:"Error",description:f.message,variant:"destructive"})}),m=mt({mutationFn:async f=>{const{error:g}=await U.from("recruit_goals").delete().eq("id",f);if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),p=f=>{const g=r.find(y=>y.id===f.target_stage_id);return{count:a.filter(y=>Qk(new Date(y.created_at),{start:new Date(f.period_start),end:new Date(f.period_end)})?f.target_stage_id?y.stage_id===f.target_stage_id:!0:!1).length,stage:g}};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(z,{size:"sm",onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(be,{className:"py-12 text-center",children:[e.jsx(bu,{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(f=>{const{count:g,stage:v}=p(f),y=Math.min(100,g/f.target_count*100),b=Qk(new Date,{start:new Date(f.period_start),end:new Date(f.period_end)});return e.jsxs(be,{className:b?"":"opacity-60",children:[e.jsx(_t,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-sm",children:f.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ys(new Date(f.period_start),"MMM d")," – ",Ys(new Date(f.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx(ze,{className:"text-[10px]",children:"Active"}):e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>m.mutate(f.id),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Le,{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:g}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",f.target_count]})]}),e.jsx(Di,{value:y,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[y.toFixed(0),"% complete"]})]})]},f.id)})}),e.jsx(Is,{open:i,onOpenChange:l,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:f=>{f.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Goal Title *"}),e.jsx(pe,{required:!0,value:o.title,onChange:f=>c(g=>({...g,title:f.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Target Count *"}),e.jsx(pe,{type:"number",min:"1",required:!0,value:o.target_count,onChange:f=>c(g=>({...g,target_count:f.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{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:f=>c(g=>({...g,target_stage_id:f.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(f=>e.jsx("option",{value:f.id,children:f.name},f.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(ee,{children:"Start Date"}),e.jsx(pe,{type:"date",required:!0,value:o.period_start,onChange:f=>c(g=>({...g,period_start:f.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"End Date"}),e.jsx(pe,{type:"date",required:!0,value:o.period_end,onChange:f=>c(g=>({...g,period_end:f.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(z,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(z,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const Brr={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function Eas({email:s,mergeValues:t=Brr,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(Is,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Ls,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Rs,{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(Zr,{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 Ait({brokerageId:s}){const t=$t(),{user:n}=hs(),[r,a]=_.useState(""),[i,l]=_.useState(!1),[o,c]=_.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=rt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:f,error:g}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(g)throw g;return f}}),{data:u}=rt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:f,error:g}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(g)throw g;return f}});_.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(f=>({...f,merge_fields:{...f.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),_.useEffect(()=>{n!=null&&n.id&&U.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:f})=>a((f==null?void 0:f.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:f}=await U.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),f?ne.error(f.message):ne.success("Scheduling link saved!")},m=mt({mutationFn:async()=>{const f={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:g}=await U.from("brokerage_recruit_settings").update(f).eq("id",d.id);if(g)throw g}else{const{error:g}=await U.from("brokerage_recruit_settings").insert(f);if(g)throw g}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ne.success("Recruiting email settings saved!")},onError:f=>ne.error(f.message)}),p=(f,g)=>{c(v=>({...v,merge_fields:{...v.merge_fields,[f]:g}}))};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(ya,{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(pe,{value:r,onChange:f=>a(f.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(z,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Bo,{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(ee,{className:"text-xs",children:"Sender Display Name"}),e.jsx(pe,{value:o.sender_name,onChange:f=>c({...o,sender_name:f.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email Address"}),e.jsx(pe,{value:o.sender_email,onChange:f=>c({...o,sender_email:f.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(ee,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(pe,{value:o.reply_to_email,onChange:f=>c({...o,reply_to_email:f.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(Ch,{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(oas,{brokerageId:s,onVerifiedSelect:f=>{c(g=>({...g,sender_email:f})),ne.success(`Sender set to ${f}`)}})]}),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(ee,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(pe,{value:o.merge_fields.brokerage_name||"",onChange:f=>p("brokerage_name",f.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{city}}"}),e.jsx(pe,{value:o.merge_fields.city||"",onChange:f=>p("city",f.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(pe,{value:o.merge_fields.sender_name||"",onChange:f=>p("sender_name",f.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(z,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const Tas=LS.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["u",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setUnderline:()=>({commands:s})=>s.setMark(this.name),toggleUnderline:()=>({commands:s})=>s.toggleMark(this.name),unsetUnderline:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),Z4t=[{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 Q0({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(ug,{children:[e.jsx(hg,{asChild:!0,children:e.jsx(z,{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(Tx,{side:"bottom",className:"text-xs",children:a})]})}function $rr({content:s,onChange:t}){const n=ULe({extensions:[qLe.configure({heading:{levels:[1,2,3]}}),Tas,HLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),GLe.configure({types:["heading","paragraph"]}),Mtt,uYt],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())}});_.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=_.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=_.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(UN,{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(Q0,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:HA,tooltip:"Bold"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:KA,tooltip:"Italic"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:b7,tooltip:"Underline"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:xJ,tooltip:"Strikethrough"}),e.jsx(fc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:GU,tooltip:"Heading 1"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:a7,tooltip:"Heading 2"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:WU,tooltip:"Heading 3"}),e.jsx(fc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:My,tooltip:"Bullet List"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:bj,tooltip:"Numbered List"}),e.jsx(Q0,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:wj,tooltip:"Blockquote"}),e.jsx(Q0,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:gN,tooltip:"Divider"}),e.jsx(fc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Q0,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:QM,tooltip:"Align Left"}),e.jsx(Q0,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:XM,tooltip:"Align Center"}),e.jsx(Q0,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:JM,tooltip:"Align Right"}),e.jsx(fc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Q0,{onClick:r,active:n.isActive("link"),icon:Kc,tooltip:"Insert Link"}),e.jsx(fc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Q0,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:nE,tooltip:"Undo"}),e.jsx(Q0,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:tE,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(z,{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(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(wq,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(qd,{align:"end",className:"w-56",children:Z4t.map(i=>e.jsxs(ua,{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($Le,{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:"}),Z4t.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 Urr({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(Is,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Ls,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(_r,{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(Fr,{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(Gde,{icon:on,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(Gde,{icon:xa,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(Gde,{icon:Gh,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(Gde,{icon:nl,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(Zr,{className:"h-3 w-3"})," Last sent: ",Ys(new Date(r.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:r.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(be,{className:"overflow-hidden",children:e.jsxs(Le,{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(on,{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(xa,{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(Gh,{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(nl,{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 Gde({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(be,{children:e.jsx(Le,{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 Eit(s){return rt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await U.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 X4t={cold:{icon:aj,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:bN,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:vu,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function Mas({brokerageId:s}){var ge,Ee,Ne,Pe;const{user:t}=hs(),n=$t(),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState("editor"),[g,v]=_.useState(null),[y,b]=_.useState(null),{data:w={}}=Eit(s),[S,C]=_.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:E}=rt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Oe,error:ke}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(ke)throw ke;return Oe}}),{data:P}=rt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Oe,error:ke}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ke)throw ke;return Oe}}),M={first_name:"Sarah",brokerage_name:((ge=P==null?void 0:P.merge_fields)==null?void 0:ge.brokerage_name)||(E==null?void 0:E.name)||"Your Brokerage",city:((Ee=P==null?void 0:P.merge_fields)==null?void 0:Ee.city)||(E==null?void 0:E.city)||"Your City",sender_name:((Ne=P==null?void 0:P.merge_fields)==null?void 0:Ne.sender_name)||(P==null?void 0:P.sender_name)||"Your Name"},I=Oe=>Oe.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:D=[],isLoading:F}=rt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Oe,error:ke}=await U.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ke)throw ke;return Oe}}),{data:q={}}=rt({queryKey:["recruit-campaign-emails",s],enabled:D.length>0,queryFn:async()=>{const Oe=D.map(Ae=>Ae.id),{data:ke,error:Ve}=await U.from("recruit_campaign_emails").select("*").in("campaign_id",Oe).order("email_number");if(Ve)throw Ve;const _e={};return ke.forEach(Ae=>{_e[Ae.campaign_id]||(_e[Ae.campaign_id]=[]),_e[Ae.campaign_id].push(Ae)}),_e}}),G=Object.values(q).flat().map(Oe=>Oe.id),{data:V=[]}=rt({queryKey:["recruit-subject-overrides",s],enabled:G.length>0,queryFn:async()=>{const{data:Oe,error:ke}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ke)throw ke;return Oe}}),H={};V.forEach(Oe=>{H[Oe.campaign_email_id]=Oe.selected_subject_index});const K=mt({mutationFn:async({campaignEmailId:Oe,selectedIndex:ke})=>{const{error:Ve}=await U.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Oe,selected_subject_index:ke,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ne.success("Subject line updated for your brokerage")},onError:Oe=>ne.error(Oe.message)}),Z=mt({mutationFn:async Oe=>{const{error:ke}=await U.from("recruit_campaign_emails").update({title:Oe.title,subject_line:Oe.subject_line,subject_line_options:Oe.subject_line_options,body_html:Oe.body_html,body_text:Oe.body_text,delay_days:Oe.delay_days,updated_at:new Date().toISOString()}).eq("id",Oe.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Email template saved!"),l(null)},onError:Oe=>ne.error(Oe.message)}),oe=mt({mutationFn:async()=>{const Oe=S.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ke,error:Ve}=await U.from("recruit_campaigns").insert({name:S.name,slug:Oe,description:S.description||null,theme:S.theme||null,goal:S.goal||null,primary_cta:S.primary_cta||"Learn more",warmth_level:S.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:S.sender_name||null,sender_email:S.sender_email||null,reply_to_email:S.reply_to_email||null,is_active:!0,sort_order:D.length+1}).select().single();if(Ve)throw Ve;const _e=[{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:Ae}=await U.from("recruit_campaign_emails").insert(_e.map(Se=>({campaign_id:ke.id,...Se,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(Ae)throw Ae;return ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Campaign created with 4 starter emails!"),m(!1),C({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Oe=>ne.error(Oe.message)}),re=mt({mutationFn:async Oe=>{const{error:ke}=await U.from("recruit_campaigns").update({name:Oe.name,description:Oe.description,theme:Oe.theme,goal:Oe.goal,primary_cta:Oe.primary_cta,warmth_level:Oe.warmth_level,sender_name:Oe.sender_name,sender_email:Oe.sender_email,reply_to_email:Oe.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Oe.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ne.success("Campaign settings saved!"),v(null)},onError:Oe=>ne.error(Oe.message)}),ae=mt({mutationFn:async Oe=>{var We,qe;const{data:ke}=await U.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Oe).order("email_number",{ascending:!1}).limit(1),Ve=((We=ke==null?void 0:ke[0])==null?void 0:We.email_number)??0,_e=((qe=ke==null?void 0:ke[0])==null?void 0:qe.delay_days)??0,Ae=Ve+1,{error:Se}=await U.from("recruit_campaign_emails").insert({campaign_id:Oe,email_number:Ae,title:`Email ${Ae}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:_e+7,is_active:!0});if(Se)throw Se},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Email added to campaign!")},onError:Oe=>ne.error(Oe.message)}),J=mt({mutationFn:async Oe=>{const{error:ke}=await U.from("recruit_campaigns").delete().eq("id",Oe);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Campaign deleted")},onError:Oe=>ne.error(Oe.message)}),te=mt({mutationFn:async Oe=>{const{error:ke}=await U.from("recruit_campaign_emails").delete().eq("id",Oe);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Email removed from campaign")},onError:Oe=>ne.error(Oe.message)}),ce=mt({mutationFn:async({emailId:Oe,delay_days:ke})=>{const{error:Ve}=await U.from("recruit_campaign_emails").update({delay_days:ke,updated_at:new Date().toISOString()}).eq("id",Oe);if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Send delay updated")},onError:Oe=>ne.error(Oe.message)});if(F)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 ve=D.filter(Oe=>!Oe.brokerage_id),me=D.filter(Oe=>Oe.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(z,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Gc,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(z,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(be,{className:"border-primary/20 bg-primary/5",children:e.jsx(Le,{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(Gc,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),me.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(JU,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:me.map(Oe=>he(Oe,!0))})]}),ve.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ve.map(Oe=>he(Oe,!1))})]}),D.length===0&&e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(on,{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(z,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(Urr,{open:!!y,onClose:()=>b(null),campaignName:(y==null?void 0:y.name)||"",stat:y&&w[y.id]||null}),o&&e.jsx(Eas,{email:o,mergeValues:M,selectedSubjectIndex:H[o.id],onClose:()=>c(null)}),e.jsx(Is,{open:!!i,onOpenChange:Oe=>!Oe&&l(null),children:e.jsxs(Ls,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(aP,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(_r,{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(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(pe,{value:i.title,onChange:Oe=>l({...i,title:Oe.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(pe,{type:"number",min:0,max:90,value:i.delay_days,onChange:Oe=>l({...i,delay_days:parseInt(Oe.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(pe,{value:i.subject_line,onChange:Oe=>l({...i,subject_line:Oe.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{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(Ps,{value:((Pe=i.subject_line_options)==null?void 0:Pe.join(` `))||"",onChange:Oe=>l({...i,subject_line_options:Oe.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(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(Qr,{value:p,onValueChange:Oe=>f(Oe),children:e.jsxs(Jr,{className:"h-7",children:[e.jsx(Wt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Wt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),p==="editor"?e.jsx($rr,{content:i.body_html,onChange:Oe=>l({...i,body_html:Oe})}):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:I(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:I(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(z,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(z,{size:"sm",onClick:()=>Z.mutate(i),disabled:Z.isPending,className:"gap-1.5",children:[e.jsx(Bo,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(Is,{open:h,onOpenChange:m,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(_r,{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(ee,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(pe,{value:S.name,onChange:Oe=>C({...S,name:Oe.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(ee,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(ls,{value:S.warmth_level,onValueChange:Oe=>C({...S,warmth_level:Oe}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(He,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(He,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(pe,{value:S.primary_cta,onChange:Oe=>C({...S,primary_cta:Oe.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ps,{value:S.description,onChange:Oe=>C({...S,description:Oe.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Goal"}),e.jsx(pe,{value:S.goal,onChange:Oe=>C({...S,goal:Oe.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(f1,{children:[e.jsx(x1,{asChild:!0,children:e.jsxs(z,{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(on,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(cl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(g1,{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(ee,{className:"text-xs",children:"Sender Name"}),e.jsx(pe,{value:S.sender_name,onChange:Oe=>C({...S,sender_name:Oe.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email"}),e.jsx(pe,{value:S.sender_email,onChange:Oe=>C({...S,sender_email:Oe.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(ee,{className:"text-xs",children:"Reply-To Email"}),e.jsx(pe,{value:S.reply_to_email,onChange:Oe=>C({...S,reply_to_email:Oe.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(z,{className:"w-full",disabled:!S.name.trim()||oe.isPending,onClick:()=>oe.mutate(),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(Is,{open:!!g,onOpenChange:Oe=>!Oe&&v(null),children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Gc,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(_r,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),g&&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(ee,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(pe,{value:g.name,onChange:Oe=>v({...g,name:Oe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(ls,{value:g.warmth_level,onValueChange:Oe=>v({...g,warmth_level:Oe}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"cold",children:"❄️ Cold"}),e.jsx(He,{value:"warm",children:"☀️ Warm"}),e.jsx(He,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Goal"}),e.jsx(pe,{value:g.goal||"",onChange:Oe=>v({...g,goal:Oe.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(on,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Name"}),e.jsx(pe,{value:g.sender_name||"",onChange:Oe=>v({...g,sender_name:Oe.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email"}),e.jsx(pe,{value:g.sender_email||"",onChange:Oe=>v({...g,sender_email:Oe.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(ee,{className:"text-xs",children:"Reply-To Email"}),e.jsx(pe,{value:g.reply_to_email||"",onChange:Oe=>v({...g,reply_to_email:Oe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(z,{className:"w-full",onClick:()=>re.mutate(g),disabled:re.isPending,children:[e.jsx(Bo,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(Is,{open:d,onOpenChange:u,children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Default Recruiting Email Settings"}),e.jsx(_r,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(Ait,{brokerageId:s})]})})]});function he(Oe,ke){const Ve=X4t[Oe.warmth_level]||X4t.cold,_e=Ve.icon,Ae=q[Oe.id]||[],Se=r===Oe.id,We=!!(Oe.sender_name||Oe.sender_email||Oe.reply_to_email),qe=w[Oe.id];return e.jsxs(be,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(_t,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Se?null:Oe.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 ${Ve.bg} flex items-center justify-center`,children:e.jsx(_e,{className:`h-5 w-5 ${Ve.color}`})}),e.jsxs("div",{children:[e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[Oe.name,e.jsx(ze,{variant:Oe.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Oe.is_active?"Active":"Draft"}),ke&&e.jsx(ze,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),We&&e.jsxs(ze,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(on,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(En,{className:"text-xs mt-0.5",children:Oe.theme||Oe.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Be=>{Be.stopPropagation(),v({...Oe})},children:e.jsx(Gc,{className:"h-4 w-4 text-muted-foreground"})}),ke&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async Be=>{Be.stopPropagation(),await Qi("Delete this campaign and all its emails? This cannot be undone.")&&J.mutate(Oe.id)},children:e.jsx(Cn,{className:"h-4 w-4"})}),qe&&qe.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(on,{className:"h-2.5 w-2.5"})," ",qe.sent.toLocaleString()]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${qe.openRate.toFixed(1)}% open rate`,children:[e.jsx(xa,{className:"h-2.5 w-2.5"})," ",qe.opened.toLocaleString()," (",qe.openRate.toFixed(0),"%)"]}),e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${qe.clickRate.toFixed(1)}% click rate`,children:[e.jsx(Gh,{className:"h-2.5 w-2.5"})," ",qe.clicked.toLocaleString()," (",qe.clickRate.toFixed(1),"%)"]})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Be=>{Be.stopPropagation(),b(Oe)},title:"View detailed engagement stats",children:[e.jsx(wl,{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(on,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Ae.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Se?e.jsx(h1,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(cl,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Se&&e.jsxs(Le,{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:Oe.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:Oe.primary_cta||"—"})]})]}),We&&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(on,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Oe.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Oe.sender_name]}),Oe.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Oe.sender_email]}),Oe.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Oe.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Ae.map((Be,Ze)=>{var $e,Xe;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Zent.stopPropagation(),onBlur:nt=>{const Ge=parseInt(nt.target.value)||0;Ge!==Be.delay_days&&ce.mutate({emailId:Be.id,delay_days:Ge})},onKeyDown:nt=>{nt.key==="Enter"&&nt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),Be.email_number===1?"Sent immediately":`Day ${Be.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",I((($e=Be.subject_line_options)==null?void 0:$e.length)>0&&Be.subject_line_options[H[Be.id]??0]||Be.subject_line)]})]}),((Xe=Be.subject_line_options)==null?void 0:Xe.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(ls,{value:String(H[Be.id]??0),onValueChange:nt=>K.mutate({campaignEmailId:Be.id,selectedIndex:parseInt(nt)}),children:[e.jsx(rs,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(cs,{placeholder:"Choose subject line"})}),e.jsx(as,{children:Be.subject_line_options.map((nt,Ge)=>e.jsxs(He,{value:String(Ge),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Ge===0?"Primary":`Alt ${Ge}`,":"]}),I(nt)]},Ge))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Be),children:e.jsx(xa,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Be}),f("editor")},children:e.jsx(Wa,{className:"h-4 w-4"})}),ke&&Ae.length>1&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await Qi("Delete this email from the sequence?")&&te.mutate(Be.id)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})})]},Be.id)})}),ke&&e.jsxs(z,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ae.mutate(Oe.id),disabled:ae.isPending,children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Oe.id)}}const Q4t={active:{icon:su,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:S0,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Xl,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Bd,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},J4t={sent:{icon:on,color:"text-blue-500"},opened:{icon:xa,color:"text-amber-500"},clicked:{icon:Gh,color:"text-green-500"},failed:{icon:nl,color:"text-destructive"}};function Pas({brokerageId:s}){var Pe,Oe,ke,Ve,_e;const{user:t}=hs(),n=$t(),[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(new Set),[d,u]=_.useState("assignments"),[h,m]=_.useState(null),[p,f]=_.useState(""),[g,v]=_.useState("all"),[y,b]=_.useState("all"),[w,S]=_.useState(!1),{data:C}=xae(),{data:E={}}=rt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Ae,error:Se}=await U.from("recruit_campaign_emails").select("*").order("email_number");if(Se)throw Se;const We={};return(Ae??[]).forEach(qe=>{We[qe.campaign_id]||(We[qe.campaign_id]=[]),We[qe.campaign_id].push(qe)}),We}}),{data:P}=rt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Ae,error:Se}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(Se)throw Se;return Ae}}),{data:M}=rt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Ae,error:Se}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Se)throw Se;return Ae}}),{data:I=[]}=rt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Ae,error:Se}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Se)throw Se;return Ae}}),D={};I.forEach(Ae=>{D[Ae.campaign_email_id]=Ae.selected_subject_index});const F={first_name:((Pe=h==null?void 0:h.prospect)==null?void 0:Pe.first_name)||"Sarah",brokerage_name:((Oe=M==null?void 0:M.merge_fields)==null?void 0:Oe.brokerage_name)||(P==null?void 0:P.name)||"Your Brokerage",city:((ke=M==null?void 0:M.merge_fields)==null?void 0:ke.city)||(P==null?void 0:P.city)||"Your City",sender_name:((Ve=M==null?void 0:M.merge_fields)==null?void 0:Ve.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},q=Ae=>{const Se=E[Ae.campaign_id]||[],We=Ae.current_email_number+1;return Se.find(qe=>qe.email_number===We)||null},{data:G=[],isLoading:V}=rt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Se=[],We=0;for(;;){const{data:qe,error:Be}=await U.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(We,We+1e3-1);if(Be)throw Be;if(Se=Se.concat(qe??[]),!qe||qe.length<1e3)break;We+=1e3}return Se}}),{data:H=[]}=rt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Ae,error:Se}=await U.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(Se)throw Se;return Ae}}),{data:K=[]}=rt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Ae,error:Se}=await U.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Se)throw Se;return Ae}}),{data:Z=[]}=rt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Se=[],We=0;for(;;){const{data:qe,error:Be}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(We,We+1e3-1);if(Be)throw Be;if(Se=Se.concat(qe??[]),!qe||qe.length<1e3)break;We+=1e3}return Se}}),oe=new Set(G.map(Ae=>`${Ae.prospect_id}-${Ae.campaign_id}`)),re=mt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Ae=new Date,Se=Array.from(o).filter(qe=>!oe.has(`${qe}-${i}`)).map(qe=>({prospect_id:qe,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Ae.toISOString(),started_at:Ae.toISOString()}));if(Se.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:We}=await U.from("recruit_campaign_assignments").insert(Se);if(We)throw We},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ne.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Ae=>ne.error(Ae.message)}),ae=mt({mutationFn:async({id:Ae,newStatus:Se})=>{const{error:We}=await U.from("recruit_campaign_assignments").update({status:Se,updated_at:new Date().toISOString()}).eq("id",Ae);if(We)throw We},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ne.success("Assignment updated")}}),J=mt({mutationFn:async()=>{const{data:Ae,error:Se}=await U.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Se)throw Se;return Ae},onSuccess:Ae=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ne.success(`Wave sent! ${Ae.sent} emails delivered, ${Ae.skipped} skipped, ${Ae.failed} failed`)},onError:Ae=>ne.error(`Send failed: ${Ae.message}`)}),te=G.filter(Ae=>Ae.status==="active").length;G.filter(Ae=>Ae.status==="completed").length;const ce=G.filter(Ae=>Ae.status==="active"&&Ae.next_send_at&&new Date(Ae.next_send_at)<=new Date).length,{data:ve={}}=Eit(s),me=G.reduce((Ae,Se)=>Ae+Math.max(0,Se.current_email_number||0),0),he=Object.values(ve).reduce((Ae,Se)=>Ae+Se.opened,0),ge=Object.values(ve).reduce((Ae,Se)=>Ae+Se.clicked,0);Object.values(ve).reduce((Ae,Se)=>Ae+Se.failed,0);const Ee=me>0?Math.round(he/me*100):0,Ne=me>0?ge/me*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ce>0&&e.jsxs(z,{variant:"outline",onClick:()=>{J.mutate()},disabled:J.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(cf,{className:"h-4 w-4 mr-1"}),J.isPending?"Sending...":`Send Next Wave (${ce})`]}),e.jsxs(z,{onClick:()=>a(!0),children:[e.jsx(Fr,{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(be,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(On,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:G.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(su,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:te}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(on,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:me.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(xa,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ee,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",he.toLocaleString(),")"]})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Gh,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ne.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",ge.toLocaleString(),")"]})]})]})})]}),e.jsxs(Qr,{value:d,onValueChange:u,children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"assignments",children:["Active Drips (",te,")"]}),e.jsxs(Wt,{value:"history",children:["Send History (",me.toLocaleString(),")"]})]}),e.jsx(Kt,{value:"assignments",className:"mt-4",children:V?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):G.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Fr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No campaigns assigned yet"}),e.jsx("p",{className:"text-sm",children:"Assign a recruiting campaign to your prospects to start automated outreach"})]})}):e.jsx("div",{className:"space-y-2",children:G.map(Ae=>{var $e,Xe,nt,Ge;const Se=Q4t[Ae.status]||Q4t.active,We=Se.icon,Be=(E[Ae.campaign_id]||[]).length||4,Ze=q(Ae);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 ${Se.color} border-0`,children:[e.jsx(We,{className:"h-3 w-3 mr-1"}),Se.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[($e=Ae.prospect)==null?void 0:$e.first_name," ",(Xe=Ae.prospect)==null?void 0:Xe.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(nt=Ae.prospect)==null?void 0:nt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ge=Ae.campaign)==null?void 0:Ge.name," · Email ",Ae.current_email_number,"/",Be,Ae.next_send_at&&Ae.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Zr,{className:"h-3 w-3 inline"})," Next: ",Ys(new Date(Ae.next_send_at),"MMM d, h:mm a"),new Date(Ae.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:[Ze&&e.jsx(z,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Ae),children:e.jsx(xa,{className:"h-3.5 w-3.5"})}),Ae.status==="active"&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>ae.mutate({id:Ae.id,newStatus:"paused"}),children:e.jsx(S0,{className:"h-3.5 w-3.5"})}),Ae.status==="paused"&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>ae.mutate({id:Ae.id,newStatus:"active"}),children:e.jsx(su,{className:"h-3.5 w-3.5"})}),(Ae.status==="active"||Ae.status==="paused")&&e.jsx(z,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ae.mutate({id:Ae.id,newStatus:"cancelled"}),children:e.jsx(Bd,{className:"h-3.5 w-3.5"})})]})]},Ae.id)})})}),e.jsxs(Kt,{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(ls,{value:g,onValueChange:v,children:[e.jsx(rs,{className:"w-[220px] h-8 text-xs",children:e.jsx(cs,{placeholder:"All campaigns"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All campaigns"}),K.map(Ae=>e.jsx(He,{value:Ae.id,children:Ae.name},Ae.id))]})]}),e.jsxs(ls,{value:y,onValueChange:b,children:[e.jsx(rs,{className:"w-[160px] h-8 text-xs",children:e.jsx(cs,{placeholder:"All statuses"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All statuses"}),e.jsx(He,{value:"sent",children:"Sent (no engagement)"}),e.jsx(He,{value:"opened",children:"Opened"}),e.jsx(He,{value:"clicked",children:"Clicked"})]})]}),(g!=="all"||y!=="all")&&e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{v("all"),b("all")},children:"Clear"})]}),(()=>{var Se;const Ae=H.filter(We=>{var qe;return!(g!=="all"&&((qe=We.campaign_email)==null?void 0:qe.campaign_id)!==g||y==="opened"&&!We.opened_at||y==="clicked"&&!We.clicked_at||y==="sent"&&(We.opened_at||We.clicked_at))});return Ae.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(on,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:H.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:H.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 ",Ae.length," of ",H.length," recent sends",g!=="all"&&` · ${(Se=K.find(We=>We.id===g))==null?void 0:Se.name}`]}),e.jsx("div",{className:"space-y-1",children:Ae.map(We=>{var $e,Xe,nt;const qe=J4t[We.status]||J4t.sent,Be=qe.icon,Ze=($e=K.find(Ge=>{var Je;return Ge.id===((Je=We.campaign_email)==null?void 0:Je.campaign_id)}))==null?void 0:$e.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(Be,{className:`h-4 w-4 flex-shrink-0 ${qe.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(Xe=We.prospect)==null?void 0:Xe.first_name," ",(nt=We.prospect)==null?void 0:nt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",We.email_number]}),Ze&&e.jsx(ze,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Ze})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:We.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[We.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(xa,{className:"h-3 w-3"})," ",Ys(new Date(We.opened_at),"MMM d")]}),We.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Gh,{className:"h-3 w-3"})," ",Ys(new Date(We.clicked_at),"MMM d")]}),e.jsx("span",{children:Ys(new Date(We.sent_at),"MMM d, h:mm a")})]})]},We.id)})})]})})()]})]}),e.jsx(Is,{open:r,onOpenChange:Ae=>{a(Ae),Ae||(f(""),c(new Set),l(""))},children:e.jsxs(Ls,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Os,{className:"px-6 pt-6 pb-4",children:[e.jsx(Rs,{children:"Assign Campaign to Prospects"}),e.jsx(_r,{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(ee,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(ls,{value:i,onValueChange:l,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose a campaign..."})}),e.jsx(as,{children:K.map(Ae=>e.jsx(He,{value:Ae.id,children:Ae.name},Ae.id))})]})]}),i&&(()=>{const Ae=p.toLowerCase(),Se=Z.filter(Be=>`${Be.first_name} ${Be.last_name}`.toLowerCase().includes(Ae)||Be.email.toLowerCase().includes(Ae)),We=Se.filter(Be=>!oe.has(`${Be.id}-${i}`)),qe=We.length>0&&We.every(Be=>o.has(Be.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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(Rr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:p,onChange:Be=>f(Be.target.value),className:"pl-9 h-9"})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(qe){const Be=new Set(o);We.forEach(Ze=>Be.delete(Ze.id)),c(Be)}else{const Be=new Set(o);We.forEach(Ze=>Be.add(Ze.id)),c(Be)}},children:[e.jsx(e7,{className:"h-3.5 w-3.5 mr-1"}),qe?"Deselect All":`Select All (${We.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Se.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:p?"No prospects match your search":"No prospects found for this brokerage"}):Se.map(Be=>{const Ze=oe.has(`${Be.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Ze?"opacity-40":""}`,children:[e.jsx(za,{checked:o.has(Be.id),disabled:Ze,onCheckedChange:$e=>{const Xe=new Set(o);$e?Xe.add(Be.id):Xe.delete(Be.id),c(Xe)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Be.first_name," ",Be.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Be.email})]}),Ze&&e.jsx(ze,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Be.id)})}),Se.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Se.length," of ",Z.length," prospects",We.length0&&e.jsx(be,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Le,{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:(_e=K.find(Ae=>Ae.id===i))==null?void 0:_e.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(hr,{className:"px-6 py-4 border-t",children:[e.jsx(z,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(z,{onClick:()=>{re.mutate()},disabled:re.isPending||!i||o.size===0,children:[e.jsx(Fr,{className:"h-4 w-4 mr-1"}),re.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Ae=q(h);return Ae?e.jsx(Eas,{email:Ae,mergeValues:F,selectedSubjectIndex:D[Ae.id],onClose:()=>m(null)}):null})(),e.jsx(wLe,{open:w,onOpenChange:S,hasPending:C==null?void 0:C.hasPendingSes,pendingEmails:C==null?void 0:C.pendingEmails})]})}function Las({brokerageId:s}){const t=$t(),[n,r]=_.useState([]),[a,i]=_.useState([]),[l,o]=_.useState(!1),c=_.useRef(!1),{data:d,isLoading:u}=rt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:v,error:y}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(y)throw y;return v},enabled:!!s});_.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=mt({mutationFn:async()=>{for(const b of a){const{error:w}=await U.from("recruit_pipeline_stages").delete().eq("id",b);if(w)throw w}const v=n.filter(b=>b.id&&!b.isNew),y=n.filter(b=>!b.id||b.isNew);for(const b of v){const{error:w}=await U.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(w)throw w}if(y.length>0){const{error:b}=await U.from("recruit_pipeline_stages").insert(y.map(w=>({brokerage_id:s,name:w.name,color:w.color,sort_order:w.sort_order})));if(b)throw b}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ne.success("Pipeline stages saved!"),o(!1)},onError:v=>ne.error(v.message)}),m=(v,y,b)=>{r(w=>w.map((S,C)=>C===v?{...S,[y]:b}:S)),o(!0)},p=()=>{const v=n.length>0?Math.max(...n.map(y=>y.sort_order)):0;r(y=>[...y,{name:"",color:"#6366f1",sort_order:v+1,isNew:!0}]),o(!0)},f=v=>{const y=n[v];y.id&&!y.isNew&&i(b=>[...b,y.id]),r(b=>b.filter((w,S)=>S!==v)),o(!0)},g=(v,y)=>{const b=v+y;if(b<0||b>=n.length)return;const w=[...n];[w[v],w[b]]=[w[b],w[v]],w.forEach((S,C)=>S.sort_order=C+1),r(w),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,y)=>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:()=>g(y,-1),disabled:y===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>g(y,1),disabled:y===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Zf,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:v.color,onChange:b=>m(y,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(pe,{value:v.name,onChange:b=>m(y,"name",b.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:y+1}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>f(y),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Cn,{className:"h-4 w-4"})})]},v.id||`new-${y}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:p,className:"gap-1",children:[e.jsx(sn,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(z,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Bo,{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 qrr({brokerageId:s}){const{data:t=[],isLoading:n}=rt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await U.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return 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(f7,{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(be,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(f7,{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(be,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Nt,{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(on,{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(ya,{className:"h-3 w-3"}),r.unsubscribed_at&&Ys(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Le,{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 Vrr(){var o;const[s,t]=_.useState(""),[n,r]=_.useState("board"),{data:a=[],isLoading:i}=rt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await U.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx($s,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsx($s,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(ls,{value:l,onValueChange:t,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),e.jsx(cs,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(c=>e.jsx(He,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(Sas,{brokerageId:l,trigger:e.jsxs(z,{size:"sm",className:"gap-1.5",children:[e.jsx(Xr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(Qr,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Jr,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Wt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Wt,{value:"contacts",children:[e.jsx(On,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Wt,{value:"video-outreach",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Wt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Wt,{value:"referrals",children:"Referrals"}),e.jsx(Wt,{value:"interest",children:"Interest Form"}),e.jsx(Wt,{value:"landing-page",children:"Landing Page"}),e.jsx(Wt,{value:"goals",children:"Goals"}),e.jsx(Wt,{value:"metrics",children:"Metrics"}),e.jsx(Wt,{value:"templates",children:"Email Templates"}),e.jsxs(Wt,{value:"campaigns",children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Wt,{value:"drip-assignments",children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Wt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Wt,{value:"email-settings",children:[e.jsx(Gc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Wt,{value:"pipeline-stages",children:[e.jsx(uP,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Wt,{value:"unsubscribed",children:[e.jsx(f7,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Kt,{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(z,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(op,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(z,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(fq,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(yas,{brokerageId:l}):e.jsx(vZe,{brokerageId:l})]}),e.jsx(Kt,{value:"contacts",children:e.jsx(vZe,{brokerageId:l})}),e.jsx(Kt,{value:"video-outreach",children:e.jsx(Cas,{brokerageId:l})}),e.jsx(Kt,{value:"follow-ups",children:e.jsx(Nas,{brokerageId:l})}),e.jsx(Kt,{value:"referrals",children:e.jsx(was,{brokerageId:l})}),e.jsx(Kt,{value:"interest",children:e.jsx(jas,{brokerageId:l})}),e.jsx(Kt,{value:"landing-page",children:e.jsx(kas,{brokerageId:l})}),e.jsx(Kt,{value:"goals",children:e.jsx(Aas,{brokerageId:l})}),e.jsx(Kt,{value:"metrics",children:e.jsx(vas,{brokerageId:l})}),e.jsx(Kt,{value:"templates",children:e.jsx(bas,{brokerageId:l})}),e.jsx(Kt,{value:"campaigns",children:e.jsx(Mas,{brokerageId:l})}),e.jsx(Kt,{value:"drip-assignments",children:e.jsx(Pas,{brokerageId:l})}),e.jsx(Kt,{value:"activity",children:e.jsx(_as,{brokerageId:l})}),e.jsx(Kt,{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(Ait,{brokerageId:l})]})}),e.jsx(Kt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(Las,{brokerageId:l})})}),e.jsx(Kt,{value:"unsubscribed",children:e.jsx(qrr,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(oi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}const eCt=()=>{const s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime()},d$=s=>{const t=s.split(/[-/T]/).slice(0,3).map(Number);return new Date(t[0],(t[1]||1)-1,t[2]||1).getTime()},u$=s=>Date.parse(s);async function HZ(s,t,n){const a=[];for(let i=0;;i+=1e3){const l=n(U.from(s).select(t)).range(i,i+1e3-1),{data:o,error:c}=await l;if(c)throw c;if(a.push(...o??[]),!o||o.length<1e3)break}return a}function Hrr(s){var o;const t=Lz(s),n=Eit(s),r=rt({queryKey:["recruit-command-sources",s,t.prospects.length],enabled:!!s&&!t.isLoading,queryFn:async()=>{if(!s)return{followUps:[],activities:[],goals:[],assignments:[],campaigns:[]};const c=t.prospects.map(f=>f.id),[d,u,h,m,p]=await Promise.all([c.length?HZ("recruit_follow_ups","id, prospect_id, title, due_date, completed_at, assigned_to",f=>f.in("prospect_id",c).order("due_date")):Promise.resolve([]),c.length?HZ("recruit_activities","id, prospect_id, activity_type, title, created_by, created_at",f=>f.in("prospect_id",c).order("created_at",{ascending:!1})):Promise.resolve([]),HZ("recruit_goals","id, title, target_count, target_stage_id, period_start, period_end",f=>f.eq("brokerage_id",s).order("period_end",{ascending:!1})),HZ("recruit_campaign_assignments","id, prospect_id, status",f=>f.eq("brokerage_id",s)),HZ("recruit_campaigns","id, name, is_active, brokerage_id",f=>f.or(`brokerage_id.is.null,brokerage_id.eq.${s}`))]);return{followUps:d,activities:u,goals:h,assignments:m,campaigns:p}}}),a=_.useMemo(()=>{var d;const c=new Set;return t.prospects.forEach(u=>u.created_by&&c.add(u.created_by)),(((d=r.data)==null?void 0:d.activities)??[]).forEach(u=>u.created_by&&c.add(u.created_by)),[...c]},[t.prospects,(o=r.data)==null?void 0:o.activities]),i=rt({queryKey:["recruit-command-profiles",s,a],enabled:a.length>0,queryFn:async()=>{const{data:c,error:d}=await U.from("profiles").select("id, name, email").in("id",a);if(d)throw d;return c??[]}});return{..._.useMemo(()=>{var ve,me,he,ge,Ee;const c=t.prospects,d=t.stages,u=((ve=r.data)==null?void 0:ve.followUps)??[],h=((me=r.data)==null?void 0:me.activities)??[],m=((he=r.data)==null?void 0:he.goals)??[],p=((ge=r.data)==null?void 0:ge.assignments)??[],f=((Ee=r.data)==null?void 0:Ee.campaigns)??[],g=eCt(),v=g+864e5,y=Date.now()-30*864e5,b=Date.now()-21*864e5,w=new Map(c.map(Ne=>[Ne.id,Ne])),S=u.filter(Ne=>!Ne.completed_at),C=S.filter(Ne=>u$(Ne.due_date){const Pe=u$(Ne.due_date);return Pe>=g&&Pe{const Pe=w.get(Ne.prospect_id);if(!Pe)return[];const Oe=u$(Ne.due_date)Ne.prospect_id));c.filter(Ne=>u$(Ne.updated_at)P.push({id:`stalled-${Ne.id}`,prospect:Ne,title:"No next step scheduled",detail:"No movement in 21+ days",tone:"stalled",dueAt:null}));const I=d.map(Ne=>({...Ne,count:c.filter(Pe=>Pe.stage_id===Ne.id).length,stalled:c.filter(Pe=>Pe.stage_id===Ne.id&&u$(Pe.updated_at)d$(Ne.period_start)<=D&&d$(Ne.period_end)>=D)??null,q=F?c.filter(Ne=>d$(Ne.created_at)>=d$(F.period_start)&&d$(Ne.created_at)<=d$(F.period_end)&&(!F.target_stage_id||Ne.stage_id===F.target_stage_id)).length:0,G=Object.values(n.data??{}),V=G.reduce((Ne,Pe)=>Ne+Pe.sent,0),H=G.reduce((Ne,Pe)=>Ne+Pe.opened,0),K=V?Math.round(H/V*100):0,Z=new Map((i.data??[]).map(Ne=>[Ne.id,Ne])),oe=a.map(Ne=>{var Ve;const Pe=h.filter(_e=>_e.created_by===Ne),Oe=Pe.filter(_e=>u$(_e.created_at)>=y),ke=Z.get(Ne);return{id:Ne,name:(ke==null?void 0:ke.name)||(ke==null?void 0:ke.email)||"Unknown recruiter",email:(ke==null?void 0:ke.email)||"",prospects:c.filter(_e=>_e.created_by===Ne).length,activities30d:Oe.length,lastActivityAt:((Ve=Pe[0])==null?void 0:Ve.created_at)??null}}).sort((Ne,Pe)=>Pe.activities30d-Ne.activities30d),re=new Map;c.forEach(Ne=>{const Pe=(Ne.source||"Not recorded").replace(/_/g," ");re.set(Pe,(re.get(Pe)??0)+1)});const ae=[...re.entries()].sort((Ne,Pe)=>Pe[1]-Ne[1]).slice(0,6),J=new Set(["signed","onboarded","hired","joined"]),te=new Set(d.filter(Ne=>J.has(Ne.name.toLowerCase())).map(Ne=>Ne.id)),ce=c.filter(Ne=>Ne.stage_id&&te.has(Ne.stage_id)).length;return{prospects:c,stages:I,followUps:u,activities:h,priority:P.slice(0,12),overdueCount:C.length,dueTodayCount:E.length,currentGoal:F,goalCurrent:q,goalPercent:F?Math.min(100,Math.round(q/Math.max(1,F.target_count)*100)):0,campaignOpenRate:K,campaignSent:V,activeCampaigns:f.filter(Ne=>Ne.is_active).length,activeAssignments:p.filter(Ne=>Ne.status==="active").length,recruiters:oe,sources:ae,converted:ce,conversionRate:c.length?Math.round(ce/c.length*100):0}},[t.prospects,t.stages,r.data,n.data,i.data,a]),pipeline:t,isLoading:t.isLoading||r.isLoading||n.isLoading||i.isLoading}}const Grr=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Wrr=s=>{if(!s)return"No activity";const t=Math.max(0,Math.floor((Date.now()-Date.parse(s))/864e5));return t===0?"Today":t===1?"Yesterday":`${t}d ago`},Wde=({label:s,value:t,detail:n,icon:r,tone:a,onClick:i})=>e.jsxs("button",{type:"button",onClick:i,className:"flex min-h-[112px] w-full items-start justify-between rounded-md border bg-card p-4 text-left shadow-xs transition-colors hover:border-primary/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 font-['Outfit'] text-3xl font-bold text-foreground",children:t}),e.jsx("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:n})]}),e.jsx("span",{className:Ct("flex h-10 w-10 shrink-0 items-center justify-center rounded-full",a),children:e.jsx(r,{className:"h-5 w-5"})})]});function Krr({brokerageId:s,onNavigate:t,onOpenProspect:n,onAddProspect:r}){var u;const a=Hrr(s),[i,l]=_.useState("all"),o=i==="all"?a.priority:a.priority.filter(h=>h.tone===i),c=Math.max(1,...a.stages.map(h=>h.count)),d=Math.max(1,...a.sources.map(([,h])=>h));return a.isLoading?e.jsxs("div",{className:"space-y-4","aria-busy":"true",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[0,1,2,3].map(h=>e.jsx(ln,{className:"h-28 rounded-md"},h))}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.5fr)_minmax(300px,.8fr)]",children:[e.jsx(ln,{className:"h-[520px] rounded-md"}),e.jsx(ln,{className:"h-[520px] rounded-md"})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Wde,{label:"Active pipeline",value:a.prospects.length,detail:`${a.converted} converted · ${a.conversionRate}% rate`,icon:vy,tone:"bg-primary/10 text-primary",onClick:()=>t("pipeline-board")}),e.jsx(Wde,{label:"Follow-ups due",value:a.overdueCount+a.dueTodayCount,detail:`${a.overdueCount} overdue · ${a.dueTodayCount} today`,icon:OU,tone:a.overdueCount?"bg-destructive/10 text-destructive":"bg-amber-500/10 text-amber-700",onClick:()=>t("pipeline-follow-ups")}),e.jsx(Wde,{label:"Campaign engagement",value:`${a.campaignOpenRate}%`,detail:`${a.campaignSent} sent · ${a.activeAssignments} enrolled`,icon:QU,tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>t("campaigns-manager")}),e.jsx(Wde,{label:"Current goal",value:a.currentGoal?`${a.goalCurrent}/${a.currentGoal.target_count}`:"—",detail:((u=a.currentGoal)==null?void 0:u.title)||"No active goal set",icon:bu,tone:"bg-recruit-gold/15 text-recruit-navy",onClick:()=>t("reporting-goals")})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(310px,.75fr)]",children:[e.jsxs("section",{className:"overflow-hidden rounded-md border bg-card shadow-xs",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Needs attention"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The next recruiting moves with the most urgency"})]}),e.jsx("div",{className:"flex flex-wrap gap-1 rounded-md bg-muted/50 p-1",children:["all","overdue","today","stalled"].map(h=>e.jsx(z,{size:"sm",variant:i===h?"default":"ghost",className:"h-7 px-2.5 text-xs capitalize",onClick:()=>l(h),children:h},h))})]}),e.jsxs("div",{className:"divide-y",children:[o.length===0&&e.jsxs("div",{className:"px-4 py-12 text-center",children:[e.jsx(Mr,{className:"mx-auto mb-2 h-7 w-7 text-emerald-600"}),e.jsx("p",{className:"text-sm font-medium",children:"Your priority queue is clear."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Add a prospect or review the full pipeline for your next move."})]}),o.slice(0,8).map(h=>{const m=`${h.prospect.first_name} ${h.prospect.last_name||""}`.trim();return e.jsxs("button",{type:"button",onClick:()=>n(h.prospect),className:"group flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[e.jsx(ja,{className:"h-9 w-9",children:e.jsx(Na,{className:"bg-primary/10 text-xs font-semibold text-primary",children:Grr(m)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:m}),e.jsx(ze,{className:Ct("border-0 text-[10px]",h.tone==="overdue"?"bg-destructive/10 text-destructive":h.tone==="today"?"bg-amber-500/10 text-amber-700":"bg-muted text-muted-foreground"),children:h.tone==="stalled"?"Stalled":h.tone==="today"?"Due today":"Overdue"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[h.title," · ",h.prospect.current_brokerage||h.detail]})]}),e.jsx(Da,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-primary"})]},h.id)})]}),e.jsxs("footer",{className:"flex flex-wrap items-center justify-between gap-2 border-t bg-muted/10 px-4 py-3",children:[e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>t("pipeline-follow-ups"),children:["View all follow-ups ",e.jsx(Da,{className:"ml-1.5 h-3.5 w-3.5"})]}),e.jsxs(z,{size:"sm",onClick:r,children:[e.jsx(Pl,{className:"mr-1.5 h-3.5 w-3.5"}),"Add prospect"]})]})]}),e.jsxs("section",{className:"rounded-md border bg-card p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Goal pace"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Progress toward the current target"})]}),e.jsxs("span",{className:"font-['Outfit'] text-xl font-bold text-primary",children:[a.goalPercent,"%"]})]}),e.jsx(Di,{value:a.goalPercent,className:"h-2.5"}),e.jsxs("div",{className:"mt-5 border-t pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h3",{className:"font-['Outfit'] text-sm font-semibold",children:"Recruiter accountability"}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>t("reporting-activity"),children:"Full activity"})]}),e.jsxs("div",{className:"space-y-3",children:[a.recruiters.slice(0,5).map((h,m)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-full bg-muted text-xs font-bold",children:m+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:h.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Last activity ",Wrr(h.lastActivityAt)]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-['Outfit'] text-base font-bold",children:h.activities30d}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"30d moves"})]})]},h.id)),!a.recruiters.length&&e.jsx("p",{className:"py-5 text-center text-sm text-muted-foreground",children:"Recruiter activity will appear here."})]})]})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(be,{className:"rounded-md p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Pipeline momentum"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Volume and stalled prospects by stage"})]}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>t("pipeline-board"),children:"Open board"})]}),e.jsxs("div",{className:"space-y-3",children:[a.stages.map(h=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 font-medium",children:[e.jsx("span",{className:"h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:h.color}}),e.jsx("span",{className:"truncate",children:h.name}),h.stalled>0&&e.jsxs("span",{className:"text-amber-700",children:[h.stalled," stalled"]})]}),e.jsx("span",{className:"font-bold",children:h.count})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] motion-reduce:transition-none",style:{width:`${Math.max(h.count?5:0,h.count/c*100)}%`}})})]},h.id)),!a.stages.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Set up pipeline stages to see momentum."})]})]}),e.jsxs(be,{className:"rounded-md p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Source intelligence"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where recruiting relationships originate"})]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs font-semibold text-primary",children:[e.jsx(kl,{className:"h-3.5 w-3.5"}),a.conversionRate,"% conversion"]})]}),e.jsxs("div",{className:"space-y-3",children:[a.sources.map(([h,m])=>e.jsxs("div",{className:"grid grid-cols-[minmax(100px,1fr)_2fr_32px] items-center gap-3",children:[e.jsx("span",{className:"truncate text-xs font-medium capitalize",children:h}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-recruit-gold",style:{width:`${Math.max(6,m/d*100)}%`}})}),e.jsx("span",{className:"text-right text-xs font-bold",children:m})]},h)),!a.sources.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Source data will appear as prospects are added."})]}),e.jsxs(z,{variant:"outline",size:"sm",className:"mt-5 w-full",onClick:()=>t("reporting-metrics"),children:[e.jsx(wl,{className:"mr-1.5 h-3.5 w-3.5"}),"Open recruiting analytics"]})]})]})]})}function Yrr({brokerageId:s}){const[t,n]=_.useState(""),[r,a]=_.useState("all"),{data:i,isLoading:l}=rt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var v;const{data:d,error:u}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(y=>[y.id,y]));if(Array.from(h.keys()).length===0)return[];const{data:p}=await U.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:f}=await U.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),g=[];for(const y of p||[]){const b=h.get(y.prospect_id);b&&g.push({id:`v-${y.id}`,kind:"video",prospect_id:y.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(v=y.video)!=null&&v.title?`Video: ${y.video.title}`:"Recruiting Video",status:y.cta_clicked_at?"clicked":y.first_viewed_at?"viewed":"sent",sent_at:y.sent_at,opened_at:y.first_viewed_at,clicked_at:y.cta_clicked_at,view_count:y.view_count,share_token:y.share_token})}for(const y of f||[]){if(!y.sent_at)continue;const b=h.get(y.prospect_id);b&&g.push({id:`c-${y.id}`,kind:"campaign",prospect_id:y.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:y.subject||`Email #${y.email_number}`,status:y.status||"sent",sent_at:y.sent_at,opened_at:y.opened_at,clicked_at:y.clicked_at,error:y.error_message})}return g.sort((y,b)=>new Date(b.sent_at).getTime()-new Date(y.sent_at).getTime()),g}}),o=_.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=_.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:Fr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:Xr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:on,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:xa,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Gh,color:"text-emerald-500"}].map(d=>e.jsx(be,{children:e.jsxs(Le,{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(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Nt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qr,{value:r,onValueChange:d=>a(d),children:e.jsxs(Jr,{className:"h-8",children:[e.jsx(Wt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Wt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Wt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Le,{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(on,{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(Xr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(ze,{variant:"outline",className:"gap-1",children:[e.jsx(on,{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(Ho,{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(Gh,{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(xa,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),"Sent"]}),d.error&&e.jsx("p",{className:"text-[10px] text-destructive mt-0.5 max-w-[200px] truncate",title:d.error,children:d.error})]}),e.jsxs("td",{className:"px-3 py-2 text-xs text-muted-foreground whitespace-nowrap",children:[Ys(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Ys(new Date(d.sent_at),"h:mm a")})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("div",{className:"flex items-center gap-2 justify-end text-xs text-muted-foreground",children:[d.kind==="video"&&d.view_count!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xa,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(z,{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(mr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}const tCt={pipeline:[{value:"pipeline-board",label:"Board",icon:op},{value:"pipeline-table",label:"Table",icon:fq},{value:"pipeline-contacts",label:"Contacts",icon:On},{value:"pipeline-follow-ups",label:"Follow-ups",icon:Wf},{value:"pipeline-referrals",label:"Referrals",icon:bq}],outreach:[{value:"outreach-video",label:"Video outreach",icon:Xr},{value:"outreach-templates",label:"Email templates",icon:JU},{value:"outreach-sent",label:"Sent emails",icon:on}],campaigns:[{value:"campaigns-manager",label:"Campaigns",icon:on},{value:"campaigns-assignments",label:"Drip assignments",icon:Fr}],assets:[{value:"assets-landing",label:"Landing page",icon:K2},{value:"assets-interest",label:"Interest form",icon:Wf}],reporting:[{value:"reporting-metrics",label:"Analytics",icon:wl},{value:"reporting-goals",label:"Goals",icon:bu},{value:"reporting-activity",label:"Recruiter activity",icon:On}],settings:[{value:"settings-email",label:"Email settings",icon:Gc},{value:"settings-stages",label:"Pipeline stages",icon:uP}]},Ias=[{value:"command",label:"Command"},{value:"pipeline",label:"Pipeline"},{value:"outreach",label:"Outreach"},{value:"campaigns",label:"Campaigns"},{value:"assets",label:"Growth assets"},{value:"reporting",label:"Reporting"},{value:"settings",label:"Settings"}],Zrr=s=>{var t;return((t=Ias.find(n=>s===n.value||s.startsWith(`${n.value}-`)))==null?void 0:t.value)??"command"};function Xrr(){var P;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=hs(),r=t||((P=s[0])==null?void 0:P.id)||"",a=Lz(r||null),[i,l]=_.useState("command"),[o,c]=_.useState(!1),[d,u]=_.useState(!1),[h,m]=_.useState(null),[p,f]=_.useState(!1),[g,v]=_.useState(""),y=Zrr(i),b=s.find(M=>M.id===r),w=_.useMemo(()=>{const M=g.trim().toLowerCase();return M?a.prospects.filter(I=>`${I.first_name} ${I.last_name||""} ${I.current_brokerage||""} ${I.email||""}`.toLowerCase().includes(M)).slice(0,6):[]},[a.prospects,g]),S=M=>l(M),C=M=>{m(M),f(!0),v("")},E=M=>l(M==="command"?"command":tCt[M][0].value);return s.length===0?e.jsx($s,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"py-16 text-center text-muted-foreground",children:[e.jsx(oi,{className:"mx-auto mb-4 h-12 w-12 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx($s,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"recruiting-console -m-4 min-h-[calc(100vh-72px)] bg-background font-['Figtree'] sm:-m-6 lg:-m-8",children:[e.jsxs("header",{className:"bg-secondary px-4 py-4 text-secondary-foreground sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground",children:e.jsx(bq,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"truncate text-xl font-bold",children:"Recruiting Command"}),e.jsxs("p",{className:"truncate text-xs text-secondary-foreground/70",children:[(b==null?void 0:b.name)||"Brokerage"," · Pipeline, outreach and growth"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative min-w-0 sm:w-72",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-secondary-foreground/60"}),e.jsx(pe,{value:g,onChange:M=>v(M.target.value),placeholder:"Search prospects…",className:"border-secondary-foreground/15 bg-primary/40 pl-9 text-secondary-foreground placeholder:text-secondary-foreground/55 focus-visible:ring-recruit-gold"}),g.trim()&&e.jsxs("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg",children:[w.map(M=>e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 border-b px-3 py-2.5 text-left text-sm last:border-0 hover:bg-accent",onClick:()=>C(M),children:[e.jsxs("span",{className:"truncate font-medium",children:[M.first_name," ",M.last_name]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:M.current_brokerage||"Prospect"})]},M.id)),w.length===0&&e.jsx("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"No matching prospects."})]})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{className:"bg-recruit-gold text-recruit-navy hover:bg-recruit-gold/90",children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"}),"New prospect ",e.jsx(cl,{className:"ml-2 h-3.5 w-3.5"})]})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onSelect:()=>c(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add prospect"]}),e.jsxs(ua,{onSelect:()=>u(!0),children:[e.jsx(Ra,{className:"mr-2 h-4 w-4"}),"Import CSV"]})]})]})]})]}),e.jsx("nav",{className:"-mx-4 mt-4 overflow-x-auto px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8","aria-label":"Recruiting sections",children:e.jsx("div",{className:"flex min-w-max items-center gap-1",children:Ias.map(M=>e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>E(M.value),className:Ct("h-9 rounded-none border-b-2 px-3 text-secondary-foreground/70 hover:bg-secondary-foreground/5 hover:text-secondary-foreground",y===M.value?"border-recruit-gold text-recruit-gold":"border-transparent"),children:M.label},M.value))})})]}),e.jsxs("div",{className:"px-4 py-5 sm:px-6 lg:px-8",children:[s.length>1&&e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ls,{value:r,onValueChange:n,children:[e.jsxs(rs,{className:"w-[280px] bg-card",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),e.jsx(cs,{})]}),e.jsx(as,{children:s.map(M=>e.jsx(He,{value:M.id,children:M.name},M.id))})]})]}),y!=="command"&&e.jsx("div",{className:"mb-5 overflow-x-auto pb-1",children:e.jsx(Qr,{value:i,onValueChange:l,children:e.jsx(Jr,{className:"h-auto min-w-max rounded-md border bg-card p-1",children:tCt[y].map(M=>{const I=M.icon;return e.jsxs(Wt,{value:M.value,className:"gap-1.5",children:[e.jsx(I,{className:"h-3.5 w-3.5"}),M.label]},M.value)})})})}),y==="command"&&r&&e.jsx(Krr,{brokerageId:r,onNavigate:S,onOpenProspect:C,onAddProspect:()=>c(!0)}),i==="pipeline-board"&&e.jsx(yas,{brokerageId:r}),(i==="pipeline-table"||i==="pipeline-contacts")&&e.jsx(vZe,{brokerageId:r}),i==="pipeline-follow-ups"&&e.jsx(Nas,{brokerageId:r}),i==="pipeline-referrals"&&e.jsx(was,{brokerageId:r}),i==="outreach-video"&&e.jsx(Cas,{brokerageId:r}),i==="outreach-templates"&&e.jsx(bas,{brokerageId:r}),i==="outreach-sent"&&e.jsx(Yrr,{brokerageId:r}),i==="campaigns-manager"&&e.jsx(Mas,{brokerageId:r}),i==="campaigns-assignments"&&e.jsx(Pas,{brokerageId:r}),i==="assets-landing"&&e.jsx(kas,{brokerageId:r}),i==="assets-interest"&&e.jsx(jas,{brokerageId:r}),i==="reporting-metrics"&&e.jsx(vas,{brokerageId:r}),i==="reporting-goals"&&e.jsx(Aas,{brokerageId:r}),i==="reporting-activity"&&e.jsx(_as,{brokerageId:r}),i==="settings-email"&&e.jsxs("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h2",{className:"font-['Outfit'] text-lg font-semibold",children:"Email settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure sender identity, merge fields and brokerage location."})]}),e.jsx(Ait,{brokerageId:r})]}),i==="settings-stages"&&e.jsx("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:e.jsx(Las,{brokerageId:r})})]}),e.jsx(Nit,{open:o,onOpenChange:c,stages:a.stages,onSubmit:M=>a.addProspect.mutate(M),isSubmitting:a.addProspect.isPending}),e.jsx(Cit,{open:d,onOpenChange:u,brokerageId:r,stages:a.stages}),e.jsx(Sit,{prospect:h,stages:a.stages,brokerageId:r,open:p,onOpenChange:f,onUpdate:M=>{a.updateProspect.mutate(M),m(I=>I?{...I,...M}:null)},onDelete:M=>a.deleteProspect.mutate(M)})]})})}const Qrr=[{key:"license_number",label:"License #"},{key:"license_state",label:"License state"},{key:"license_expiration",label:"License expiration",type:"date"},{key:"eo_carrier",label:"E&O carrier"},{key:"eo_policy_number",label:"E&O policy #"},{key:"eo_expiration",label:"E&O expiration",type:"date"},{key:"first_year_licensed",label:"First year licensed",type:"number"},{key:"anniversary_date",label:"Anniversary",type:"date"},{key:"birthday",label:"Birthday",type:"date"},{key:"mobile_phone",label:"Mobile"},{key:"personal_email",label:"Personal email"},{key:"address_line1",label:"Address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"postal_code",label:"Zip"},{key:"specialization",label:"Specialization"},{key:"prior_firm",label:"Prior firm"},{key:"designations",label:"Designations"},{key:"goal_amount",label:"Production goal",type:"number"},{key:"internal_role",label:"Role"}],Jrr=({brokerageId:s,agentUserId:t,readOnly:n})=>{const{toast:r}=_i(),{data:a}=A6n(s,t),{saveRecord:i}=n8e(s),[l,o]=_.useState({brokerage_id:s,agent_user_id:t});return _.useEffect(()=>{o({brokerage_id:s,agent_user_id:t,...a||{}})},[a,s,t]),e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 xl:grid-cols-3",children:Qrr.map(c=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:c.label}),e.jsx(pe,{type:c.type||"text",disabled:n,value:l[c.key]??"",onChange:d=>o({...l,[c.key]:c.type==="number"?d.target.value===""?null:Number(d.target.value):d.target.value||null})})]},String(c.key)))}),!n&&e.jsxs(z,{onClick:async()=>{await i.mutateAsync(l),r({title:"Record saved"})},children:[e.jsx(Bo,{className:"mr-2 h-4 w-4"})," Save record"]})]})},ear=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=E6n(s,t),{data:r=[]}=xYt(s,t),{addNote:a,deleteNote:i}=n8e(s),[l,o]=_.useState("");return e.jsxs("div",{className:"grid gap-6 xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Private notes"}),e.jsx(ze,{variant:"secondary",children:"Managers only"})]}),e.jsx(Ps,{rows:3,value:l,onChange:c=>o(c.target.value),placeholder:"Add a note about this agent…"}),e.jsx(z,{size:"sm",disabled:!l.trim(),onClick:async()=>{await a.mutateAsync({agentUserId:t,body:l.trim()}),o("")},children:"Add note"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet."}),n.map(c=>e.jsxs("div",{className:"rounded-md border bg-card p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:c.body}),e.jsx(z,{size:"icon",variant:"ghost",className:"text-destructive",onClick:()=>i.mutate({id:c.id,agentUserId:t}),"aria-label":"Delete note",children:e.jsx(Cn,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})})]},c.id))]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pm,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Activity"})]}),e.jsxs("div",{className:"space-y-2",children:[r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}),r.map(c=>e.jsxs("div",{className:"relative border-l-2 border-primary/40 bg-muted/30 px-4 py-2.5",children:[e.jsx("p",{className:"text-sm",children:c.description}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})})]},c.id))]})]})]})},sCt=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Das=s=>s?s.split(/[-/T]/).slice(0,3).join("/"):null,tar=s=>s.assignment?s.total>0&&s.done===s.total?{label:"Completed",className:"bg-emerald-500/10 text-emerald-700"}:s.overdue>0?{label:"Overdue",className:"bg-destructive/10 text-destructive"}:s.needsReview>0?{label:"Waiting on review",className:"bg-amber-500/10 text-amber-700"}:{label:"In progress",className:"bg-primary/10 text-primary"}:{label:"Not started",className:"bg-muted/70 text-muted-foreground"},Kde=({label:s,value:t,icon:n,active:r,tone:a,onClick:i})=>e.jsxs("button",{type:"button",onClick:i,"aria-pressed":r,className:Ct("flex min-h-[92px] w-full items-center justify-between rounded-md border bg-card p-4 text-left shadow-xs transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",r&&"border-primary bg-primary/5 ring-1 ring-primary/20"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 font-['Outfit'] text-3xl font-bold text-foreground",children:t})]}),e.jsx("span",{className:Ct("flex h-10 w-10 items-center justify-center rounded-full",a),children:e.jsx(n,{className:"h-5 w-5"})})]}),sar=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=xYt(s,t);return e.jsxs("aside",{className:"rounded-md border bg-card p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h3",{className:"font-['Outfit'] text-sm font-semibold",children:"Recent activity"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Latest updates"})]}),e.jsxs("div",{className:"space-y-4",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),n.slice(0,6).map((r,a)=>e.jsxs("div",{className:"relative flex gap-3",children:[e.jsx("span",{className:Ct("mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full ring-4 ring-background",a===0?"bg-primary":"bg-muted-foreground/40")}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm leading-snug",children:r.description}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Das(r.created_at)})]})]},r.id))]})]})},nar=({brokerageId:s})=>{var F,q;const{toast:t}=_i(),{data:n=[],isLoading:r}=pYt(s),{data:a=[]}=mYt(s),{assignTemplate:i,removeAssignment:l}=n8e(s),[o,c]=_.useState(""),[d,u]=_.useState("all"),[h,m]=_.useState(null),[p,f]=_.useState(!1),[g,v]=_.useState(null),[y,b]=_.useState(""),w=_.useMemo(()=>{const G=o.trim().toLowerCase();return n.filter(V=>{if(G&&!V.name.toLowerCase().includes(G)&&!V.email.toLowerCase().includes(G))return!1;const H=!!V.assignment&&V.total>0&&V.done===V.total;return d==="not_started"?!V.assignment:d==="in_progress"?!!V.assignment&&!H:d==="finished"?H:d==="review"?V.needsReview>0:d==="overdue"?V.overdue>0:!0})},[n,o,d]);_.useEffect(()=>{var G;h&&w.some(V=>V.agentId===h)||m(((G=w[0])==null?void 0:G.agentId)??null)},[w,h]);const S=n.find(G=>G.agentId===h)||null,{data:C}=fYt((F=S==null?void 0:S.assignment)==null?void 0:F.id),E=(C==null?void 0:C.steps)||[],P=E.filter(PA).length,M=E.length?Math.round(P/E.length*100):0,I=_.useMemo(()=>{const G=n.filter(V=>V.assignment);return{inProgress:G.filter(V=>!(V.total>0&&V.done===V.total)).length,finished:G.filter(V=>V.total>0&&V.done===V.total).length,needsReview:n.reduce((V,H)=>V+H.needsReview,0),overdue:n.reduce((V,H)=>V+H.overdue,0)}},[n]),D=G=>{m(G),f(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Kde,{label:"In progress",value:I.inProgress,icon:vy,active:d==="in_progress",tone:"bg-primary/10 text-primary",onClick:()=>u(d==="in_progress"?"all":"in_progress")}),e.jsx(Kde,{label:"Finished",value:I.finished,icon:Mr,active:d==="finished",tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>u(d==="finished"?"all":"finished")}),e.jsx(Kde,{label:"Waiting on review",value:I.needsReview,icon:OU,active:d==="review",tone:"bg-amber-500/10 text-amber-700",onClick:()=>u(d==="review"?"all":"review")}),e.jsx(Kde,{label:"Overdue steps",value:I.overdue,icon:nl,active:d==="overdue",tone:"bg-destructive/10 text-destructive",onClick:()=>u(d==="overdue"?"all":"overdue")})]}),e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[310px_minmax(0,1fr)] xl:grid-cols-[340px_minmax(0,1fr)]",children:[e.jsxs("section",{className:Ct("border-r bg-muted/10",p&&"hidden lg:block"),children:[e.jsxs("header",{className:"border-b p-4",children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Agents"}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Track each agent’s onboarding"}),e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"h-9 bg-background pl-9",placeholder:"Search agents",value:o,onChange:G=>c(G.target.value)})]}),e.jsxs(ls,{value:d,onValueChange:G=>u(G),children:[e.jsx(rs,{className:"h-9 bg-background",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All agents"}),e.jsx(He,{value:"not_started",children:"Not started"}),e.jsx(He,{value:"in_progress",children:"In progress"}),e.jsx(He,{value:"finished",children:"Finished"}),e.jsx(He,{value:"review",children:"Waiting on review"}),e.jsx(He,{value:"overdue",children:"Overdue"})]})]})]}),e.jsxs("div",{className:"max-h-[650px] overflow-y-auto p-2",children:[r&&e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"Loading…"}),!r&&w.length===0&&e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"No agents match."}),w.map(G=>{const V=G.total?Math.round(G.done/G.total*100):0,H=tar(G);return e.jsxs("button",{type:"button",onClick:()=>D(G.agentId),className:Ct("mb-1 flex w-full items-center gap-3 rounded-md border border-transparent p-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",G.agentId===h&&"border-primary/30 bg-primary/5"),children:[e.jsxs(ja,{className:"h-10 w-10 border-2 border-background shadow-xs",children:[e.jsx(xi,{src:G.avatarUrl||void 0,alt:G.name,className:"object-cover"}),e.jsx(Na,{className:"bg-primary/10 text-xs font-semibold text-primary",children:sCt(G.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:G.name}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:G.assignment?`${V}% complete`:"No flow assigned"}),e.jsx(ze,{className:Ct("mt-1 border-0 px-1.5 py-0 text-[10px] font-medium",H.className),children:H.label})]}),G.needsReview>0&&e.jsx("span",{className:"flex h-6 min-w-6 items-center justify-center rounded-full bg-amber-500/10 px-1.5 text-[10px] font-bold text-amber-700",children:G.needsReview})]},G.agentId)})]})]}),e.jsx("section",{className:Ct("min-w-0",!p&&"hidden lg:block"),children:S?e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"border-b bg-card p-4 md:p-5",children:[e.jsxs(z,{variant:"ghost",size:"sm",className:"mb-3 -ml-2 lg:hidden",onClick:()=>f(!1),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"All agents"]}),e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(ja,{className:"h-14 w-14 border shadow-xs",children:[e.jsx(xi,{src:S.avatarUrl||void 0,alt:S.name,className:"object-cover"}),e.jsx(Na,{className:"bg-primary text-base font-semibold text-primary-foreground",children:sCt(S.name)})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate font-['Outfit'] text-xl font-bold",children:S.name}),e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:S.email}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[((q=S.assignment)==null?void 0:q.template_name)||"No flow assigned",S.joinedAt?` · Joined ${Das(S.joinedAt)}`:""]})]})]}),S.assignment?e.jsxs(z,{variant:"outline",className:"text-destructive",onClick:async()=>{await l.mutateAsync(S.assignment),t({title:"Onboarding removed"})},children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"}),"Remove checklist"]}):e.jsxs(z,{onClick:()=>{var G,V;v(S),b(((G=a.find(H=>H.is_default))==null?void 0:G.id)||((V=a[0])==null?void 0:V.id)||"")},disabled:a.length===0,children:[e.jsx(su,{className:"mr-2 h-4 w-4"}),"Start onboarding"]})]}),S.assignment&&e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Onboarding progress"}),e.jsxs("span",{className:"font-['Outfit'] text-lg font-bold text-primary",children:[M,"%"]})]}),e.jsx(Di,{value:M,className:"h-2.5 bg-muted"}),e.jsxs("p",{className:"mt-1.5 text-right text-xs text-muted-foreground",children:[P," of ",E.length," steps complete"]})]}),a.length===0&&!S.assignment&&e.jsxs("p",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(nl,{className:"h-4 w-4"}),"Build an onboarding flow first on the Flows tab."]})]}),e.jsx("div",{className:"p-4 md:p-5",children:e.jsxs(Qr,{defaultValue:"checklist",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(Jr,{className:"grid h-auto min-w-[500px] grid-cols-4 rounded-md border bg-muted/40 p-1",children:[e.jsx(Wt,{value:"checklist",children:"Checklist"}),e.jsx(Wt,{value:"record",children:"Record"}),e.jsx(Wt,{value:"notes",children:"Notes & activity"}),e.jsx(Wt,{value:"documents",children:"Documents"})]})}),e.jsx(Kt,{value:"checklist",children:S.assignment?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(240px,.8fr)]",children:[e.jsx(CWe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(C==null?void 0:C.documents)||[],mode:"manager"}),e.jsx(sar,{brokerageId:s,agentUserId:S.agentId})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No checklist assigned yet."})}),e.jsx(Kt,{value:"record",children:e.jsx(Jrr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Kt,{value:"notes",children:e.jsx(ear,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Kt,{value:"documents",children:S.assignment?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(n7,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-['Outfit'] font-semibold",children:"Onboarding documents"})]}),e.jsx(CWe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(C==null?void 0:C.documents)||[],mode:"manager",displayMode:"documents"})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No documents yet."})})]})})]}):e.jsxs("div",{className:"flex min-h-[620px] flex-col items-center justify-center text-center",children:[e.jsx(fN,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select an agent to see their onboarding."})]})})]}),e.jsx(Is,{open:!!g,onOpenChange:G=>!G&&v(null),children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Start onboarding"}),e.jsxs(_r,{children:["Pick the flow for ",g==null?void 0:g.name,". Later flow edits will not change this checklist."]})]}),e.jsxs(ls,{value:y,onValueChange:b,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose a flow"})}),e.jsx(as,{children:a.map(G=>e.jsx(He,{value:G.id,children:G.name},G.id))})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),e.jsxs(z,{disabled:!y||!g,onClick:async()=>{if(g)try{await i.mutateAsync({agentUserId:g.agentId,templateId:y}),t({title:"Onboarding started"}),v(null)}catch(G){t({title:"Could not start",description:G.message,variant:"destructive"})}},children:[e.jsx(f6,{className:"mr-2 h-4 w-4"}),"Start"]})]})]})})]})},rar=s=>s==="document"?$r:s==="form"?cb:Zw,aar=({brokerageId:s})=>{var G,V;const{toast:t}=_i(),{data:n=[],isLoading:r}=mYt(s),[a,i]=_.useState(null),l=a??((G=n[0])==null?void 0:G.id)??null,o=n.find(H=>H.id===l)||null,{data:c=[]}=S6n(l),{createTemplate:d,updateTemplate:u,deleteTemplate:h,upsertStep:m,deleteStep:p,reorderSteps:f}=T6n(s),{data:g=[]}=rt({queryKey:["brokerage-form-templates",s],queryFn:async()=>{const{data:H,error:K}=await U.from("form_templates").select("id, name").eq("brokerage_id",s).eq("is_archived",!1).order("name");if(K)throw K;return H||[]}}),[v,y]=_.useState(!1),[b,w]=_.useState(""),[S,C]=_.useState(""),[E,P]=_.useState(!1),[M,I]=_.useState(null),D=()=>I({title:"",description:"",step_type:"document",assignee:"agent",due_days:null}),F=async()=>{var H;!l||!((H=M==null?void 0:M.title)!=null&&H.trim())||(await m.mutateAsync({...M.id?{id:M.id}:{},template_id:l,title:M.title.trim(),description:M.description||null,step_type:M.step_type||"document",assignee:M.assignee||"agent",form_template_id:M.step_type==="form"&&M.form_template_id||null,due_days:M.due_days??null,sort_order:M.sort_order??c.length}),P(!1),I(null),t({title:"Step saved"}))},q=async(H,K)=>{const Z=[...c],oe=H+K;oe<0||oe>=Z.length||([Z[H],Z[oe]]=[Z[oe],Z[H]],await f.mutateAsync({steps:Z,templateId:l}))};return e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[300px_minmax(0,1fr)]",children:[e.jsxs(be,{className:"rounded-none border-0 border-r shadow-none",children:[e.jsxs(_t,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Nt,{className:"text-base",children:"Onboarding flows"}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>y(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]}),e.jsx(En,{children:"Reusable checklists for new agents"})]}),e.jsxs(Le,{className:"space-y-2",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}),!r&&n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No flows yet. Create your first one."}),n.map(H=>e.jsxs("button",{onClick:()=>i(H.id),className:`w-full rounded-md border p-3 text-left transition-colors ${H.id===l?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:H.name}),H.is_default&&e.jsxs(ze,{variant:"secondary",className:"gap-1",children:[e.jsx(Ia,{className:"h-3 w-3"})," Default"]})]}),H.description&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:H.description})]},H.id))]})]}),e.jsx(be,{className:"rounded-none border-0 shadow-none",children:o?e.jsxs(e.Fragment,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:o.name}),e.jsx(En,{children:o.description||"No description"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>u.mutate({id:o.id,is_default:!o.is_default}),children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"}),o.is_default?"Unset default":"Set default"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{D(),P(!0)},children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Add step"]}),e.jsx(z,{size:"sm",variant:"ghost",className:"text-destructive",onClick:async()=>{await h.mutateAsync(o.id),i(null)},children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})}),e.jsxs(Le,{className:"space-y-2",children:[c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No steps yet — add documents, forms and tasks agents need to complete."}),c.map((H,K)=>{const Z=rar(H.step_type);return e.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-3 transition-colors hover:bg-muted/40",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary",children:e.jsx(Z,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:H.title}),e.jsx(ze,{variant:"outline",className:"capitalize",children:H.step_type}),e.jsx(ze,{variant:"secondary",className:"capitalize",children:H.assignee}),H.due_days!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["due in ",H.due_days,"d"]})]}),H.description&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:H.description})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>q(K,-1),"aria-label":"Move up",children:e.jsx(ap,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>q(K,1),"aria-label":"Move down",children:e.jsx(Vf,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",onClick:()=>{I(H),P(!0)},"aria-label":"Edit step",children:e.jsx(Wa,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"text-destructive",onClick:()=>p.mutate({id:H.id,templateId:o.id}),"aria-label":"Delete step",children:e.jsx(Cn,{className:"h-4 w-4"})})]})]},H.id)})]})]}):e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Wf,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create an onboarding flow."})]})}),e.jsx(Is,{open:v,onOpenChange:y,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"New onboarding flow"}),e.jsx(_r,{children:"Name it for the kind of agent it fits."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:b,onChange:H=>w(H.target.value),placeholder:"New Agent Onboarding"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:S,onChange:H=>C(H.target.value),rows:3})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(z,{disabled:!b.trim(),onClick:async()=>{const H=await d.mutateAsync({name:b.trim(),description:S});i(H.id),w(""),C(""),y(!1)},children:"Create"})]})]})}),e.jsx(Is,{open:E,onOpenChange:P,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:M!=null&&M.id?"Edit step":"Add step"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:(M==null?void 0:M.title)||"",onChange:H=>I({...M,title:H.target.value}),placeholder:"Independent contractor agreement"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Instructions"}),e.jsx(Ps,{rows:2,value:(M==null?void 0:M.description)||"",onChange:H=>I({...M,description:H.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ls,{value:(M==null?void 0:M.step_type)||"document",onValueChange:H=>I({...M,step_type:H}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"document",children:"Document upload"}),e.jsx(He,{value:"form",children:"Form from library"}),e.jsx(He,{value:"task",children:"Task / check off"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Who completes it"}),e.jsxs(ls,{value:(M==null?void 0:M.assignee)||"agent",onValueChange:H=>I({...M,assignee:H}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"agent",children:"Agent"}),e.jsx(He,{value:"manager",children:"Manager"})]})]})]})]}),(M==null?void 0:M.step_type)==="form"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Form"}),e.jsxs(ls,{value:(M==null?void 0:M.form_template_id)||"",onValueChange:H=>I({...M,form_template_id:H}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose a form"})}),e.jsx(as,{children:g.map(H=>e.jsx(He,{value:H.id,children:H.name},H.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Due (days after start)"}),e.jsx(pe,{type:"number",min:0,value:(M==null?void 0:M.due_days)??"",onChange:H=>I({...M,due_days:H.target.value===""?null:Number(H.target.value)}),placeholder:"Optional"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>P(!1),children:"Cancel"}),e.jsx(z,{onClick:F,disabled:!((V=M==null?void 0:M.title)!=null&&V.trim()),children:"Save step"})]})]})})]})},iar=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=hs(),o=zn(),[c,d]=_.useState(!1),u=i||(a.length>0?a[0].id:r);return _.useEffect(()=>{if(s){if(!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),d(!0)}},[s,t,n,o,a,i,l]),c?e.jsx($s,{title:"Agent Onboarding",description:"Build your onboarding flow, collect documents and keep notes",children:e.jsxs("div",{className:"onboarding-console space-y-5 font-['Figtree']",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(ls,{value:i||"",onValueChange:l,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),e.jsx(cs,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(h=>e.jsx(He,{value:h.id,children:h.name},h.id))})]})]}),u?e.jsxs(Qr,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(Jr,{className:"grid h-10 w-full max-w-sm grid-cols-2 rounded-md border bg-muted/40 p-1",children:[e.jsx(Wt,{value:"board",children:"Agents"}),e.jsx(Wt,{value:"flows",children:"Flows"})]}),e.jsx(Kt,{value:"board",children:e.jsx(nar,{brokerageId:u})}),e.jsx(Kt,{value:"flows",children:e.jsx(aar,{brokerageId:u})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(oi,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},oar={checklist_applied:"Checklist applied",document_uploaded:"Document uploaded",item_approved:"Item approved",item_rejected:"Changes requested",item_added:"Item added",item_updated:"Item updated"};function lar({dealId:s}){const{data:t=[]}=gTs(s),[n,r]=_.useState({});return _.useEffect(()=>{const a=Array.from(new Set(t.map(i=>i.actor_user_id).filter(Boolean)));a.length!==0&&(async()=>{const{data:i}=await U.from("profiles").select("id, name, email").in("id",a),l={};(i||[]).forEach(o=>{l[o.id]=o.name||o.email||"Someone"}),r(l)})()},[t]),t.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No compliance activity yet."}):e.jsx("div",{className:"space-y-3",children:t.map(a=>e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-1.5 h-2 w-2 flex-shrink-0 rounded-full bg-primary/60"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:oar[a.event_type]||a.event_type}),a.detail&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.detail}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.actor_user_id?n[a.actor_user_id]||"Someone":"System"," ·"," ",new Date(a.created_at).toLocaleString()]})]})]},a.id))})}function car({brokerageId:s,deal:t,open:n,onOpenChange:r}){const{data:a=[]}=VRt(s),i=vTs(),[l,o]=_.useState("");if(!t)return null;const c=oVe(t),d=async()=>{if(l)try{await i.mutateAsync({dealId:t.deal_id,brokerageId:s,templateId:l,deal:{contract_date:t.contract_date,target_close_date:t.target_close_date}}),ne.success("Checklist added to this file")}catch(u){ne.error(u.message||"Could not apply checklist")}};return e.jsx(Wg,{open:n,onOpenChange:r,children:e.jsxs(gg,{className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(Dy,{className:"text-left",children:[e.jsx(Ry,{className:"pr-8",children:t.property_address||t.deal_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx(ze,{variant:"secondary",children:t.agent_name||"Agent"}),t.stage_name&&e.jsx(ze,{variant:"outline",children:t.stage_name}),e.jsx(ze,{variant:c==="compliant"?"default":"outline",children:qRt[c]})]})]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-3 rounded-lg border p-3 text-center text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Contract"}),e.jsx("p",{className:"font-medium",children:t.contract_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Target close"}),e.jsx("p",{className:"font-medium",children:t.target_close_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Approved"}),e.jsxs("p",{className:"font-medium",children:[t.approved_items,"/",t.total_items]})]})]}),e.jsxs(Qr,{defaultValue:"checklist",className:"mt-5",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsx(Wt,{value:"checklist",children:"Checklist"}),e.jsx(Wt,{value:"messages",children:"Messages"}),e.jsx(Wt,{value:"audit",children:"Audit trail"})]}),e.jsxs(Kt,{value:"checklist",className:"mt-4 space-y-4",children:[t.total_items===0&&a.length>0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Apply a checklist"})}),e.jsx(as,{children:a.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))})]}),e.jsx(z,{onClick:d,disabled:!l||i.isPending,children:"Apply"})]}),e.jsx(Vss,{dealId:t.deal_id,canReview:!0})]}),e.jsx(Kt,{value:"messages",className:"mt-4",children:e.jsx(Hss,{dealId:t.deal_id,brokerageId:s,role:"staff",counterpartName:t.agent_name})}),e.jsx(Kt,{value:"audit",className:"mt-4",children:e.jsx(lar,{dealId:t.deal_id})})]})]})})}function dar({metrics:s}){const t=[{label:"Active transactions",value:String(s.activeDeals),caption:`${s.closedThisYear} closed this year`,icon:oi,tint:"bg-blue-500/10 text-blue-600"},{label:"Pipeline volume",value:tp(s.pipelineVolume),caption:`${tp(s.closedVolumeThisYear)} closed YTD`,icon:kl,tint:"bg-indigo-500/10 text-indigo-600"},{label:"Projected commission",value:tp(s.pipelineGci),caption:"Gross on active files",icon:Nd,tint:"bg-emerald-500/10 text-emerald-600"},{label:"Est. brokerage share",value:tp(s.brokerageShare),caption:`${tp(s.closedCompanyDollarYtd)} company dollar YTD`,icon:lJ,tint:"bg-teal-500/10 text-teal-600"},{label:"Closing soon",value:String(s.closingNext30),caption:`${s.closingThisMonth} this month`,icon:Ud,tint:"bg-amber-500/10 text-amber-600"}],n=[{label:"Files awaiting review",value:s.needsReview,icon:n7,tint:"text-blue-600"},{label:"Changes requested",value:s.changesRequested,icon:sJ,tint:"text-destructive"},{label:"Overdue items",value:s.overdueItems,icon:nl,tint:"text-amber-600"}];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-5",children:t.map(r=>e.jsx(be,{className:"border-border/60",children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:Ct("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",r.tint),children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:r.label}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:r.value}),e.jsx("p",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:r.caption})]})]})})},r.label))}),e.jsx(be,{className:"border-border/60",children:e.jsx(Le,{className:"flex flex-wrap items-center gap-x-8 gap-y-3 p-4",children:n.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.icon,{className:Ct("h-4 w-4",r.tint)}),e.jsx("span",{className:"text-sm font-semibold tabular-nums",children:r.value}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r.label})]},r.label))})})]})}function uar({outlook:s}){const t=s.some(n=>n.deals>0);return e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"Closing outlook"}),e.jsx(En,{children:"Expected closings over the next 6 months"})]}),e.jsx(Le,{className:"pt-2",children:t?e.jsx("div",{className:"h-[220px] w-full",children:e.jsx(Nb,{width:"100%",height:"100%",children:e.jsxs(KW,{data:s,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(TE,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(Mv,{dataKey:"label",tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pv,{tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))",tickFormatter:n=>tp(Number(n)),width:54}),e.jsx(Rf,{cursor:{fill:"hsl(var(--muted) / 0.4)"},contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12,color:"hsl(var(--popover-foreground))"},formatter:(n,r,a)=>{var i,l;return[`${tp(Number(n))} · ${((i=a==null?void 0:a.payload)==null?void 0:i.deals)??0} deal${((l=a==null?void 0:a.payload)==null?void 0:l.deals)===1?"":"s"}`,"Volume"]}}),e.jsx(W_,{dataKey:"volume",radius:[6,6,0,0],children:s.map(n=>e.jsx(cz,{fill:n.closed?"hsl(var(--primary))":"hsl(var(--primary) / 0.45)"},n.key))})]})})}):e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No closing dates set on the current transactions yet."})})]})}function har({agents:s,totalVolume:t,selectedAgentId:n,onSelectAgent:r}){return s.length===0?null:e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"Agent production"}),e.jsx(En,{children:"Company-visible transactions by agent — tap a row to filter the board"})]}),e.jsx(Le,{className:"space-y-1 pt-2",children:s.slice(0,12).map(a=>{const i=t>0?Math.round(a.volume/t*100):0,l=n===a.userId;return e.jsxs("button",{onClick:()=>r(l?"all":a.userId),className:`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60 ${l?"bg-muted":""}`,children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:a.avatarUrl||void 0,alt:a.name}),e.jsx(Na,{className:"text-[11px]",children:a.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:a.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.activeDeals," active · ",a.closedDeals," closed",a.overdue>0?` · ${a.overdue} overdue`:""]}),e.jsx("div",{className:"mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${i}%`}})})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-sm font-semibold tabular-nums",children:tp(a.volume)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground tabular-nums",children:[tp(a.gci)," GCI"]})]})]},a.userId)})})]})}const nCt={ownerUserId:"",dealName:"",dealType:"buyer",stageId:"",propertyAddress:"",city:"",state:"",zipCode:"",contractDate:"",targetCloseDate:"",actualCloseDate:"",price:"",commissionPercentage:"",notes:""};function mar({brokerageId:s,open:t,onOpenChange:n}){const[r,a]=_.useState(nCt),[i,l]=_.useState(""),{data:o=[],isLoading:c}=kTs(t?s:null),{data:d=[],isLoading:u}=STs(r.ownerUserId||null),h=CTs();_.useEffect(()=>{t||(a(nCt),l(""))},[t]),_.useEffect(()=>{d.length>0&&!d.some(w=>w.id===r.stageId)&&a(w=>({...w,stageId:d[0].id}))},[d,r.stageId]);const m=_.useMemo(()=>{const w=i.trim().toLowerCase();return w?o.filter(S=>`${S.name??""} ${S.email??""}`.toLowerCase().includes(w)):o},[o,i]),p=(w,S)=>a(C=>({...C,[w]:S})),f=r.price?Number(r.price):null,g=r.commissionPercentage?Number(r.commissionPercentage):null,v=f!=null&&g!=null&&Number.isFinite(f)&&Number.isFinite(g)?Math.round(f*(g/100)*100)/100:null,y=!!r.ownerUserId&&!!r.stageId&&r.dealName.trim().length>0&&!h.isPending,b=async()=>{try{await h.mutateAsync({brokerageId:s,ownerUserId:r.ownerUserId,dealName:r.dealName,dealType:r.dealType,stageId:r.stageId||null,propertyAddress:r.propertyAddress,city:r.city,state:r.state,zipCode:r.zipCode,contractDate:r.contractDate,targetCloseDate:r.targetCloseDate,actualCloseDate:r.actualCloseDate,price:f!=null&&Number.isFinite(f)?f:null,commissionPercentage:g!=null&&Number.isFinite(g)?g:null,notes:r.notes});const w=o.find(S=>S.id===r.ownerUserId);ne.success(`Deal added to ${(w==null?void 0:w.name)||"the agent"}'s pipeline.`),n(!1)}catch(w){ne.error((w==null?void 0:w.message)||"Could not add the deal.")}};return e.jsx(Is,{open:t,onOpenChange:n,children:e.jsxs(Ls,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add a deal for an agent"}),e.jsx(_r,{children:"The deal is created in the agent's own pipeline, so it shows up here and in their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Agent"}),e.jsx(pe,{placeholder:"Search agents by name or email",value:i,onChange:w=>l(w.target.value)}),e.jsxs(ls,{value:r.ownerUserId,onValueChange:w=>p("ownerUserId",w),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:c?"Loading agents…":"Select an agent"})}),e.jsx(as,{children:m.map(w=>e.jsx(He,{value:w.id,children:w.name||w.email||"Agent"},w.id))})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Deal name"}),e.jsx(pe,{placeholder:"Client name or property address",value:r.dealName,onChange:w=>p("dealName",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ls,{value:r.dealType,onValueChange:w=>p("dealType",w),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Stage"}),e.jsxs(ls,{value:r.stageId,onValueChange:w=>p("stageId",w),disabled:!r.ownerUserId||u,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:r.ownerUserId?u?"Loading stages…":"Select a stage":"Pick an agent first"})}),e.jsx(as,{children:d.map(w=>e.jsx(He,{value:w.id,children:w.name},w.id))})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Property address"}),e.jsx(pe,{value:r.propertyAddress,onChange:w=>p("propertyAddress",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:r.city,onChange:w=>p("city",w.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:r.state,onChange:w=>p("state",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:r.zipCode,onChange:w=>p("zipCode",w.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contract date"}),e.jsx(pe,{type:"date",value:r.contractDate,onChange:w=>p("contractDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Target close date"}),e.jsx(pe,{type:"date",value:r.targetCloseDate,onChange:w=>p("targetCloseDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Actual close date"}),e.jsx(pe,{type:"date",value:r.actualCloseDate,onChange:w=>p("actualCloseDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Price"}),e.jsx(pe,{type:"number",inputMode:"decimal",value:r.price,onChange:w=>p("price",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Commission %"}),e.jsx(pe,{type:"number",inputMode:"decimal",step:"0.01",value:r.commissionPercentage,onChange:w=>p("commissionPercentage",w.target.value)}),v!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expected commission: $",v.toLocaleString()]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ps,{rows:3,value:r.notes,onChange:w=>p("notes",w.target.value)})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(z,{onClick:b,disabled:!y,children:[h.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Add deal"]})]})]})})}const par={not_started:"bg-muted text-muted-foreground",in_review:"bg-amber-500/15 text-amber-600",changes_requested:"bg-destructive/15 text-destructive",compliant:"bg-emerald-500/15 text-emerald-600"};function far({brokerageId:s,canAddDeals:t=!1}){const{data:n=[],isLoading:r}=jJe(s),[a,i]=_.useState(""),[l,o]=_.useState("all"),[c,d]=_.useState("all"),[u,h]=_.useState("all"),[m,p]=_.useState("stage"),[f,g]=_.useState(null),[v,y]=_.useState(!1),b=_.useMemo(()=>vtr(n),[n]),w=_.useMemo(()=>{const P=new Map;return n.forEach(M=>P.set(M.owner_user_id,M.agent_name||"Agent")),Array.from(P,([M,I])=>({id:M,name:I}))},[n]),S=_.useMemo(()=>{const P=new Set;return n.forEach(M=>M.stage_name&&P.add(M.stage_name)),Array.from(P).sort((M,I)=>M.localeCompare(I))},[n]),C=_.useMemo(()=>{const P=a.trim().toLowerCase();return n.filter(M=>{if(c!=="all"&&M.owner_user_id!==c||u!=="all"&&(M.stage_name||"No stage")!==u)return!1;const I=oVe(M);return(l==="overdue"?M.overdue_items===0:l!=="all"&&l!==I)?!1:P?[M.deal_name,M.property_address,M.city,M.agent_name].filter(Boolean).some(D=>D.toLowerCase().includes(P)):!0})},[n,a,l,c,u]),E=_.useMemo(()=>{const P=[...C],M=I=>I.actual_close_date||I.target_close_date||"";return P.sort((I,D)=>{switch(m){case"agent":return(I.agent_name||"").localeCompare(D.agent_name||"");case"close":return(M(I)||"9999").localeCompare(M(D)||"9999");case"overdue":return D.overdue_items-I.overdue_items;case"progress":{const F=q=>q.total_items?q.approved_items/q.total_items:0;return F(I)-F(D)}case"stage":default:{const F=(I.stage_name||"zzz").localeCompare(D.stage_name||"zzz");return F!==0?F:(I.agent_name||"").localeCompare(D.agent_name||"")}}}),P},[C,m]);return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(bt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[t&&e.jsx("div",{className:"flex justify-end",children:e.jsxs(z,{onClick:()=>y(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add deal"]})}),t&&e.jsx(mar,{brokerageId:s,open:v,onOpenChange:y}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(dar,{metrics:b}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(uar,{outlook:b.outlook}),e.jsx(har,{agents:b.agents,totalVolume:b.totalVolume,selectedAgentId:c,onSelectAgent:d})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search address, agent or file name",value:a,onChange:P=>i(P.target.value)})]}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All statuses"}),e.jsx(He,{value:"not_started",children:"Not started"}),e.jsx(He,{value:"in_review",children:"In review"}),e.jsx(He,{value:"changes_requested",children:"Changes requested"}),e.jsx(He,{value:"compliant",children:"Compliant"}),e.jsx(He,{value:"overdue",children:"Has overdue items"})]})]}),e.jsxs(ls,{value:u,onValueChange:h,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All stages"}),S.map(P=>e.jsx(He,{value:P,children:P},P))]})]}),e.jsxs(ls,{value:m,onValueChange:p,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"stage",children:"Sort: Deal stage"}),e.jsx(He,{value:"agent",children:"Sort: Agent"}),e.jsx(He,{value:"close",children:"Sort: Closing date"}),e.jsx(He,{value:"overdue",children:"Sort: Most overdue"}),e.jsx(He,{value:"progress",children:"Sort: Least complete"})]})]}),e.jsxs(ls,{value:c,onValueChange:d,children:[e.jsx(rs,{className:"lg:w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All agents"}),w.map(P=>e.jsx(He,{value:P.id,children:P.name},P.id))]})]})]}),E.length===0?e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wv,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No transactions to review"}),e.jsx("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:"Deals appear here once an agent reaches a company-visible phase — everything earlier stays private to the agent."})]})}):e.jsx("div",{className:"space-y-2",children:E.map(P=>{const M=oVe(P),I=P.total_items?Math.round(P.approved_items/P.total_items*100):0;return e.jsxs("button",{onClick:()=>g(P),className:"w-full rounded-lg border p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:P.property_address||P.deal_name}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[P.agent_name,P.stage_name?` · ${P.stage_name}`:"",P.actual_close_date?` · Closed ${P.actual_close_date}`:P.target_close_date?` · Closes ${P.target_close_date}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[P.overdue_items>0&&e.jsxs(ze,{variant:"destructive",className:"gap-1 text-[10px]",children:[e.jsx(nl,{className:"h-3 w-3"})," ",P.overdue_items," overdue"]}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[11px] font-medium ${par[M]}`,children:qRt[M]})]})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-3",children:[e.jsx(Di,{value:I,className:"h-1.5 flex-1"}),e.jsxs("span",{className:"w-24 text-right text-[11px] text-muted-foreground",children:[P.approved_items," of ",P.total_items," approved"]})]})]},P.deal_id)})}),e.jsx(car,{brokerageId:s,deal:f,open:!!f,onOpenChange:P=>!P&&g(null)})]})}const rCt=[{value:"any",label:"Any deal type"},{value:"listing",label:"Listing"},{value:"buyer",label:"Buyer"},{value:"lease",label:"Lease"},{value:"referral",label:"Referral"}];function xar({brokerageId:s}){var b,w;const{data:t=[],isLoading:n}=VRt(s),r=mTs(),a=pTs(),[i,l]=_.useState(null),o=i??((b=t[0])==null?void 0:b.id)??null,c=t.find(S=>S.id===o)||null,{data:d=[]}=hTs(o),u=fTs(),h=xTs(),[m,p]=_.useState(!1),[f,g]=_.useState(null),v=async()=>{try{const S=await r.mutateAsync({brokerage_id:s,name:"New checklist",deal_type:null,is_active:!0});l(S)}catch(S){ne.error(S.message||"Could not create checklist")}},y=async()=>{var S;if(!(!o||!((S=f==null?void 0:f.title)!=null&&S.trim())))try{await u.mutateAsync({...f,template_id:o,title:f.title.trim(),sort_order:f.sort_order??d.length}),p(!1),g(null)}catch(C){ne.error(C.message||"Could not save item")}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[280px_1fr]",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"flex-row items-center justify-between space-y-0",children:[e.jsx(Nt,{className:"text-base",children:"Checklists"}),e.jsx(z,{size:"sm",variant:"outline",onClick:v,children:e.jsx(sn,{className:"h-4 w-4"})})]}),e.jsx(Le,{className:"space-y-2",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create a checklist per deal type — Listing, Buyer, Lease."}):t.map(S=>{var C;return e.jsxs("button",{onClick:()=>l(S.id),className:`w-full rounded-lg border p-3 text-left transition-colors ${S.id===o?"border-primary bg-primary/5":"hover:bg-muted"}`,children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(C=rCt.find(E=>E.value===(S.deal_type||"any")))==null?void 0:C.label})]},S.id)})})]}),c?e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-lg",children:"Checklist details"}),e.jsx(En,{children:"Applied automatically when a deal becomes company-visible."})]}),e.jsxs(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{defaultValue:c.name,onBlur:S=>r.mutate({id:c.id,brokerage_id:s,name:S.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Applies to"}),e.jsxs(ls,{value:c.deal_type||"any",onValueChange:S=>r.mutate({id:c.id,brokerage_id:s,deal_type:S==="any"?null:S}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:rCt.map(S=>e.jsx(He,{value:S.value,children:S.label},S.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Required items"}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{g({phase:"contract",requires_document:!0,required_for_closing:!0}),p(!0)},children:[e.jsx(sn,{className:"mr-1 h-4 w-4"})," Add item"]})]}),d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items yet."}):e.jsx("div",{className:"space-y-2",children:d.map(S=>{var C;return e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>{g(S),p(!0)},children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:((C=jAe.find(E=>E.value===S.phase))==null?void 0:C.label)||S.phase}),S.requires_document&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Document"}),S.required_for_closing&&e.jsx(ze,{variant:"outline",className:"text-[10px]",children:"Required to close"}),S.due_anchor&&e.jsxs(ze,{variant:"outline",className:"text-[10px]",children:[S.due_offset_days??0,"d after"," ",S.due_anchor==="contract_date"?"contract":"target close"]})]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>h.mutate({id:S.id,templateId:c.id}),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]},S.id)})})]}),e.jsxs(z,{variant:"outline",className:"text-destructive",onClick:async()=>{await Qi(`Delete "${c.name}"?`)&&(a.mutate({id:c.id,brokerageId:s}),l(null))},children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Delete checklist"]})]})]}):e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx($r,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create a checklist to add required documents."})]})}),e.jsx(Is,{open:m,onOpenChange:p,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:f!=null&&f.id?"Edit item":"Add item"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:(f==null?void 0:f.title)||"",onChange:S=>g(C=>({...C,title:S.target.value})),placeholder:"Purchase agreement (fully executed)"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Instructions for the agent"}),e.jsx(Ps,{rows:2,value:(f==null?void 0:f.description)||"",onChange:S=>g(C=>({...C,description:S.target.value}))})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phase"}),e.jsxs(ls,{value:(f==null?void 0:f.phase)||"contract",onValueChange:S=>g(C=>({...C,phase:S})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:jAe.map(S=>e.jsx(He,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Due"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"number",className:"w-20",value:(f==null?void 0:f.due_offset_days)??"",onChange:S=>g(C=>({...C,due_offset_days:S.target.value===""?null:Number(S.target.value)})),placeholder:"days"}),e.jsxs(ls,{value:(f==null?void 0:f.due_anchor)||"none",onValueChange:S=>g(C=>({...C,due_anchor:S==="none"?null:S})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"none",children:"No due date"}),e.jsx(He,{value:"contract_date",children:"after contract date"}),e.jsx(He,{value:"target_close_date",children:"after target close"})]})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(ee,{className:"text-sm",children:"Requires an uploaded document"}),e.jsx(mn,{checked:(f==null?void 0:f.requires_document)??!0,onCheckedChange:S=>g(C=>({...C,requires_document:S}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(ee,{className:"text-sm",children:"Required before closing"}),e.jsx(mn,{checked:(f==null?void 0:f.required_for_closing)??!0,onCheckedChange:S=>g(C=>({...C,required_for_closing:S}))})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(z,{onClick:y,disabled:!((w=f==null?void 0:f.title)!=null&&w.trim())||u.isPending,children:[u.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save"]})]})]})})]})}function gar({brokerageId:s}){const{data:t,isLoading:n}=dTs(s),r=uTs(),{data:a=[]}=oTs(s),i=lTs(),l=cTs(),[o,c]=_.useState(["contract","closing","closed"]),[d,u]=_.useState(!0),[h,m]=_.useState(!0),[p,f]=_.useState(""),[g,v]=_.useState(!1);_.useEffect(()=>{t&&(c(t.visible_phases||[]),u(t.include_contract_dated_deals),m(t.is_enabled))},[t]);const y=S=>c(C=>C.includes(S)?C.filter(E=>E!==S):[...C,S]),b=async()=>{try{await r.mutateAsync({brokerage_id:s,visible_phases:o,include_contract_dated_deals:d,is_enabled:h}),ne.success("Compliance settings saved")}catch(S){ne.error(S.message||"Could not save settings")}},w=async()=>{const S=p.trim().toLowerCase();if(S){v(!0);try{const{data:C,error:E}=await U.from("profiles").select("id, email").ilike("email",S).maybeSingle();if(E)throw E;if(!C){ne.error("No LevelUp account found with that email");return}await i.mutateAsync({brokerageId:s,userId:C.id}),f(""),ne.success("Transaction admin added")}catch(C){ne.error(C.message||"Could not add transaction admin")}finally{v(!1)}}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(bt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-lg",children:"What the company can see"}),e.jsx(En,{children:"Agent leads, consultations and early conversations stay private. Deals become visible to compliance once they reach one of the phases below."})]}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Compliance tracking on"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to hide all agent deals from the company view."})]}),e.jsx(mn,{checked:h,onCheckedChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Company-visible phases"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:jAe.map(S=>e.jsx("button",{type:"button",onClick:()=>y(S.value),className:`rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${o.includes(S.value)?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:bg-muted"}`,children:S.label},S.value))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Include any deal with a contract date"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Recommended — catches "agreement signed" deals even when an agent uses custom stage names.'})]}),e.jsx(mn,{checked:d,onCheckedChange:u})]}),e.jsxs(z,{onClick:b,disabled:r.isPending,children:[r.isPending&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save settings"]})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ch,{className:"h-4 w-4"})," Transaction admins"]}),e.jsx(En,{children:"Give staff compliance-only access — deals, documents, checklists and notes. No recruiting or billing."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"admin@yourbrokerage.com",value:p,onChange:S=>f(S.target.value),onKeyDown:S=>S.key==="Enter"&&w()}),e.jsx(z,{onClick:w,disabled:g||!p.trim(),children:g?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Pl,{className:"h-4 w-4"})})]}),a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No transaction admins yet."}):e.jsx("div",{className:"space-y-2",children:a.map(S=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.name||S.email}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:S.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{variant:"secondary",className:"text-[10px]",children:"Compliance"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>l.mutate({id:S.id,brokerageId:s}),children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})})]})]},S.id))})]})]})]})}const yar=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=hs(),o=zn(),{data:c=[],isLoading:d}=wJe(),[u,h]=_.useState(!1),m=c.length>0,p=t||n,f=_.useMemo(()=>{var g;return i||(a.length>0?a[0].id:null)||((g=c[0])==null?void 0:g.brokerage_id)||r},[i,a,c,r]);return _.useEffect(()=>{if(!(!s||d)){if(!p&&!m){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),h(!0)}},[s,d,p,m,o,a,i,l]),u?e.jsx($s,{title:"Transactions & Compliance",description:"Review agent files, required documents and closing compliance",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(ls,{value:i||"",onValueChange:l,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),e.jsx(cs,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:a.map(g=>e.jsx(He,{value:g.id,children:g.name},g.id))})]})]}),f?e.jsxs(Qr,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(Jr,{className:`grid w-full ${p?"max-w-lg grid-cols-3":"max-w-xs grid-cols-1"}`,children:[e.jsx(Wt,{value:"board",children:"Transactions"}),p&&e.jsx(Wt,{value:"checklists",children:"Checklists"}),p&&e.jsx(Wt,{value:"settings",children:"Settings"})]}),e.jsx(Kt,{value:"board",children:e.jsx(far,{brokerageId:f,canAddDeals:p||m})}),p&&e.jsx(Kt,{value:"checklists",children:e.jsx(xar,{brokerageId:f})}),p&&e.jsx(Kt,{value:"settings",children:e.jsx(gar,{brokerageId:f})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(oi,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},Yse=U,YBe={draft:"Draft",approved:"Approved",paid:"Paid",void:"Void"},ob=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function HG(s){const t=ob(s.gross_commission),n=ob(s.referral_amount)>0?ob(s.referral_amount):t*ob(s.referral_fee_pct)/100,r=Math.max(0,t-n),a=r*(100-ob(s.agent_split_pct))/100,i=r*ob(s.franchise_fee_pct)/100,l=ob(s.transaction_fee),o=(s.line_items||[]).reduce((u,h)=>u+ob(h.amount),0),c=a+i+l,d=r-c-o;return{gross:t,referral:n,adjustedGross:r,brokerageSplit:a,franchiseFee:i,transactionFee:l,otherCharges:o,companyDollar:c,agentNet:d}}function bar(s,t){const n=ob(s.brokerage_split_pct),r=(t==null?void 0:t.agent_split_pct)!=null?ob(t.agent_split_pct):n?100-n:70;return{deal_id:s.deal_id,agent_user_id:s.owner_user_id,status:"draft",property_address:s.property_address||s.deal_name,escrow_company:null,escrow_number:null,closing_date:s.actual_close_date||s.target_close_date,sale_price:qG(s),gross_commission:VG(s),agent_split_pct:r,franchise_fee_pct:s.franchise_fee_pct!=null?ob(s.franchise_fee_pct):ob(t==null?void 0:t.franchise_fee_pct),transaction_fee:s.transaction_fee!=null?ob(s.transaction_fee):ob(t==null?void 0:t.transaction_fee),referral_fee_pct:ob(t==null?void 0:t.referral_fee_pct),referral_amount:0,referral_payee:null,line_items:[],notes:null}}function Ras(s){return rt({queryKey:["disbursements",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await Yse.from("brokerage_disbursements").select("*").eq("brokerage_id",s).order("closing_date",{ascending:!1,nullsFirst:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t.map(r=>({...r,line_items:r.line_items||[]}))}})}function _ar(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{const a=HG(r),i={brokerage_id:s,deal_id:r.deal_id,agent_user_id:r.agent_user_id,status:r.status,property_address:r.property_address,escrow_company:r.escrow_company,escrow_number:r.escrow_number,closing_date:r.closing_date,sale_price:r.sale_price||0,gross_commission:r.gross_commission||0,agent_split_pct:r.agent_split_pct||0,franchise_fee_pct:r.franchise_fee_pct||0,transaction_fee:r.transaction_fee||0,referral_fee_pct:r.referral_fee_pct||0,referral_amount:r.referral_amount||0,referral_payee:r.referral_payee,line_items:r.line_items||[],notes:r.notes,company_dollar:a.companyDollar,agent_net:a.agentNet};if(r.id){const{error:l}=await Yse.from("brokerage_disbursements").update(i).eq("id",r.id);if(l)throw l}else{i.created_by=(n==null?void 0:n.id)??null;const{error:l}=await Yse.from("brokerage_disbursements").insert(i);if(l)throw l}},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),ne.success("Disbursement saved")},onError:r=>ne.error(r.message||"Could not save the disbursement")})}function war(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async({id:r,status:a})=>{const i={status:a};a==="approved"&&(i.approved_at=new Date().toISOString(),i.approved_by=(n==null?void 0:n.id)??null),a==="paid"&&(i.paid_at=new Date().toISOString());const{error:l}=await Yse.from("brokerage_disbursements").update(i).eq("id",r);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["disbursements",s]}),onError:r=>ne.error(r.message||"Could not update the status")})}function jar(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await Yse.from("brokerage_disbursements").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),ne.success("Disbursement removed")},onError:n=>ne.error(n.message||"Could not remove the disbursement")})}function Fas(s){return rt({queryKey:["brokerage-agent-records",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await U.from("brokerage_agent_records").select("*").eq("brokerage_id",s).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}const F6e=U;function Nar(s){return rt({queryKey:["ops-follow-ups",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await F6e.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).limit(1e3);if(n)throw n;const r=t||[];if(!r.length)return[];const a=new Map(r.map(o=>[o.id,[o.first_name,o.last_name].filter(Boolean).join(" ")])),{data:i,error:l}=await F6e.from("recruit_follow_ups").select("id, title, due_date, prospect_id, completed_at").in("prospect_id",r.map(o=>o.id)).is("completed_at",null).order("due_date",{ascending:!0}).limit(500);if(l)throw l;return(i||[]).map(o=>({id:o.id,title:o.title,due_date:o.due_date,prospectName:a.get(o.prospect_id)||null}))}})}function kar(s){return rt({queryKey:["ops-help-requests",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await F6e.from("brokerage_help_requests").select("id, title, request_type, event_start_at, requester_user_id").eq("brokerage_id",s).eq("status","open").order("event_start_at",{ascending:!0}).limit(200);if(n)throw n;const r=t||[],a=Array.from(new Set(r.map(l=>l.requester_user_id).filter(Boolean))),i=new Map;if(a.length){const{data:l}=await F6e.from("profiles").select("id, name").in("id",a);(l||[]).forEach(o=>i.set(o.id,o.name))}return r.map(l=>({id:l.id,title:l.title,request_type:l.request_type,event_start_at:l.event_start_at,requesterName:i.get(l.requester_user_id)??null}))}})}const jC=U,Oas=[{value:"general",label:"General"},{value:"compliance",label:"Compliance"},{value:"disbursements",label:"Disbursements"},{value:"renewals",label:"Renewals"},{value:"onboarding",label:"Onboarding"},{value:"recruiting",label:"Recruiting"},{value:"help_board",label:"Help Board"},{value:"marketing",label:"Marketing"},{value:"listings",label:"Listings"}],O6e=Object.fromEntries(Oas.map(s=>[s.value,s.label])),bZe={todo:"To do",in_progress:"In progress",done:"Done"},Sar={low:"Low",medium:"Medium",high:"High",urgent:"Urgent"};function Car(s){return rt({queryKey:["ops-tasks",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await jC.from("brokerage_operations_tasks").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}function Aar(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{var o;const a={brokerage_id:s,assignee_user_id:r.assignee_user_id||null,category:r.category||"general",title:r.title.trim(),description:((o=r.description)==null?void 0:o.trim())||null,status:r.status||"todo",priority:r.priority||"medium",due_date:r.due_date||null,source_type:r.source_type||"manual",source_id:r.source_id||null,source_url:r.source_url||null};if(a.status==="done"&&(a.completed_at=new Date().toISOString()),r.id){const{error:c}=await jC.from("brokerage_operations_tasks").update(a).eq("id",r.id);if(c)throw c;return r.id}a.created_by=(n==null?void 0:n.id)??null;const{data:i,error:l}=await jC.from("brokerage_operations_tasks").insert(a).select("id").single();if(l)throw l;return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),ne.success("Task saved")},onError:r=>ne.error(r.message||"Could not save task")})}function Ear(s){const t=$t();return mt({mutationFn:async({id:n,status:r})=>{const{error:a}=await jC.from("brokerage_operations_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]})},onError:n=>ne.error(n.message||"Could not update task")})}function Tar(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await jC.from("brokerage_operations_tasks").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),ne.success("Task removed")},onError:n=>ne.error(n.message||"Could not remove task")})}function Mar(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{const{error:a}=await jC.from("brokerage_operations_tasks").insert({brokerage_id:s,created_by:(n==null?void 0:n.id)??null,title:r.title,category:r.category,status:"done",source_type:r.sourceType,source_id:r.sourceId,dismissed_at:new Date().toISOString(),dismissed_by:(n==null?void 0:n.id)??null,completed_at:new Date().toISOString()});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),ne.success("Dismissed")},onError:r=>ne.error(r.message||"Could not dismiss")})}function Par(s){return rt({queryKey:["ops-task-comments",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await jC.from("brokerage_operations_task_comments").select("*").eq("task_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function Lar(){const s=$t(),{user:t}=hs();return mt({mutationFn:async({taskId:n,body:r})=>{const{error:a}=await jC.from("brokerage_operations_task_comments").insert({task_id:n,body:r.trim(),author_user_id:t==null?void 0:t.id});if(a)throw a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["ops-task-comments",r.taskId]}),onError:n=>ne.error(n.message||"Could not add note")})}function Iar(s){const{user:t}=hs();return rt({queryKey:["ops-digest-prefs",s,t==null?void 0:t.id],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await jC.from("brokerage_operations_digest_prefs").select("*").eq("brokerage_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})}function Dar(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{const{error:a}=await jC.from("brokerage_operations_digest_prefs").upsert({user_id:n.id,brokerage_id:s,email_enabled:r.email_enabled??!1,push_enabled:r.push_enabled??!1,send_day:r.send_day??1},{onConflict:"user_id,brokerage_id"});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-digest-prefs",s]}),ne.success("Notification settings saved")},onError:r=>ne.error(r.message||"Could not save settings")})}const Rar={license:"License renewal",eo:"E&O insurance",anniversary:"Work anniversary",birthday:"Birthday"},zas=864e5,Bas=()=>{const s=new Date;return{y:s.getFullYear(),m:s.getMonth()+1,d:s.getDate()}},NU=(s,t,n)=>Date.UTC(s,t-1,n),Tit=s=>{const t=ZS(s);return t?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(Date.UTC(t.y,t.m-1,t.d))):s},z6e=s=>String(s).padStart(2,"0");function aCt(s){const t=ZS(s||"");if(!t)return null;const n=Bas(),r=Math.round((NU(t.y,t.m,t.d)-NU(n.y,n.m,n.d))/zas);return{dueDate:`${t.y}-${z6e(t.m)}-${z6e(t.d)}`,daysUntil:r,expired:r<0}}function iCt(s){const t=ZS(s||"");if(!t)return null;const n=Bas();let r=n.y;NU(r,t.m,t.d)[i.agentId,i])),a=[];return s.forEach(i=>{const l=r.get(i.agent_user_id),o={agentId:i.agent_user_id,agentName:(l==null?void 0:l.name)||"Agent",avatarUrl:(l==null?void 0:l.avatarUrl)??null},c=aCt(i.license_expiration);c&&a.push({...o,kind:"license",sourceDate:i.license_expiration,detail:[i.license_state,i.license_number].filter(Boolean).join(" · ")||null,...c});const d=aCt(i.eo_expiration);d&&a.push({...o,kind:"eo",sourceDate:i.eo_expiration,detail:[i.eo_carrier,i.eo_policy_number].filter(Boolean).join(" · ")||null,...d});const u=iCt(i.anniversary_date);u&&a.push({...o,kind:"anniversary",sourceDate:i.anniversary_date,detail:u.years?`${u.years} year${u.years===1?"":"s"} with the brokerage`:null,...u});const h=iCt(i.birthday);h&&a.push({...o,kind:"birthday",sourceDate:i.birthday,detail:null,dueDate:h.dueDate,daysUntil:h.daysUntil,expired:!1})}),a.filter(i=>i.expired||i.daysUntil<=n).sort((i,l)=>i.daysUntil-l.daysUntil||i.agentName.localeCompare(l.agentName))}function Far(s,t,n){const r=new Map(n.map(i=>[i.userId,i])),a=new Map(t.map(i=>[i.agentId,i]));return s.filter(i=>Number(i.goal_amount)>0).map(i=>{const l=a.get(i.agent_user_id),o=r.get(i.agent_user_id),c=Number(i.goal_amount)||0,d=(o==null?void 0:o.volume)||0;return{agentId:i.agent_user_id,name:(l==null?void 0:l.name)||"Agent",avatarUrl:(l==null?void 0:l.avatarUrl)??null,goal:c,volume:d,gci:(o==null?void 0:o.gci)||0,closedDeals:(o==null?void 0:o.closedDeals)||0,pct:c>0?Math.min(999,d/c*100):0}}).sort((i,l)=>l.pct-i.pct)}const Oar=864e5;function GZ(s){const t=ZS(s||"");if(!t)return null;const n=new Date,r=Date.UTC(n.getFullYear(),n.getMonth(),n.getDate());return Math.round((Date.UTC(t.y,t.m-1,t.d)-r)/Oar)}function zar(s){const t=new Set(s.tasks.filter(i=>i.source_id&&(i.dismissed_at||i.status==="done"||i.source_type!=="manual")).map(i=>`${i.source_type}:${i.source_id}`)),n=[],r=i=>{t.has(`${i.sourceType}:${i.sourceId}`)||n.push(i)};s.complianceDeals.forEach(i=>{i.submitted_items>0&&r({key:`compliance-review-${i.deal_id}`,sourceType:"compliance",sourceId:`review:${i.deal_id}`,category:"compliance",title:`${i.submitted_items} document${i.submitted_items===1?"":"s"} awaiting review`,context:i.deal_name,agentName:i.agent_name,avatarUrl:i.agent_avatar_url,dueDate:i.target_close_date,daysUntil:GZ(i.target_close_date),overdue:i.overdue_items>0,priority:i.overdue_items>0?"urgent":"high",url:"/brokerage/transactions",actionLabel:"Review"}),i.rejected_items>0&&r({key:`compliance-rejected-${i.deal_id}`,sourceType:"compliance",sourceId:`rejected:${i.deal_id}`,category:"compliance",title:`${i.rejected_items} item${i.rejected_items===1?"":"s"} need changes`,context:i.deal_name,agentName:i.agent_name,avatarUrl:i.agent_avatar_url,dueDate:i.target_close_date,daysUntil:GZ(i.target_close_date),overdue:!1,priority:"medium",url:"/brokerage/transactions",actionLabel:"Open file"})}),s.disbursements.forEach(i=>{var o;if(i.status!=="draft"&&i.status!=="approved")return;const l=GZ(i.closing_date);r({key:`disbursement-${i.id}`,sourceType:"disbursement",sourceId:i.id,category:"disbursements",title:i.status==="draft"?"Disbursement awaiting approval":"Approved disbursement awaiting payment",context:i.property_address||"Commission disbursement",agentName:((o=s.nameFor)==null?void 0:o.call(s,i.agent_user_id))??null,avatarUrl:null,dueDate:i.closing_date,daysUntil:l,overdue:l!==null&&l<0,priority:i.status==="draft"?"high":"medium",url:"/brokerage/commission-plans",actionLabel:i.status==="draft"?"Approve":"Mark paid"})}),$as(s.agentRecords,s.renewalAgents,30).filter(i=>i.kind==="license"||i.kind==="eo").forEach(i=>{r({key:`renewal-${i.kind}-${i.agentId}`,sourceType:"renewal",sourceId:`${i.kind}:${i.agentId}:${i.dueDate}`,category:"renewals",title:i.expired?`${i.kind==="license"?"License":"E&O policy"} expired`:`${i.kind==="license"?"License":"E&O policy"} expires in ${i.daysUntil} day${i.daysUntil===1?"":"s"}`,context:i.detail||null,agentName:i.agentName,avatarUrl:i.avatarUrl,dueDate:i.dueDate,daysUntil:i.daysUntil,overdue:i.expired,priority:i.expired?"urgent":"high",url:"/brokerage/commission-plans",actionLabel:"Open record"})}),s.roster.forEach(i=>{i.overdue>0&&r({key:`onboarding-overdue-${i.agentId}`,sourceType:"onboarding",sourceId:`overdue:${i.agentId}`,category:"onboarding",title:`${i.overdue} onboarding step${i.overdue===1?"":"s"} overdue`,context:"Agent onboarding",agentName:i.name,avatarUrl:i.avatarUrl,dueDate:null,daysUntil:null,overdue:!0,priority:"high",url:"/brokerage/onboarding",actionLabel:"Open"}),i.needsReview>0&&r({key:`onboarding-review-${i.agentId}`,sourceType:"onboarding",sourceId:`review:${i.agentId}`,category:"onboarding",title:`${i.needsReview} onboarding item${i.needsReview===1?"":"s"} to review`,context:"Agent onboarding",agentName:i.name,avatarUrl:i.avatarUrl,dueDate:null,daysUntil:null,overdue:!1,priority:"medium",url:"/brokerage/onboarding",actionLabel:"Review"})}),s.followUps.forEach(i=>{const l=GZ(i.due_date?i.due_date.slice(0,10):null);l===null||l>0||r({key:`recruiting-${i.id}`,sourceType:"recruiting",sourceId:i.id,category:"recruiting",title:i.title||"Recruiting follow-up",context:i.prospectName,agentName:null,avatarUrl:null,dueDate:i.due_date?i.due_date.slice(0,10):null,daysUntil:l,overdue:l<0,priority:l<0?"high":"medium",url:"/brokerage/recruiting",actionLabel:"Follow up"})}),s.helpRequests.forEach(i=>{const l=i.event_start_at?i.event_start_at.slice(0,10):null,o=GZ(l);r({key:`help-${i.id}`,sourceType:"help_board",sourceId:i.id,category:"help_board",title:i.title||"Coverage needed",context:i.requesterName?`Posted by ${i.requesterName}`:"Help Board",agentName:null,avatarUrl:null,dueDate:l,daysUntil:o,overdue:o!==null&&o<0,priority:o!==null&&o<=2?"high":"low",url:`/brokerage/help-board/${i.id}`,actionLabel:"Open"})});const a={urgent:0,high:1,medium:2,low:3};return n.sort((i,l)=>{if(i.overdue!==l.overdue)return i.overdue?-1:1;if(a[i.priority]!==a[l.priority])return a[i.priority]-a[l.priority];const o=i.daysUntil??9999,c=l.daysUntil??9999;return o-c})}const Bar={urgent:"bg-destructive/10 text-destructive border-destructive/30",high:"bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-400",medium:"bg-muted text-muted-foreground border-border",low:"bg-muted text-muted-foreground border-border"},$ar=s=>(s||"?").split(" ").map(t=>t[0]).filter(Boolean).slice(0,2).join("").toUpperCase();function Uar({items:s,loading:t,onDismiss:n,onTrack:r}){const a=zn(),[i,l]=_.useState("all"),o=_.useMemo(()=>{const h=new Set(s.map(m=>m.category));return Array.from(h)},[s]),c=_.useMemo(()=>i==="all"?s:s.filter(h=>h.category===i),[s,i]),d=s.filter(h=>h.overdue).length,u=s.filter(h=>!h.overdue&&h.daysUntil!==null&&h.daysUntil<=7).length;return t?e.jsx("div",{className:"space-y-3",children:[0,1,2,3].map(h=>e.jsx(ln,{className:"h-20 w-full"},h))}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Needs attention"}),e.jsx("p",{className:"text-2xl font-semibold",children:s.length})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Overdue"}),e.jsx("p",{className:Ct("text-2xl font-semibold",d>0&&"text-destructive"),children:d})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Due this week"}),e.jsx("p",{className:"text-2xl font-semibold",children:u})]})})]}),e.jsxs(be,{children:[e.jsxs(_t,{className:"flex-row items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:"What needs your attention"}),e.jsx(En,{children:"Pulled live from compliance, financials, onboarding, recruiting and the help board."})]}),e.jsxs(ls,{value:i,onValueChange:l,children:[e.jsx(rs,{className:"w-[160px] shrink-0",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All areas"}),o.map(h=>e.jsx(He,{value:h,children:O6e[h]||h},h))]})]})]}),e.jsx(Le,{className:"space-y-2",children:c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Mr,{className:"mb-3 h-10 w-10 text-emerald-500"}),e.jsx("p",{className:"font-medium",children:"Nothing needs attention right now"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"New items appear here as files, renewals and requests come in."})]}):c.map(h=>e.jsxs("div",{className:Ct("flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center",h.overdue&&"border-destructive/40 bg-destructive/[0.03]"),children:[e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[h.avatarUrl&&e.jsx(xi,{src:h.avatarUrl,alt:""}),e.jsx(Na,{className:"text-xs",children:$ar(h.agentName)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:h.title}),e.jsx(ze,{variant:"outline",className:Ct("text-[10px]",Bar[h.priority]),children:O6e[h.category]||h.category})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[h.agentName&&e.jsx("span",{children:h.agentName}),h.context&&e.jsx("span",{className:"truncate",children:h.context}),h.dueDate&&e.jsxs("span",{className:Ct("flex items-center gap-1",h.overdue&&"font-medium text-destructive"),children:[h.overdue?e.jsx(nl,{className:"h-3 w-3"}):e.jsx(Ud,{className:"h-3 w-3"}),Tit(h.dueDate)]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx(z,{size:"sm",onClick:()=>a(h.url),children:h.actionLabel}),e.jsx(z,{size:"sm",variant:"outline",title:"Track as a task",onClick:()=>r({title:h.title,description:[h.agentName,h.context].filter(Boolean).join(" — ")||null,category:h.category,priority:h.priority,due_date:h.dueDate,source_type:h.sourceType,source_id:h.sourceId,source_url:h.url}),children:e.jsx(YQ,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"ghost",title:"Dismiss",onClick:()=>n(h),children:e.jsx(er,{className:"h-4 w-4"})})]})]},h.key))})]})]})}const Yde=["todo","in_progress","done"],qar={urgent:"bg-destructive",high:"bg-amber-500",medium:"bg-primary/60",low:"bg-muted-foreground/40"};function Var({tasks:s,people:t,loading:n,onNew:r,onEdit:a,onStatus:i,onDelete:l}){const[o,c]=_.useState("all"),[d,u]=_.useState("all"),h=_.useMemo(()=>s.filter(g=>!g.dismissed_at).filter(g=>o==="all"?!0:o==="unassigned"?!g.assignee_user_id:g.assignee_user_id===o).filter(g=>d==="all"?!0:g.category===d),[s,o,d]),m=g=>{var v;return g?((v=t.find(y=>y.id===g))==null?void 0:v.name)||"Team member":"Unassigned"},p=_.useMemo(()=>Array.from(new Set(s.map(g=>g.category))),[s]);if(n)return e.jsx(ln,{className:"h-72 w-full"});const f=(g,v)=>{const y=Yde.indexOf(g.status),b=Yde[y+v];b&&i(g,b)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ls,{value:o,onValueChange:c,children:[e.jsx(rs,{className:"w-[180px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"Everyone"}),e.jsx(He,{value:"unassigned",children:"Unassigned"}),t.map(g=>e.jsx(He,{value:g.id,children:g.name},g.id))]})]}),e.jsxs(ls,{value:d,onValueChange:u,children:[e.jsx(rs,{className:"w-[170px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All categories"}),p.map(g=>e.jsx(He,{value:g,children:O6e[g]||g},g))]})]}),e.jsxs(z,{className:"ml-auto",onClick:r,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," New task"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:Yde.map(g=>{const v=h.filter(y=>y.status===g);return e.jsxs(be,{className:"flex flex-col",children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"flex items-center justify-between text-sm",children:[bZe[g],e.jsx(ze,{variant:"secondary",children:v.length})]})}),e.jsxs(Le,{className:"space-y-2",children:[v.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nothing here"}),v.map(y=>{const b=!!y.due_date&&y.status!=="done"&&y.due_datea(y),children:[e.jsx("p",{className:"truncate font-medium",children:y.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[O6e[y.category]||y.category," · ",m(y.assignee_user_id)]})]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[e.jsxs(ua,{onClick:()=>a(y),children:[e.jsx(Wa,{className:"mr-2 h-4 w-4"})," Edit"]}),Yde.filter(w=>w!==y.status).map(w=>e.jsxs(ua,{onClick:()=>i(y,w),children:["Move to ",bZe[w]]},w)),e.jsxs(ua,{className:"text-destructive",onClick:()=>l(y),children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),y.due_date&&e.jsxs("p",{className:Ct("mt-2 flex items-center gap-1 text-xs",b?"text-destructive":"text-muted-foreground"),children:[e.jsx(Ud,{className:"h-3 w-3"})," ",Tit(y.due_date)]}),e.jsxs("div",{className:"mt-2 flex gap-1 md:hidden",children:[e.jsx(z,{size:"sm",variant:"outline",className:"flex-1",disabled:g==="todo",onClick:()=>f(y,-1),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsx(z,{size:"sm",variant:"outline",className:"flex-1",disabled:g==="done",onClick:()=>f(y,1),children:e.jsx(Da,{className:"h-4 w-4"})})]})]},y.id)})]})]},g)})})]})}const Har=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],oCt=(s,t,n)=>`${s}-${String(t+1).padStart(2,"0")}-${String(n).padStart(2,"0")}`;function Gar({items:s,tasks:t,closings:n}){const r=new Date,[a,i]=_.useState({y:r.getFullYear(),m:r.getMonth()}),[l,o]=_.useState(null),c=_.useMemo(()=>{const b=[];return s.forEach(w=>{w.dueDate&&b.push({id:w.key,label:w.title,tone:"bg-amber-500",date:w.dueDate})}),t.filter(w=>!w.dismissed_at&&w.due_date&&w.status!=="done").forEach(w=>b.push({id:w.id,label:w.title,tone:"bg-primary",date:w.due_date})),n.forEach(w=>{w.date&&b.push({id:`close-${w.id}`,label:`Closing — ${w.label}`,tone:"bg-emerald-500",date:w.date.slice(0,10)})}),b},[s,t,n]),d=_.useMemo(()=>{const b=new Map;return c.forEach(w=>{const S=b.get(w.date)||[];S.push(w),b.set(w.date,S)}),b},[c]),u=new Date(Date.UTC(a.y,a.m,1)),h=u.getUTCDay(),m=new Date(Date.UTC(a.y,a.m+1,0)).getUTCDate(),p=[...Array.from({length:h},()=>null),...Array.from({length:m},(b,w)=>w+1)],f=new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric",timeZone:"UTC"}).format(u),g=oCt(r.getFullYear(),r.getMonth(),r.getDate()),v=l?d.get(l)||[]:[],y=b=>i(w=>{const S=w.m+b;return S<0?{y:w.y-1,m:11}:S>11?{y:w.y+1,m:0}:{y:w.y,m:S}});return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[2fr,1fr]",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:f}),e.jsx(En,{children:"Closings, renewals and due dates in one place."})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(z,{size:"icon",variant:"outline",onClick:()=>y(-1),children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"outline",onClick:()=>y(1),children:e.jsx(yi,{className:"h-4 w-4"})})]})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"grid grid-cols-7 gap-1 text-center text-xs text-muted-foreground",children:Har.map(b=>e.jsx("div",{className:"py-1",children:b},b))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:p.map((b,w)=>{if(b===null)return e.jsx("div",{},`pad-${w}`);const S=oCt(a.y,a.m,b),C=d.get(S)||[];return e.jsxs("button",{onClick:()=>o(S),className:Ct("flex min-h-[64px] flex-col items-start rounded-md border p-1 text-left text-xs transition hover:bg-muted/60",S===g&&"border-primary",l===S&&"bg-muted"),children:[e.jsx("span",{className:Ct("mb-1 font-medium",S===g&&"text-primary"),children:b}),e.jsx("span",{className:"flex flex-wrap gap-0.5",children:C.slice(0,4).map(E=>e.jsx("span",{className:Ct("h-1.5 w-1.5 rounded-full",E.tone)},E.id))}),C.length>0&&e.jsxs("span",{className:"mt-auto text-[10px] text-muted-foreground",children:[C.length," item",C.length===1?"":"s"]})]},S)})})]})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:l?new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeZone:"UTC"}).format(new Date(`${l}T12:00:00Z`)):"Pick a day"}),e.jsx(En,{children:l?`${v.length} item${v.length===1?"":"s"}`:"Select a date to see what is happening."})]}),e.jsxs(Le,{className:"space-y-2",children:[l&&v.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled."}),v.map(b=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border p-2 text-sm",children:[e.jsx("span",{className:Ct("mt-1.5 h-2 w-2 shrink-0 rounded-full",b.tone)}),e.jsx("span",{className:"min-w-0 flex-1",children:b.label})]},b.id)),e.jsx("div",{className:"pt-2",children:e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-muted-foreground",children:[e.jsxs(ze,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-emerald-500"})," Closings"]}),e.jsxs(ze,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-amber-500"})," Action items"]}),e.jsxs(ze,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-primary"})," Tasks"]})]})})]})]})]})}function War({taskId:s,people:t}){const{data:n=[]}=Par(s),r=Lar(),[a,i]=_.useState(""),l=o=>{var c;return((c=t.find(d=>d.id===o))==null?void 0:c.name)||"Team member"};return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Notes"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet."}),n.map(o=>e.jsxs("div",{className:"rounded-md bg-muted/50 p-2 text-sm",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l(o.author_user_id)," · ",new Date(o.created_at).toLocaleDateString()]}),e.jsx("p",{className:"whitespace-pre-wrap",children:o.body})]},o.id))]}),e.jsx(Ps,{rows:2,placeholder:"Add a note…",value:a,onChange:o=>i(o.target.value)}),e.jsx(z,{size:"sm",variant:"outline",disabled:!a.trim()||r.isPending,onClick:()=>r.mutate({taskId:s,body:a},{onSuccess:()=>i("")}),children:"Add note"})]})}const lCt={title:"",description:"",category:"general",status:"todo",priority:"medium",due_date:null,assignee_user_id:null};function Kar({open:s,onOpenChange:t,task:n,initial:r,people:a,onSave:i,saving:l}){const[o,c]=_.useState(lCt);_.useEffect(()=>{s&&c(n?{id:n.id,title:n.title,description:n.description||"",category:n.category,status:n.status,priority:n.priority,due_date:n.due_date,assignee_user_id:n.assignee_user_id,source_type:n.source_type,source_id:n.source_id,source_url:n.source_url}:{...lCt,...r||{}})},[s,n,r]);const d=u=>c(h=>({...h,...u}));return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:n?"Edit task":"New task"}),e.jsx(_r,{children:"Assign office work to yourself or another manager."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"ops-title",children:"Title"}),e.jsx(pe,{id:"ops-title",value:o.title,onChange:u=>d({title:u.target.value}),placeholder:"Order new signage for the Maple listing"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"ops-desc",children:"Details"}),e.jsx(Ps,{id:"ops-desc",rows:3,value:o.description||"",onChange:u=>d({description:u.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ls,{value:o.category,onValueChange:u=>d({category:u}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Oas.map(u=>e.jsx(He,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Priority"}),e.jsxs(ls,{value:o.priority,onValueChange:u=>d({priority:u}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(Sar).map(([u,h])=>e.jsx(He,{value:u,children:h},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ls,{value:o.status,onValueChange:u=>d({status:u}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.entries(bZe).map(([u,h])=>e.jsx(He,{value:u,children:h},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"ops-due",children:"Due date"}),e.jsx(pe,{id:"ops-due",type:"date",value:o.due_date||"",onChange:u=>d({due_date:u.target.value||null})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Assigned to"}),e.jsxs(ls,{value:o.assignee_user_id||"unassigned",onValueChange:u=>d({assignee_user_id:u==="unassigned"?null:u}),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"unassigned",children:"Unassigned"}),a.map(u=>e.jsx(He,{value:u.id,children:u.name},u.id))]})]})]}),n&&e.jsx(War,{taskId:n.id,people:a})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{disabled:!o.title.trim()||l,onClick:()=>i(o),children:l?"Saving…":"Save task"})]})]})})}const Yar=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Zar({brokerageId:s}){const{data:t}=Iar(s),n=Dar(s),[r,a]=_.useState(!1),[i,l]=_.useState(!1),[o,c]=_.useState("1");return _.useEffect(()=>{a((t==null?void 0:t.email_enabled)??!1),l((t==null?void 0:t.push_enabled)??!1),c(String((t==null?void 0:t.send_day)??1))},[t]),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Weekly summary"}),e.jsx(En,{children:"Off by default. Turn it on and you alone get a weekly rundown of what is open, due and overdue."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"digest-email",children:"Email me the weekly summary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sent once a week to your account email."})]}),e.jsx(mn,{id:"digest-email",checked:r,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"digest-push",children:"Send me a phone notification"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Same summary, delivered as a push alert."})]}),e.jsx(mn,{id:"digest-push",checked:i,onCheckedChange:l})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Send day"}),e.jsxs(ls,{value:o,onValueChange:c,disabled:!r&&!i,children:[e.jsx(rs,{className:"w-[200px]",children:e.jsx(cs,{})}),e.jsx(as,{children:Yar.map((d,u)=>e.jsx(He,{value:String(u),children:d},d))})]})]}),e.jsx(z,{disabled:n.isPending,onClick:()=>n.mutate({email_enabled:r,push_enabled:i,send_day:Number(o)}),children:n.isPending?"Saving…":"Save settings"})]})]})}const Xar=()=>{const{user:s,rolesLoading:t,isBrokerageManager:n,isAdmin:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l,setSelectedBrokerageId:o}=hs(),c=zn(),{data:d=[],isLoading:u}=wJe(),[h,m]=_.useState(!1),p=d.length>0,f=n||r,g=_.useMemo(()=>{var ge;return l||(i.length>0?i[0].id:null)||((ge=d[0])==null?void 0:ge.brokerage_id)||a},[l,i,d,a]);_.useEffect(()=>{if(!(!s||u||t)){if(!f&&!p){c("/dashboard");return}!l&&i.length>0&&o(i[0].id),m(!0)}},[s,u,t,f,p,c,i,l,o]);const{data:v=[],isLoading:y}=jJe(g),{data:b=[]}=Ras(g),{data:w=[]}=Fas(g),{data:S=[]}=pYt(g),{data:C=[]}=Nar(g),{data:E=[]}=kar(g),{data:P=[],isLoading:M}=Car(g),I=Aar(g),D=Ear(g),F=Tar(g),q=Mar(g),[G,V]=_.useState(!1),[H,K]=_.useState(null),[Z,oe]=_.useState(null),re=_.useMemo(()=>S.map(ge=>({id:ge.agentId,name:ge.name})),[S]),ae=ge=>{var Ee;return ge?((Ee=re.find(Ne=>Ne.id===ge))==null?void 0:Ee.name)??null:null},J=_.useMemo(()=>zar({complianceDeals:v,disbursements:b,agentRecords:w,renewalAgents:S.map(ge=>({agentId:ge.agentId,name:ge.name,avatarUrl:ge.avatarUrl})),roster:S.map(ge=>({agentId:ge.agentId,name:ge.name,avatarUrl:ge.avatarUrl,overdue:ge.overdue,needsReview:ge.needsReview})),followUps:C,helpRequests:E,tasks:P,nameFor:ae}),[v,b,w,S,C,E,P]),te=_.useMemo(()=>v.filter(ge=>ge.target_close_date).map(ge=>({id:ge.deal_id,label:ge.property_address||ge.deal_name,date:ge.target_close_date})),[v]),ce=()=>{K(null),oe(null),V(!0)},ve=ge=>{K(null),oe(ge),V(!0)},me=ge=>{K(ge),oe(null),V(!0)},he=ge=>q.mutate({sourceType:ge.sourceType,sourceId:ge.sourceId,title:ge.title,category:ge.category});return h?e.jsx($s,{title:"Operations",description:"Everything that needs a decision today, plus your office task board and calendar",children:e.jsxs("div",{className:"space-y-6",children:[i.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(ls,{value:l||"",onValueChange:o,children:[e.jsxs(rs,{className:"w-[280px]",children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),e.jsx(cs,{placeholder:"Select brokerage"})]}),e.jsx(as,{children:i.map(ge=>e.jsx(He,{value:ge.id,children:ge.name},ge.id))})]})]}),g?e.jsxs(Qr,{defaultValue:"today",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(Jr,{className:"grid h-auto min-w-[460px] grid-cols-4",children:[e.jsx(Wt,{value:"today",children:"Today"}),e.jsx(Wt,{value:"tasks",children:"Task board"}),e.jsx(Wt,{value:"calendar",children:"Calendar"}),e.jsx(Wt,{value:"notifications",children:"Notifications"})]})}),e.jsx(Kt,{value:"today",children:e.jsx(Uar,{items:J,loading:y,onDismiss:he,onTrack:ve})}),e.jsx(Kt,{value:"tasks",children:e.jsx(Var,{tasks:P,people:re,loading:M,onNew:ce,onEdit:me,onStatus:(ge,Ee)=>D.mutate({id:ge.id,status:Ee}),onDelete:ge=>F.mutate(ge.id)})}),e.jsx(Kt,{value:"calendar",children:e.jsx(Gar,{items:J,tasks:P,closings:te})}),e.jsx(Kt,{value:"notifications",children:e.jsx(Zar,{brokerageId:g})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(oi,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]}),e.jsx(Kar,{open:G,onOpenChange:V,task:H,initial:Z,people:re,saving:I.isPending,onSave:ge=>I.mutate(ge,{onSuccess:()=>V(!1)})})]})}):null},cCt="id, agent_id, brokerage_id, team_id, owner_type, subdomain_slug, custom_domain, site_title, org_name, org_logo_url, brand_color, is_active, created_at";function ZBe(s,t){return t?`https://${t}`:s?`https://${s}.thelocalmove.com`:null}function Uas(){const{user:s,isAdmin:t,isBrokerageManager:n,managedBrokerages:r,brokerageId:a,selectedBrokerageId:i}=hs(),{data:l=[]}=Kre(),o=_.useMemo(()=>l.filter(p=>p.role==="team_leader"),[l]),c=_.useMemo(()=>r.length?r:(n||t)&&a?[{id:a,name:"My brokerage"}]:[],[r,n,t,a]),d=_.useMemo(()=>c.map(p=>p.id),[c]),u=_.useMemo(()=>o.map(p=>p.teamId),[o]),h=rt({queryKey:["my-websites",s==null?void 0:s.id,d.join(","),u.join(",")],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const[p,f]=await Promise.all([U.from("lead_sites").select(cCt).eq("agent_id",s.id).order("created_at",{ascending:!0}),d.length||u.length?U.from("lead_sites").select(cCt).or([d.length?`brokerage_id.in.(${d.join(",")})`:"",u.length?`team_id.in.(${u.join(",")})`:""].filter(Boolean).join(",")):Promise.resolve({data:[],error:null})]);if(p.error)throw p.error;if(f.error)throw f.error;return{own:(p.data||[]).filter(g=>(g.owner_type||"agent")==="agent"),org:f.data||[]}}}),m=_.useMemo(()=>{var y,b,w;const p=((y=h.data)==null?void 0:y.own)||[],f=((b=h.data)==null?void 0:b.org)||[],g=[],v=p.find(S=>S.is_active)||p[0]||null;v?g.push({kind:"agent",id:v.id,ownerId:null,name:v.site_title||"My website",kindLabel:"My agent site",slug:v.subdomain_slug,customDomain:v.custom_domain,isActive:!!v.is_active,logoUrl:null,brandColor:v.brand_color,editPath:`/my-website/${v.id}/edit`,publicUrl:ZBe(v.subdomain_slug,v.custom_domain),exists:!0}):g.push({kind:"agent",id:null,ownerId:null,name:"My agent site",kindLabel:"My agent site",slug:null,customDomain:null,isActive:!1,logoUrl:null,brandColor:null,editPath:"/need-a-website",publicUrl:null,exists:!1});for(const S of c){const C=f.find(E=>E.owner_type==="brokerage"&&E.brokerage_id===S.id)||null;g.push({kind:"brokerage",id:(C==null?void 0:C.id)??null,ownerId:S.id,name:(C==null?void 0:C.org_name)||(C==null?void 0:C.site_title)||S.name,kindLabel:"Company site",slug:(C==null?void 0:C.subdomain_slug)??null,customDomain:(C==null?void 0:C.custom_domain)??null,isActive:!!(C!=null&&C.is_active),logoUrl:(C==null?void 0:C.org_logo_url)??null,brandColor:(C==null?void 0:C.brand_color)??null,editPath:"/brokerage/website",publicUrl:ZBe((C==null?void 0:C.subdomain_slug)??null,(C==null?void 0:C.custom_domain)??null),exists:!!C})}for(const S of o){const C=f.find(E=>E.owner_type==="team"&&E.team_id===S.teamId)||null;g.push({kind:"team",id:(C==null?void 0:C.id)??null,ownerId:S.teamId,name:(C==null?void 0:C.org_name)||(C==null?void 0:C.site_title)||((w=S.team)==null?void 0:w.name)||"My team",kindLabel:"Team site",slug:(C==null?void 0:C.subdomain_slug)??null,customDomain:(C==null?void 0:C.custom_domain)??null,isActive:!!(C!=null&&C.is_active),logoUrl:(C==null?void 0:C.org_logo_url)??null,brandColor:(C==null?void 0:C.brand_color)??null,editPath:`/team/website?teamId=${S.teamId}`,publicUrl:ZBe((C==null?void 0:C.subdomain_slug)??null,(C==null?void 0:C.custom_domain)??null),exists:!!C})}return g},[h.data,c,o]);return{websites:m,isLoading:h.isLoading,ledTeams:o,hasOrgSites:m.some(p=>p.kind!=="agent")}}const Qar={agent:Wo,brokerage:oi,team:On};function Jar({site:s}){const t=zn(),n=Qar[s.kind],r=s.customDomain||(s.slug?`${s.slug}.thelocalmove.com`:null);return e.jsx(be,{className:"overflow-hidden transition-shadow hover:shadow-md",children:e.jsxs(Le,{className:"flex flex-col gap-5 p-6 sm:flex-row sm:items-center",children:[e.jsx("div",{className:"flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl",style:{backgroundColor:s.brandColor||"hsl(var(--muted))"},children:s.logoUrl?e.jsx("img",{src:s.logoUrl,alt:"",className:"max-h-full max-w-full object-contain"}):e.jsx(n,{className:`h-7 w-7 ${s.brandColor?"text-white":"text-muted-foreground"}`})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-lg font-semibold",children:s.name}),s.exists?s.isActive?e.jsx(ze,{children:"Live"}):e.jsx(ze,{variant:"secondary",children:"Private preview"}):e.jsx(ze,{variant:"outline",children:"Not created yet"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s.kindLabel}),e.jsx("p",{className:"mt-1 truncate text-sm text-muted-foreground",children:r||"Pick a web address when you create it"})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[s.exists&&s.publicUrl&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:s.publicUrl,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," View"]})}),e.jsx(z,{onClick:()=>t(s.editPath),children:s.exists?e.jsxs(e.Fragment,{children:[e.jsx(Wa,{className:"mr-2 h-4 w-4"})," Edit site"]}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Create site"]})})]})]})})}function eir(){const{websites:s,isLoading:t}=Uas();return e.jsx($s,{title:"My Websites",description:"Every website you can edit, in one place",children:e.jsx("div",{className:"mx-auto max-w-4xl space-y-4 p-4 lg:p-8",children:t?[0,1].map(n=>e.jsx("div",{className:"h-32 animate-pulse rounded-xl bg-muted"},n)):e.jsxs(e.Fragment,{children:[s.map(n=>e.jsx(Jar,{site:n},`${n.kind}-${n.ownerId||"me"}`)),e.jsxs("p",{className:"pt-2 text-center text-sm text-muted-foreground",children:["Looking for lead magnets, pop-ups and other add-ons?"," ",e.jsx(or,{to:"/website-apps",className:"underline",children:"Website Apps"})]})]})})})}const dCt={bold_national:{display:"'Archivo', 'Helvetica Neue', Arial, sans-serif",body:"'Inter', system-ui, sans-serif",radius:"0.25rem"},editorial_boutique:{display:"'Playfair Display', Georgia, serif",body:"'Inter', system-ui, sans-serif",radius:"0px"},modern_minimal:{display:"'Sora', system-ui, sans-serif",body:"'Manrope', system-ui, sans-serif",radius:"0.75rem"},coastal_luxury:{display:"'Cormorant Garamond', Georgia, serif",body:"'Karla', system-ui, sans-serif",radius:"0.5rem"}};function Djr(s,t){var a;const n=(t==null?void 0:t.orgPreset)||((a=s==null?void 0:s.themeConfig)==null?void 0:a.orgPreset)||"editorial_boutique",r=dCt[n]||dCt.editorial_boutique;return{primary:(s==null?void 0:s.brandColor)||(t==null?void 0:t.primaryColor)||"#12222e",accent:(s==null?void 0:s.accentColor)||(t==null?void 0:t.accentColor)||"#c9a96e",display:r.display,body:r.body,radius:r.radius,name:(s==null?void 0:s.orgName)||(s==null?void 0:s.siteTitle)||"Our Company",logoUrl:(s==null?void 0:s.orgLogoUrl)||(s==null?void 0:s.teamLogoUrl)||null,logoDarkUrl:(s==null?void 0:s.orgLogoDarkUrl)||(s==null?void 0:s.orgLogoUrl)||(s==null?void 0:s.teamLogoUrl)||null}}const qas=[{key:"bold_national",label:"Bold National",description:"Confident, bold type and a tight grid — national franchise energy."},{key:"editorial_boutique",label:"Editorial Boutique",description:"Serif display type and magazine layouts for a boutique feel."},{key:"modern_minimal",label:"Modern Minimal",description:"Clean geometry, generous whitespace, soft rounded cards."},{key:"coastal_luxury",label:"Coastal Luxury",description:"Airy, elegant serif with warm light and wide imagery."}];function Vas(s){return(s==null?void 0:s.orgProfile)||{}}function Rjr(s){const t=(s==null?void 0:s.ownerType)==="team";return{isTeam:t,org:t?"team":"brokerage",people:t?"Our Team":"Our Agents",meetPeople:t?"Meet Our Team":"Meet Our Agents",peopleNoun:t?"team members":"agents",joinShort:t?"Join Our Team":"Join Us",joinTitle:t?"Join Our Team":"Careers"}}function Fjr(s){var n;if((s==null?void 0:s.ownerType)!=="team")return null;const t=(n=Vas(s).affiliation)==null?void 0:n.trim();return t||null}function Ojr(s){const t=Vas(s),n=(t.offices||[]).filter(o=>o&&(o.address||o.city||o.phone||o.email)),r=n[0]||{},a=[r.name||null,r.address||null,[r.city,r.state].filter(Boolean).join(", ")+(r.zip?` ${r.zip}`:"")].filter(o=>!!o&&o.trim().length>0),i=[{label:"Facebook",url:t.facebookUrl},{label:"Instagram",url:t.instagramUrl},{label:"LinkedIn",url:t.linkedinUrl},{label:"YouTube",url:t.youtubeUrl}].filter(o=>!!o.url),l=s!=null&&s.brokerageLicenseNumber?`License #${s.brokerageLicenseNumber}${s!=null&&s.licenseState?` (${s.licenseState})`:""}`:null;return{phone:r.phone||null,email:r.email||null,addressLines:a,hours:r.hours||null,offices:n,social:i,legalName:(s==null?void 0:s.brokerageLegalName)||null,licenseLine:l}}const tir=10*1024*1024;function XBe({label:s,hint:t,value:n,onChange:r,slot:a,siteId:i,dark:l,className:o}){const c=_.useRef(null),[d,u]=_.useState(!1),[h,m]=_.useState(!1),p=async f=>{if(!f.type.startsWith("image/")){ne.error("Please choose an image file");return}if(f.size>tir){ne.error("Image must be under 10MB");return}u(!0);try{const g=(f.name.split(".").pop()||"png").toLowerCase(),v=`org-sites/${i}/${a}-${Date.now()}.${g}`,{error:y}=await U.storage.from("agent-uploads").upload(v,f,{upsert:!0,contentType:f.type});if(y)throw y;const{data:b}=U.storage.from("agent-uploads").getPublicUrl(v);r(b.publicUrl),ne.success(`${s} uploaded`)}catch(g){ne.error(g.message||"Upload failed")}finally{u(!1),c.current&&(c.current.value="")}};return e.jsxs("div",{className:o,children:[e.jsx(ee,{className:"text-sm font-medium",children:s}),t&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t}),e.jsxs("div",{onDragOver:f=>{f.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:f=>{var v;f.preventDefault(),m(!1);const g=(v=f.dataTransfer.files)==null?void 0:v[0];g&&p(g)},onClick:()=>{var f;return!d&&((f=c.current)==null?void 0:f.click())},className:`mt-2 flex cursor-pointer items-center gap-4 rounded-lg border-2 border-dashed p-4 transition-colors ${h?"border-primary bg-primary/5":"border-muted-foreground/25 hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:`flex h-20 w-28 shrink-0 items-center justify-center overflow-hidden rounded-md ${l?"bg-slate-900":"bg-muted"}`,children:n?e.jsx("img",{src:n,alt:s,className:"max-h-full max-w-full object-contain"}):e.jsx(nc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:d?"Uploading…":n?"Replace image":"Drag an image here, or click to choose"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"PNG, JPG or SVG up to 10MB"})]}),d?e.jsx(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Ra,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("input",{ref:c,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var v;const g=(v=f.target.files)==null?void 0:v[0];g&&p(g)}}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(pe,{value:n||"",onChange:f=>r(f.target.value||null),placeholder:"…or paste an image URL",className:"h-9 text-xs"}),n&&e.jsx(z,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>r(null),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})}const sir=10*1024*1024;function nir({value:s,onChange:t,userId:n}){const r=_.useRef(null),[a,i]=_.useState(!1),l=async o=>{if(!o.type.startsWith("image/")){ne.error("Please choose an image file.");return}if(o.size>sir){ne.error("That photo is over 10MB — please pick a smaller one.");return}i(!0);try{const c=(o.name.split(".").pop()||"jpg").toLowerCase(),d=`${n}/headshot-${Date.now()}.${c}`,{error:u}=await U.storage.from("avatars").upload(d,o,{upsert:!0,contentType:o.type});if(u)throw u;const{data:h}=U.storage.from("avatars").getPublicUrl(d);t(h.publicUrl),ne.success("Headshot uploaded.")}catch(c){ne.error((c==null?void 0:c.message)||"Could not upload that photo.")}finally{i(!1),r.current&&(r.current.value="")}};return e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Headshot"}),e.jsxs("div",{className:"mt-2 flex items-center gap-4",children:[e.jsx("div",{className:"flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted",children:s?e.jsx("img",{src:s,alt:"",className:"h-full w-full object-cover object-top"}):e.jsx(Oo,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var o;return(o=r.current)==null?void 0:o.click()},children:[a?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ra,{className:"mr-2 h-4 w-4"}),s?"Replace photo":"Upload photo"]}),s&&e.jsxs(z,{type:"button",variant:"ghost",size:"sm",onClick:()=>t(null),children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Remove"]})]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"A square, head-and-shoulders photo looks best. Up to 10MB."}),e.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&l(c)}})]})}function rir({siteId:s,member:t,open:n,onOpenChange:r}){var E;const a=$t(),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(null),[g,v]=_.useState(""),[y,b]=_.useState(""),[w,S]=_.useState("");_.useEffect(()=>{var P,M,I,D;!n||!t||(S(t.headline||""),l(((P=t.profile)==null?void 0:P.name)||""),c(((M=t.profile)==null?void 0:M.title)||""),m(((I=t.profile)==null?void 0:I.email)||""),f(((D=t.profile)==null?void 0:D.avatar_url)||null),u(""),v(""),b(""),(async()=>{const{data:F}=await U.from("profiles").select("name, title, phone, email, avatar_url, bio, areas_served").eq("id",t.user_id).maybeSingle();F&&(l(F.name||""),c(F.title||""),u(F.phone||""),m(F.email||""),f(F.avatar_url||null),b(F.bio||""),v(F.areas_served||""))})())},[n,t]);const C=mt({mutationFn:async()=>{if(!t)return;const{error:P}=await U.from("profiles").update({name:i.trim()||null,title:o.trim()||null,phone:d.trim()||null,avatar_url:p,bio:y.trim()||null,areas_served:g.trim()||null}).eq("id",t.user_id);if(P)throw P;const{error:M}=await U.from("org_site_agents").update({headline:w.trim()||null}).eq("id",t.id);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["org-site-roster-admin",s]}),a.invalidateQueries({queryKey:["org-site-roster",s]}),ne.success("Member details saved."),r(!1)},onError:P=>{var M;return ne.error((M=P==null?void 0:P.message)!=null&&M.includes("row-level security")?"You can only edit people on your own team.":(P==null?void 0:P.message)||"Could not save those details.")}});return e.jsx(Is,{open:n,onOpenChange:r,children:e.jsxs(Ls,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:["Edit ",((E=t==null?void 0:t.profile)==null?void 0:E.name)||"member"]}),e.jsx(_r,{children:"These details show on your website's roster and on this person's profile page."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(nir,{value:p,onChange:f,userId:(t==null?void 0:t.user_id)||""}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:i,onChange:P=>l(P.target.value),placeholder:"Full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:o,onChange:P=>c(P.target.value),placeholder:"REALTOR®"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:d,onChange:P=>u(P.target.value),placeholder:"(555) 555-1234"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h,disabled:!0,placeholder:"—"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only they can change their sign-in email."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headline on the website"}),e.jsx(pe,{value:w,onChange:P=>S(P.target.value),placeholder:"Luxury & waterfront specialist"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Areas they serve"}),e.jsx(pe,{value:g,onChange:P=>v(P.target.value),placeholder:"Lakeland, Winter Haven, Auburndale"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Bio"}),e.jsx(Ps,{rows:4,value:y,onChange:P=>b(P.target.value),placeholder:"A short introduction."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(z,{onClick:()=>C.mutate(),disabled:C.isPending,children:C.isPending?"Saving…":"Save member"})]})]})})}const air="id, agent_id, subdomain_slug, custom_domain, site_title, site_tagline, is_active, brand_color, accent_color, theme_config, owner_type, org_tier, org_name, org_logo_url, org_logo_dark_url, org_profile, brokerage_id, team_id";function iir(s){const{brokerageId:t,teamId:n}=s;return rt({queryKey:["org-site",t,n],enabled:!!(t||n),queryFn:async()=>{let r=U.from("lead_sites").select(air).limit(1);r=n?r.eq("team_id",n).eq("owner_type","team"):r.eq("brokerage_id",t).eq("owner_type","brokerage");const{data:a,error:i}=await r.maybeSingle();if(i)throw i;return a??null}})}function oir(s){return rt({queryKey:["org-site-roster-admin",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("org_site_agents").select("id, site_id, user_id, display_order, is_featured, is_visible, profile_slug, headline, blurb, specialties, languages").eq("site_id",s).order("display_order",{ascending:!0});if(n)throw n;const r=t||[];if(!r.length)return[];const{data:a}=await U.from("profiles").select("id, name, avatar_url, email, title").in("id",r.map(l=>l.user_id)),i=new Map((a||[]).map(l=>[l.id,l]));return r.map(l=>({...l,profile:i.get(l.user_id)}))}})}function lir(s){const t=$t();return mt({mutationFn:async()=>{const{data:n,error:r}=await U.rpc("sync_org_site_roster",{p_site_id:s});if(r)throw r;return n},onSuccess:n=>{t.invalidateQueries({queryKey:["org-site-roster-admin",s]}),t.invalidateQueries({queryKey:["org-site-roster",s]}),ne.success(n?`${n} agent${n===1?"":"s"} added to the roster.`:"Roster is already up to date.")},onError:n=>ne.error(n.message||"Could not refresh the roster.")})}function cir(s){const t=$t();return mt({mutationFn:async({id:n,patch:r})=>{const{error:a}=await U.from("org_site_agents").update(r).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["org-site-roster-admin",s]}),t.invalidateQueries({queryKey:["org-site-roster",s]})},onError:n=>ne.error(n.message||"Could not save that change.")})}function dir(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await U.from("lead_sites").update(n).eq("id",s);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["org-site"]}),ne.success("Saved.")},onError:n=>ne.error(n.message||"Could not save the website.")})}function Zde(s){return s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function Mit({brokerageId:s,teamId:t,orgLabel:n="brokerage"}){const{data:r,isLoading:a,refetch:i}=iir({brokerageId:s,teamId:t});return a?e.jsx("div",{className:"flex h-40 items-center justify-center",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):r?e.jsx(hir,{site:r,orgLabel:n}):e.jsx(uir,{brokerageId:s,teamId:t,orgLabel:n,onCreated:()=>i()})}function uir({brokerageId:s,teamId:t,orgLabel:n,onCreated:r}){const{user:a}=hs(),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState("editorial_boutique"),[h,m]=_.useState(!1),[p,f]=_.useState(null);_.useEffect(()=>{let v=!1;return(async()=>{if(t){const{data:S}=await U.from("teams").select("name, description, avatar_url, brokerage_id").eq("id",t).maybeSingle();if(v||!S)return;const C=S.name||"";C&&(l(M=>M||C),c(M=>M||Zde(C)));let E=null,P=null;if(S.brokerage_id){const[{data:M},{data:I}]=await Promise.all([U.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle(),U.from("brokerage_brand_profiles").select("primary_color, accent_color, legal_name, license_number").eq("brokerage_id",S.brokerage_id).maybeSingle()]);E=(M==null?void 0:M.name)||null,P=I}if(v)return;f({logo:S.avatar_url||null,primary:(P==null?void 0:P.primary_color)||null,accent:(P==null?void 0:P.accent_color)||null,legalName:(P==null?void 0:P.legal_name)||null,license:(P==null?void 0:P.license_number)||null,about:S.description||null,affiliation:E});return}if(!s)return;const[{data:y},{data:b}]=await Promise.all([U.from("brokerage_brand_profiles").select("logo_url, primary_color, accent_color, legal_name, license_number").eq("brokerage_id",s).maybeSingle(),U.from("brokerages").select("name").eq("id",s).maybeSingle()]);if(v)return;const w=(b==null?void 0:b.name)||"";w&&(l(S=>S||w),c(S=>S||Zde(w))),f({logo:(y==null?void 0:y.logo_url)||null,primary:(y==null?void 0:y.primary_color)||null,accent:(y==null?void 0:y.accent_color)||null,legalName:(y==null?void 0:y.legal_name)||null,license:(y==null?void 0:y.license_number)||null,about:null,affiliation:null})})(),()=>{v=!0}},[s,t]);const g=async()=>{if(!a||!s&&!t)return;if(!i.trim()||!o.trim()){ne.error(`Add a ${n} name and web address.`);return}m(!0);const{error:v}=await U.from("lead_sites").insert({agent_id:a.id,brokerage_id:t?null:s,team_id:t||null,owner_type:t?"team":"brokerage",org_tier:"essential",org_name:i.trim(),site_title:i.trim(),subdomain_slug:o.trim(),is_active:!1,org_logo_url:(p==null?void 0:p.logo)||null,brand_color:(p==null?void 0:p.primary)||"#12222e",accent_color:(p==null?void 0:p.accent)||"#c9a96e",brokerage_legal_name:(p==null?void 0:p.legalName)||null,brokerage_license_number:(p==null?void 0:p.license)||null,org_profile:{offices:[{name:t?`${i.trim()} — Office`:`${i.trim()} — Main Office`}],...p!=null&&p.about?{about:p.about}:{},...p!=null&&p.affiliation?{affiliation:p.affiliation}:{}},theme_config:{orgPreset:d}});if(m(!1),v){ne.error(v.message.includes("duplicate")?"That web address is taken — try another.":v.message);return}ne.success("Website created as a private preview."),r()};return e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Wo,{className:"h-5 w-5"})," Create your ",n," website"]}),e.jsxs(En,{children:["One site for your whole ",n," — every agent's profile, every listing, city pages, blog, recruiting page and lead capture straight into LevelUp. It starts as a private preview that only you can see."]})]}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:n==="team"?"Team name":"Company name"}),e.jsx(pe,{value:i,onChange:v=>{l(v.target.value),o||c(Zde(v.target.value))},placeholder:n==="team"?"The Bishop Group":"RE/MAX Executives"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Web address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:o,onChange:v=>c(Zde(v.target.value)),placeholder:"bishop-group"}),e.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:".thelocalmove.com"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can point your own domain at it later."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:qas.map(v=>e.jsxs("button",{type:"button",onClick:()=>u(v.key),className:`rounded-lg border p-4 text-left transition-colors ${d===v.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:v.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:v.description})]},v.key))})]}),(p==null?void 0:p.logo)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"We'll start the site with your company logo and brand colors — you can change them anytime."}),e.jsx(z,{onClick:g,disabled:h,className:"w-full",children:h?"Creating…":"Create website"})]})]})}function hir({site:s,orgLabel:t}){var ae;const{isAdmin:n}=hs(),r=dir(s.id),{data:a=[],isLoading:i}=oir(s.id),l=lir(s.id),o=cir(s.id),[c,d]=_.useState(s.site_title||""),[u,h]=_.useState(s.site_tagline||""),[m,p]=_.useState(s.org_name||""),[f,g]=_.useState(s.org_logo_url||null),[v,y]=_.useState(s.org_logo_dark_url||null),[b,w]=_.useState(s.org_profile||{}),S=(J,te)=>w(ce=>({...ce,[J]:te})),C=b.offices||[],E=(J,te)=>S("offices",C.map((ce,ve)=>ve===J?{...ce,...te}:ce)),P=b.stats||[],M=b.serviceAreas||[],[I,D]=_.useState(null),[F,q]=_.useState(s.brand_color||"#12222e"),[G,V]=_.useState(s.accent_color||"#c9a96e"),[H,K]=_.useState(s.custom_domain||""),Z=((ae=s.theme_config)==null?void 0:ae.orgPreset)||"editorial_boutique",oe=s.custom_domain?`https://${s.custom_domain}`:`https://${s.subdomain_slug}.thelocalmove.com`,re=`${oe}?previewSlug=${s.subdomain_slug}`;return e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(_t,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsxs(Nt,{className:"flex flex-wrap items-center gap-2",children:[s.org_name||s.site_title,e.jsx(ze,{variant:s.is_active?"default":"secondary",children:s.is_active?"Live":"Preview"}),e.jsx(ze,{variant:"outline",children:s.org_tier==="pro"?"Pro (IDX)":"Essential"})]}),e.jsx(En,{children:oe})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:s.is_active?oe:re,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," Preview"]})}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:"Published"}),e.jsx(mn,{checked:s.is_active,onCheckedChange:J=>r.mutate({is_active:J})})]})]})]})}),e.jsxs(Qr,{defaultValue:"brand",children:[e.jsxs(Jr,{className:"h-auto flex-wrap justify-start gap-1",children:[e.jsx(Wt,{value:"brand",children:"Identity"}),e.jsx(Wt,{value:"story",children:"Story"}),e.jsx(Wt,{value:"offices",children:"Offices"}),e.jsx(Wt,{value:"social",children:"Social"}),e.jsxs(Wt,{value:"agents",children:["Agents (",a.length,")"]}),e.jsx(Wt,{value:"domain",children:"Address"}),e.jsx(Wt,{value:"plan",children:"Plan"})]}),e.jsx(Kt,{value:"brand",className:"mt-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Brand & content"}),e.jsx(En,{children:"The look adapts to your colors, logo and chosen design."})]}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:t==="team"?"Team name":"Company name"}),e.jsx(pe,{value:m,onChange:J=>p(J.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:c,onChange:J=>d(J.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(Ps,{rows:2,value:u,onChange:J=>h(J.target.value)})]}),t==="team"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage the team hangs its license with"}),e.jsx(pe,{value:b.affiliation||"",onChange:J=>S("affiliation",J.target.value),placeholder:"RE/MAX Integrity"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown quietly in the footer and on the About page — most states require a team's advertising to name the brokerage."})]}),e.jsxs("div",{className:"grid gap-5 sm:grid-cols-2",children:[e.jsx(XBe,{label:t==="team"?"Team logo":"Company logo",hint:"Shown in the header. Use a version that reads well on white.",value:f,onChange:g,slot:"logo",siteId:s.id}),e.jsx(XBe,{label:"Logo for dark backgrounds",hint:"Optional — used in the footer and dark headers.",value:v,onChange:y,slot:"logo-dark",siteId:s.id,dark:!0})]}),e.jsx(XBe,{label:"Homepage hero image",hint:"A wide photo of your market, office or team. 2000px wide works best.",value:b.heroImageUrl,onChange:J=>S("heroImageUrl",J||void 0),slot:"hero",siteId:s.id}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Primary color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:F,onChange:J=>q(J.target.value),className:"h-10 w-14 rounded border"}),e.jsx(pe,{value:F,onChange:J=>q(J.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:G,onChange:J=>V(J.target.value),className:"h-10 w-14 rounded border"}),e.jsx(pe,{value:G,onChange:J=>V(J.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:qas.map(J=>e.jsxs("button",{type:"button",onClick:()=>r.mutate({theme_config:{...s.theme_config||{},orgPreset:J.key}}),className:`rounded-lg border p-4 text-left transition-colors ${Z===J.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:J.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:J.description})]},J.key))})]}),e.jsx(z,{onClick:()=>r.mutate({org_name:m||null,site_title:c||null,site_tagline:u||null,org_logo_url:f||null,org_logo_dark_url:v||null,org_profile:b,brand_color:F,accent_color:G}),disabled:r.isPending,children:r.isPending?"Saving…":"Save changes"})]})]})}),e.jsx(Kt,{value:"story",className:"mt-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Your story"}),e.jsxs(En,{children:["This is your ",t," speaking — not any individual agent. It fills the About page and the homepage numbers."]})]}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["About ",t==="team"?"the team":"the company"]}),e.jsx(Ps,{rows:7,value:b.about||"",onChange:J=>S("about",J.target.value),placeholder:"Who you are, how long you've served the area, and what clients can expect."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Founded"}),e.jsx(pe,{value:b.foundedYear||"",onChange:J=>S("foundedYear",J.target.value),placeholder:"1998"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Why agents join us"}),e.jsx(Ps,{rows:4,value:b.whyJoin||"",onChange:J=>S("whyJoin",J.target.value),placeholder:"Shown on your careers page and the homepage recruiting section."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Areas we serve"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every city or area you work in — not just where you have listings right now. These show in the “Areas We Serve” section and in your markets count."}),M.map((J,te)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:J,onChange:ce=>S("serviceAreas",M.map((ve,me)=>me===te?ce.target.value:ve)),placeholder:"Lakeland, FL"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>S("serviceAreas",M.filter((ce,ve)=>ve!==te)),children:e.jsx(Cn,{className:"h-4 w-4"})})]},te)),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>S("serviceAreas",[...M,""]),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Add an area"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Homepage numbers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Up to four. Leave empty and we'll show agent, listing and market counts automatically."}),P.map((J,te)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:J.value,onChange:ce=>S("stats",P.map((ve,me)=>me===te?{...ve,value:ce.target.value}:ve)),placeholder:"$412M",className:"max-w-[140px]"}),e.jsx(pe,{value:J.label,onChange:ce=>S("stats",P.map((ve,me)=>me===te?{...ve,label:ce.target.value}:ve)),placeholder:"Sold last year"}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>S("stats",P.filter((ce,ve)=>ve!==te)),children:e.jsx(Cn,{className:"h-4 w-4"})})]},te)),P.length<4&&e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>S("stats",[...P,{label:"",value:""}]),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Add a number"]})]}),e.jsx(z,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save story"})]})]})}),e.jsx(Kt,{value:"offices",className:"mt-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Offices"}),e.jsx(En,{children:"These appear on your contact page and in the footer. The first one is your main office."})]}),e.jsxs(Le,{className:"space-y-5",children:[C.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No offices yet — add your main office so visitors can reach you."}),C.map((J,te)=>e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm font-medium",children:te===0?"Main office":`Office ${te+1}`}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>S("offices",C.filter((ce,ve)=>ve!==te)),children:e.jsx(Cn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(pe,{value:J.name||"",onChange:ce=>E(te,{name:ce.target.value}),placeholder:"Office name"}),e.jsx(pe,{value:J.phone||"",onChange:ce=>E(te,{phone:ce.target.value}),placeholder:"Phone"}),e.jsx(pe,{value:J.email||"",onChange:ce=>E(te,{email:ce.target.value}),placeholder:"Email"}),e.jsx(pe,{value:J.hours||"",onChange:ce=>E(te,{hours:ce.target.value}),placeholder:"Mon–Fri 9–5"}),e.jsx(pe,{value:J.address||"",onChange:ce=>E(te,{address:ce.target.value}),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(pe,{value:J.city||"",onChange:ce=>E(te,{city:ce.target.value}),placeholder:"City"}),e.jsx(pe,{value:J.state||"",onChange:ce=>E(te,{state:ce.target.value}),placeholder:"ST"}),e.jsx(pe,{value:J.zip||"",onChange:ce=>E(te,{zip:ce.target.value}),placeholder:"ZIP"})]})]})]},te)),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>S("offices",[...C,{}]),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Add an office"]}),e.jsx(z,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save offices"})]})]})]})}),e.jsx(Kt,{value:"social",className:"mt-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Social profiles"}),e.jsxs(En,{children:["Your ",t," accounts — linked in the footer and on the contact page."]})]}),e.jsxs(Le,{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(ee,{children:"Facebook"}),e.jsx(pe,{value:b.facebookUrl||"",onChange:J=>S("facebookUrl",J.target.value),placeholder:"https://facebook.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Instagram"}),e.jsx(pe,{value:b.instagramUrl||"",onChange:J=>S("instagramUrl",J.target.value),placeholder:"https://instagram.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"LinkedIn"}),e.jsx(pe,{value:b.linkedinUrl||"",onChange:J=>S("linkedinUrl",J.target.value),placeholder:"https://linkedin.com/company/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"YouTube"}),e.jsx(pe,{value:b.youtubeUrl||"",onChange:J=>S("youtubeUrl",J.target.value),placeholder:"https://youtube.com/@…"})]})]}),e.jsx(z,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save social links"})]})]})}),e.jsxs(Kt,{value:"agents",className:"mt-6",children:[e.jsxs(be,{children:[e.jsxs(_t,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Nt,{children:"Agent roster"}),e.jsx(En,{children:"Everyone here gets a profile page on your site with their own listings."})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx(Gi,{className:`mr-2 h-4 w-4 ${l.isPending?"animate-spin":""}`})," Refresh from LevelUp"]})]}),e.jsx(Le,{className:"space-y-3",children:i?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loading roster…"}):a.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents yet — click “Refresh from LevelUp” to pull in your agents."}):a.map(J=>{var te,ce,ve,me;return e.jsxs("div",{className:"flex flex-wrap items-center gap-4 rounded-lg border p-4",children:[(te=J.profile)!=null&&te.avatar_url?e.jsx("img",{src:J.profile.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover object-top"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-muted"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:((ce=J.profile)==null?void 0:ce.name)||"Unnamed agent"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:J.headline||((ve=J.profile)==null?void 0:ve.title)||((me=J.profile)==null?void 0:me.email)})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>D(J),children:[e.jsx(Wa,{className:"mr-2 h-4 w-4"})," Edit"]}),e.jsxs(z,{variant:J.is_featured?"default":"outline",size:"sm",onClick:()=>o.mutate({id:J.id,patch:{is_featured:!J.is_featured}}),children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," ",J.is_featured?"Featured":"Feature"]}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>o.mutate({id:J.id,patch:{is_visible:!J.is_visible}}),children:[J.is_visible?e.jsx(xa,{className:"mr-2 h-4 w-4"}):e.jsx(Yf,{className:"mr-2 h-4 w-4"}),J.is_visible?"Shown":"Hidden"]})]},J.id)})})]}),e.jsx(rir,{siteId:s.id,member:I,open:!!I,onOpenChange:J=>!J&&D(null)})]}),e.jsx(Kt,{value:"domain",className:"mt-6",children:e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Web address"}),e.jsx(En,{children:"Use the free address or point your own domain at the site."})]}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Free address"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.subdomain_slug,".thelocalmove.com"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Your own domain"}),e.jsx(pe,{value:H,onChange:J=>K(J.target.value.trim().toLowerCase()),placeholder:"www.yourcompany.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add the domain here, then point its DNS to LevelUp. Our team confirms it once the DNS is in place."})]}),e.jsx(z,{onClick:()=>r.mutate({custom_domain:H||null}),disabled:r.isPending,children:r.isPending?"Saving…":"Save address"})]})]})}),e.jsxs(Kt,{value:"plan",className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs(be,{className:s.org_tier==="essential"?"border-primary":"",children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Essential"}),e.jsx(En,{children:"Everything except live MLS search."})]}),e.jsxs(Le,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Company homepage, about and contact"}),e.jsx("p",{children:"• Full agent roster with individual profile pages"}),e.jsx("p",{children:"• Every agent's Listing Exchange listings"}),e.jsx("p",{children:"• Blog, city pages, SEO and lead capture"}),e.jsx("p",{children:"• Recruiting page tied to your pipeline"})]})]}),e.jsxs(be,{className:s.org_tier==="pro"?"border-primary":"",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Pro"]}),e.jsx(En,{children:"Everything in Essential, plus live MLS."})]}),e.jsxs(Le,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Full IDX property search"}),e.jsx("p",{children:"• Office listing feed and sold comps"}),e.jsx("p",{children:"• Saved searches and buyer alerts"}),e.jsx("p",{children:"• Market reports and CMA tools"}),e.jsx("p",{className:"pt-2 text-foreground",children:s.org_tier==="pro"?"Your site is on Pro.":"Ask your LevelUp rep to switch this site to Pro — nothing gets rebuilt."})]})]})]}),n&&e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{className:"text-base",children:"Admin: plan control"}),e.jsx(En,{children:"Switch this site between Essential and Pro."})]}),e.jsxs(Le,{className:"flex items-center gap-3",children:[e.jsx(z,{variant:s.org_tier==="essential"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"essential"}),children:"Essential"}),e.jsx(z,{variant:s.org_tier==="pro"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"pro"}),children:"Pro (IDX)"})]})]})]})]})]})}const uCt={agent:Wo,brokerage:oi,team:On};function Has({current:s,className:t}){const n=zn(),{websites:r}=Uas();if(r.length<2)return null;const a=r.find(l=>l.kind===s.kind&&(!s.ownerId||l.ownerId===s.ownerId))||r.find(l=>l.kind===s.kind),i=uCt[(a==null?void 0:a.kind)||"agent"];return e.jsx("div",{className:t,children:e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsxs(z,{variant:"outline",className:"h-auto w-full justify-between gap-3 py-2.5 sm:w-auto sm:min-w-[320px]",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3 text-left",children:[e.jsx(i,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:(a==null?void 0:a.name)||"Choose a website"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:a==null?void 0:a.kindLabel})]})]}),e.jsx(R_,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),e.jsxs(qd,{align:"start",className:"w-[320px]",children:[e.jsx(qP,{children:"Switch website"}),r.map(l=>{const o=uCt[l.kind],c=l===a;return e.jsxs(ua,{onSelect:()=>n(l.editPath),className:"gap-3 py-2.5",children:[e.jsx(o,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm",children:l.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.kindLabel})]}),l.exists?l.isActive?null:e.jsx(ze,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Preview"}):e.jsx(ze,{variant:"outline",className:"shrink-0 text-[10px]",children:"Not created"}),c&&e.jsx(Wr,{className:"h-4 w-4 shrink-0"})]},`${l.kind}-${l.ownerId||"me"}`)}),e.jsx(Iy,{}),e.jsxs(ua,{onSelect:()=>n("/websites"),className:"gap-3",children:[e.jsx(op,{className:"h-4 w-4 text-muted-foreground"})," See all my websites"]})]})]})})}function mir(){const s=zn(),[t]=Gl(),{data:n=[],isLoading:r}=Kre(),a=_.useMemo(()=>n.filter(o=>o.role==="team_leader"),[n]),i=t.get("teamId"),l=a.find(o=>o.teamId===i)||a[0]||null;return _.useEffect(()=>{!r&&a.length===0&&s("/websites")},[r,a.length,s]),e.jsx($s,{title:"Team Website",description:"Your team site — members, listings and leads",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 lg:p-8",children:[e.jsx(Has,{current:{kind:"team",ownerId:l==null?void 0:l.teamId}}),r?e.jsx("div",{className:"h-40 animate-pulse rounded-xl bg-muted"}):l?e.jsx(Mit,{teamId:l.teamId,orgLabel:"team"}):e.jsx(be,{children:e.jsx(Le,{className:"p-8 text-center text-sm text-muted-foreground",children:"Only team leaders can build a team website."})})]})})}function pir(){const{user:s,isAdmin:t,isBrokerageManager:n,rolesLoading:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l}=hs(),o=zn(),c=_.useMemo(()=>{var d;return l||((d=i[0])==null?void 0:d.id)||a},[l,i,a]);return _.useEffect(()=>{r||!s||!t&&!n&&o("/dashboard")},[r,s,t,n,o]),e.jsx($s,{title:"Company Website",description:"Your brokerage website — agents, listings, recruiting and leads",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 lg:p-8",children:[e.jsx(Has,{current:{kind:"brokerage",ownerId:c}}),e.jsx(Mit,{brokerageId:c,orgLabel:"brokerage"})]})})}const hCt={name:"",description:"",agent_split_pct:"70",team_split_pct:"",cap_amount:"",monthly_fee:"",transaction_fee:"",franchise_fee_pct:"",referral_fee_pct:"",commission_calc_method:"standard",is_active:!0};function fir({open:s,onOpenChange:t,plan:n,onSave:r,saving:a}){const[i,l]=_.useState(hCt);_.useEffect(()=>{var d,u;s&&l(n?{name:n.name,description:n.description||"",agent_split_pct:String(n.agent_split_pct),team_split_pct:n.team_split_pct?String(n.team_split_pct):"",cap_amount:((d=n.cap_amount)==null?void 0:d.toString())||"",monthly_fee:n.monthly_fee?String(n.monthly_fee):"",transaction_fee:n.transaction_fee?String(n.transaction_fee):"",franchise_fee_pct:n.franchise_fee_pct?String(n.franchise_fee_pct):"",referral_fee_pct:((u=n.referral_fee_pct)==null?void 0:u.toString())||"",commission_calc_method:n.commission_calc_method||"standard",is_active:n.is_active}:hCt)},[s,n]);const o=(d,u)=>l(h=>({...h,[d]:u})),c=()=>{r({id:n==null?void 0:n.id,name:i.name.trim(),description:i.description.trim()||null,agent_split_pct:parseFloat(i.agent_split_pct)||0,team_split_pct:i.team_split_pct?Math.min(100,Math.max(0,parseFloat(i.team_split_pct)||0)):0,cap_amount:i.cap_amount?parseFloat(i.cap_amount):null,monthly_fee:i.monthly_fee?parseFloat(i.monthly_fee):0,transaction_fee:i.transaction_fee?parseFloat(i.transaction_fee):0,franchise_fee_pct:i.franchise_fee_pct?parseFloat(i.franchise_fee_pct):0,referral_fee_pct:i.referral_fee_pct?parseFloat(i.referral_fee_pct):null,commission_calc_method:i.commission_calc_method,is_active:i.is_active})};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:n?"Edit commission plan":"New commission plan"}),e.jsx(_r,{children:n?"Saving creates a new version — the previous terms stay on record.":'A named plan you can assign to agents, e.g. "70/30 with $16K cap".'})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-name",children:"Plan name"}),e.jsx(pe,{id:"plan-name",value:i.name,onChange:d=>o("name",d.target.value),placeholder:"70/30 split"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-desc",children:"Description (optional)"}),e.jsx(Ps,{id:"plan-desc",value:i.description,onChange:d=>o("description",d.target.value),rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-split",children:"Agent split %"}),e.jsx(pe,{id:"plan-split",type:"number",min:"0",max:"100",step:"0.5",value:i.agent_split_pct,onChange:d=>o("agent_split_pct",d.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Brokerage keeps ",Math.max(0,100-(parseFloat(i.agent_split_pct)||0)),"%"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-cap",children:"Annual cap ($)"}),e.jsx(pe,{id:"plan-cap",type:"number",min:"0",value:i.cap_amount,onChange:d=>o("cap_amount",d.target.value),placeholder:"No cap"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Total brokerage takes before 100%"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-monthly",children:"Monthly desk fee ($)"}),e.jsx(pe,{id:"plan-monthly",type:"number",min:"0",value:i.monthly_fee,onChange:d=>o("monthly_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-txn",children:"Per-transaction fee ($)"}),e.jsx(pe,{id:"plan-txn",type:"number",min:"0",value:i.transaction_fee,onChange:d=>o("transaction_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-franchise",children:"Franchise fee %"}),e.jsx(pe,{id:"plan-franchise",type:"number",min:"0",step:"0.1",value:i.franchise_fee_pct,onChange:d=>o("franchise_fee_pct",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-referral",children:"Default referral fee %"}),e.jsx(pe,{id:"plan-referral",type:"number",min:"0",step:"0.1",value:i.referral_fee_pct,onChange:d=>o("referral_fee_pct",d.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-team",children:"Team split %"}),e.jsx(pe,{id:"plan-team",type:"number",min:"0",max:"100",step:"0.5",value:i.team_split_pct,onChange:d=>o("team_split_pct",d.target.value),placeholder:"0"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only applies to agents on a team"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Calculation method"}),e.jsxs(ls,{value:i.commission_calc_method,onValueChange:d=>o("commission_calc_method",d),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"standard",children:"Standard — all fees off gross commission"}),e.jsx(He,{value:"referral_first",children:"Referral first — split applies after referral fee"})]})]})]}),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:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only active plans can be assigned to agents"})]}),e.jsx(mn,{checked:i.is_active,onCheckedChange:d=>o("is_active",d)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{onClick:c,disabled:a||!i.name.trim(),children:a?"Saving…":n?"Save new version":"Create plan"})]})]})})}const mCt=()=>new Date().toISOString().slice(0,10);function xir({open:s,onOpenChange:t,agent:n,plans:r,onAssign:a,saving:i}){const[l,o]=_.useState(""),[c,d]=_.useState(mCt()),[u,h]=_.useState(""),[m,p]=_.useState("");return _.useEffect(()=>{var f,g,v,y,b;s&&(o(((f=n==null?void 0:n.plan)==null?void 0:f.id)||((g=r[0])==null?void 0:g.id)||""),d(((v=n==null?void 0:n.assignment)==null?void 0:v.start_date)||mCt()),h(((y=n==null?void 0:n.assignment)==null?void 0:y.anniversary_date)||""),p(((b=n==null?void 0:n.assignment)==null?void 0:b.notes)||""))},[s,n,r]),e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{children:[n!=null&&n.assignment?"Change plan":"Assign plan"," — ",n==null?void 0:n.name]}),e.jsx(_r,{children:n!=null&&n.assignment?"The current plan ends on the new start date; cap tracking starts fresh.":"The plan pre-fills commission splits and fees on the agent’s new deals."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Commission plan"}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose a plan"})}),e.jsx(as,{children:r.map(f=>e.jsxs(He,{value:f.id,children:[f.name," — ",f.agent_split_pct,"/",Math.max(0,100-f.agent_split_pct),f.cap_amount?` · $${f.cap_amount.toLocaleString()} cap`:" · no cap"]},f.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ap-start",children:"Start date"}),e.jsx(pe,{id:"ap-start",type:"date",value:c,onChange:f=>d(f.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ap-anniv",children:"Anniversary date"}),e.jsx(pe,{id:"ap-anniv",type:"date",value:u,onChange:f=>h(f.target.value)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Cap resets yearly on this date (defaults to start date)"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ap-notes",children:"Notes (optional)"}),e.jsx(Ps,{id:"ap-notes",rows:2,value:m,onChange:f=>p(f.target.value),placeholder:"e.g. Negotiated 80/20 for first year"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{disabled:i||!l||!c||!n,onClick:()=>n&&a({agent_user_id:n.agentId,plan_id:l,start_date:c,anniversary_date:u||null,notes:m.trim()||null}),children:i?"Saving…":"Save assignment"})]})]})})}const yDe=U,o3e={monthly_fee:"Monthly desk fee",transaction_fee:"Transaction fee",adjustment:"Adjustment",payment:"Payment received"};function gir(s){return rt({queryKey:["fee-ledger",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await yDe.from("agent_fee_ledger").select("*").eq("brokerage_id",s).order("entry_date",{ascending:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}function yir(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{const{error:a}=await yDe.from("agent_fee_ledger").insert({agent_user_id:r.agent_user_id,brokerage_id:s,entry_type:r.entry_type,amount:r.amount,entry_date:r.entry_date,note:r.note||null,created_by:(n==null?void 0:n.id)??null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),ne.success("Ledger entry added")},onError:r=>ne.error(r.message||"Could not add entry")})}function vir(s){const t=$t();return mt({mutationFn:async n=>{const{error:r}=await yDe.from("agent_fee_ledger").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),ne.success("Entry removed")},onError:n=>ne.error(n.message||"Could not remove entry")})}function bir(s){const t=$t(),{user:n}=hs();return mt({mutationFn:async r=>{const a=`${r.month}-01`,i=new Set(r.existing.filter(c=>c.entry_type==="monthly_fee"&&(c.entry_date||"").slice(0,7)===r.month).map(c=>c.agent_user_id)),l=r.agents.filter(c=>c.monthlyFee>0&&!i.has(c.agentId)).map(c=>({agent_user_id:c.agentId,brokerage_id:s,entry_type:"monthly_fee",amount:c.monthlyFee,entry_date:a,note:`Desk fee ${r.month}`,created_by:(n==null?void 0:n.id)??null}));if(!l.length)return 0;const{error:o}=await yDe.from("agent_fee_ledger").insert(l);if(o)throw o;return l.length},onSuccess:r=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),ne.success(r?`Posted ${r} desk fee${r===1?"":"s"}`:"All desk fees already posted")},onError:r=>ne.error(r.message||"Could not post desk fees")})}const _ir=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Gas(s,t){return s.filter(n=>{const r=ZS(n.actual_close_date);return!!r&&r.y===t})}function Was(s,t,n,r=[]){const a=Gas(s,n),i=Array.from({length:12},(c,d)=>({key:`${n}-${String(d+1).padStart(2,"0")}`,label:_ir[d],companyDollar:0,gci:0,deals:0})),l=new Map;r.forEach(c=>l.set(c.agentId,{userId:c.agentId,name:c.name,avatarUrl:c.avatarUrl,closedDeals:0,volume:0,gci:0,companyDollar:0,agentShare:0,feesCharged:0,feesPaid:0,balance:0}));const o={year:n,closedDeals:a.length,volume:0,gci:0,companyDollar:0,agentShare:0,feesOutstanding:0,months:i,agents:[]};return a.forEach(c=>{const d=qG(c),u=VG(c),h=Kse(c),m=Math.max(0,u-h);o.volume+=d,o.gci+=u,o.companyDollar+=h,o.agentShare+=m;const p=ZS(c.actual_close_date);if(p){const g=i[p.m-1];g&&(g.companyDollar+=h,g.gci+=u,g.deals+=1)}const f=l.get(c.owner_user_id)||{userId:c.owner_user_id,name:c.agent_name||"Agent",avatarUrl:c.agent_avatar_url,closedDeals:0,volume:0,gci:0,companyDollar:0,agentShare:0,feesCharged:0,feesPaid:0,balance:0};f.closedDeals+=1,f.volume+=d,f.gci+=u,f.companyDollar+=h,f.agentShare+=m,l.set(c.owner_user_id,f)}),t.forEach(c=>{const d=Number(c.amount)||0,u=l.get(c.agent_user_id);u&&(c.entry_type==="payment"?u.feesPaid+=Math.abs(d):u.feesCharged+=d)}),l.forEach(c=>{c.balance=c.feesCharged-c.feesPaid,o.feesOutstanding+=c.balance}),o.agents=Array.from(l.values()).filter(c=>c.closedDeals>0||c.feesCharged>0||c.feesPaid>0).sort((c,d)=>d.companyDollar-c.companyDollar||d.volume-c.volume),o}const wir=[64,110,113],QBe=[42,76,100],$T=[110,118,125],Cw=s=>`$${Math.round(s).toLocaleString("en-US")}`,pCt=s=>{const t=ZS(s);return t?`${String(t.m).padStart(2,"0")}/${String(t.d).padStart(2,"0")}/${String(t.y).slice(2)}`:"—"},fCt=(s,t,n)=>{let r=t||"";for(;r.length>3&&s.getTextWidth(r)>n;)r=r.slice(0,-1);return r===t?r:`${r.trim()}…`};function jir(s){const t=new Po({unit:"pt",format:"letter"}),n=t.internal.pageSize.getWidth(),r=t.internal.pageSize.getHeight(),a=48;let i=0;t.setFillColor(...QBe),t.rect(0,0,n,92,"F"),t.setTextColor(255,255,255),t.setFont("helvetica","bold"),t.setFontSize(18),t.text(s.brokerageName||"Brokerage",a,40),t.setFont("helvetica","normal"),t.setFontSize(11),t.text(`Agent commission statement · ${s.year}`,a,60),t.setFontSize(9),t.text(`Generated ${new Date().toLocaleDateString("en-US")}`,n-a,60,{align:"right"}),i=122,t.setTextColor(0,0,0),t.setFont("helvetica","bold"),t.setFontSize(14),t.text(s.agentName,a,i),t.setFont("helvetica","normal"),t.setFontSize(9),t.setTextColor(...$T);const l=[s.agentEmail,s.planName?`Plan: ${s.planName}`:null,s.planSummary].filter(Boolean).join(" · ");l&&t.text(l,a,i+14),i+=40;const o=s.deals.reduce((y,b)=>{const w=VG(b),S=Kse(b);return y.volume+=qG(b),y.gci+=w,y.company+=S,y.agent+=Math.max(0,w-S),y},{volume:0,gci:0,company:0,agent:0}),c=s.ledger.filter(y=>y.entry_type!=="payment").reduce((y,b)=>y+(Number(b.amount)||0),0),d=s.ledger.filter(y=>y.entry_type==="payment").reduce((y,b)=>y+Math.abs(Number(b.amount)||0),0),u=c-d,h=[{label:"Closed sides",value:String(s.deals.length)},{label:"Volume",value:Cw(o.volume)},{label:"Gross commission",value:Cw(o.gci)},{label:"Agent share",value:Cw(o.agent)}],m=(n-a*2-18)/4;if(h.forEach((y,b)=>{const w=a+b*(m+6);t.setDrawColor(224,228,232),t.setFillColor(248,250,250),t.roundedRect(w,i,m,48,6,6,"FD"),t.setFontSize(8),t.setTextColor(...$T),t.text(y.label,w+10,i+17),t.setFontSize(13),t.setFont("helvetica","bold"),t.setTextColor(...QBe),t.text(y.value,w+10,i+36),t.setFont("helvetica","normal")}),i+=72,s.capAmount){const y=Math.min(100,(s.capProgress||0)/s.capAmount*100);t.setFontSize(9),t.setTextColor(...$T),t.text(`Cap progress: ${Cw(s.capProgress||0)} of ${Cw(s.capAmount)} (${Math.round(y)}%)`,a,i);const b=n-a*2;t.setFillColor(232,236,238),t.roundedRect(a,i+6,b,7,3.5,3.5,"F"),t.setFillColor(...wir),t.roundedRect(a,i+6,Math.max(2,b*y/100),7,3.5,3.5,"F"),i+=34}const p=y=>{i>r-120&&(t.addPage(),i=60),t.setFont("helvetica","bold"),t.setFontSize(11),t.setTextColor(...QBe),t.text(y,a,i),t.setFont("helvetica","normal"),i+=14},f=()=>{t.setDrawColor(234,238,240),t.line(a,i,n-a,i)};p("Closed transactions");const g=[a,a+62,a+280,a+360,a+440];t.setFontSize(8),t.setTextColor(...$T),t.text("Closed",g[0],i),t.text("Property",g[1],i),t.text("Volume",g[2],i,{align:"right"}),t.text("GCI",g[3],i,{align:"right"}),t.text("Agent share",n-a,i,{align:"right"}),i+=5,f(),i+=13,t.setTextColor(30,34,38),t.setFontSize(9),s.deals.length||(t.setTextColor(...$T),t.text("No closed transactions in this period.",a,i),i+=18,t.setTextColor(30,34,38)),s.deals.slice().sort((y,b)=>(y.actual_close_date||"").localeCompare(b.actual_close_date||"")).forEach(y=>{i>r-90&&(t.addPage(),i=60);const b=VG(y),w=Math.max(0,b-Kse(y));t.text(pCt(y.actual_close_date),g[0],i),t.text(fCt(t,y.property_address||y.deal_name||"Transaction",205),g[1],i),t.text(Cw(qG(y)),g[2],i,{align:"right"}),t.text(Cw(b),g[3],i,{align:"right"}),t.text(Cw(w),n-a,i,{align:"right"}),i+=16}),i+=4,f(),i+=15,t.setFont("helvetica","bold"),t.text("Totals",g[1],i),t.text(Cw(o.volume),g[2],i,{align:"right"}),t.text(Cw(o.gci),g[3],i,{align:"right"}),t.text(Cw(o.agent),n-a,i,{align:"right"}),t.setFont("helvetica","normal"),i+=34,p("Fees & payments"),t.setFontSize(8),t.setTextColor(...$T),t.text("Date",g[0],i),t.text("Item",g[1],i),t.text("Amount",n-a,i,{align:"right"}),i+=5,f(),i+=13,t.setFontSize(9),t.setTextColor(30,34,38),s.ledger.length||(t.setTextColor(...$T),t.text("No fees or payments recorded.",a,i),i+=18,t.setTextColor(30,34,38)),s.ledger.slice().sort((y,b)=>(y.entry_date||"").localeCompare(b.entry_date||"")).forEach(y=>{i>r-90&&(t.addPage(),i=60);const b=Number(y.amount)||0,w=y.entry_type==="payment",S=o3e[y.entry_type]||y.entry_type;t.text(pCt(y.entry_date),g[0],i),t.text(fCt(t,y.note?`${S} — ${y.note}`:S,330),g[1],i),t.text(`${w?"-":""}${Cw(Math.abs(b))}`,n-a,i,{align:"right"}),i+=16}),i+=4,f(),i+=15,t.setFont("helvetica","bold"),t.text("Balance due to brokerage",g[1],i),t.text(Cw(u),n-a,i,{align:"right"});const v=t.getNumberOfPages();for(let y=1;y<=v;y++)t.setPage(y),t.setFont("helvetica","normal"),t.setFontSize(8),t.setTextColor(...$T),t.text("Estimated figures based on recorded transactions and plan terms. Not an accounting document.",a,r-28),t.text(`Page ${y} of ${v}`,n-a,r-28,{align:"right"});return t}function Nir(s){const t=jir(s),n=s.agentName.replace(/[^a-z0-9]+/gi,"-").toLowerCase();t.save(`statement-${n}-${s.year}.pdf`)}const xCt=s=>`$${Math.round(s).toLocaleString()}`;function kir({deals:s,ledger:t,roster:n,brokerageName:r,loading:a}){const i=new Date().getFullYear(),[l,o]=_.useState(String(i)),c=_.useMemo(()=>{const m=new Set([i]);return s.forEach(p=>{const f=ZS(p.actual_close_date);f&&m.add(f.y)}),Array.from(m).sort((p,f)=>f-p)},[s,i]),d=_.useMemo(()=>Was(s,t,Number(l),n.map(m=>({agentId:m.agentId,name:m.name,avatarUrl:m.avatarUrl}))),[s,t,n,l]),u=Math.max(1,...d.months.map(m=>m.companyDollar)),h=m=>{var v,y,b;const p=n.find(w=>w.agentId===m),f=d.agents.find(w=>w.userId===m),g=Gas(s,Number(l)).filter(w=>w.owner_user_id===m);Nir({brokerageName:r,agentName:(p==null?void 0:p.name)||(f==null?void 0:f.name)||"Agent",agentEmail:(p==null?void 0:p.email)||null,planName:((v=p==null?void 0:p.plan)==null?void 0:v.name)||null,planSummary:p!=null&&p.plan?`${p.plan.agent_split_pct}/${Math.max(0,100-p.plan.agent_split_pct)} split`:null,year:Number(l),deals:g,ledger:t.filter(w=>w.agent_user_id===m&&(w.entry_date||"").slice(0,4)===l),capAmount:((y=p==null?void 0:p.plan)==null?void 0:y.cap_amount)??null,capProgress:((b=p==null?void 0:p.progress)==null?void 0:b.cap_progress)??null})};return a?e.jsxs("div",{className:"space-y-3",children:[e.jsx(ln,{className:"h-24 w-full rounded-xl"}),e.jsx(ln,{className:"h-64 w-full rounded-xl"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Closed business and company dollar earned, by month and by agent."}),e.jsxs(ls,{value:l,onValueChange:o,children:[e.jsx(rs,{className:"w-32",children:e.jsx(cs,{})}),e.jsx(as,{children:c.map(m=>e.jsx(He,{value:String(m),children:m},m))})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[{label:"Closed sides",value:String(d.closedDeals)},{label:"Closed volume",value:tp(d.volume)},{label:"Gross commission",value:tp(d.gci)},{label:"Company dollar",value:tp(d.companyDollar),accent:!0}].map(m=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:m.label}),e.jsx("p",{className:`text-2xl font-bold tabular-nums tracking-tight ${m.accent?"text-teal-600":""}`,children:m.value})]})},m.label))}),e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(kl,{className:"h-4 w-4 text-teal-600"})," Company dollar by month"]}),e.jsx(En,{children:"Brokerage split, franchise fees and transaction fees on closed deals"})]}),e.jsx(Le,{children:e.jsx("div",{className:"flex h-40 items-end gap-1.5",children:d.months.map(m=>e.jsxs("div",{className:"group flex flex-1 flex-col items-center gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium tabular-nums text-muted-foreground opacity-0 transition group-hover:opacity-100",children:tp(m.companyDollar)}),e.jsx("div",{className:"w-full rounded-t bg-teal-500/80 transition group-hover:bg-teal-600",style:{height:`${Math.max(2,m.companyDollar/u*110)}px`},title:`${m.label}: ${xCt(m.companyDollar)} from ${m.deals} closed`}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:m.label})]},m.key))})})]}),e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"Agent production & statements"}),e.jsx(En,{children:"Download a per-agent statement with closed deals, fees and balance"})]}),e.jsx(Le,{className:"pt-1",children:d.agents.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No closed deals recorded yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[640px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Closed"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Volume"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"GCI"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Company $"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Balance"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:d.agents.map(m=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(ja,{className:"h-7 w-7",children:[e.jsx(xi,{src:m.avatarUrl||void 0,alt:m.name}),e.jsx(Na,{className:"text-[10px]",children:m.name.slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"truncate font-medium",children:m.name})]})}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.closedDeals}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:tp(m.volume)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:tp(m.gci)}),e.jsx("td",{className:"py-2.5 text-right font-medium tabular-nums text-teal-700",children:tp(m.companyDollar)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.balance>0?e.jsx(ze,{variant:"outline",className:"border-amber-300 text-amber-700",children:xCt(m.balance)}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2.5 text-right",children:e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>h(m.userId),children:[e.jsx(xj,{className:"mr-1.5 h-4 w-4"})," Statement"]})})]},m.userId))})]})})})]})]})}const gCt=s=>`$${Math.round(s).toLocaleString()}`,Sir=()=>new Date().toISOString().slice(0,10),Cir=()=>new Date().toISOString().slice(0,7);function Air({brokerageId:s,ledger:t,roster:n,loading:r}){const a=yir(s),i=vir(s),l=bir(s),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState("adjustment"),[p,f]=_.useState(""),[g,v]=_.useState(Sir()),[y,b]=_.useState(""),[w,S]=_.useState(Cir()),[C,E]=_.useState("all"),P=V=>{var H;return((H=n.find(K=>K.agentId===V))==null?void 0:H.name)||"Agent"},M=_.useMemo(()=>{const V=new Map;return t.forEach(H=>{const K=Number(H.amount)||0,Z=H.entry_type==="payment"?-Math.abs(K):K;V.set(H.agent_user_id,(V.get(H.agent_user_id)||0)+Z)}),V},[t]),I=_.useMemo(()=>Array.from(M.values()).reduce((V,H)=>V+Math.max(0,H),0),[M]),D=_.useMemo(()=>t.filter(V=>V.entry_type==="payment").reduce((V,H)=>V+Math.abs(Number(H.amount)||0),0),[t]),F=_.useMemo(()=>C==="all"?t:t.filter(V=>V.agent_user_id===C),[t,C]),q=n.filter(V=>V.plan&&(V.plan.monthly_fee||0)>0).map(V=>({agentId:V.agentId,name:V.name,monthlyFee:V.plan.monthly_fee})),G=()=>{const V=parseFloat(p);!d||!Number.isFinite(V)||V<=0||a.mutate({agent_user_id:d,entry_type:h,amount:V,entry_date:g,note:y},{onSuccess:()=>{c(!1),f(""),b("")}})};return r?e.jsx(ln,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Outstanding fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:tp(I)})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Payments recorded"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:tp(D)})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents with a desk fee"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:q.length})]})})]}),e.jsxs(be,{className:"border-border/60",children:[e.jsx(_t,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:"Fee ledger"}),e.jsx(En,{children:"Desk fees, transaction fees, adjustments and payments received"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(pe,{type:"month",value:w,onChange:V=>S(V.target.value),className:"h-9 w-[150px]"}),e.jsxs(z,{variant:"outline",size:"sm",disabled:l.isPending||q.length===0,onClick:()=>l.mutate({month:w,agents:q,existing:t}),children:[e.jsx(v0,{className:"mr-1.5 h-4 w-4"})," Post desk fees"]}),e.jsxs(z,{size:"sm",onClick:()=>c(!0),children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," Add entry"]})]})]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs(ls,{value:C,onValueChange:E,children:[e.jsx(rs,{className:"h-9 w-full sm:w-64",children:e.jsx(cs,{placeholder:"All agents"})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All agents"}),n.map(V=>e.jsxs(He,{value:V.agentId,children:[V.name,M.get(V.agentId)?` · ${gCt(M.get(V.agentId))}`:""]},V.agentId))]})]}),F.length===0?e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No ledger entries yet. Post this month's desk fees or add an entry."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[620px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Date"}),e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-left font-medium",children:"Item"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Amount"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:F.map(V=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5 tabular-nums text-muted-foreground",children:V.entry_date}),e.jsx("td",{className:"py-2.5 font-medium",children:P(V.agent_user_id)}),e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(ze,{variant:V.entry_type==="payment"?"secondary":"outline",children:o3e[V.entry_type]||V.entry_type}),V.note&&e.jsx("span",{className:"text-xs text-muted-foreground",children:V.note})]})}),e.jsxs("td",{className:`py-2.5 text-right font-medium tabular-nums ${V.entry_type==="payment"?"text-emerald-600":""}`,children:[V.entry_type==="payment"?"-":"",gCt(Math.abs(Number(V.amount)||0))]}),e.jsx("td",{className:"py-2.5 text-right",children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>i.mutate(V.id),children:e.jsx(Cn,{className:"h-4 w-4"})})})]},V.id))})]})})]})]}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add ledger entry"}),e.jsx(_r,{children:"Record a fee charged to an agent, or a payment they made."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Agent"}),e.jsxs(ls,{value:d,onValueChange:u,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose an agent"})}),e.jsx(as,{children:n.map(V=>e.jsx(He,{value:V.agentId,children:V.name},V.agentId))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ls,{value:h,onValueChange:V=>m(V),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:Object.keys(o3e).map(V=>e.jsx(He,{value:V,children:o3e[V]},V))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Amount"}),e.jsx(pe,{type:"number",min:"0",step:"0.01",value:p,onChange:V=>f(V.target.value),placeholder:"0.00"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Date"}),e.jsx(pe,{type:"date",value:g,onChange:V=>v(V.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Note (optional)"}),e.jsx(Ps,{rows:2,value:y,onChange:V=>b(V.target.value)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(z,{onClick:G,disabled:a.isPending||!d||!p,children:"Add entry"})]})]})})]})}const Eir={license:WQ,eo:Ch,anniversary:Ix,birthday:Hf},Tir=[30,60,90,180];function Mir({records:s,roster:t,deals:n,loading:r}){const[a,i]=_.useState(90),l=_.useMemo(()=>t.map(v=>({agentId:v.agentId,name:v.name,avatarUrl:v.avatarUrl})),[t]),o=_.useMemo(()=>$as(s,l,a),[s,l,a]),c=o.filter(v=>v.expired),d=o.filter(v=>!v.expired&&(v.kind==="license"||v.kind==="eo")),u=o.filter(v=>v.kind==="anniversary"||v.kind==="birthday"),h=_.useMemo(()=>{const v=new Map(s.map(y=>[y.agent_user_id,y]));return t.filter(y=>{const b=v.get(y.agentId);return!(b!=null&&b.license_expiration)||!(b!=null&&b.eo_expiration)})},[s,t]),m=new Date().getFullYear(),p=_.useMemo(()=>Was(n,[],m,l).agents,[n,l,m]),f=_.useMemo(()=>Far(s,l,p),[s,l,p]);if(r)return e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((v,y)=>e.jsx(ln,{className:"h-32 w-full rounded-xl"},y))});const g=(v,y)=>{const b=Eir[v.kind];return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:v.avatarUrl||void 0,alt:v.agentName}),e.jsx(Na,{className:"text-[10px]",children:v.agentName.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:v.agentName}),e.jsxs("p",{className:"flex items-center gap-1.5 truncate text-[11px] text-muted-foreground",children:[e.jsx(b,{className:"h-3 w-3"}),Rar[v.kind],v.detail?` · ${v.detail}`:""]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-xs font-medium tabular-nums",children:Tit(v.dueDate)}),v.expired?e.jsxs(ze,{variant:"destructive",className:"mt-0.5 h-5 text-[10px]",children:[Math.abs(v.daysUntil)," days overdue"]}):e.jsx("p",{className:`text-[11px] ${v.daysUntil<=30?"font-medium text-amber-600":"text-muted-foreground"}`,children:v.daysUntil===0?"Today":`in ${v.daysUntil} days`})]})]},`${v.agentId}-${v.kind}-${y}`)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-red-500/10 text-red-600",children:e.jsx(nl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Expired"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:c.length})]})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600",children:e.jsx(Ud,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Due in ",a," days"]}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:d.length})]})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-slate-500/10 text-slate-600",children:e.jsx(Ch,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Missing license or E&O date"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:h.length})]})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"mr-1 text-xs text-muted-foreground",children:"Look ahead:"}),Tir.map(v=>e.jsxs(z,{size:"sm",variant:a===v?"default":"outline",onClick:()=>i(v),children:[v," days"]},v))]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"License & E&O renewals"}),e.jsx(En,{children:"Expired items first, then everything due inside your window"})]}),e.jsx(Le,{className:"space-y-0.5 pt-2",children:c.length===0&&d.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["Nothing expiring in the next ",a," days."]}):[...c,...d].map(g)})]}),e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"Anniversaries & birthdays"}),e.jsx(En,{children:"Reach out before the day — retention lives here"})]}),e.jsx(Le,{className:"space-y-0.5 pt-2",children:u.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["No milestones in the next ",a," days."]}):u.map(g)})]})]}),e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsxs(Nt,{className:"flex items-center gap-2 text-base",children:[e.jsx(bu,{className:"h-4 w-4 text-teal-600"})," Production goals — ",m]}),e.jsx(En,{children:"Goal amounts come from each agent's record; progress uses closed volume this year"})]}),e.jsx(Le,{className:"space-y-2 pt-2",children:f.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No production goals set yet — add one on an agent's record in Onboarding."}):f.map(v=>e.jsxs("div",{className:"rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ja,{className:"h-8 w-8 shrink-0",children:[e.jsx(xi,{src:v.avatarUrl||void 0,alt:v.name}),e.jsx(Na,{className:"text-[10px]",children:v.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:v.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[tp(v.volume)," of ",tp(v.goal)," · ",v.closedDeals," closed"]})]}),e.jsxs("span",{className:"shrink-0 text-sm font-semibold tabular-nums",children:[Math.round(v.pct),"%"]})]}),e.jsx(Di,{value:Math.min(100,v.pct),className:"mt-2 h-1.5"})]},v.agentId))})]})]})}const Xde=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`;function Pir({open:s,onOpenChange:t,draft:n,roster:r,onSave:a,saving:i}){const[l,o]=_.useState(n);_.useEffect(()=>o(n),[n]);const c=_.useMemo(()=>HG(l||{}),[l]);if(!l)return null;const d=m=>o({...l,...m}),u=(m,p,f)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:p}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",value:l[m]??0,onChange:g=>d({[m]:parseFloat(g.target.value)||0})}),f&&e.jsx("span",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:f})]})]}),h=(m,p)=>{const f=[...l.line_items||[]];f[m]={...f[m],...p},d({line_items:f})};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"max-h-[90vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:l.id?"Edit disbursement":"New disbursement"}),e.jsx(_r,{children:"Set the closing details and how the commission is split. The CDA is generated from these numbers."})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Agent"}),e.jsxs(ls,{value:l.agent_user_id,onValueChange:m=>d({agent_user_id:m}),children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"Choose an agent"})}),e.jsx(as,{children:r.map(m=>e.jsx(He,{value:m.agentId,children:m.name},m.agentId))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Closing date"}),e.jsx(pe,{type:"date",value:l.closing_date||"",onChange:m=>d({closing_date:m.target.value||null})})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(ee,{className:"text-xs",children:"Property"}),e.jsx(pe,{value:l.property_address||"",onChange:m=>d({property_address:m.target.value}),placeholder:"123 Main St, Nashville TN"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Escrow / title company"}),e.jsx(pe,{value:l.escrow_company||"",onChange:m=>d({escrow_company:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Escrow / file number"}),e.jsx(pe,{value:l.escrow_number||"",onChange:m=>d({escrow_number:m.target.value})})]}),u("sale_price","Sale price","$"),u("gross_commission","Gross commission","$"),u("agent_split_pct","Agent split","%"),u("franchise_fee_pct","Franchise fee","%"),u("transaction_fee","Transaction fee","$"),u("referral_fee_pct","Referral fee","%"),u("referral_amount","Referral flat amount","$"),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Referral paid to"}),e.jsx(pe,{value:l.referral_payee||"",onChange:m=>d({referral_payee:m.target.value})})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Other charges & credits"}),e.jsxs(z,{type:"button",size:"sm",variant:"outline",onClick:()=>d({line_items:[...l.line_items||[],{label:"",amount:0}]}),children:[e.jsx(sn,{className:"mr-1 h-3.5 w-3.5"})," Add line"]})]}),(l.line_items||[]).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Positive amounts are deducted from the agent; use a negative amount for a credit."}),(l.line_items||[]).map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"flex-1",value:m.label,placeholder:"E&O fee, sign rental, admin fee…",onChange:f=>h(p,{label:f.target.value})}),e.jsx(pe,{className:"w-32",type:"number",value:m.amount,onChange:f=>h(p,{amount:parseFloat(f.target.value)||0})}),e.jsx(z,{type:"button",size:"icon",variant:"ghost",onClick:()=>d({line_items:(l.line_items||[]).filter((f,g)=>g!==p)}),children:e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground"})})]},p))]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Notes for escrow"}),e.jsx(Ps,{rows:2,value:l.notes||"",onChange:m=>d({notes:m.target.value}),placeholder:"Wire instructions, check delivery, anything escrow should know"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 rounded-lg bg-muted/50 p-3 sm:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Gross"}),e.jsx("p",{className:"font-semibold tabular-nums",children:Xde(c.gross)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Referral"}),e.jsx("p",{className:"font-semibold tabular-nums",children:Xde(c.referral)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-semibold tabular-nums text-teal-600",children:Xde(c.companyDollar+c.otherCharges)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agent net"}),e.jsx("p",{className:"font-semibold tabular-nums text-emerald-600",children:Xde(c.agentNet)})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(z,{disabled:!l.agent_user_id||i,onClick:()=>a(l),children:i?"Saving…":"Save disbursement"})]})]})})}const JBe=[42,76,100],yCt=[64,110,113],e$e=[110,118,125],Qde=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString("en-US")}`,vCt=s=>{const t=ZS(s);return t?new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t.y,t.m-1,t.d))):"—"};function Lir(s){const t=s.disbursement,n=HG(t),r=new Po({unit:"pt",format:"letter"}),a=r.internal.pageSize.getWidth(),i=r.internal.pageSize.getHeight(),l=48;r.setFillColor(...JBe),r.rect(0,0,a,86,"F"),r.setTextColor(255,255,255),r.setFont("helvetica","bold"),r.setFontSize(16),r.text("Commission Disbursement Authorization",l,40),r.setFont("helvetica","normal"),r.setFontSize(10),r.text(s.brokerageName,l,60),r.text(`Issued ${vCt(new Date().toISOString().slice(0,10))}`,a-l,60,{align:"right"});let o=118;const c=(h,m,p,f)=>{r.setFontSize(8),r.setTextColor(...e$e),r.text(h.toUpperCase(),p,o),r.setFontSize(10.5),r.setTextColor(25,30,35),r.text(r.splitTextToSize(m||"—",f)[0],p,o+15)},d=(a-l*2)/2;c("Property",t.property_address||"—",l,d-12),c("Closing date",vCt(t.closing_date),l+d,d),o+=40,c("Escrow / title company",t.escrow_company||"—",l,d-12),c("Escrow / file number",t.escrow_number||"—",l+d,d),o+=40,c("Agent",s.agentName,l,d-12),c("Sale price",Qde(t.sale_price),l+d,d),o+=46,r.setDrawColor(224,228,232),r.line(l,o,a-l,o),o+=24,r.setFont("helvetica","bold"),r.setFontSize(11),r.setTextColor(...JBe),r.text("Disbursement of commission",l,o),r.setFont("helvetica","normal"),o+=20;const u=(h,m,p)=>{o>i-140&&(r.addPage(),o=60),r.setFont("helvetica",p!=null&&p.bold?"bold":"normal"),r.setFontSize(10);const f=p!=null&&p.teal?yCt:[25,30,35];r.setTextColor(f[0],f[1],f[2]),r.text(h,l,o),r.text(Qde(m),a-l,o,{align:"right"}),o+=8,r.setDrawColor(238,241,243),r.line(l,o,a-l,o),o+=14,r.setFont("helvetica","normal")};return u("Gross commission due at closing",n.gross,{bold:!0}),n.referral>0&&u(`Referral fee${t.referral_payee?` — ${t.referral_payee}`:""}`,-n.referral),n.referral>0&&u("Adjusted gross commission",n.adjustedGross,{bold:!0}),u(`Brokerage split (${Math.round(100-Number(t.agent_split_pct||0))}% to brokerage)`,-n.brokerageSplit),n.franchiseFee>0&&u(`Franchise fee (${t.franchise_fee_pct}%)`,-n.franchiseFee),n.transactionFee>0&&u("Transaction fee",-n.transactionFee),(t.line_items||[]).forEach(h=>u(h.label||"Adjustment",-Number(h.amount||0))),o+=6,r.setFillColor(246,249,249),r.roundedRect(l,o-4,a-l*2,76,6,6,"F"),o+=16,r.setFont("helvetica","bold"),r.setFontSize(11),r.setTextColor(...JBe),r.text(`Pay to ${s.brokerageName}`,l+14,o),r.text(Qde(n.companyDollar+n.otherCharges),a-l-14,o,{align:"right"}),o+=24,r.setTextColor(...yCt),r.text(`Pay to ${s.agentName}`,l+14,o),r.text(Qde(n.agentNet),a-l-14,o,{align:"right"}),r.setFont("helvetica","normal"),o+=52,t.notes&&(r.setFontSize(9),r.setTextColor(...e$e),r.splitTextToSize(t.notes,a-l*2).forEach(h=>{r.text(h,l,o),o+=12}),o+=10),o>i-130&&(r.addPage(),o=80),o=Math.max(o,i-150),r.setDrawColor(150,158,165),r.line(l,o,l+220,o),r.line(a-l-160,o,a-l,o),r.setFontSize(8),r.setTextColor(...e$e),r.text("Authorized broker signature",l,o+13),r.text("Date",a-l-160,o+13),r.setFontSize(7.5),r.text("This authorization instructs the escrow or title company to disburse the commission as set out above. Amounts are subject to the final settlement statement.",l,i-44,{maxWidth:a-l*2}),r}function Iir(s){const t=(s.disbursement.property_address||s.agentName||"cda").replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,48);Lir(s).save(`cda-${t}.pdf`)}const Dir=s=>{const t=s==null?"":String(s);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t},OI=s=>Math.round(s*100)/100,Rir=["Date","Ref Number","Name","Account","Memo","Debit","Credit"];function Fir(s,t){const n=[];return s.forEach((r,a)=>{const i=HG(r),l=r.closing_date||r.created_at.slice(0,10),o=r.escrow_number||`CDA-${String(a+1).padStart(4,"0")}`,c=t(r.agent_user_id),d=r.property_address||"Commission disbursement";n.push({date:l,refNumber:o,name:c,account:"Commission Income",memo:d,debit:"",credit:OI(i.gross)}),i.referral>0&&n.push({date:l,refNumber:o,name:r.referral_payee||"Referral partner",account:"Referral Fees",memo:d,debit:OI(i.referral),credit:""}),i.agentNet!==0&&n.push({date:l,refNumber:o,name:c,account:"Agent Commission Expense",memo:d,debit:OI(i.agentNet),credit:""}),i.franchiseFee>0&&n.push({date:l,refNumber:o,name:c,account:"Franchise Fees",memo:d,debit:OI(i.franchiseFee),credit:""}),(r.line_items||[]).forEach(h=>{const m=Number(h.amount)||0;m&&n.push({date:l,refNumber:o,name:c,account:h.label||"Agent Charges",memo:d,debit:m<0?OI(-m):"",credit:m>0?OI(m):""})});const u=OI(i.gross-i.referral-i.agentNet-i.franchiseFee);u!==0&&n.push({date:l,refNumber:o,name:c,account:"Undeposited Funds",memo:d,debit:u>0?u:"",credit:u<0?-u:""})}),n}function Oir(s){const t=[Rir.join(",")];return s.forEach(n=>t.push([n.date,n.refNumber,n.name,n.account,n.memo,n.debit,n.credit].map(Dir).join(","))),t.join(` `)}function zir(s,t,n=`quickbooks-disbursements-${new Date().toISOString().slice(0,10)}.csv`){const r=new Blob([Oir(Fir(s,t))],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(r),i=document.createElement("a");i.href=a,i.download=n,i.click(),URL.revokeObjectURL(a)}const Bir={draft:"bg-muted text-muted-foreground",approved:"bg-blue-500/10 text-blue-600",paid:"bg-emerald-500/10 text-emerald-600",void:"bg-destructive/10 text-destructive"},t$e=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`,$ir=s=>{const t=ZS(s);return t?`${t.m}/${t.d}/${String(t.y).slice(2)}`:"—"};function Uir({brokerageId:s,disbursements:t,deals:n,roster:r,brokerageName:a,loading:i}){const l=_ar(s),o=war(s),c=jar(s),[d,u]=_.useState(null),[h,m]=_.useState("all"),p=w=>{var S;return((S=r.find(C=>C.agentId===w))==null?void 0:S.name)||"Agent"},f=_.useMemo(()=>h==="all"?t:t.filter(w=>w.status===h),[t,h]),g=_.useMemo(()=>t.filter(S=>S.status!=="void").reduce((S,C)=>{const E=HG(C);return S.gross+=E.gross,S.company+=E.companyDollar+E.otherCharges,S.agent+=E.agentNet,C.status==="draft"&&(S.pending+=1),S},{gross:0,company:0,agent:0,pending:0}),[t]),v=_.useMemo(()=>{const w=new Set(t.map(S=>S.deal_id).filter(Boolean));return n.filter(S=>!!S.actual_close_date&&!w.has(S.deal_id)).slice(0,20)},[n,t]),y=w=>{var C;const S=((C=r.find(E=>E.agentId===w.owner_user_id))==null?void 0:C.plan)||null;u(bar(w,S))},b=()=>{var w,S,C,E,P,M,I;return{deal_id:null,agent_user_id:((w=r[0])==null?void 0:w.agentId)||"",status:"draft",property_address:"",escrow_company:null,escrow_number:null,closing_date:new Date().toISOString().slice(0,10),sale_price:0,gross_commission:0,agent_split_pct:((C=(S=r[0])==null?void 0:S.plan)==null?void 0:C.agent_split_pct)??70,franchise_fee_pct:((P=(E=r[0])==null?void 0:E.plan)==null?void 0:P.franchise_fee_pct)??0,transaction_fee:((I=(M=r[0])==null?void 0:M.plan)==null?void 0:I.transaction_fee)??0,referral_fee_pct:0,referral_amount:0,referral_payee:null,line_items:[],notes:null}};return i?e.jsx(ln,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-4",children:[e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Commission authorized"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:tp(g.gross)})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To the brokerage"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-teal-600",children:tp(g.company)})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To agents"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:tp(g.agent)})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting approval"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:g.pending})]})})]}),v.length>0&&e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"Closed deals without a disbursement"}),e.jsx(En,{children:"Start a CDA prefilled from the deal and the agent's commission plan"})]}),e.jsx(Le,{className:"flex flex-wrap gap-2 pt-2",children:v.map(w=>e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>y(w),children:[e.jsx(aq,{className:"mr-1.5 h-3.5 w-3.5"}),w.property_address||w.deal_name]},w.deal_id))})]}),e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"flex flex-row flex-wrap items-center justify-between gap-3 pb-2",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:"Disbursement authorizations"}),e.jsx(En,{children:"Approve, mark paid, print the CDA or export to QuickBooks"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ls,{value:h,onValueChange:w=>m(w),children:[e.jsx(rs,{className:"h-9 w-[150px]",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"all",children:"All statuses"}),Object.keys(YBe).map(w=>e.jsx(He,{value:w,children:YBe[w]},w))]})]}),e.jsxs(z,{size:"sm",variant:"outline",disabled:!f.length,onClick:()=>zir(f,p),children:[e.jsx(Ga,{className:"mr-1.5 h-4 w-4"})," QuickBooks CSV"]}),e.jsxs(z,{size:"sm",disabled:!r.length,onClick:()=>u(b()),children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," New CDA"]})]})]}),e.jsxs(Le,{className:"space-y-1 pt-2",children:[!f.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No disbursements yet — start one from a closed deal above."}),f.map(w=>{const S=HG(w);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:w.property_address||"Transaction"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p(w.agent_user_id)," · closed ",$ir(w.closing_date),w.escrow_number?` · file ${w.escrow_number}`:""]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Gross"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums",children:t$e(S.gross)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums text-teal-600",children:t$e(S.companyDollar+S.otherCharges)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agent"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums text-emerald-600",children:t$e(S.agentNet)})]}),e.jsx(ze,{variant:"secondary",className:Bir[w.status],children:YBe[w.status]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>Iir({disbursement:w,brokerageName:a,agentName:p(w.agent_user_id)}),children:[e.jsx($r,{className:"mr-1.5 h-3.5 w-3.5"})," CDA"]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{size:"icon",variant:"ghost",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[e.jsx(ua,{onClick:()=>u({...w}),children:"Edit"}),w.status==="draft"&&e.jsxs(ua,{onClick:()=>o.mutate({id:w.id,status:"approved"}),children:[e.jsx(Mr,{className:"mr-2 h-4 w-4"})," Approve"]}),w.status!=="paid"&&w.status!=="void"&&e.jsxs(ua,{onClick:()=>o.mutate({id:w.id,status:"paid"}),children:[e.jsx(w7,{className:"mr-2 h-4 w-4"})," Mark paid"]}),w.status!=="void"&&e.jsx(ua,{onClick:()=>o.mutate({id:w.id,status:"void"}),children:"Void"}),e.jsxs(ua,{className:"text-destructive",onClick:()=>c.mutate(w.id),children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]},w.id)})]})]}),e.jsx(Pir,{open:!!d,onOpenChange:w=>!w&&u(null),draft:d,roster:r,saving:l.isPending,onSave:w=>l.mutate(w,{onSuccess:()=>u(null)})})]})}const Jde=s=>`$${Math.round(s).toLocaleString()}`,qir=()=>{var H;const{brokerageId:s,managedBrokerages:t,selectedBrokerageId:n}=hs(),r=_.useMemo(()=>{var K;return n||((K=t[0])==null?void 0:K.id)||s},[n,t,s]),{data:a=[],isLoading:i}=LKn(r,!0),{data:l=[],isLoading:o}=RKn(r),c=IKn(r),d=FKn(r),u=OKn(r),{data:h=[],isLoading:m}=jJe(r),{data:p=[],isLoading:f}=gir(r),{data:g=[],isLoading:v}=Fas(r),{data:y=[],isLoading:b}=Ras(r),w=((H=t.find(K=>K.id===r))==null?void 0:H.name)||"Brokerage",[S,C]=_.useState(!1),[E,P]=_.useState(null),[M,I]=_.useState(!1),[D,F]=_.useState(null),q=a.filter(K=>K.is_active),G=l.filter(K=>K.assignment),V=G.reduce((K,Z)=>{var oe;return K+(((oe=Z.plan)==null?void 0:oe.monthly_fee)||0)},0);return e.jsxs($s,{title:"Brokerage Financials",description:"Commission plans, cap progress, company dollar and agent fee statements",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(z_,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active plans"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:q.length})]})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-blue-500/10 text-blue-600",children:e.jsx(On,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents on a plan"}),e.jsxs("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:[G.length,e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:[" of ",l.length]})]})]})]})}),e.jsx(be,{className:"border-border/60",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-600",children:e.jsx(w7,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly desk fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:tp(V)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"expected across assigned agents"})]})]})})]}),e.jsxs(Qr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(Jr,{children:[e.jsx(Wt,{value:"agents",children:"Agents"}),e.jsx(Wt,{value:"plans",children:"Plans"}),e.jsx(Wt,{value:"company",children:"Company dollar"}),e.jsx(Wt,{value:"ledger",children:"Fees & statements"}),e.jsx(Wt,{value:"disbursements",children:"Disbursements"}),e.jsx(Wt,{value:"renewals",children:"Renewals & goals"})]})}),e.jsxs(z,{size:"sm",onClick:()=>{P(null),C(!0)},children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," New plan"]})]}),e.jsx(Kt,{value:"agents",className:"space-y-2",children:e.jsxs(be,{className:"border-border/60",children:[e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-base",children:"Agent plans & cap progress"}),e.jsx(En,{children:"Assign a plan to each agent — their new deals inherit the splits and fees automatically"})]}),e.jsx(Le,{className:"space-y-1 pt-2",children:o?Array.from({length:4}).map((K,Z)=>e.jsx(ln,{className:"h-16 w-full rounded-lg"},Z)):l.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents in this brokerage yet."}):l.map(K=>{var oe;const Z=(oe=K.progress)==null?void 0:oe.pct_to_cap;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg px-2 py-3 hover:bg-muted/50 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[e.jsx(xi,{src:K.avatarUrl||void 0,alt:K.name}),e.jsx(Na,{className:"text-[11px]",children:K.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:K.name}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:K.email})]})]}),e.jsx("div",{className:"min-w-0 flex-1",children:K.plan?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(ze,{variant:"secondary",className:"font-medium",children:K.plan.name}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[K.plan.agent_split_pct,"/",Math.max(0,100-K.plan.agent_split_pct),K.plan.cap_amount?` · ${tp(K.plan.cap_amount)} cap`:" · no cap"]})]}),K.plan.cap_amount&&K.progress?e.jsxs("div",{className:"mt-1.5 max-w-xs",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[Jde(K.progress.cap_progress)," to cap"]}),e.jsxs("span",{children:[Math.round(Z??0),"%"]})]}),e.jsx(Di,{value:Math.min(100,Z??0),className:"h-1.5"})]}):e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"No cap on this plan"})]}):e.jsx("p",{className:"text-[12px] italic text-muted-foreground",children:"No plan assigned"})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(z,{variant:"outline",size:"sm",disabled:q.length===0,onClick:()=>{F(K),I(!0)},children:K.assignment?"Change plan":"Assign plan"}),K.assignment&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",title:"Remove plan",onClick:()=>u.mutate(K.assignment.id),children:e.jsx(_q,{className:"h-4 w-4"})})]})]},K.agentId)})})]})}),e.jsx(Kt,{value:"plans",className:"space-y-3",children:i?e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Array.from({length:2}).map((K,Z)=>e.jsx(ln,{className:"h-44 w-full rounded-xl"},Z))}):a.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 py-12 text-center",children:[e.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600",children:e.jsx(z_,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No commission plans yet"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Create your first plan — e.g. a 70/30 split with an annual cap — then assign it to agents."})]}),e.jsxs(z,{onClick:()=>{P(null),C(!0)},children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," Create plan"]})]})}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:a.map(K=>e.jsxs(be,{className:`border-border/60 ${K.is_active?"":"opacity-60"}`,children:[e.jsx(_t,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:K.name}),K.description&&e.jsx(En,{className:"mt-1",children:K.description})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!K.is_active&&e.jsx(ze,{variant:"outline",children:"Retired"}),e.jsxs(ze,{variant:"secondary",children:["v",K.version_no]}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{P(K),C(!0)},children:e.jsx(Wa,{className:"h-4 w-4"})})]})]})}),e.jsxs(Le,{className:"grid grid-cols-2 gap-x-4 gap-y-2 pt-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Split (agent/brokerage)"}),e.jsxs("p",{className:"font-medium tabular-nums",children:[K.agent_split_pct,"/",Math.max(0,100-K.agent_split_pct)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Annual cap"}),e.jsx("p",{className:"font-medium tabular-nums",children:K.cap_amount?Jde(K.cap_amount):"None"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Monthly desk fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:K.monthly_fee?Jde(K.monthly_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Per-transaction fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:K.transaction_fee?Jde(K.transaction_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Franchise fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:K.franchise_fee_pct?`${K.franchise_fee_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Team split"}),e.jsx("p",{className:"font-medium tabular-nums",children:K.team_split_pct?`${K.team_split_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agents on plan"}),e.jsx("p",{className:"font-medium tabular-nums",children:l.filter(Z=>{var oe;return((oe=Z.plan)==null?void 0:oe.id)===K.id}).length})]})]})]},K.id))})}),e.jsx(Kt,{value:"company",children:e.jsx(kir,{deals:h,ledger:p,roster:l,brokerageName:w,loading:m||o})}),e.jsx(Kt,{value:"ledger",children:e.jsx(Air,{brokerageId:r,ledger:p,roster:l,loading:f||o})}),e.jsx(Kt,{value:"renewals",children:e.jsx(Mir,{records:g,roster:l,deals:h,loading:v||o})}),e.jsx(Kt,{value:"disbursements",children:e.jsx(Uir,{brokerageId:r,disbursements:y,deals:h,roster:l,brokerageName:w,loading:b||o})})]})]}),e.jsx(fir,{open:S,onOpenChange:C,plan:E,saving:c.isPending,onSave:K=>c.mutate(K,{onSuccess:()=>C(!1)})}),e.jsx(xir,{open:M,onOpenChange:I,agent:D,plans:q,saving:d.isPending,onAssign:K=>d.mutate(K,{onSuccess:()=>I(!1)})})]})};function Vir(){const[s,t]=_.useState(""),{data:n,isLoading:r}=rt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await U.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await U.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await U.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(p=>{const f=u.filter(y=>y.brokerage_id===p.id),g=h.filter(y=>y.brokerage_id===p.id),v=f.length>0?f.reduce((y,b)=>b.created_at>y?b.created_at:y,f[0].created_at):null;return{brokerage_id:p.id,brokerage_name:p.name,total_items:f.length,videos:f.filter(y=>y.content_type==="video").length,pdfs:f.filter(y=>y.content_type==="pdf").length,links:f.filter(y=>y.content_type==="link"||y.content_type==="canva_link").length,events:f.filter(y=>y.content_type==="event").length,graphics:f.filter(y=>y.content_type==="graphic").length,latest_item_date:v,categories:g.length}});return m.sort((p,f)=>f.total_items-p.total_items),m}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx($s,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xh,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Le,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Le,{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(be,{children:[e.jsx(_t,{className:"pb-2",children:e.jsx(Nt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Le,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(be,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(Za,{children:[e.jsx(Xa,{children:e.jsxs(fn,{children:[e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{className:"text-center",children:"Total"}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx($r,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Oc,{className:"h-3 w-3"})," Links"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(gc,{className:"h-3 w-3"})," Events"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(nc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Tt,{className:"text-center",children:"Categories"}),e.jsx(Tt,{children:"Last Upload"})]})}),e.jsx(Qa,{children:r?e.jsx(fn,{children:e.jsx(yt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(fn,{children:e.jsx(yt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(fn,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(yt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(yt,{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(yt,{className:"text-center",children:o.videos||"–"}),e.jsx(yt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(yt,{className:"text-center",children:o.links||"–"}),e.jsx(yt,{className:"text-center",children:o.events||"–"}),e.jsx(yt,{className:"text-center",children:o.graphics||"–"}),e.jsx(yt,{className:"text-center",children:o.categories||"–"}),e.jsx(yt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Ys(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const Hir=[{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:"📉"}],bCt=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Fm,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Fm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(of,{className:"h-4 w-4"})}],Gir=[{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:"📰"}],_Ct=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),wCt={"luxury-dark":dst,"modern-clean":ust,"bold-colorful":hst,editorial:mst};function Wir(){const[s,t]=_.useState(""),[n,r]=_.useState("address"),[a,i]=_.useState(!1),[l,o]=_.useState([]),[c,d]=_.useState(null),[u,h]=_.useState(0),[m,p]=_.useState("just-listed"),[f,g]=_.useState(["instagram-square"]),[v,y]=_.useState("luxury-dark"),[b,w]=_.useState(!1),[S,C]=_.useState(""),[E,P]=_.useState(""),[M,I]=_.useState(""),[D,F]=_.useState(!1),[q,G]=_.useState(!1),[V,H]=_.useState([]),[K,Z]=_.useState("search"),oe=_.useRef({});_.useEffect(()=>{(async()=>{const{data:{user:Ee}}=await U.auth.getUser();if(!Ee)return;const{data:Ne}=await U.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ee.id).single();if(Ne){C(Ne.name||""),I(Ne.avatar_url||"");const Pe=Ne.brokerages;P((Pe==null?void 0:Pe.name)||"")}})()},[]);const re=async()=>{var ge;if(s.trim()){i(!0),o([]);try{const{data:Ee,error:Ne}=await U.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Ne)throw Ne;if(Ee.error)throw new Error(Ee.error);o(Ee.listings||[]),((ge=Ee.listings)==null?void 0:ge.length)===0&&ne.info("No listings found. Try a different search.")}catch(Ee){ne.error(Ee.message||"Search failed")}finally{i(!1)}}},ae=ge=>{var Ee;d(ge),h(0),Z("customize"),ge.soldDate||(Ee=ge.status)!=null&&Ee.toLowerCase().includes("sold")?p("just-sold"):p("just-listed")},J=ge=>{g(Ee=>Ee.includes(ge)?Ee.filter(Ne=>Ne!==ge):[...Ee,ge])},te=_.useCallback(async()=>{if(!(!c||f.length===0)){F(!0),H([]),Z("generate");try{await new Promise(Ee=>setTimeout(Ee,500));const ge=[];for(const Ee of f){const Ne=`${v}-${Ee}`,Pe=oe.current[Ne];if(!Pe)continue;const Oe=IM[Ee],ke=await ZH(Pe,{width:Oe.width,height:Oe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ge.push({format:Ee,imageUrl:ke})}H(ge),ne.success(`Generated ${ge.length} social post${ge.length>1?"s":""}!`)}catch(ge){ne.error(ge.message||"Generation failed")}finally{F(!1)}}},[c,f,v,u,b,S,E,M,m]),ce=async()=>{if(!(!c||f.length===0)){F(!0),H([]),Z("generate");try{const ge={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ee=[];for(const Ne of f){const{data:Pe,error:Oe}=await U.functions.invoke("generate-listing-social-post",{body:{listing:ge,postType:m,format:Ne,branding:b?{enabled:!0,agentName:S,brokerage:E}:{enabled:!1}}});if(Oe)throw Oe;if(Pe.error)throw new Error(Pe.error);Ee.push({format:Ne,imageUrl:Pe.imageUrl})}H(Ee),ne.success(`Generated ${Ee.length} AI post${Ee.length>1?"s":""}!`)}catch(ge){ne.error(ge.message||"AI generation failed")}finally{F(!1)}}},ve=()=>q?ce():te(),me=(ge,Ee)=>{var Pe;const Ne=document.createElement("a");Ne.href=ge,Ne.download=`${((Pe=c==null?void 0:c.address)==null?void 0:Pe.replace(/\s+/g,"-"))||"listing"}-${m}-${Ee}.png`,document.body.appendChild(Ne),Ne.click(),document.body.removeChild(Ne)},he=c?{listing:c,postType:m,format:"instagram-square",branding:b?{enabled:!0,agentName:S,brokerage:E,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx($s,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Xh,{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:()=>Z("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${K==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Rr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(yi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&Z("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${K==="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(yi,{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 ${K==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(nc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),K==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(vBt,{})]}),e.jsx(En,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(Qr,{value:n,onValueChange:ge=>r(ge),children:e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"address",children:[e.jsx(Ha,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Wt,{value:"mls",children:[e.jsx(Ip,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:s,onChange:ge=>t(ge.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ge=>ge.key==="Enter"&&re()}),e.jsxs(z,{onClick:re,disabled:a||!s.trim(),children:[a?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{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((ge,Ee)=>{var Ne;return e.jsx(be,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ae(ge),children:e.jsx(Le,{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:(Ne=ge.photos)!=null&&Ne[0]?e.jsx("img",{src:ge.photos[0],alt:ge.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(sa,{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:_Ct(ge.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ge.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ge.city,", ",ge.state," ",ge.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ge.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(W4,{className:"h-3 w-3"})," ",ge.bedrooms]}),ge.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ey,{className:"h-3 w-3"})," ",ge.bathrooms]}),ge.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(d7,{className:"h-3 w-3"})," ",ge.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ze,{variant:"outline",className:"text-[10px]",children:ge.mlsNumber}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:ge.status})]})]})]})})},ge.mlsNumber||Ee)})})]})]}),K==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(be,{className:"lg:col-span-1",children:[e.jsx(_t,{className:"pb-3",children:e.jsx(Nt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Le,{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(z,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ge=>Math.max(0,ge-1)),disabled:u===0,children:e.jsx(Wc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx(z,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ge=>Math.min(c.photos.length-1,ge+1)),disabled:u===c.photos.length-1,children:e.jsx(yi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:_Ct(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(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Z("search"),d(null)},children:[e.jsx(Dx,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(be,{className:"lg:col-span-2",children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(En,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Le,{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(yc,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:q?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:q?"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(mn,{checked:q,onCheckedChange:G}),q&&e.jsx(rg,{className:"h-4 w-4 text-purple-500"})]})]}),!q&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yc,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Gir.map(ge=>e.jsxs("button",{onClick:()=>y(ge.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${v===ge.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ge.preview}),e.jsx("span",{className:"text-sm font-medium",children:ge.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ge.description})]},ge.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Hir.map(ge=>e.jsxs("button",{onClick:()=>p(ge.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===ge.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ge.icon})," ",ge.label]},ge.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:bCt.map(ge=>e.jsxs("button",{onClick:()=>J(ge.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${f.includes(ge.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ge.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:ge.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ge.dimensions})]})]},ge.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Oo,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(mn,{checked:b,onCheckedChange:w})]}),b&&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(ee,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(pe,{value:S,onChange:ge=>C(ge.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(pe,{value:E,onChange:ge=>P(ge.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!q&&he&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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*(IM[f[0]||"instagram-square"].height/IM[f[0]||"instagram-square"].width)},children:(()=>{const ge=wCt[v],Ee=f[0]||"instagram-square";return e.jsx(ge,{...he,format:Ee})})()})})]}),e.jsx(z,{onClick:ve,disabled:f.length===0||D,size:"lg",className:"w-full gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-5 w-5 animate-spin"})," Generating ",f.length," post",f.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[q?e.jsx(rg,{className:"h-5 w-5"}):e.jsx(un,{className:"h-5 w-5"}),"Generate ",f.length," Social Post",f.length>1?"s":"",q&&e.jsx(ze,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),K==="generate"&&e.jsxs("div",{className:"space-y-4",children:[D&&e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(bt,{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:q?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),V.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(z,{variant:"outline",size:"sm",onClick:()=>Z("customize"),children:[e.jsx(Dx,{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:V.map((ge,Ee)=>{const Ne=bCt.find(Pe=>Pe.value===ge.format);return e.jsxs(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ge.imageUrl,alt:`${ge.format} social post`,className:"w-full rounded"})}),e.jsxs(Le,{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:[Ne==null?void 0:Ne.icon,e.jsx("span",{className:"text-sm font-medium",children:Ne==null?void 0:Ne.label})]}),e.jsx(ze,{variant:"outline",className:"text-[10px]",children:Ne==null?void 0:Ne.dimensions})]}),e.jsxs(z,{size:"sm",className:"w-full gap-1.5",onClick:()=>me(ge.imageUrl,ge.format),children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ee)})})]})]}),K==="generate"&&!q&&c&&he&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:f.map(ge=>{const Ee=wCt[v],Ne=IM[ge];return e.jsx("div",{style:{width:Ne.width,height:Ne.height},children:e.jsx(Ee,{ref:Pe=>{oe.current[`${v}-${ge}`]=Pe},...he,format:ge})},`${v}-${ge}`)})})]})})}function Kir(){return rt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function Yir(s){return rt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 Zir(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Kas(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 Xir(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Qir(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 Jir(){const s=$t();return mt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 eor(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function tor(){const s=$t();return mt({mutationFn:async t=>{const{data:n,error:r}=await U.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 sor(){const s=$t();return mt({mutationFn:async t=>{const{error:n}=await U.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 nor(){const s=$t();return mt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await U.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 U.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function ror(){return rt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function aor(s){return rt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 Yas(s){return rt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function ior(){const s=$t();return mt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await U.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 oor(){const{user:s}=hs(),t=zn(),{data:n,isLoading:r}=Kir(),a=Zir(),i=Kas(),l=Xir(),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(!0),g=async()=>{if(!(!d.trim()||!s))try{const b=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:p,created_by:s.id});ne.success("Course created"),c(!1),u(""),m(""),f(!0),t(`/admin/lms/${b.id}`)}catch{ne.error("Failed to create course")}},v=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),ne.success(b.is_published?"Course unpublished":"Course published")}catch{ne.error("Failed to update course")}},y=async b=>{if(await Qi("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),ne.success("Course deleted")}catch{ne.error("Failed to delete")}};return e.jsxs($s,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(fm,{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(z,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(wl,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(z,{onClick:()=>c(!0),children:[e.jsx(sn,{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(b=>e.jsx(be,{className:"animate-pulse",children:e.jsxs(_t,{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"})]})},b))}):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(b=>{var E,P;const w=((P=(E=b.modules)==null?void 0:E[0])==null?void 0:P.count)??0,S=b.access||[],C=S.length===0?"No access set":S.some(M=>M.access_type==="all")?"All agents":`${S.length} rule(s)`;return e.jsxs(be,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.id}`),children:[e.jsx(_t,{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(Nt,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(En,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx(ze,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(Le,{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(ip,{className:"h-3.5 w-3.5"}),w," module",w!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(bj,{className:"h-3.5 w-3.5"}):e.jsx(g7,{className:"h-3.5 w-3.5"}),b.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(On,{className:"h-3.5 w-3.5"}),C]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(z,{size:"sm",variant:"ghost",onClick:M=>{M.stopPropagation(),v(b)},children:[b.is_published?e.jsx(Yf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"}),b.is_published?"Unpublish":"Publish"]}),e.jsx(z,{size:"sm",variant:"ghost",className:"text-destructive",onClick:M=>{M.stopPropagation(),y(b.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ip,{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(z,{onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create New Course"}),e.jsx(_r,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Course Title"}),e.jsx(pe,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:h,onChange:b=>m(b.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(mn,{checked:p,onCheckedChange:f})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(z,{onClick:g,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function lor(){const{courseId:s}=Mi(),t=zn(),{data:n,isLoading:r}=Yir(s),a=Kas(),i=Qir(),l=Jir(),o=eor(),c=tor(),d=sor(),u=nor(),{data:h}=rt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:Xe}=await U.from("brokerages").select("id, name").order("name");return Xe||[]}}),[m,p]=_.useState(null),[f,g]=_.useState(!1),[v,y]=_.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,w]=_.useState(null),[S,C]=_.useState({title:"",resource_type:"link",url:""}),[E,P]=_.useState(new Set),[M,I]=_.useState(null),[D,F]=_.useState(0),[q,G]=_.useState(!1),V=_.useRef(null),H=_.useRef(null),[K,Z]=_.useState(!1),[oe,re]=_.useState(""),[ae,J]=_.useState(""),[te,ce]=_.useState(""),[ve,me]=_.useState(!1);if(r)return e.jsx($s,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx($s,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(z,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const he=n.modules||[],ge=n.access||[],Ee=ge.some(Xe=>Xe.access_type==="all"),Ne=ge.filter(Xe=>Xe.access_type==="brokerage").map(Xe=>Xe.brokerage_id),Pe=(h||[]).filter(Xe=>Xe.name.toLowerCase().includes(oe.toLowerCase())),Oe=Xe=>{const nt=new Set(E);nt.has(Xe)?nt.delete(Xe):nt.add(Xe),P(nt)},ke=async()=>{if(!M)return null;G(!0),F(0);try{const{data:Xe,error:nt}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(nt)throw new Error(nt.message);const{videoId:Ge,libraryId:Je}=Xe,{data:ut,error:lt}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ge,libraryId:Je}});if(lt)throw new Error(lt.message);const qt=new XMLHttpRequest;return await new Promise((zt,Zt)=>{qt.upload.onprogress=ms=>{ms.lengthComputable&&F(Math.round(ms.loaded/ms.total*100))},qt.onload=()=>qt.status>=200&&qt.status<300?zt():Zt(new Error(`Upload failed: ${qt.status}`)),qt.onerror=()=>Zt(new Error("Upload failed")),qt.open("PUT",ut.uploadUrl),qt.setRequestHeader("AccessKey",ut.apiKey),qt.send(M)}),`https://iframe.mediadelivery.net/embed/${Je}/${Ge}`}catch(Xe){return console.error("Bunny upload error:",Xe),ne.error("Video upload failed"),null}finally{G(!1),F(0)}},Ve=async()=>{if(v.title.trim())try{let Xe=v.video_url.trim()||void 0;if(M){const nt=await ke();if(!nt)return;Xe=nt}await i.mutateAsync({course_id:n.id,title:v.title.trim(),description:v.description.trim()||void 0,video_url:Xe,text_content:v.text_content.trim()||void 0,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):void 0,sort_order:he.length}),ne.success("Module added"),g(!1),y({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),I(null)}catch{ne.error("Failed to add module")}},_e=async()=>{if(m)try{let Xe=v.video_url.trim()||null;if(M){const nt=await ke();if(!nt)return;Xe=nt}await l.mutateAsync({id:m.id,title:v.title.trim(),description:v.description.trim()||null,video_url:Xe,text_content:v.text_content.trim()||null,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):null}),ne.success("Module updated"),p(null),I(null)}catch{ne.error("Failed to update")}},Ae=async Xe=>{if(await Qi("Delete this module?"))try{await o.mutateAsync(Xe),ne.success("Module deleted")}catch{ne.error("Failed to delete")}},Se=async Xe=>{if(S.title.trim())try{await c.mutateAsync({module_id:Xe,title:S.title.trim(),resource_type:S.resource_type,url:S.url.trim()||void 0}),ne.success("Resource added"),w(null),C({title:"",resource_type:"link",url:""})}catch{ne.error("Failed to add resource")}},We=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ne.success("Access updated: All brokerages / all agents")}catch{ne.error("Failed to update access")}},qe=async Xe=>{const nt=ge.filter(lt=>lt.access_type==="brokerage").map(lt=>lt.brokerage_id),Ge=nt.includes(Xe);let Je;Ge?Je=nt.filter(lt=>lt!==Xe):Je=[...nt,Xe];const ut=Je.map(lt=>({access_type:"brokerage",brokerage_id:lt}));try{await u.mutateAsync({courseId:n.id,accessRules:ut}),ne.success(Ge?"Brokerage removed":"Brokerage added")}catch{ne.error("Failed to update access")}},Be=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ne.success("Access cleared")}catch{ne.error("Failed")}},Ze=async(Xe,nt)=>{const Ge=nt==="up"?Xe-1:Xe+1;if(!(Ge<0||Ge>=he.length))try{await Promise.all([l.mutateAsync({id:he[Xe].id,sort_order:Ge}),l.mutateAsync({id:he[Ge].id,sort_order:Xe})])}catch{ne.error("Failed to reorder")}},$e=async()=>{try{await a.mutateAsync({id:n.id,title:ae,description:te||null}),ne.success("Course updated"),me(!1)}catch{ne.error("Failed to update")}};return e.jsxs($s,{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(z,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(ka,{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(bj,{className:"h-3.5 w-3.5"}):e.jsx(g7,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[he.length," module",he.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>{J(n.title),ce(n.description||""),me(!0)},children:[e.jsx(Wa,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(z,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>ne.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(Yf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(xa,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(Qr,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"modules",children:"Modules"}),e.jsx(Wt,{value:"access",children:"Access & Permissions"}),e.jsx(Wt,{value:"settings",children:"Settings"})]}),e.jsxs(Kt,{value:"modules",className:"mt-6 space-y-4",children:[he.map((Xe,nt)=>e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Oe(Xe.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(),Ze(nt,"up")},disabled:nt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(h1,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ge=>{Ge.stopPropagation(),Ze(nt,"down")},disabled:nt===he.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(cl,{className:"h-3.5 w-3.5"})})]})}),e.jsx(ze,{variant:"outline",className:"shrink-0 font-mono text-xs",children:nt+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Xe.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[Xe.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Xr,{className:"h-3 w-3"})," Video"]}),Xe.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx($r,{className:"h-3 w-3"})," Text"]}),Xe.duration_minutes&&e.jsxs("span",{children:[Xe.duration_minutes," min"]}),Xe.resources&&Xe.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Oc,{className:"h-3 w-3"})," ",Xe.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{size:"sm",variant:"ghost",onClick:Ge=>{var Je;Ge.stopPropagation(),p(Xe),y({title:Xe.title,description:Xe.description||"",video_url:Xe.video_url||"",text_content:Xe.text_content||"",duration_minutes:((Je=Xe.duration_minutes)==null?void 0:Je.toString())||""})},children:e.jsx(Wa,{className:"h-3.5 w-3.5"})}),e.jsx(z,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ge=>{Ge.stopPropagation(),Ae(Xe.id)},children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]})]}),E.has(Xe.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[Xe.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Xe.description}),Xe.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:Xe.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:Xe.video_url})]}),Xe.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:Xe.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(z,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{w(Xe.id),C({title:"",resource_type:"link",url:""})},children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),Xe.resources&&Xe.resources.length>0?e.jsx("div",{className:"space-y-1",children:Xe.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(z,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(Ge.id),children:e.jsx(er,{className:"h-3 w-3"})})]},Ge.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},Xe.id)),e.jsxs(z,{variant:"outline",className:"w-full border-dashed",onClick:()=>{g(!0),y({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Kt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Le,{className:"space-y-5",children:[e.jsxs("div",{className:Ct("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ee?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:We,children:[e.jsx("div",{className:Ct("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ee?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(Wo,{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(mn,{checked:Ee,onCheckedChange:We})]}),!Ee&&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:Ne.length===0?"No brokerages selected — agents won't see this course":`${Ne.length} brokerage${Ne.length!==1?"s":""} selected`})]}),Ne.length>0&&e.jsx(z,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Be,children:"Clear all"})]}),e.jsx(pe,{placeholder:"Search brokerages...",value:oe,onChange:Xe=>re(Xe.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Pe.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Pe.map(Xe=>{const nt=Ne.includes(Xe.id);return e.jsxs("div",{className:Ct("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",nt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>qe(Xe.id),children:[e.jsx("div",{className:Ct("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",nt?"bg-primary border-primary":"border-muted-foreground/30"),children:nt&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(oi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:Xe.name}),nt&&e.jsx(ze,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},Xe.id)})})]})]})]})}),e.jsxs(Kt,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Le,{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(()=>ne.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(er,{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(N0,{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:H,type:"file",accept:"image/*",className:"hidden",onChange:async Xe=>{var Ge;const nt=(Ge=Xe.target.files)==null?void 0:Ge[0];if(!(!nt||!n)){Z(!0);try{const Je=nt.name.split(".").pop(),ut=`${n.id}/thumbnail.${Je}`,{error:lt}=await U.storage.from("lms-thumbnails").upload(ut,nt,{upsert:!0});if(lt)throw lt;const{data:qt}=U.storage.from("lms-thumbnails").getPublicUrl(ut),zt=`${qt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:zt}),ne.success("Thumbnail uploaded")}catch{ne.error("Failed to upload thumbnail")}finally{Z(!1),H.current&&(H.current.value="")}}}}),e.jsxs(z,{variant:"outline",size:"sm",disabled:K,onClick:()=>{var Xe;return(Xe=H.current)==null?void 0:Xe.click()},children:[K?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ra,{className:"h-4 w-4 mr-2"}),K?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Course Settings"})}),e.jsxs(Le,{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(mn,{checked:n.is_sequential,onCheckedChange:Xe=>a.mutateAsync({id:n.id,is_sequential:Xe}).then(()=>ne.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(mn,{checked:n.is_published,onCheckedChange:Xe=>a.mutateAsync({id:n.id,is_published:Xe}).then(()=>ne.success("Updated"))})]})]})]})]})]})]}),e.jsx(Is,{open:f||!!m,onOpenChange:Xe=>{Xe||(g(!1),p(null))},children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:m?"Edit Module":"Add Module"}),e.jsx(_r,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:v.title,onChange:Xe=>y(nt=>({...nt,title:Xe.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:v.description,onChange:Xe=>y(nt=>({...nt,description:Xe.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Ct("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 Xe;return(Xe=V.current)==null?void 0:Xe.click()},children:[e.jsx("input",{ref:V,type:"file",accept:"video/*",className:"hidden",onChange:Xe=>{var Ge;const nt=(Ge=Xe.target.files)==null?void 0:Ge[0];nt&&(I(nt),y(Je=>({...Je,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(Xr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:M.name}),e.jsx(z,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:Xe=>{Xe.stopPropagation(),I(null)},children:e.jsx(er,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(Ra,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),q&&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(bt,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",D,"%"]})]}),e.jsx(Di,{value:D,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(pe,{value:v.video_url,onChange:Xe=>y(nt=>({...nt,video_url:Xe.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Text Content"}),e.jsx(Ps,{value:v.text_content,onChange:Xe=>y(nt=>({...nt,text_content:Xe.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Duration (minutes)"}),e.jsx(pe,{type:"number",value:v.duration_minutes,onChange:Xe=>y(nt=>({...nt,duration_minutes:Xe.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>{g(!1),p(null),I(null)},children:"Cancel"}),e.jsxs(z,{onClick:m?_e:Ve,disabled:!v.title.trim()||q,children:[q?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bo,{className:"h-4 w-4 mr-2"}),q?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(Is,{open:!!b,onOpenChange:Xe=>{Xe||w(null)},children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Add Resource"}),e.jsx(_r,{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(ee,{children:"Title"}),e.jsx(pe,{value:S.title,onChange:Xe=>C(nt=>({...nt,title:Xe.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Type"}),e.jsxs(ls,{value:S.resource_type,onValueChange:Xe=>C(nt=>({...nt,resource_type:Xe})),children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"link",children:"Link"}),e.jsx(He,{value:"pdf",children:"PDF"}),e.jsx(He,{value:"template",children:"Template"}),e.jsx(He,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"URL"}),e.jsx(pe,{value:S.url,onChange:Xe=>C(nt=>({...nt,url:Xe.target.value})),placeholder:"https://..."})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>w(null),children:"Cancel"}),e.jsx(z,{onClick:()=>b&&Se(b),disabled:!S.title.trim(),children:"Add Resource"})]})]})}),e.jsx(Is,{open:ve,onOpenChange:me,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Edit Course"}),e.jsx(_r,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:ae,onChange:Xe=>J(Xe.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ps,{value:te,onChange:Xe=>ce(Xe.target.value),rows:3})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>me(!1),children:"Cancel"}),e.jsx(z,{onClick:$e,disabled:!ae.trim(),children:"Save"})]})]})})]})}function cor(){return rt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_stats");if(t)throw t;return s}})}function dor(){return rt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function uor(s){return rt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function hor(){const s=zn(),{data:t,isLoading:n}=cor(),{data:r,isLoading:a}=dor(),[i,l]=_.useState(null),{data:o,isLoading:c}=uor(i),[d,u]=_.useState(""),h=r==null?void 0:r.find(f=>f.course_id===i),m=o==null?void 0:o.filter(f=>{var g,v;return!d||((g=f.agent_name)==null?void 0:g.toLowerCase().includes(d.toLowerCase()))||((v=f.email)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))}),p=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:ip,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Mr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:On,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:jl,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:kl,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:wl,color:"text-rose-500"}];return e.jsx($s,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(ka,{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(fm,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:p.map(f=>e.jsx(be,{className:Ct("transition-all",n&&"animate-pulse"),children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(f.icon,{className:Ct("h-4 w-4",f.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:f.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":f.value})]})},f.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(wl,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(be,{className:"animate-pulse",children:e.jsx(Le,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},f))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(f=>{const g=i===f.course_id;return e.jsx(be,{className:Ct("cursor-pointer transition-all hover:shadow-md",g?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(g?null:f.course_id),children:e.jsxs(Le,{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:f.course_title}),e.jsx(ze,{variant:f.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:f.is_published?"Live":"Draft"})]})}),e.jsx(yi,{className:Ct("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",g&&"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:f.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:f.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:f.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:[f.avg_completion_pct,"%"]})]}),e.jsx(Di,{value:f.avg_completion_pct,className:"h-2"})]})]})},f.course_id)})}):e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{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(jj,{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(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:d,onChange:f=>u(f.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(f=>e.jsx(be,{className:"animate-pulse",children:e.jsx(Le,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},f))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((f,g)=>{const v=f.completion_pct>=100;return e.jsx(be,{className:Ct("transition-all",v&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ct("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",g===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":g===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":g===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:g+1}),e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[e.jsx(xi,{src:f.avatar_url||void 0}),e.jsx(Na,{className:"text-xs bg-primary/10 text-primary",children:(f.agent_name||f.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:f.agent_name||f.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(Mr,{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:[f.modules_completed,"/",f.total_modules," modules"]}),f.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),Ys(new Date(f.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Ct("text-sm font-bold",v?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[f.completion_pct,"%"]}),e.jsx(Di,{value:f.completion_pct,className:"h-1.5 mt-1"})]})]})})},f.user_id)})}):e.jsx(be,{className:"border-dashed",children:e.jsx(Le,{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(be,{className:"border-dashed",children:e.jsxs(Le,{className:"py-16 text-center",children:[e.jsx(On,{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 mor(){const{user:s}=hs(),t=zn(),{data:n,isLoading:r}=ror();return e.jsx($s,{title:"LevelUp U",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/10 via-primary/5 to-background border p-8",children:[e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center",children:e.jsx(fm,{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(be,{className:"animate-pulse",children:e.jsxs(Le,{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(por,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ip,{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 por({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=Yas(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(be,{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(fm,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Le,{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(ip,{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(bj,{className:"h-3.5 w-3.5"}):e.jsx(g7,{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(Di,{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(yi,{className:"h-3.5 w-3.5"})]})})]})]})}function xor(){const{courseId:s}=Mi(),t=zn(),{user:n}=hs(),{data:r,isLoading:a}=aor(s),{data:i}=Yas(s),l=ior(),[o,c]=_.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(b=>b.completed).map(b=>b.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;_.useEffect(()=>{if(d.length>0&&!o){const b=d.find(w=>!u.has(w.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const p=d.find(b=>b.id===o),f=d.findIndex(b=>b.id===o),g=(b,w)=>{if(!(r!=null&&r.is_sequential)||w===0)return!1;for(let S=0;S{if(!(!p||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:p.id,userId:n.id}),ne.success("Module completed! 🎉"),f{const w=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(w)return`https://www.youtube.com/embed/${w[1]}`;const S=b.match(/vimeo\.com\/(\d+)/);if(S)return`https://player.vimeo.com/video/${S[1]}`;const C=b.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return C?`https://iframe.mediadelivery.net/embed/${C[1]}/${C[2]}?responsive=true`:b};return a?e.jsx($s,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):r?e.jsx($s,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:r.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[h,"/",d.length," completed"]}),e.jsxs("span",{children:[m,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(Di,{value:m,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(be,{className:"lg:sticky lg:top-4",children:e.jsxs(Le,{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(Ki,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,w)=>{const S=g(b,w),C=u.has(b.id),E=b.id===o;return e.jsxs("button",{disabled:S,onClick:()=>!S&&c(b.id),className:Ct("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",E?"bg-primary/10 text-primary":"hover:bg-muted/50",S&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:S?e.jsx(Hl,{className:"h-4 w-4 text-muted-foreground"}):C?e.jsx(Mr,{className:"h-4 w-4 text-green-500"}):e.jsx(Gf,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Ct("font-medium truncate",E&&"text-primary"),children:[w+1,". ",b.title]}),b.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(Zr,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[p.video_url&&e.jsx(be,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:y(p.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:p.title}),p.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:p.description})]}),u.has(p.id)?e.jsxs(ze,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Mr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(z,{size:"sm",onClick:v,disabled:l.isPending,children:[e.jsx(Mr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),p.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:p.text_content}),p.resources&&p.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.resources.map(b=>e.jsxs("a",{href:b.url||b.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:[b.resource_type==="pdf"?e.jsx($r,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(fm,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(Oc,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},b.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(z,{variant:"outline",size:"sm",disabled:f===0,onClick:()=>f>0&&c(d[f-1].id),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),fc(d[f+1].id),children:["Next ",e.jsx(yi,{className:"h-3.5 w-3.5 ml-1"})]}):m===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(be,{children:e.jsx(Le,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx($s,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(z,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function gor({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(Ar.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(Ar.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(Ar.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(Ar.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(Ar.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(Da,{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(Ar.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 qj({children:s,className:t="",delay:n=0,direction:r="up"}){const a=_.useRef(null),i=yFs(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(Ar.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 yor({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(qj,{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(qj,{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 vor({images:s,primaryColor:t,accentColor:n}){const[r,a]=_.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(qj,{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(On,{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(qj,{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(er,{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 bor({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(qj,{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(qj,{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(wj,{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 _or({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(qj,{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(qj,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ps,{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(z,{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(Da,{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(Om,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function wor({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=_.useState(1),[d,u]=_.useState(""),h=3,m=!!s.first_name&&!!s.email,p=f=>{u(f),t(g=>({...g,why_interested:f})),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(qj,{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(Hl,{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(qj,{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(f=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:f<=o?a:"#e5e7eb"}},f)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(bW,{mode:"wait",children:[o===1&&e.jsxs(Ar.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(f=>e.jsxs("button",{type:"button",onClick:()=>p(f.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:f.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:f.label}),e.jsx(Da,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},f.val))]},"step1"),o===2&&e.jsxs(Ar.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(ee,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(pe,{required:!0,value:s.first_name,onChange:f=>t(g=>({...g,first_name:f.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(pe,{value:s.last_name,onChange:f=>t(g=>({...g,last_name:f.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(pe,{type:"email",required:!0,value:s.email,onChange:f=>t(g=>({...g,email:f.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(pe,{value:s.phone,onChange:f=>t(g=>({...g,phone:f.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(z,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(z,{type:"button",disabled:!m,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(Da,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Ar.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(ee,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(pe,{value:s.current_brokerage,onChange:f=>t(g=>({...g,current_brokerage:f.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(ee,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(pe,{type:"number",min:"0",value:s.experience_years,onChange:f=>t(g=>({...g,experience_years:f.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(pe,{value:s.annual_production,onChange:f=>t(g=>({...g,annual_production:f.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ps,{value:s.why_interested,onChange:f=>t(g=>({...g,why_interested:f.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(z,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(z,{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(Wr,{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(Om,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(qi,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(va,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function jor({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=_i(),[l,o]=_.useState("250000"),[c,d]=_.useState("12"),[u,h]=_.useState("70"),[m,p]=_.useState("150"),[f,g]=_.useState(""),[v,y]=_.useState(!1),[b,w]=_.useState(!1),S=s.commission_split_pct??80,C=s.cap_amount??16e3,E=s.post_cap_split_pct??100,P=s.monthly_fee??99,M=s.transaction_fee??0,I=_.useMemo(()=>{const q=parseFloat(l)||0,G=Math.max(0,parseInt(c,10)||0),V=parseFloat(u)||0,H=parseFloat(m)||0,K=q*(V/100)-H*12-M*G,Z=1-S/100,oe=Z>0?C/Z:q,re=Math.min(q,oe),ae=Math.max(0,q-oe),J=re*Z+ae*(1-E/100),te=q-J-P*12-M*G,ce=te-K;return{currentNet:K,newNet:te,diff:ce}},[l,c,u,m,S,C,E,P,M]),D=q=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(q),F=async q=>{if(q.preventDefault(),!!f){w(!0);try{const{error:G}=await U.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:f,source:"calculator"});if(G)throw G;const{error:V}=await U.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:f,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(m)||0},plan:{commission_split_pct:S,cap_amount:C,post_cap_split_pct:E,monthly_fee:P,transaction_fee:M},result:I,primary_color:t,accent_color:n}});V&&console.error("Breakdown email failed:",V),y(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(G){i({title:"Error",description:G.message,variant:"destructive"})}finally{w(!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(qj,{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(Hl,{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(qj,{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(pj,{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(ee,{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(pe,{type:"number",value:l,onChange:q=>o(q.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(pe,{type:"number",min:"0",value:c,onChange:q=>d(q.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(pe,{type:"number",value:u,onChange:q=>h(q.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{type:"number",value:m,onChange:q=>p(q.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(kl,{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:D(I.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:D(I.newNet)})]})]}),e.jsxs(Ar.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:I.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[I.diff>=0?"+":"",D(I.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:I.diff>=0?"more per year":"per year"})]},I.diff),s.show_email_capture&&!v&&e.jsxs("form",{onSubmit:F,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(pe,{type:"email",required:!0,value:f,onChange:q=>g(q.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(z,{type:"submit",disabled:b,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(Wr,{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 Nor({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=_i(),[i,l]=_.useState(""),[o,c]=_.useState(""),[d,u]=_.useState(!1),[h,m]=_.useState(!1),p=async f=>{f.preventDefault(),m(!0);try{const{error:g}=await U.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(g)throw g;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(g){a({title:"Error",description:g.message,variant:"destructive"})}finally{m(!1)}};return e.jsx("section",{className:"py-20 md:py-24 px-6 bg-white",children:e.jsx("div",{className:"max-w-3xl mx-auto",children:e.jsx(qj,{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(xj,{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(Hl,{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(Wr,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:p,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(pe,{value:o,onChange:f=>c(f.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(pe,{type:"email",required:!0,value:i,onChange:f=>l(f.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(z,{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(xj,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function kor(){const{slug:s}=Mi(),{toast:t}=_i(),[n,r]=_.useState(!1),[a,i]=_.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});_.useEffect(()=>{document.body.classList.add("recruit-landing-page");const I=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(G=>document.querySelectorAll(G).forEach(V=>V.style.display="none"))};I();const D=[setTimeout(I,500),setTimeout(I,1500),setTimeout(I,3e3)],F=new MutationObserver(I);return F.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),D.forEach(clearTimeout),F.disconnect()}},[]);const{data:l,isLoading:o,error:c}=rt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:I,error:D}=await U.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(D)throw D;return I},enabled:!!s}),{data:d}=rt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:I,error:D}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(D&&D.code!=="PGRST116")throw D;return I},enabled:!!(l!=null&&l.id)}),u=mt({mutationFn:async()=>{const I={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:D}=await U.from("recruit_interest_submissions").insert(I);if(D)throw D;U.functions.invoke("recruit-lead-notify",{body:{lead:I,brokerage_id:l.id}}).catch(F=>console.error("Lead notification error:",F))},onSuccess:()=>r(!0),onError:I=>t({title:"Error",description:I.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(oi,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,m=(h==null?void 0:h.primary_color)||"#406E71",p=(h==null?void 0:h.accent_color)||"#2a4c64",f=(h==null?void 0:h.benefits)||[],g=(h==null?void 0:h.testimonials)||[],v=(h==null?void 0:h.gallery_images)||[],y=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,b=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",w=(h==null?void 0:h.calculator_enabled)===!0,S=(h==null?void 0:h.calculator_config)||{},C=(h==null?void 0:h.lead_magnet_enabled)===!0,E=(h==null?void 0:h.lead_magnet_config)||{},P=(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(Ar.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${m}, ${p})`},children:e.jsx(Wr,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:p},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:p},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:m}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":m,"--recruit-accent":p},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:p},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${m}, ${p})`},children:["Apply Now ",e.jsx(Da,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(gor,{headline:y,subtext:b,primaryColor:m,accentColor:p,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(yor,{benefits:f,accentColor:p,primaryColor:m}),e.jsx(vor,{images:v,primaryColor:m,accentColor:p}),e.jsx(bor,{testimonials:g,primaryColor:m,accentColor:p}),w&&e.jsx(jor,{config:S,primaryColor:m,accentColor:p,brokerageId:l.id,brokerageName:l.name}),C&&e.jsx(Nor,{config:E,primaryColor:m,accentColor:p,brokerageId:l.id}),P==="multi_step"?e.jsx(wor,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p,showConfidentialBadges:M}):e.jsx(_or,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function Sor(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 Cor(){var m,p,f,g;const{shareToken:s}=Mi(),t=_.useRef(!1),{data:n,isLoading:r,error:a}=rt({queryKey:["public-recruit-video",s],queryFn:async()=>{var C;if(!s)throw new Error("No token");const{data:v,error:y}=await U.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(y)throw y;const{data:b}=await U.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(C=v.video)==null?void 0:C.owner_user_id).single(),{data:w}=await U.from("brokerages").select("name").eq("id",v.brokerage_id).single(),{data:S}=await U.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:b,brokerage:w,settings:S}},enabled:!!s});if(_.useEffect(()=>{var v;!((v=n==null?void 0:n.rv)!=null&&v.id)||t.current||(t.current=!0,U.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((p=i.prospect)==null?void 0:p.first_name)||"there",h=(f=i.video)!=null&&f.playback_url?Sor(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(dl,{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:((g=l==null?void 0:l.name)==null?void 0:g.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(z,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{U.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ya,{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 Aor="relzejiswnotikjgvjhz",jCt=`https://${Aor}.supabase.co/functions/v1/recruit-unsubscribe`;function Eor(){const[s]=Gl(),t=s.get("token")||"",[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState(""),[u,h]=_.useState({});_.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const p=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(y=>document.querySelectorAll(y).forEach(b=>b.style.display="none"))};p();const f=[setTimeout(p,500),setTimeout(p,1500),setTimeout(p,3e3)],g=new MutationObserver(p);return g.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),f.forEach(clearTimeout),g.disconnect()}},[]),_.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${jCt}?token=${encodeURIComponent(t)}`).then(async p=>{const f=await p.json();if(!p.ok)throw new Error(f.error||"Lookup failed");h(f),f.already_unsubscribed&&o(!0)}).catch(p=>h({error:p.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const p=await fetch(jCt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),f=await p.json();if(!p.ok)throw new Error(f.error||"Failed");o(!0)}catch(p){h({...u,error:p.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(bt,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):u.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Ho,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:u.error}),e.jsx("p",{className:"text-xs text-slate-400 pt-2",children:"If you continue to receive emails you don't want, please reply directly to one of them and we'll remove you immediately."})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(Mr,{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(Ch,{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(Ch,{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(ee,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ps,{id:"reason",value:c,onChange:p=>d(p.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(z,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(bt,{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 Tor="relzejiswnotikjgvjhz",NCt=`https://${Tor}.supabase.co/functions/v1/event-invite-unsubscribe`;function Mor(){const[s]=Gl(),t=s.get("token")||"",[n,r]=_.useState(!0),[a,i]=_.useState(!1),[l,o]=_.useState(!1),[c,d]=_.useState({});_.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),_.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${NCt}?token=${encodeURIComponent(t)}`).then(async h=>{const m=await h.json();if(!h.ok)throw new Error(m.error||"Lookup failed");d(m),m.already_unsubscribed&&o(!0)}).catch(h=>d({error:h.message||"Could not load status"})).finally(()=>r(!1))},[t]);const u=async()=>{i(!0);try{const h=await fetch(NCt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),m=await h.json();if(!h.ok)throw new Error(m.error||"Failed");o(!0)}catch(h){d({...c,error:h.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(bt,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):c.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Ho,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:c.error})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(Mr,{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(Ch,{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(PQ,{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(z,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(bt,{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 Por(){var I,D,F;const s=zn(),t=$t(),{isAdmin:n}=hs(),[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState(null),{data:d,isLoading:u}=rt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:q},error:G}=await U.auth.getUser();if(G)throw G;if(!q)return[];const{data:V,error:H}=await U.from("social_accounts").select("*").eq("user_id",q.id).order("created_at",{ascending:!1});if(H)throw H;return V}}),{data:h}=rt({queryKey:["google-business-status"],queryFn:async()=>{const{data:q,error:G}=await U.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(G)throw G;return q}}),m=mt({mutationFn:async q=>{const{data:G,error:V}=await U.functions.invoke("google-business-oauth",{body:{action:"set_primary_location",locationId:q}});if(V)throw V;return G},onSuccess:()=>{ne.success("Business updated"),t.invalidateQueries({queryKey:["google-business-status"]}),t.invalidateQueries({queryKey:["my-social-accounts"]})},onError:()=>ne.error("Could not update your business selection")}),p=mt({mutationFn:async()=>{const{error:q}=await U.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["google-business-status"]}),t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ne.success("Google Business disconnected")},onError:()=>ne.error("Failed to disconnect Google Business")}),f=mt({mutationFn:async q=>{const{data:{user:G},error:V}=await U.auth.getUser();if(V)throw V;if(!G)throw new Error("Not authenticated");const{error:H}=await U.from("social_accounts").delete().eq("id",q).eq("user_id",G.id);if(H)throw H},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ne.success("Account disconnected successfully")},onError:()=>{ne.error("Failed to disconnect account")}}),g=async q=>{a(!0),sessionStorage.setItem("social-connect-return-to",window.location.pathname);try{const{data:G,error:V}=await U.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:q}});if(V)throw V;if(G!=null&&G.authUrl)window.location.href=G.authUrl;else throw new Error("Failed to get authorization URL")}catch(G){console.error("Meta OAuth error:",G),ne.error("Failed to start connection. Please try again."),a(!1)}},v=async()=>{a(!0);try{const{data:q,error:G}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(G)throw G;if(q!=null&&q.authUrl)window.location.href=q.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(q){console.error("LinkedIn OAuth error:",q),ne.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:q,error:G}=await U.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/social-connections"}});if(G)throw G;if(q!=null&&q.authUrl)window.location.href=q.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(q){console.error("Google OAuth error:",q),ne.error("Failed to start Google connection. Please try again."),a(!1)}},b=(d==null?void 0:d.filter(q=>q.platform==="facebook"))||[],w=(d==null?void 0:d.filter(q=>q.platform==="instagram"))||[],S=(d==null?void 0:d.filter(q=>q.platform==="linkedin"))||[];d!=null&&d.filter(q=>q.platform==="google_business");const C=(h==null?void 0:h.connected)===!0,E=((I=h==null?void 0:h.locations)==null?void 0:I.find(q=>q.is_primary))??((D=h==null?void 0:h.locations)==null?void 0:D[0]),P=((d==null?void 0:d.length)||0)>0,M=async(q,G)=>{l(q),c(null);try{const{data:V,error:H}=await U.functions.invoke("meta-api-test",{body:{testType:"all",accountId:q}});if(H)throw H;c(V.results||[]),ne.success(V.summary||"API tests completed")}catch(V){console.error("Meta API test error:",V),ne.error("Failed to run API tests")}finally{l(null)}};return e.jsx($s,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(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(z,{variant:"ghost",onClick:()=>s("/social-studio"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Social Studio"]}),P&&e.jsx(be,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Le,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Xl,{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(be,{children:[e.jsx(_t,{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(of,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Facebook"}),e.jsx(En,{children:"Connect your Facebook Page"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Gi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(q=>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(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:q.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(of,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:q.page_name||q.platform_username||"Facebook Page"}),e.jsx(ze,{variant:q.is_active?"default":"secondary",className:"text-xs",children:q.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Facebook?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>f.mutate(q.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},q.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(z,{onClick:()=>g("facebook"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),b.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{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(Fm,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Instagram"}),e.jsx(En,{children:"Connect your Instagram Business or Creator account"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Gi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length>0?e.jsx("div",{className:"space-y-3",children:w.map(q=>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(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:q.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(Fm,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",q.platform_username||"Instagram Account"]}),e.jsx(ze,{variant:q.is_active?"default":"secondary",className:"text-xs",children:q.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Instagram?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>f.mutate(q.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},q.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(z,{onClick:()=>g("instagram"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),w.length>0?"Reconnect Instagram":"Connect Instagram"]}),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(be,{children:[e.jsx(_t,{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(fg,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"LinkedIn"}),e.jsx(En,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Gi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length>0?e.jsx("div",{className:"space-y-3",children:S.map(q=>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(ja,{className:"h-10 w-10",children:[e.jsx(xi,{src:q.profile_picture_url||""}),e.jsx(Na,{children:e.jsx(fg,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:q.platform_username||"LinkedIn Account"}),e.jsx(ze,{variant:q.is_active?"default":"secondary",className:"text-xs",children:q.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect LinkedIn?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>f.mutate(q.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},q.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(z,{onClick:v,disabled:r,className:"w-full gap-2",variant:S.length>0?"outline":"default",children:[r?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),S.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(be,{className:"relative overflow-hidden",children:[e.jsx(_t,{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(Ha,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Google Business"}),e.jsx(En,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[(h==null?void 0:h.needsReconnect)&&C&&e.jsx("div",{className:"rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-200",children:"We upgraded our Google connection. Please reconnect once so posting and reviews keep working."}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Gi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):C?e.jsx("div",{className:"space-y-3",children: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.jsx(ja,{className:"h-10 w-10",children:e.jsx(Na,{children:e.jsx(Ha,{className:"h-5 w-5"})})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(E==null?void 0:E.location_name)||(h==null?void 0:h.email)||"Google Business"}),e.jsx(ze,{variant:"default",className:"text-xs",children:"Connected"})]})]}),e.jsxs(Ql,{children:[e.jsx(Ex,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Disconnect Google Business?"}),e.jsx(ql,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:()=>p.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Google Business account connected yet"}),(((F=h==null?void 0:h.locations)==null?void 0:F.length)??0)>1&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which business should we use?"}),h.locations.map(q=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm truncate",children:q.location_name||q.location_id}),q.is_primary?e.jsx(ze,{variant:"default",className:"text-xs shrink-0",children:"Active"}):e.jsx(z,{size:"sm",variant:"outline",className:"shrink-0",disabled:m.isPending,onClick:()=>m.mutate(q.location_id),children:"Use this"})]},q.id))]}),e.jsxs(z,{onClick:y,disabled:r,className:"w-full gap-2",variant:C&&!(h!=null&&h.needsReconnect)?"outline":"default",children:[r?e.jsx(Gi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),C?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates and manage reviews from your Google Business Profile"})]})]})]}),n&&(b.length>0||w.length>0)&&e.jsxs(be,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(_t,{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(Z4,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(En,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Le,{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(q=>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(of,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:q.page_name||"Facebook Page"})]}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>M(q.id),disabled:i===q.id,children:i===q.id?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Z4,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${q.id}`)),w.map(q=>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(Fm,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",q.platform_username||"Instagram"]})]}),e.jsx(z,{size:"sm",variant:"outline",onClick:()=>M(q.id),disabled:i===q.id,children:i===q.id?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Z4,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${q.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((q,G)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[q.status==="success"?e.jsx(Mr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):q.status==="pending"?e.jsx(bt,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Bd,{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:q.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:q.details})]})]},G))})]}),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(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-lg",children:"How it works"})}),e.jsx(Le,{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 Lor(){const[s]=Gl(),t=zn(),[n,r]=_.useState("loading"),a=_.useRef(!1),[i,l]=_.useState("Processing your connection..."),[o,c]=_.useState(null),[d,u]=_.useState(!1),h=(()=>{const m=sessionStorage.getItem("social-connect-return-to");return m&&m.startsWith("/")&&!m.startsWith("/admin")?m:"/social-connections"})();return _.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var y;const p=s.get("code"),f=s.get("error"),g=s.get("error_description"),v=s.get("state");if(f){r("error"),l(g||"Authorization was denied"),ne.error("Connection failed: "+(g||f));return}if(!p){r("error"),l("No authorization code received"),ne.error("No authorization code received");return}try{const{data:b,error:w}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:p,state:v,callbackPath:"/social-connections/callback"}});if(w)throw w;if(b!=null&&b.success)r("success"),l(`Successfully connected ${((y=b.accounts)==null?void 0:y.length)||0} account(s)!`),ne.success("Social accounts connected successfully!");else throw c((b==null?void 0:b.code)||null),u(!!(b!=null&&b.existingConnectionPreserved)),new Error((b==null?void 0:b.error)||"Unknown error")}catch(b){console.error("OAuth callback error:",b),r("error");const w=b instanceof Error?b.message:"Failed to connect accounts";l(w),ne.error("Failed to connect: "+(b instanceof Error?b.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{className:"text-center",children:[n==="loading"&&e.jsx(bt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Xl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Bd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Nt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(En,{children:i})]}),e.jsxs(Le,{className:"flex flex-col items-center gap-4",children:[n==="error"&&o==="no_managed_pages"&&e.jsxs("div",{className:"w-full rounded-lg border bg-muted/40 p-4 text-left text-sm space-y-3",children:[e.jsx("p",{className:"font-medium text-foreground",children:"How to connect your Facebook Page"}),e.jsxs("ol",{className:"list-decimal space-y-1.5 pl-5 text-muted-foreground",children:[e.jsxs("li",{children:["Click ",e.jsx("span",{className:"font-medium text-foreground",children:"Try Again"})," below."]}),e.jsxs("li",{children:["On the Meta screen that lists your Pages, choose your Page by name — or pick",e.jsx("span",{className:"font-medium text-foreground",children:" Opt in to all current and future Pages"}),"."]}),e.jsx("li",{children:"Leave every permission switched on, then finish."}),e.jsx("li",{children:"If your Page still doesn’t appear, try once more so LevelUp can recover the exact Page selected in Meta."})]}),d&&e.jsx("p",{className:"font-medium text-foreground",children:"Your existing Facebook Page connection is still active."})]}),n!=="loading"&&e.jsx(z,{onClick:()=>t(h),children:n==="success"?"View Connected Accounts":"Try Again"})]})]})})}function Ior(){const[s]=Gl(),t=zn();return _.useEffect(()=>{const n=new URLSearchParams,r=s.get("error");r?n.set("google_error",r):s.get("code")&&n.set("google_error","legacy_callback_retry");const a=n.toString();t(`/apps/reviews${a?`?${a}`:""}`,{replace:!0})},[s,t]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-primary"})})}function Dor(){const[s]=Gl(),t=zn(),[n,r]=_.useState("loading"),[a,i]=_.useState("Connecting your LinkedIn account...");return _.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"),ne.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ne.error("No authorization code received");return}try{const{data:m,error:p}=await U.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(p)throw p;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),ne.success("LinkedIn connected successfully!");else throw new Error((m==null?void 0:m.error)||"Failed to connect LinkedIn account")}catch(m){console.error("LinkedIn callback error:",m),r("error"),i(m instanceof Error?m.message:"Failed to connect LinkedIn account"),ne.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(be,{className:"w-full max-w-md",children:[e.jsxs(_t,{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(bt,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Xl,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Bd,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Nt,{className:"flex items-center justify-center gap-2",children:[e.jsx(fg,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(En,{children:a})]}),e.jsx(Le,{className:"flex justify-center",children:e.jsx(z,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Ror(){const s=zn(),[t,n]=_.useState(null),{data:r,isLoading:a}=uas(t||void 0,!0),{data:i,isLoading:l}=jit(!0),{cartItems:o}=OPe(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx($s,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(ln,{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(ln,{className:"h-72 w-full"},u))})]})}):e.jsx($s,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(z,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(bS,{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(z,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx(z,{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(be,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(u),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[u.images&&u.images.length>0?e.jsx("img",{src:((h=u.images.find(m=>m.is_primary))==null?void 0:h.image_url)||u.images[0].image_url,alt:u.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Sh,{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(Le,{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(Sh,{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 Zas=_.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Zas.displayName="Breadcrumb";const Xas=_.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Ct("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));Xas.displayName="BreadcrumbList";const l3e=_.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Ct("inline-flex items-center gap-1.5",s),...t}));l3e.displayName="BreadcrumbItem";const _Ze=_.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?aQe:"a";return e.jsx(a,{ref:r,className:Ct("transition-colors hover:text-foreground",t),...n})});_Ze.displayName="BreadcrumbLink";const Qas=_.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Ct("font-normal text-foreground",s),...t}));Qas.displayName="BreadcrumbPage";const wZe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Ct("[&>svg]:size-3.5",t),...n,children:s??e.jsx(yi,{})});wZe.displayName="BreadcrumbSeparator";function For(){var G,V;const{productId:s}=Mi(),t=zn(),{data:n,isLoading:r}=Anr(s||""),{addToCart:a,cartItems:i}=OPe(),[l,o]=_.useState(null),[c,d]=_.useState(1),[u,h]=_.useState(0),[m,p]=_.useState(null),[f,g]=_.useState(!1),[v,y]=_.useState(!1),b=(G=n==null?void 0:n.variants)==null?void 0:G.find(H=>H.id===l),w=((V=n==null?void 0:n.variants)==null?void 0:V.filter(H=>H.is_active))||[],S=Number((n==null?void 0:n.base_price)||0),C=b?Number(b.price_adjustment):0,E=S+C,P=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((H,K)=>H+K.quantity,0),I=async H=>{if(!H.target.files||H.target.files.length===0)return;g(!0);const K=H.target.files[0],Z=K.name.split(".").pop(),oe=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${Z}`;try{const{error:re}=await U.storage.from("marketplace").upload(oe,K);if(re)throw re;const{data:{publicUrl:ae}}=U.storage.from("marketplace").getPublicUrl(oe);p(ae),ne.success("Artwork uploaded successfully")}catch(re){ne.error("Failed to upload artwork: "+re.message)}finally{g(!1)}},D=()=>{if(n){if(w.length>0&&!l){ne.error("Please select an option");return}a(n,b||void 0,c,m||void 0),y(!0),ne.success("Added to cart!"),setTimeout(()=>y(!1),2e3)}},F=()=>{n!=null&&n.images&&h(H=>(H+1)%n.images.length)},q=()=>{n!=null&&n.images&&h(H=>(H-1+n.images.length)%n.images.length)};return r?e.jsx($s,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(ln,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ln,{className:"h-8 w-3/4"}),e.jsx(ln,{className:"h-6 w-1/4"}),e.jsx(ln,{className:"h-24 w-full"}),e.jsx(ln,{className:"h-12 w-full"})]})]})}):n?e.jsxs($s,{title:n.name,children:[e.jsx(Zas,{className:"mb-6",children:e.jsxs(Xas,{children:[e.jsx(l3e,{children:e.jsx(_Ze,{asChild:!0,children:e.jsx(or,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(wZe,{}),e.jsx(l3e,{children:e.jsx(_Ze,{asChild:!0,children:e.jsx(or,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(wZe,{}),e.jsx(l3e,{children:e.jsx(Qas,{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(z,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:q,children:e.jsx(Wc,{className:"h-6 w-6"})}),e.jsx(z,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:F,children:e.jsx(yi,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Sh,{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((H,K)=>e.jsx("button",{onClick:()=>h(K),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${K===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:H.image_url,alt:"",className:"w-full h-full object-cover"})},H.id))}),n.video&&e.jsx(be,{children:e.jsxs(Le,{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:["$",E.toFixed(2)]}),P>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",P.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})}),w.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:w.map(H=>e.jsxs(z,{variant:l===H.id?"default":"outline",onClick:()=>o(H.id),children:[H.name,Number(H.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(H.price_adjustment)>0?"+":"","$",Number(H.price_adjustment).toFixed(2),")"]})]},H.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Upload Your Artwork (Optional)"}),m?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:m,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(z,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>p(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:I,className:"hidden",id:"artwork-upload",disabled:f}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(Ra,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:f?"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(ee,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{variant:"outline",size:"icon",onClick:()=>d(H=>Math.max(1,H-1)),children:"-"}),e.jsx(pe,{type:"number",value:c,onChange:H=>d(Math.max(1,parseInt(H.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(z,{variant:"outline",size:"icon",onClick:()=>d(H=>H+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(z,{size:"lg",className:"flex-1",onClick:D,disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(bS,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(z,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(bS,{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($s,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Sh,{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(z,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function Oor(){const s=zn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=OPe(),[d,u]=_.useState(!1),[h,m]=_.useState(""),p=async()=>{if(t.length===0){ne.error("Your cart is empty");return}u(!0);try{const{data:f,error:g}=await U.functions.invoke("marketplace-checkout",{body:{items:t.map(v=>{var y;return{product_id:v.product.id,variant_id:((y=v.variant)==null?void 0:y.id)||null,quantity:v.quantity,artwork_url:v.artworkUrl||null}}),notes:h.trim()||null}});if(g)throw g;if(f!=null&&f.url)c(),window.open(f.url,"_blank");else throw new Error("No checkout URL received")}catch(f){ne.error("Checkout failed: "+f.message)}finally{u(!1)}};return t.length===0?e.jsx($s,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(J4,{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(z,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx($s,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(f=>{var g,v;return e.jsx(be,{children:e.jsx(Le,{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:f.product.images&&f.product.images.length>0?e.jsx("img",{src:((g=f.product.images.find(y=>y.is_primary))==null?void 0:g.image_url)||f.product.images[0].image_url,alt:f.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(J4,{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:f.product.name}),f.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:f.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(f).toFixed(2),Number(f.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(f.product.shipping_fee).toFixed(2)," shipping"]})]}),f.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(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var y;return n(f.product.id,(y=f.variant)==null?void 0:y.id)},children:e.jsx(Cn,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var y;return r(f.product.id,(y=f.variant)==null?void 0:y.id,f.quantity-1)},disabled:f.quantity<=1,children:e.jsx(gN,{className:"h-3 w-3"})}),e.jsx(pe,{type:"number",value:f.quantity,onChange:y=>{var b;return r(f.product.id,(b=f.variant)==null?void 0:b.id,parseInt(y.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(z,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var y;return r(f.product.id,(y=f.variant)==null?void 0:y.id,f.quantity+1)},children:e.jsx(sn,{className:"h-3 w-3"})})]})]})]})})},`${f.product.id}-${((v=f.variant)==null?void 0:v.id)||"base"}`)}),e.jsx(z,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(be,{className:"sticky top-4",children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Order Summary"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((f,g)=>f+g.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(fc,{}),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(fc,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ps,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:f=>m(f.target.value),rows:3,className:"resize-none"})]}),e.jsx(z,{className:"w-full",size:"lg",onClick:p,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Da,{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 zor(){const s=zn(),{data:t,isLoading:n}=znr();return n?e.jsx($s,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(ln,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx($s,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Sh,{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(z,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx($s,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(be,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:Ys(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(ze,{className:wit[r.status],children:rV[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(z,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(mr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(yi,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const kCt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function Bor({currentStatus:s,statusHistory:t}){const n=kCt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:kCt.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(Mr,{className:"h-4 w-4"}):o?e.jsx(Zr,{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:rV[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ys(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function $or(){var y;const{orderId:s}=Mi(),t=zn(),{data:n,isLoading:r,refetch:a}=Bnr(s||""),i=qnr(),l=Vnr(),[o,c]=_.useState(!1),[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState(null),g=async b=>{f(b);try{await i.mutateAsync({orderId:s,itemId:b}),ne.success("Proof approved!"),a()}catch{ne.error("Failed to approve proof")}finally{f(null)}},v=async()=>{if(d){f(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ne.success("Revision requested"),c(!1),m(""),u(null),a()}catch{ne.error("Failed to request revision")}finally{f(null)}}};return r?e.jsx($s,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(ln,{className:"h-64 w-full"}),e.jsx(ln,{className:"h-48 w-full"})]}),e.jsx(ln,{className:"h-96 w-full"})]})}):n?e.jsxs($s,{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(be,{children:[e.jsxs(_t,{className:"flex flex-row items-center justify-between",children:[e.jsx(Nt,{children:"Order Status"}),e.jsx(ze,{className:wit[n.status],children:rV[n.status]})]}),e.jsx(Le,{children:e.jsx(Bor,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Items"})}),e.jsx(Le,{className:"space-y-4",children:(y=n.items)==null?void 0:y.map(b=>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:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",b.quantity," × $",Number(b.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(b.unit_price)*b.quantity).toFixed(2)]})]}),b.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:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(rP,{className:"h-4 w-4"}),"View Artwork",e.jsx(mr,{className:"h-3 w-3"})]})]}),b.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:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(rP,{className:"h-4 w-4"}),"View Proof",e.jsx(mr,{className:"h-3 w-3"})]}),b.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(z,{size:"sm",onClick:()=>g(b.id),disabled:p===b.id,children:[p===b.id?e.jsx(bt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ug,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(z,{size:"sm",variant:"outline",onClick:()=>{u(b.id),c(!0)},disabled:p===b.id,children:[e.jsx(yJ,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs(ze,{className:"bg-green-100 text-green-800",children:[e.jsx(Mr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),b.proof_status==="rejected"&&b.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:b.proof_notes})]})]})]},b.id))})]}),n.shipping_name&&e.jsxs(be,{children:[e.jsx(_t,{children:e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(vJ,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Le,{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(z,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(mr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(be,{className:"sticky top-4",children:[e.jsx(_t,{children:e.jsx(Nt,{children:"Order Summary"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Ys(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(fc,{}),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(fc,{}),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(fc,{}),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(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Request Changes"}),e.jsx(_r,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ps,{placeholder:"Describe the changes needed...",value:h,onChange:b=>m(b.target.value),rows:4}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(z,{onClick:v,disabled:!h.trim()||p!==null,children:[p?e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx($s,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Sh,{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(z,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function Uor(){const s=zn(),[t]=Gl();return t.get("session_id"),_.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx($s,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(be,{children:e.jsxs(Le,{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(Mr,{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(Sh,{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(z,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(Da,{className:"h-4 w-4 ml-2"})]}),e.jsx(z,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function qor(){const{user:s}=hs(),[t,n]=_.useState("store"),[r,a]=_.useState(null),[i,l]=_.useState(null),[o,c]=_.useState(!1),[d,u]=_.useState(5),[h,m]=_.useState(""),[p,f]=_.useState(!1),[g,v]=_.useState(!1),[y,b]=_.useState(""),[w,S]=_.useState(null),[C,E]=_.useState(!1),{hasSubmittedReview:P,submitReview:M,markPostedToGoogle:I}=jFt(),{data:D}=mas(),{data:F,isLoading:q}=has(),{data:G,isLoading:V}=Xnr(r),{data:H,isLoading:K}=Qnr(s==null?void 0:s.id),{data:Z=0}=err(s==null?void 0:s.id),oe=trr(),re=new Set((H==null?void 0:H.map(he=>he.item_id))||[]),ae=async()=>{if(i)try{const he=await oe.mutateAsync(i.id);i.item_type==="reelflow_credits"?ne.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ne.success(`Successfully purchased "${i.name}"!`),l(null)}catch(he){ne.error(he.message||"Failed to purchase item")}},J=async()=>{if(!h.trim()){ne.error("Please write a review");return}f(!0);const he=await M(d,h);f(!1),he.success?(ne.success("Thank you for your review! You earned 25 points!"),b(h),v(!0),m(""),u(5)):ne.error(he.error||"Failed to submit review")},te=()=>{navigator.clipboard.writeText(y),ne.success("Review copied to clipboard!")},ce=()=>{I(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},ve=()=>{v(!1),c(!1),b("")};return q||V||K?e.jsx($s,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ln,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(he=>e.jsx(ln,{className:"h-64"},he))})]})}):e.jsxs($s,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(be,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Le,{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(Ia,{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:Z.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(jl,{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(vu,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(f1,{open:C,onOpenChange:E,children:e.jsxs(be,{className:"border-primary/20",children:[e.jsx(x1,{asChild:!0,children:e.jsx(_t,{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(jl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Nt,{className:"text-base",children:"How to Earn Points"}),e.jsx(En,{children:"See all the ways you can earn spendable points"})]})]}),C?e.jsx(h1,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(cl,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(g1,{children:e.jsx(Le,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[D==null?void 0:D.filter(he=>he.is_active).map(he=>{const ge=Ee=>{switch(Ee){case"event_attendance":return e.jsx(ya,{className:"h-5 w-5"});case"leave_review":return e.jsx(Ia,{className:"h-5 w-5"});case"add_listing":return e.jsx(sa,{className:"h-5 w-5"});case"first_contact":return e.jsx(On,{className:"h-5 w-5"});case"first_video":return e.jsx(Xr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(qi,{className:"h-5 w-5"});default:return e.jsx(Ko,{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:ge(he.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:he.action_name}),he.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.description})]}),e.jsxs(ze,{variant:"secondary",className:"font-bold shrink-0",children:["+",he.points]})]},he.id)}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-500 shrink-0",children:e.jsx(vu,{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"})]})]})})})]})}),!P&&e.jsx(be,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Le,{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(qi,{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(z,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(Qr,{value:t,onValueChange:n,children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(J4,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Wt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Sh,{className:"h-4 w-4"}),"My Rewards",H&&H.length>0&&e.jsx(ze,{variant:"secondary",className:"ml-1",children:H.length})]})]}),e.jsxs(Kt,{value:"store",className:"mt-6",children:[F&&F.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(z,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),F.map(he=>e.jsxs(z,{variant:r===he.id?"default":"outline",size:"sm",onClick:()=>a(he.id),children:[he.icon&&`${he.icon} `,he.name]},he.id))]}),!G||G.length===0?e.jsx(be,{children:e.jsx(Le,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ko,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:G.map(he=>{const ge=he.item_type==="reelflow_credits",Ee=!ge&&re.has(he.id),Ne=!ge&&he.max_quantity!==null&&he.current_quantity===0,Pe=Z>=he.points_cost;return e.jsxs(be,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Ee?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>S(he),children:[he.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:he.preview_image_url,alt:he.name,className:"w-full h-full object-cover"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(Mr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Ne&&!Ee&&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(Ko,{className:"h-12 w-12 text-muted-foreground/50"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(ze,{className:"bg-green-500 text-white",children:[e.jsx(Mr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(_t,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Nt,{className:"text-lg",children:he.name}),e.jsxs(ze,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1"}),he.points_cost]})]}),he.category&&e.jsxs(ze,{variant:"outline",className:"w-fit",children:[he.category.icon&&`${he.category.icon} `,he.category.name]})]}),e.jsxs(Le,{children:[e.jsx(En,{className:"mb-4 line-clamp-2",children:he.description||"No description available"}),he.max_quantity!==null&&!Ee&&!ge&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[he.current_quantity," of ",he.max_quantity," remaining"]}),ge&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",he.max_quantity," ReelFlow credits per purchase"]}),Ee?e.jsx(z,{className:"w-full",onClick:Oe=>{Oe.stopPropagation(),he.file_url&&WBe(he.file_url,he.name)},disabled:!he.file_url,children:he.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(z,{className:"w-full",onClick:Oe=>{Oe.stopPropagation(),l(he)},disabled:Ne||!Pe,children:Ne?"Sold Out":Pe?e.jsxs(e.Fragment,{children:[e.jsx(J4,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${he.points_cost-Z} more pts`})]})]},he.id)})})]}),e.jsx(Kt,{value:"my-rewards",className:"mt-6",children:!H||H.length===0?e.jsx(be,{children:e.jsx(Le,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Sh,{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:H.map(he=>{var ge,Ee,Ne,Pe,Oe,ke,Ve;return e.jsxs(be,{className:"overflow-hidden",children:[(ge=he.item)!=null&&ge.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:he.item.preview_image_url,alt:((Ee=he.item)==null?void 0:Ee.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(Ko,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(_t,{className:"pb-2",children:[e.jsx(Nt,{className:"text-lg",children:((Ne=he.item)==null?void 0:Ne.name)||"Unknown Item"}),e.jsxs(En,{className:"text-xs",children:["Purchased for ",he.points_spent," points • ",new Date(he.purchased_at).toLocaleDateString()]})]}),e.jsx(Le,{children:((Pe=he.item)==null?void 0:Pe.item_type)==="reelflow_credits"?e.jsxs(z,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Mr,{className:"h-4 w-4 mr-2 text-green-500"}),(Oe=he.item)==null?void 0:Oe.max_quantity," Credits Applied"]}):e.jsx(z,{className:"w-full",onClick:()=>{var _e,Ae;(_e=he.item)!=null&&_e.file_url&&WBe(he.item.file_url,(Ae=he.item)==null?void 0:Ae.name)},disabled:!((ke=he.item)!=null&&ke.file_url),children:((Ve=he.item)==null?void 0:Ve.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},he.id)})})})]})]}),e.jsx(Ql,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(zl,{children:[e.jsxs(Bl,{children:[e.jsx(Ul,{children:"Confirm Purchase"}),e.jsxs(ql,{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:[Z," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[Z-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs($l,{children:[e.jsx(Vl,{children:"Cancel"}),e.jsx(Ml,{onClick:ae,disabled:oe.isPending,children:oe.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(Is,{open:o,onOpenChange:he=>{!he&&g?ve():c(he)},children:e.jsx(Ls,{children:g?e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Mr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(_r,{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:['"',y,'"']})]}),e.jsxs(z,{variant:"outline",className:"w-full",onClick:te,children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(hr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(z,{variant:"outline",onClick:ve,children:"Maybe Later"}),e.jsxs(z,{onClick:ce,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Leave a Review"}),e.jsx(_r,{children:"Share your experience with LevelUp and earn 25 spendable points!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Rating"}),e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(he=>e.jsx("button",{type:"button",onClick:()=>u(he),className:"focus:outline-none",children:e.jsx(Ia,{className:`h-8 w-8 transition-colors ${d>=he?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},he))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ps,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:he=>m(he.target.value),rows:4})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(z,{onClick:J,disabled:p,className:"bg-yellow-600 hover:bg-yellow-700",children:p?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(Is,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Ls,{className:"max-w-lg",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[w==null?void 0:w.name,e.jsxs(ze,{variant:"secondary",className:"font-bold",children:[e.jsx(Ia,{className:"h-3 w-3 mr-1"}),w==null?void 0:w.points_cost]})]}),(w==null?void 0:w.category)&&e.jsxs(ze,{variant:"outline",className:"w-fit",children:[w.category.icon&&`${w.category.icon} `,w.category.name]})]}),(w==null?void 0:w.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:w.preview_image_url,alt:w.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(w==null?void 0:w.description)||"No description available"}),(w==null?void 0:w.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",w==null?void 0:w.max_quantity," ReelFlow credits per purchase"]}),(w==null?void 0:w.item_type)!=="reelflow_credits"&&(w==null?void 0:w.max_quantity)!==null&&!re.has((w==null?void 0:w.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[w==null?void 0:w.current_quantity," of ",w==null?void 0:w.max_quantity," remaining"]})]}),e.jsx(hr,{children:w&&w.item_type!=="reelflow_credits"&&re.has(w.id)?e.jsx(z,{className:"w-full",onClick:()=>{w.file_url&&WBe(w.file_url,w.name)},disabled:!w.file_url,children:w.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Access"]})}):w&&e.jsx(z,{className:"w-full",onClick:()=>{S(null),l(w)},disabled:w.item_type!=="reelflow_credits"&&w.max_quantity!==null&&w.current_quantity===0||Z{s&&K()},[s==null?void 0:s.id]);const K=async()=>{if(!s)return;o(!0),y(!1),g(!0);const{data:Oe}=await U.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Oe==null||Oe.forEach(Ae=>{Ae.action_key==="referral_signup"&&h(Ae.points),Ae.action_key==="referral_paid"&&p(Ae.points)});const{data:ke}=await U.from("profiles").select("name").eq("id",s.id).maybeSingle();ke!=null&&ke.name&&w(ke.name);let{data:Ve}=await U.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ve){const{data:Ae}=await U.rpc("generate_agent_referral_code",{_user_id:s.id}),Se=Ae||`agent${s.id.slice(0,6)}`,{data:We,error:qe}=await U.from("agent_referral_codes").insert({user_id:s.id,code:Se}).select("code").maybeSingle();!qe&&We&&(Ve=We)}i((Ve==null?void 0:Ve.code)??null);const{data:_e}=await U.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(_e&&_e.length>0){const Ae=_e.map(qe=>qe.referred_user_id),{data:Se}=await U.from("profiles").select("id, name, email").in("id",Ae),We=new Map((Se==null?void 0:Se.map(qe=>[qe.id,qe]))??[]);d(_e.map(qe=>({...qe,referred_profile:We.get(qe.referred_user_id)??null})))}else d([]);o(!1)},Z=_.useMemo(()=>a?`${Vor}/trial?ref=${a}`:"",[a]),oe=c.length,re=c.filter(Oe=>Oe.status==="qualified").length,ae=c.filter(Oe=>Oe.signup_points_awarded).length*u+c.filter(Oe=>Oe.paid_points_awarded).length*m,J=async()=>{Z&&(await navigator.clipboard.writeText(Z),ne.success("Referral link copied!"))},te=()=>{const Oe=encodeURIComponent("Join me on LevelUp"),ke=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: ${Z} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Oe}&body=${ke}`},ce=()=>{const Oe=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${Z}`);window.location.href=`sms:?&body=${Oe}`},ve=async()=>{if(navigator.share&&Z)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:Z})}catch{}else J()},me=Oe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Oe.trim()),he=Oe=>{const ke=(Oe??E).trim().replace(/,$/,"");if(!ke)return;const Ve=ke.split(/[\s,;]+/).filter(Boolean),_e=[...M];let Ae=0;for(const Se of Ve){if(!me(Se)){ne.error(`Invalid email: ${Se}`);continue}_e.includes(Se)||(_e.push(Se),Ae++)}I(_e),Ae>0&&P("")},ge=Oe=>I(M.filter(ke=>ke!==Oe)),Ee=()=>{G(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),F("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."),C(!0)},Ne=Oe=>{const ke=Oe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ve=b||"A fellow agent",_e="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Ae=Z;return`
LevelUp
You're Invited

${Ve} thinks you'd love LevelUp 🎉

${ke}

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

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

`.trim()},Pe=async()=>{if(M.length===0&&(E.trim()&&he(),M.length===0)){ne.error("Add at least one recipient");return}if(!q.trim()){ne.error("Subject is required");return}H(!0);const Oe=Ne(D);let ke=0,Ve=0;for(const _e of M)try{const{data:Ae,error:Se}=await U.functions.invoke("gmail-send",{body:{to:_e,subject:q,body:Oe,source:"referral_invite"}});if(Se||Ae!=null&&Ae.error)throw new Error((Se==null?void 0:Se.message)||(Ae==null?void 0:Ae.error));ke++}catch(Ae){console.error("Gmail send failed for",_e,Ae),Ve++}H(!1),ke>0?(ne.success(`Invite sent to ${ke} ${ke===1?"person":"people"}`+(Ve>0?` (${Ve} failed)`:"")),I([]),P(""),C(!1)):ne.error("Failed to send invites")};return!v&&!f?e.jsx($s,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(dl,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(be,{className:"border-2 border-dashed",children:[e.jsxs(_t,{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(Hl,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Nt,{children:"Refer & Earn is for active members"}),e.jsx(En,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Le,{className:"flex justify-center",children:e.jsx(z,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs($s,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(dl,{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(Ko,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[m," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(On,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(Mr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:re}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(jl,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ae.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(be,{children:[e.jsxs(_t,{children:[e.jsxs(Nt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(En,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{readOnly:!0,value:l?"Loading…":Z,className:"font-mono text-sm",onFocus:Oe=>Oe.currentTarget.select()}),e.jsxs(z,{onClick:J,disabled:!Z,children:[e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs(z,{size:"sm",onClick:Ee,disabled:!Z,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:te,disabled:!Z,children:[e.jsx(on,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:ce,disabled:!Z,children:[e.jsx(qi,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:ve,disabled:!Z,children:[e.jsx(sd,{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(be,{children:[e.jsxs(_t,{children:[e.jsx(Nt,{children:"Your Referrals"}),e.jsx(En,{children:"Track who joined and when they upgrade."})]}),e.jsx(Le,{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(On,{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(Oe=>{var _e,Ae;const ke=((_e=Oe.referred_profile)==null?void 0:_e.name)||((Ae=Oe.referred_profile)==null?void 0:Ae.email)||"New agent",Ve=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Oe.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:ke}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Ve]})]}),Oe.status==="qualified"?e.jsxs(ze,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Mr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(ze,{variant:"secondary",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Oe.id)})})})]}),e.jsx(be,{className:"bg-muted/30",children:e.jsxs(Le,{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:[m," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(fc,{className:"opacity-0"})]}),e.jsx(Is,{open:S,onOpenChange:C,children:e.jsxs(Ls,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(_r,{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(ee,{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(Oe=>e.jsxs(ze,{variant:"secondary",className:"gap-1 pr-1",children:[Oe,e.jsx("button",{type:"button",onClick:()=>ge(Oe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Oe}`,children:e.jsx(er,{className:"h-3 w-3"})})]},Oe)),e.jsx("input",{type:"email",value:E,onChange:Oe=>P(Oe.target.value),onKeyDown:Oe=>{Oe.key==="Enter"||Oe.key===","||Oe.key===" "?(Oe.preventDefault(),he()):Oe.key==="Backspace"&&!E&&M.length>0&&I(M.slice(0,-1))},onBlur:()=>E.trim()&&he(),onPaste:Oe=>{const ke=Oe.clipboardData.getData("text");/[\s,;]/.test(ke)&&(Oe.preventDefault(),he(ke))},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(ee,{htmlFor:"email-subject",children:"Subject"}),e.jsx(pe,{id:"email-subject",value:q,onChange:Oe=>G(Oe.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ps,{id:"personal-note",value:D,onChange:Oe=>F(Oe.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(ee,{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: ",q||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Ne(D),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>C(!1),disabled:V,children:"Cancel"}),e.jsxs(z,{onClick:Pe,disabled:V,children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),V?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const Jas=()=>{const{user:s}=hs(),t=$t(),n=rt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=rt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=mt({mutationFn:async d=>{const{data:u,error:h}=await U.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=mt({mutationFn:async({id:d,...u})=>{const{data:h,error:m}=await U.from("smart_presentations").update(u).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=mt({mutationFn:async d=>{const{data:u,error:h}=await U.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"]}),ne.success("Presentation published!")}}),o=mt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ne.success("Presentation archived")}}),c=mt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ne.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}},Gor=()=>{const s=zn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=Jas(),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),ne.success("Link copied!")};return e.jsx($s,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(z,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(ln,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(be,{children:e.jsxs(Le,{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(C0,{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(z,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(be,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Le,{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($r,{className:"h-5 w-5 text-primary"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:o.title}),i(o)]}),e.jsxs("div",{className:"flex items-center gap-x-3 gap-y-0.5 flex-wrap text-sm text-muted-foreground mt-0.5",children:[o.client_name&&e.jsx("span",{children:o.client_name}),e.jsxs("span",{children:["Created ",Ys(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xa,{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(z,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(z,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(z,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ng,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(ua,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ua,{onClick:()=>a.mutate(o),children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ua,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(w0,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},SCt={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."}]},Wor=[{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 Kor(s){const t=SCt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(SCt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return Wor}function Yor({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=_.useState(!1),[i,l]=_.useState("script"),[o,c]=_.useState(0),[d,u]=_.useState(0),{canRecord:h}=fZt(),m=RC(),[p,f]=_.useState(""),[g,v]=_.useState(!1),[y,b]=_.useState(!0),[w,S]=_.useState(!1),[C,E]=_.useState(null),P=Kor(s),M=()=>{l("script"),c(0),u(0),f(""),v(!1),b(!0),S(!1),E(null)},I=V=>{!V&&(i==="uploading"||i==="processing")||(a(V),V||M())},D=V=>{E(V),f(P[V].text),v(!1)},F=()=>{l("record"),b(p.trim().length>0)},q=()=>{f(""),b(!1),l("record")},G=_.useCallback(async(V,H)=>{l("uploading");try{const K=s||"Presentation Video",{videoId:Z,uploadUrl:oe,libraryId:re}=await qL(K),{apiKey:ae}=await VL(Z),J=new XMLHttpRequest;J.upload.onprogress=he=>{he.lengthComputable&&c(he.loaded/he.total*100)},await new Promise((he,ge)=>{J.onload=()=>J.status>=200&&J.status<300?he():ge(new Error("Upload failed")),J.onerror=()=>ge(new Error("Upload failed")),J.open("PUT",oe),J.setRequestHeader("AccessKey",ae),J.send(V)}),l("processing");let te=0;const ce=Date.now(),ve=9e4;let me=null;for(;te<4;){if(await new Promise(ge=>setTimeout(ge,3e3)),Date.now()-ce>ve){const ge=V.size/1048576,Ee=`https://iframe.mediadelivery.net/embed/${re}/${Z}?responsive=true`;await m.mutateAsync({bunny_video_id:Z,playback_url:Ee,file_size_mb:ge,title:K,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ee),ne.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const he=await DN(Z);if(te=he.status,u(he.encodeProgress||0),te===4)me={playbackUrl:he.directPlayUrl,thumbnailUrl:he.thumbnailUrl,previewUrl:he.previewUrl||null,duration:he.length||H,fileSizeMb:(he.storageSize||V.size)/(1024*1024)};else if(te===5||te===6)throw new Error("Video processing failed")}if(!me)throw new Error("No video data");await m.mutateAsync({bunny_video_id:Z,contact_id:t||void 0,playback_url:me.playbackUrl,thumbnail_url:me.thumbnailUrl,preview_url:me.previewUrl,duration_seconds:me.duration,file_size_mb:me.fileSizeMb,title:K,status:"ready",touch_type:"presentation"}),n(me.playbackUrl),ne.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(K){console.error("Recording upload error:",K),ne.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(Is,{open:r,onOpenChange:I,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Ls,{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(Os,{children:e.jsxs(Rs,{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:P.map((V,H)=>e.jsxs("button",{onClick:()=>D(H),className:Ct("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",C===H?"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($r,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:V.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:V.text})]},H))})]}),p&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!g&&e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Wa,{className:"h-3 w-3"}),"Edit"]})]}),g?e.jsx(Ps,{value:p,onChange:V=>f(V.target.value),rows:5,placeholder:"Type your script here...",className:"text-sm"}):e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-sm text-foreground leading-relaxed",children:p})]}),!p&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(Ps,{value:p,onChange:V=>{f(V.target.value),E(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(z,{variant:"ghost",size:"sm",onClick:q,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(z,{onClick:F,disabled:!1,children:p.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(nl,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),p.trim()&&e.jsxs(z,{variant:"ghost",size:"sm",onClick:()=>b(!y),className:"h-7 text-xs gap-1",children:[y?e.jsx(Yf,{className:"h-3 w-3"}):e.jsx(xa,{className:"h-3 w-3"}),y?"Hide Script":"Show Script"]})]}),e.jsx(YE,{maxDurationSeconds:600,onRecordingComplete:G,onRecordingStateChange:S,onError:V=>ne.error(V),teleprompterContent:p.trim()?e.jsx(Iat,{text:p,isVisible:y,onToggleVisibility:()=>b(!y),isRecording:w,startCountdown:!1}):void 0}),e.jsx(z,{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(bt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Di,{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(bt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Di,{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(Xl,{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 Zor({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=_.useState(!1),[i,l]=_.useState(null),[o,c]=_.useState("idle"),[d,u]=_.useState(0),h=_.useRef(null),m=RC(),{data:p}=h8e(),f=(p==null?void 0:p.total_storage_mb)||0,v=((p==null?void 0:p.max_storage_mb)||1024)-f,y=()=>{l(null),c("idle"),u(0)},b=P=>{!P&&o!=="idle"&&o!=="done"||(a(P),P||y())},w=P=>{var D;const M=(D=P.target.files)==null?void 0:D[0];if(!M)return;if(!M.type.startsWith("video/")){ne.error("Please select a video file");return}const I=M.size/(1024*1024);if(I>500){ne.error("Video file must be less than 500MB");return}if(I>v){ne.error(`Not enough storage. You have ${v.toFixed(1)} MB remaining.`);return}l(M)},S=_.useCallback(async()=>{if(i){c("creating"),u(0);try{const P=s||i.name,{data:M,error:I}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:P,isAgentVideo:!0}});if(I)throw new Error(I.message);const{videoId:D,libraryId:F}=M;c("uploading");const{data:q,error:G}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:D,isAgentVideo:!0}});if(G)throw new Error(G.message);await new Promise((K,Z)=>{const oe=new XMLHttpRequest;oe.upload.addEventListener("progress",re=>{re.lengthComputable&&u(Math.round(re.loaded/re.total*100))}),oe.addEventListener("load",()=>oe.status>=200&&oe.status<300?K():Z(new Error(`Upload failed (${oe.status})`))),oe.addEventListener("error",()=>Z(new Error("Upload failed"))),oe.open("PUT",q.uploadUrl),oe.setRequestHeader("AccessKey",q.apiKey),oe.send(i)}),c("processing");const V=i.size/(1024*1024),H=`https://iframe.mediadelivery.net/embed/${F}/${D}`;await m.mutateAsync({bunny_video_id:D,playback_url:H,file_size_mb:V,title:P,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(H),c("done"),ne.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(P){console.error("Upload error:",P),ne.error(P instanceof Error?P.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),C=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},E=o!=="idle"&&o!=="done";return e.jsxs(Is,{open:r,onOpenChange:b,children:[e.jsx(rl,{asChild:!0,children:e.jsxs(z,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(Ra,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Ls,{className:"sm:max-w-md",children:[e.jsx(Os,{children:e.jsxs(Rs,{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(Xr,{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"]})]}),!E&&e.jsx(z,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(er,{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 P;return(P=h.current)==null?void 0:P.click()},children:[e.jsx(Ra,{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:w,disabled:E}),E&&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(bt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:C()})]}),e.jsx(Di,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>b(!1),disabled:E,children:"Cancel"}),e.jsx(z,{onClick:S,disabled:!i||E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const CCt=[{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"}],ACt=()=>{const s=zn(),{id:t}=Mi(),{user:n}=hs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Jas(),{isGmailConnected:c,gmailEmail:d}=bg(),[u,h]=_.useState(!1),[m,p]=_.useState("client"),[f,g]=_.useState(!1),[v,y]=_.useState(""),[b,w]=_.useState([]),[S,C]=_.useState(!1),[E,P]=_.useState(null),[M,I]=_.useState(!1),[D,F]=_.useState(""),[q,G]=_.useState(""),[V,H]=_.useState(""),[K,Z]=_.useState("buyer"),[oe,re]=_.useState(""),[ae,J]=_.useState(null),[te,ce]=_.useState(""),[ve,me]=_.useState([]),[he,ge]=_.useState("schedule_call"),[Ee,Ne]=_.useState("Schedule a Call"),[Pe,Oe]=_.useState(""),[ke,Ve]=_.useState(""),[_e,Ae]=_.useState(null),[Se,We]=_.useState(t||null),[qe,Be]=_.useState(null),[Ze,$e]=_.useState(!1),Xe=async(wt,Us)=>{if(!n)return;const Es=5*1024*1024;if(wt.size>Es){ne.error("Image must be under 5MB");return}if(!wt.type.startsWith("image/")){ne.error("Please upload an image file");return}Ae(Us);try{const kn=wt.name.split(".").pop()||"jpg",Sn=`${n.id}/${Date.now()}.${kn}`,{error:bn}=await U.storage.from("listing-photos").upload(Sn,wt);if(bn)throw bn;const{data:{publicUrl:cr}}=U.storage.from("listing-photos").getPublicUrl(Sn);qt(Us,{image_url:cr}),ne.success("Image uploaded")}catch{ne.error("Failed to upload image")}finally{Ae(null)}};_.useEffect(()=>{t&&nt(t)},[t]);const nt=async wt=>{const{data:Us,error:Es}=await U.from("smart_presentations").select("*").eq("id",wt).single();if(Es||!Us)return;const kn=Us;if(g(!0),ce(kn.title),F(kn.client_name||""),re(kn.property_address||""),me(kn.sections||[]),ge(kn.cta_type||"schedule_call"),Ne(kn.cta_label||"Schedule a Call"),Oe(kn.cta_url||""),Ve(kn.heading||""),Be(kn.share_token),$e(kn.status==="published"),We(kn.id),p("builder"),kn.contact_id){const{data:Sn}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",kn.contact_id).maybeSingle();Sn&&(P(Sn),G(Sn.email||""),H(Sn.phone||""))}};_.useEffect(()=>{if(!n||v.length<1){w([]);return}const wt=setTimeout(async()=>{C(!0);const{data:Us}=await U.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);w(Us||[]),C(!1)},300);return()=>clearTimeout(wt)},[v,n]);const Ge=wt=>{P(wt),F(`${wt.first_name} ${wt.last_name||""}`.trim()),G(wt.email||""),H(wt.phone||""),I(!1)},Je=async()=>{if(!D.trim()){ne.error("Client name is required");return}const wt=D.trim().split(" "),Us=wt[0],Es=wt.slice(1).join(" ")||null,{data:kn,error:Sn}=await U.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Us,last_name:Es,email:q||null,phone:V||null,lead_source:"Smart Presentation"}).select().single();if(Sn){ne.error("Failed to create client");return}P(kn),ne.success("Client created & saved to Agent OS"),p("template")},ut=wt=>{J(wt);const Us=(wt.sections||[]).map(Es=>({...Es,is_visible:!0,video_url:"",text:""}));if(me(Us),ce(wt.name+(D?` for ${D}`:"")),wt.cta_config){const Es=wt.cta_config;ge(Es.type||"schedule_call"),Ne(Es.label||"Schedule a Call")}p("builder")},lt=()=>{me([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ce(D?`Presentation for ${D}`:"New Presentation"),p("builder")},qt=(wt,Us)=>{me(Es=>Es.map((kn,Sn)=>Sn===wt?{...kn,...Us}:kn))},zt=wt=>{qt(wt,{is_visible:!ve[wt].is_visible})},Zt=()=>{me(wt=>[...wt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},ms=wt=>{me(Us=>Us.filter((Es,kn)=>kn!==wt))},Dt=async()=>{if(!te.trim()){ne.error("Title is required");return}try{if(Se){const wt=await l.mutateAsync({id:Se,title:te,sections:ve,client_name:D,property_address:oe||null,cta_type:he,cta_label:Ee,cta_url:Pe||null,heading:ke||null});ne.success("Saved")}else{const wt=await i.mutateAsync({title:te,contact_id:(E==null?void 0:E.id)||void 0,client_name:D,property_address:oe||void 0,template_id:(ae==null?void 0:ae.id)||void 0,sections:ve,cta_type:he,cta_label:Ee,cta_url:Pe||void 0,heading:ke||void 0});We(wt.id),Be(wt.share_token),ne.success("Presentation created!")}}catch(wt){console.error("Failed to save presentation:",wt);const Us=(wt==null?void 0:wt.message)||(wt==null?void 0:wt.toString())||"Unknown error";ne.error(`Failed to save: ${Us}`)}},It=async()=>{try{await Dt();const wt=Se;if(wt){const Us=await o.mutateAsync(wt);Be(Us.share_token),$e(!0),p("share")}}catch(wt){console.error("Failed to publish presentation:",wt),ne.error(`Failed to publish: ${(wt==null?void 0:wt.message)||"Unknown error"}`)}},qs=qe?`https://presentations.relevelup.com/${qe}`:"";return e.jsx($s,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:f?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m==="client"&&"Who is this presentation for?",m==="template"&&"Choose a starting template",m==="builder"&&"Customize your presentation",m==="share"&&"Share with your client"]})]})]}),!f&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((wt,Us)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Ct("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===wt?"bg-primary text-primary-foreground":Us<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Us<["client","template","builder","share"].indexOf(m)?e.jsx(Wr,{className:"h-4 w-4"}):Us+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:wt}),Us<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},wt))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{P(null),F(""),G(""),H(""),I(!1),p("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Fr,{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(Da,{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(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Rr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:v,onChange:wt=>y(wt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[S&&e.jsx(ln,{className:"h-12 w-full"}),b.map(wt=>e.jsxs("button",{onClick:()=>Ge(wt),className:Ct("w-full text-left p-3 rounded-lg border transition-colors",(E==null?void 0:E.id)===wt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[wt.first_name," ",wt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:wt.email||wt.phone||"No contact info"})]},wt.id)),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),v&&b.length===0&&!S&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),E&&e.jsxs(z,{onClick:()=>p("template"),className:"w-full gap-2",children:["Continue with ",E.first_name,e.jsx(Da,{className:"h-4 w-4"})]})]})]}),e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Le,{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(ee,{className:"text-xs",children:"Name *"}),e.jsx(pe,{value:D,onChange:wt=>{F(wt.target.value),I(!0),P(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Email"}),e.jsx(pe,{value:q,onChange:wt=>G(wt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{value:V,onChange:wt=>H(wt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Client Type"}),e.jsxs(ls,{value:K,onValueChange:Z,children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"buyer",children:"Buyer"}),e.jsx(He,{value:"seller",children:"Seller"}),e.jsx(He,{value:"recruit",children:"Recruit"}),e.jsx(He,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Property Address"}),e.jsx(pe,{value:oe,onChange:wt=>re(wt.target.value),placeholder:"Optional"})]})]}),M&&D&&e.jsxs(z,{onClick:Je,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Da,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Qr,{defaultValue:"system",children:[e.jsxs(Jr,{children:[e.jsx(Wt,{value:"mine",children:"My Core Templates"}),e.jsx(Wt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Wt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Kt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(wt=>e.jsx(ln,{className:"h-32"},wt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(wt=>!wt.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(wt=>!wt.is_system).map(wt=>e.jsx(ECt,{template:wt,onSelect:ut},wt.id))})}),e.jsx(Kt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(wt=>wt.is_system).map(wt=>e.jsx(ECt,{template:wt,onSelect:ut},wt.id))})}),e.jsx(Kt,{value:"blank",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Le,{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(z,{onClick:lt,children:"Start from Scratch"})]})})})]}),e.jsxs(z,{variant:"outline",onClick:()=>p("client"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(Le,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Presentation Title"}),e.jsx(pe,{value:te,onChange:wt=>ce(wt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Page Heading"}),e.jsx(pe,{value:ke,onChange:wt=>Ve(wt.target.value),placeholder:D?`Welcome, ${D}!`:"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(ee,{children:"Client Name"}),e.jsx(pe,{value:D,onChange:wt=>F(wt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Property Address"}),e.jsx(pe,{value:oe,onChange:wt=>re(wt.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(z,{variant:"outline",size:"sm",onClick:Zt,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:ve.map((wt,Us)=>e.jsx(be,{className:Ct(!wt.is_visible&&"opacity-50"),children:e.jsx(Le,{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(Zf,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:wt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(pe,{value:wt.title,onChange:Es=>qt(Us,{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(z,{variant:"ghost",size:"icon",onClick:()=>zt(Us),children:wt.is_visible?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Yf,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"icon",onClick:()=>ms(Us),className:"text-destructive hover:text-destructive",children:e.jsx(Cn,{className:"h-4 w-4"})})]})]}),e.jsx(pe,{value:wt.description||"",onChange:Es=>qt(Us,{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(ee,{className:"text-xs",children:"Video URL"}),e.jsx(pe,{value:wt.video_url||"",onChange:Es=>qt(Us,{video_url:Es.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(Yor,{sectionTitle:wt.title,contactId:E==null?void 0:E.id,onVideoReady:Es=>qt(Us,{video_url:Es})}),e.jsx(Zor,{sectionTitle:wt.title,contactId:E==null?void 0:E.id,onVideoReady:Es=>qt(Us,{video_url:Es})}),e.jsx(pz,{userId:n==null?void 0:n.id,onSelect:Es=>qt(Us,{video_url:Es})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),wt.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:wt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(z,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>qt(Us,{image_url:""}),children:e.jsx(er,{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:[_e===Us?e.jsx(bt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(N0,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:_e===Us?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:_e===Us,onChange:Es=>{var Sn;const kn=(Sn=Es.target.files)==null?void 0:Sn[0];kn&&Xe(kn,Us),Es.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Text (optional)"}),e.jsx(GN,{content:wt.text||"",onChange:Es=>qt(Us,{text:Es}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Us))})]}),e.jsxs(be,{children:[e.jsx(_t,{children:e.jsx(Nt,{className:"text-base",children:"Call to Action"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"CTA Type"}),e.jsxs(ls,{value:he,onValueChange:wt=>{ge(wt);const Us=CCt.find(Es=>Es.value===wt);Us&&Ne(Us.label)},children:[e.jsx(rs,{children:e.jsx(cs,{})}),e.jsx(as,{children:CCt.map(wt=>e.jsx(He,{value:wt.value,children:wt.label},wt.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Button Label"}),e.jsx(pe,{value:Ee,onChange:wt=>Ne(wt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(ee,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(pe,{value:Pe,onChange:wt=>Oe(wt.target.value),placeholder:"https://calendly.com/..."}),!Pe&&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:[!f&&e.jsxs(z,{variant:"outline",onClick:()=>p("template"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(z,{variant:"outline",onClick:Dt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(z,{onClick:It,disabled:o.isPending,className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),Ze?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&qe&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(Le,{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(Wr,{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 ",D||"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(pe,{value:qs,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(z,{onClick:()=>{navigator.clipboard.writeText(qs),ne.success("Link copied!")},children:e.jsx(Sa,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(z,{variant:"outline",className:"gap-2",onClick:()=>{const wt=`Hi ${D||""}! I put together something for you — check it out: ${qs}`;navigator.clipboard.writeText(wt),ne.success("Message copied!")},children:[e.jsx(qi,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(z,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${q||""}?subject=${encodeURIComponent(te)}&body=${encodeURIComponent(`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${qs} Looking forward to connecting!`)}`)},children:[e.jsx(on,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(HN,{open:u,onOpenChange:h,contact:E?{id:E.id,first_name:E.first_name,last_name:E.last_name,email:q||E.email||""}:q?{id:"",first_name:(D==null?void 0:D.split(" ")[0])||"",last_name:(D==null?void 0:D.split(" ").slice(1).join(" "))||"",email:q}:void 0,defaultSubject:te,defaultBody:`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${qs} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(z,{variant:"outline",onClick:()=>p("builder"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(z,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},ECt=({template:s,onSelect:t})=>e.jsx(be,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Le,{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(z,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),Xor=()=>{var g;const{shareToken:s}=Mi(),[t,n]=_.useState(null),[r,a]=_.useState(!0),[i,l]=_.useState(0),[o,c]=_.useState(!1);_.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),_.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:v,error:y}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(y||!v){c(!0),a(!1);return}const{data:b}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",v.owner_user_id).single();let w;if(b!=null&&b.brokerage_id){const{data:C}=await U.from("brokerages").select("name").eq("id",b.brokerage_id).single();w=(C==null?void 0:C.name)||void 0}let S=null;if(v.contact_id){const{data:C}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",v.contact_id).single();S=C}n({...v,owner_name:b==null?void 0:b.name,owner_email:b==null?void 0:b.email,owner_phone:b==null?void 0:b.phone,owner_avatar:b==null?void 0:b.avatar_url,owner_title:(b==null?void 0:b.title)||void 0,brokerage_name:w,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await U.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 U.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(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(ln,{className:"h-12 w-3/4 mx-auto"}),e.jsx(ln,{className:"h-64 w-full"}),e.jsx(ln,{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),m=h[i],p=v=>{const y=v.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(y)return`https://www.youtube.com/embed/${y[1]}?rel=0`;if(v.includes("iframe.mediadelivery.net/play/")){const S=v.replace("/play/","/embed/"),C=S.includes("?")?"&":"?";return`${S}${C}responsive=true`}if(v.includes("iframe.mediadelivery.net")){if(v.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const C=v.includes("?")?"&":"?";return`${v}${C}responsive=true`}return""}const b=v.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const w=v.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return w?`https://iframe.mediadelivery.net/embed/${w[1]}/${w[2]}?responsive=true`:v},f=!!((g=t.cta_url)!=null&&g.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[m!=null&&m.video_url&&p(m.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:p(m.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):m!=null&&m.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:m==null?void 0:m.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:m==null?void 0:m.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:m==null?void 0:m.description})]}),(m==null?void 0:m.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((v,y)=>e.jsx("button",{onClick:()=>l(y),className:Ct("w-full text-left p-4 rounded-xl border transition-all",i===y?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(y+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children: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})]})]})},y))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),f?e.jsxs(z,{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(mr,{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(fOt,{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"})]})},s$e="__none__";function Qor({value:s,onChange:t}){const{data:n=[],isLoading:r}=Vae(),a=Xnt(),[i,l]=_.useState(!1),o=_.useMemo(()=>n.filter(h=>!h.is_starter),[n]),c=_.useMemo(()=>n.find(h=>h.is_starter&&/open house/i.test(h.name||"")),[n]),d=_.useMemo(()=>o.some(h=>/open house/i.test(h.name||"")),[o]),u=async()=>{if(c){l(!0);try{const h=await a.mutateAsync(c.id);h!=null&&h.id&&t(h.id),la({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){la({title:"Could not add campaign",description:(h==null?void 0:h.message)??"Please try again.",variant:"destructive"})}finally{l(!1)}}};return e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(mP,{className:"h-4 w-4 text-emerald-600"}),"Auto follow-up campaign"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everyone who signs in with an email is automatically enrolled."})]}),s&&e.jsx(ze,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(ls,{value:s??s$e,onValueChange:h=>t(h===s$e?null:h),disabled:r,children:[e.jsx(rs,{children:e.jsx(cs,{placeholder:"No follow-up campaign"})}),e.jsxs(as,{children:[e.jsx(He,{value:s$e,children:"No follow-up campaign"}),o.map(h=>e.jsxs(He,{value:h.id,children:[h.icon?`${h.icon} `:"",h.name,h.is_active?"":" (paused)"]},h.id))]})]}),c&&!d&&e.jsxs(z,{type:"button",variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:u,disabled:i,children:[i?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(un,{className:"h-3.5 w-3.5 text-primary"}),'Add the "Open House Follow-Up" starter (6 emails)']}),o.length===0&&!c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a campaign in Smart Drips first, then choose it here."})]})}function Jor({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=APs(s),i=PPs(),l=LPs(),o=IPs(),c=DPs(),[d,u]=_.useState(""),[h,m]=_.useState("rating"),p=async y=>{n(y),y&&(!r||r.length===0)&&await c.mutateAsync(s)},f=async()=>{if(!d.trim())return;const y=(r==null?void 0:r.reduce((b,w)=>Math.max(b,w.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:y+1}),u("")},g=async y=>{await l.mutateAsync({id:y.id,open_house_id:s,is_active:!y.is_active})},v=async y=>{await o.mutateAsync({id:y.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(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Wf,{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(mn,{checked:t,onCheckedChange:p})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(bt,{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(y=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Zf,{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:y.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:y.question_type.replace("_"," ")})]}),e.jsx(mn,{checked:y.is_active,onCheckedChange:()=>g(y),className:"scale-75"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>v(y),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})]},y.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(pe,{value:d,onChange:y=>u(y.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:y=>y.key==="Enter"&&f()})]}),e.jsxs(ls,{value:h,onValueChange:m,children:[e.jsx(rs,{className:"w-28 h-9 text-xs",children:e.jsx(cs,{})}),e.jsxs(as,{children:[e.jsx(He,{value:"rating",children:"Rating"}),e.jsx(He,{value:"open_text",children:"Text"})]})]}),e.jsx(z,{size:"sm",variant:"outline",onClick:f,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]})]})})]})}function elr({openHouseId:s}){const{user:t}=hs(),{data:n=[],isLoading:r}=zPs(s),a=$Ps(),i=GPs(),l=(m,p)=>{const f=m+p;if(f<0||f>=n.length)return;const g=n.map(v=>v.id);[g[m],g[f]]=[g[f],g[m]],i.mutate({open_house_id:s,orderedIds:g})},[o,c]=_.useState(""),[d,u]=_.useState(!1),h=async()=>{const m=o.trim();if(m){u(!0);try{await a.mutateAsync({open_house_id:s,name:m,sort_order:n.length}),c("")}finally{u(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos (or pull a clip from your Video Library). Use the up/down arrows to reorder rooms and the arrows on each tile to reorder photos and 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(bt,{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((m,p)=>e.jsx(tlr,{room:m,index:p,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s,onMoveRoom:l},m.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(pe,{value:o,onChange:m=>c(m.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),h())}}),e.jsx(z,{onClick:h,disabled:!o.trim()||d,size:"sm",children:d?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function tlr({room:s,index:t,total:n,userId:r,openHouseId:a,onMoveRoom:i}){const l=UPs(),o=qPs(),c=VPs(),d=HPs(),u=WPs(),h=_.useRef(null),[m,p]=_.useState(!0),[f,g]=_.useState(s.name),[v,y]=_.useState(s.description||""),[b,w]=_.useState(!1),S=_.useMemo(()=>s.media.filter(q=>q.kind==="video"&&q.agent_video_id).map(q=>q.agent_video_id),[s.media]),{data:C={}}=rt({queryKey:["room-video-statuses",s.id,S.join(",")],enabled:S.length>0,queryFn:async()=>{const{data:q,error:G}=await U.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",S);if(G)throw G;const V=q||[],H=V.filter(Z=>Z.status==="processing"&&Z.bunny_video_id);await Promise.all(H.map(async Z=>{try{const{data:oe}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:Z.bunny_video_id,isAgentVideo:!0}});oe&&oe.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:oe.directPlayUrl,thumbnail_url:oe.thumbnailUrl,preview_url:oe.previewUrl,duration_seconds:oe.length||void 0,updated_at:new Date().toISOString()}).eq("id",Z.id),Z.status="ready",Z.thumbnail_url=oe.thumbnailUrl,Z.preview_url=oe.previewUrl)}catch{}}));const K={};return V.forEach(Z=>{K[Z.id]={status:Z.status,thumbnail_url:Z.thumbnail_url,preview_url:Z.preview_url}}),K},refetchInterval:q=>{const G=q.state.data;return G?Object.values(G).some(V=>V.status!=="ready"&&V.status!=="failed")?5e3:!1:5e3}}),E=()=>{f.trim()&&f!==s.name&&l.mutate({id:s.id,open_house_id:a,name:f.trim()})},P=()=>{v!==(s.description||"")&&l.mutate({id:s.id,open_house_id:a,description:v.trim()||null})},M=async()=>{await Qi(`Delete "${s.name}" and all its media?`)&&o.mutate({id:s.id,open_house_id:a})},I=q=>i(t,q),D=(q,G)=>{const V=q+G;if(V<0||V>=s.media.length)return;const H=s.media.map(K=>K.id);[H[q],H[V]]=[H[V],H[q]],u.mutate({open_house_id:a,room_id:s.id,orderedIds:H})},F=async q=>{const G=Array.from(q.target.files||[]);if(!(!G.length||!r)){w(!0);try{for(const V of G){const H=V.type.startsWith("video/"),K=H?500*1024*1024:15*1024*1024;if(V.size>K){la({title:`${V.name} is too large`,description:H?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(H){try{const J=`${s.name} – ${V.name.replace(/\.[^/.]+$/,"")}`,{data:te,error:ce}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:J,isAgentVideo:!0}});if(ce||!te)throw new Error((ce==null?void 0:ce.message)||"Could not start upload");const{videoId:ve,libraryId:me}=te,{data:he,error:ge}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ve,isAgentVideo:!0}});if(ge||!he)throw new Error((ge==null?void 0:ge.message)||"Could not get upload URL");await new Promise((ke,Ve)=>{const _e=new XMLHttpRequest;_e.addEventListener("load",()=>{_e.status>=200&&_e.status<300?ke():Ve(new Error(`Upload failed (${_e.status})`))}),_e.addEventListener("error",()=>Ve(new Error("Upload failed"))),_e.open("PUT",he.uploadUrl),_e.setRequestHeader("AccessKey",he.apiKey),_e.send(V)});const Ee=`https://iframe.mediadelivery.net/embed/${me}/${ve}`,Ne=V.size/(1024*1024),{data:Pe,error:Oe}=await U.from("agent_videos").insert({owner_user_id:r,bunny_video_id:ve,playback_url:Ee,file_size_mb:Ne,title:J,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Oe)throw Oe;await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Ee,sort_order:s.media.length,agent_video_id:Pe.id}),la({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(J){la({title:"Video upload failed",description:(J==null?void 0:J.message)||"Try again",variant:"destructive"})}continue}const Z=V.name.split(".").pop()||"jpg",oe=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${Z}`,{error:re}=await U.storage.from("open-house-tour-media").upload(oe,V,{upsert:!1,contentType:V.type});if(re){la({title:"Upload failed",description:re.message,variant:"destructive"});continue}const{data:ae}=U.storage.from("open-house-tour-media").getPublicUrl(oe);await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ae.publicUrl,sort_order:s.media.length})}}finally{w(!1),h.current&&(h.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(Zf,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>p(q=>!q),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(z,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(-1),disabled:t===0,children:e.jsx(h1,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(1),disabled:t===n-1,children:e.jsx(cl,{className:"h-4 w-4"})}),e.jsx(z,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:M,children:e.jsx(Cn,{className:"h-4 w-4"})})]}),m&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(pe,{value:f,onChange:q=>g(q.target.value),onBlur:E,placeholder:"Room name",className:"h-9"}),e.jsx(Ps,{value:v,onChange:q=>y(q.target.value),onBlur:P,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map((q,G)=>{const V=q.agent_video_id?C[q.agent_video_id]:void 0,H=V==null?void 0:V.status,K=q.kind==="video"&&H&&H!=="ready"&&H!=="failed",Z=q.kind==="video"&&H==="failed",oe=(V==null?void 0:V.thumbnail_url)||(V==null?void 0:V.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[q.kind==="video"?e.jsxs(e.Fragment,{children:[oe?e.jsx("img",{src:oe,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(q.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:q.url,className:"w-full h-full object-cover"}),!K&&!Z&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(Xr,{className:"h-6 w-6 text-white"})}),K&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(bt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),Z&&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:q.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("span",{className:"absolute top-1 left-1 px-1.5 h-5 rounded-full bg-black/60 text-white text-[10px] font-semibold flex items-center",children:G+1}),e.jsx("button",{type:"button","aria-label":"Remove media",onClick:()=>d.mutate({id:q.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(er,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"absolute inset-x-1 bottom-1 flex items-center justify-between opacity-0 group-hover:opacity-100 transition",children:[e.jsx("button",{type:"button","aria-label":"Move earlier",disabled:G===0,onClick:()=>D(G,-1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(Wc,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Move later",disabled:G===s.media.length-1,onClick:()=>D(G,1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(yi,{className:"h-3.5 w-3.5"})})]})]},q.id)})}),e.jsx("input",{ref:h,type:"file",accept:"image/*,video/*",multiple:!0,onChange:F,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",size:"sm",onClick:()=>{var q;return(q=h.current)==null?void 0:q.click()},disabled:b,className:"flex-1",children:b?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(pz,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async q=>{try{await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:q.playback_url||"",sort_order:s.media.length,agent_video_id:q.id}),la({title:"Video added to room"})}catch(G){la({title:"Failed to add video",description:G==null?void 0:G.message,variant:"destructive"})}}})]})]})]})}function slr({open:s,onOpenChange:t,openHouse:n}){const r=gOt(),{user:a}=hs(),i=_.useRef(null),l=_.useRef(null),o=_.useRef(null),c=n.kind==="virtual",[d,u]=_.useState(n.auto_forward_to_card??!1),[h,m]=_.useState(n.disclosure_pdf_url??""),[p,f]=_.useState(n.enable_survey??!1),[g,v]=_.useState(n.ask_visitor_intent??!0),[y,b]=_.useState(n.ask_visitor_address??!1),[w,S]=_.useState(n.photo_url??""),[C,E]=_.useState(!1),[P,M]=_.useState(!1),[I,D]=_.useState(!1),[F,q]=_.useState(n.property_address??""),[G,V]=_.useState(n.city??""),[H,K]=_.useState(n.state??""),[Z,oe]=_.useState(n.zip??""),[re,ae]=_.useState((n.event_date??"").slice(0,10)),[J,te]=_.useState((n.start_time??"").slice(0,5)),[ce,ve]=_.useState((n.end_time??"").slice(0,5)),[me,he]=_.useState(n.hero_video_url??""),[ge,Ee]=_.useState(!1),[Ne,Pe]=_.useState(n.price!=null?String(n.price):""),[Oe,ke]=_.useState(n.beds!=null?String(n.beds):""),[Ve,_e]=_.useState(n.baths!=null?String(n.baths):""),[Ae,Se]=_.useState(n.sqft!=null?String(n.sqft):""),[We,qe]=_.useState(n.enable_question??!0),[Be,Ze]=_.useState(n.enable_showing??!0),[$e,Xe]=_.useState(n.enable_disclosures??!0),[nt,Ge]=_.useState(n.enable_offer??!0),[Je,ut]=_.useState(n.brand_color_override??""),[lt,qt]=_.useState(n.property_description??""),[zt,Zt]=_.useState(n.drip_campaign_id??null),ms=async Es=>{var cn;const kn=(cn=Es.target.files)==null?void 0:cn[0];if(!kn||!a)return;if(kn.size>200*1024*1024){la({title:"Video must be under 200MB",variant:"destructive"});return}if(!kn.type.startsWith("video/")){la({title:"Please upload a video file",variant:"destructive"});return}Ee(!0);const Sn=kn.name.split(".").pop()||"mp4",bn=`${a.id}/${n.id}/hero-${Date.now()}.${Sn}`,{error:cr}=await U.storage.from("open-house-tour-media").upload(bn,kn,{upsert:!0,contentType:kn.type});if(cr){la({title:"Upload failed",description:cr.message,variant:"destructive"}),Ee(!1);return}const{data:Fs}=U.storage.from("open-house-tour-media").getPublicUrl(bn);he(Fs.publicUrl),Ee(!1),la({title:"Video uploaded!"})},Dt=async Es=>{var cn;const kn=(cn=Es.target.files)==null?void 0:cn[0];if(!kn||!a)return;if(kn.size>10*1024*1024){la({title:"Image must be under 10MB",variant:"destructive"});return}if(!kn.type.startsWith("image/")){la({title:"Please upload an image file",variant:"destructive"});return}M(!0);const Sn=kn.name.split(".").pop()||"jpg",bn=`${a.id}/${n.id}-${Date.now()}.${Sn}`,{error:cr}=await U.storage.from("open-house-photos").upload(bn,kn,{upsert:!0});if(cr){la({title:"Upload failed",description:cr.message,variant:"destructive"}),M(!1);return}const{data:Fs}=U.storage.from("open-house-photos").getPublicUrl(bn);S(Fs.publicUrl),M(!1),la({title:"Photo updated!"})},It=()=>{S(""),l.current&&(l.current.value="")},qs=async Es=>{var Fs;const kn=(Fs=Es.target.files)==null?void 0:Fs[0];if(!kn||!a)return;if(kn.size>20*1024*1024){la({title:"File must be under 20MB",variant:"destructive"});return}if(kn.type!=="application/pdf"){la({title:"Only PDF files are accepted",variant:"destructive"});return}E(!0);const Sn=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:bn}=await U.storage.from("open-house-photos").upload(Sn,kn,{upsert:!0});if(bn){la({title:"Upload failed",description:bn.message,variant:"destructive"}),E(!1);return}const{data:cr}=U.storage.from("open-house-photos").getPublicUrl(Sn);m(cr.publicUrl),E(!1),la({title:"PDF uploaded!"})},wt=()=>{m(""),i.current&&(i.current.value="")},Us=async()=>{if(!F.trim()){la({title:"Add a property address",variant:"destructive"});return}if(!re){la({title:"Pick a date for the open house",variant:"destructive"});return}D(!0);try{const Es={id:n.id,property_address:F.trim(),city:G.trim()||null,state:H.trim()||null,zip:Z.trim()||null,event_date:re,start_time:J||null,end_time:ce||null,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:p,ask_visitor_intent:g,ask_visitor_address:y,photo_url:w||null,drip_campaign_id:zt};c&&(Es.hero_video_url=me||null,Es.price=Ne.trim()?Number(Ne):null,Es.beds=Oe.trim()?parseInt(Oe,10):null,Es.baths=Ve.trim()?Number(Ve):null,Es.sqft=Ae.trim()?parseInt(Ae,10):null,Es.enable_question=We,Es.enable_showing=Be,Es.enable_disclosures=$e,Es.enable_offer=nt,Es.brand_color_override=Je.trim()||null,Es.property_description=lt.trim()||null),(F.trim()!==(n.property_address??"")||(G.trim()||null)!==(n.city??null)||(H.trim()||null)!==(n.state??null)||(Z.trim()||null)!==(n.zip??null))&&(Es.latitude=null,Es.longitude=null,Es.geocode_status="pending",Es.geocoded_at=null),await r.mutateAsync(Es),la({title:"Settings saved!"}),t(!1)}catch{la({title:"Failed to save",variant:"destructive"})}finally{D(!1)}};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(_r,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Date & Time"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Change when this open house takes place. Updates the sign-in page right away."}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Date"}),e.jsx(pe,{type:"date",value:re,onChange:Es=>ae(Es.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Start"}),e.jsx(pe,{type:"time",value:J,onChange:Es=>te(Es.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"End"}),e.jsx(pe,{type:"time",value:ce,onChange:Es=>ve(Es.target.value),className:"mt-1"})]})]}),e.jsx(ee,{className:"text-sm font-medium",children:"Property Address"}),e.jsx(pe,{value:F,onChange:Es=>q(Es.target.value),placeholder:"412 Oak St"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"City"}),e.jsx(pe,{value:G,onChange:Es=>V(Es.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"State"}),e.jsx(pe,{value:H,onChange:Es=>K(Es.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"ZIP"}),e.jsx(pe,{value:Z,onChange:Es=>oe(Es.target.value),className:"mt-1"})]})]})]}),c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xr,{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:ms,className:"hidden"}),me?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:me,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(z,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Es;return(Es=o.current)==null?void 0:Es.click()},disabled:ge,children:ge?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(z,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>he(""),children:e.jsx(er,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Es;return(Es=o.current)==null?void 0:Es.click()},disabled:ge,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:ge?e.jsx(bt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(elr,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(ee,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(pe,{type:"number",value:Ne,onChange:Es=>Pe(Es.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(pe,{type:"number",value:Ae,onChange:Es=>Se(Es.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(pe,{type:"number",value:Oe,onChange:Es=>ke(Es.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(pe,{type:"number",step:"0.5",value:Ve,onChange:Es=>_e(Es.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(Ps,{value:lt,onChange:Es=>qt(Es.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(ee,{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(mn,{checked:We,onCheckedChange:qe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(mn,{checked:Be,onCheckedChange:Ze})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(mn,{checked:$e,onCheckedChange:Xe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(mn,{checked:nt,onCheckedChange:Ge})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:Je||"#0f172a",onChange:Es=>ut(Es.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(pe,{value:Je,onChange:Es=>ut(Es.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Je&&e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>ut(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(Es=>e.jsx("button",{type:"button",onClick:()=>ut(Es),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:Es},"aria-label":Es},Es))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:Dt,className:"hidden"}),w?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:w,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(z,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Es;return(Es=l.current)==null?void 0:Es.click()},disabled:P,children:[P?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),P?"":"Replace"]}),e.jsx(z,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:It,children:e.jsx(er,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Es;return(Es=l.current)==null?void 0:Es.click()},disabled:P,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:P?e.jsx(bt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(nc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(Qor,{value:zt,onChange:Zt}),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(ee,{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(mn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:qs,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($r,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(z,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:wt,children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var Es;return(Es=i.current)==null?void 0:Es.click()},disabled:C,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:C?e.jsx(bt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{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(ee,{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(mn,{checked:g,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(ee,{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(mn,{checked:y,onCheckedChange:b})]})}),e.jsx(Jor,{openHouseId:n.id,enableSurvey:p,onToggleSurvey:f}),e.jsx(z,{onClick:Us,disabled:I,className:"w-full",children:I?"Saving...":"Save Settings"})]})]})})}const eis={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function nlr({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:eis[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 rlr({openHouseId:s}){const{data:t,isLoading:n}=MPs(s),{data:r}=xOt(s),a=_.useMemo(()=>{const h={};return r==null||r.forEach(m=>{h[m.id]=m}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Wf,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Le,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(be,{children:[e.jsx(_t,{className:"pb-3",children:e.jsxs(Nt,{className:"text-base flex items-center gap-2",children:[e.jsx(Wf,{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(Le,{children:e.jsxs(Qr,{defaultValue:"summary",children:[e.jsxs(Jr,{className:"mb-4",children:[e.jsxs(Wt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(wl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Wt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Oo,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Kt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(nlr,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(p=>p.question_id===h.id&&p.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(p=>{const f=a[p.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[f?`${f.first_name} ${f.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:p.text_value})]},p.id)})})]},h.id)})]}),e.jsx(Kt,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],p=l.filter(f=>f.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:p.map(f=>{const g=i.find(v=>v.id===f.question_id);return g?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:g.question_text}),e.jsx("span",{className:"font-medium",children:f.rating_value!=null?eis[f.rating_value]||f.rating_value:f.text_value})]},f.id):null})})]},h)})})]})})]})}const alr={question:{label:"Question",icon:qi,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:ya,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:$r,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Nd,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},TCt={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 ilr({openHouseId:s}){const{data:t=[],isLoading:n}=KPs(s),r=YPs(),[a,i]=_.useState(null),[l,o]=_.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,m)=>{r.mutate({id:h,status:m,open_house_id:s})};return n?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(i7,{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,m,p])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[m," ",e.jsx("span",{className:"opacity-60",children:p})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const m=alr[h.action_type],p=m.icon,f=h.payload||{},g=a===h.id,v=h.status==="contacted",y=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${y?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(g?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${m.bg}`,children:e.jsx(p,{className:`h-4 w-4 ${m.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:f.visitor_name||"Visitor"}),e.jsx(ze,{variant:"outline",className:`text-[10px] ${m.color}`,children:m.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),v&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Mr,{className:"h-3 w-3"}),"Contacted"]})]}),f.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',f.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(Zr,{className:"h-3 w-3"}),Ys(new Date(h.created_at),"MMM d, h:mm a")]}),f.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(on,{className:"h-3 w-3"}),f.email]}),f.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),f.phone]})]})]}),g?e.jsx(cl,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(yi,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),g&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[f.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',f.message,'"']}),Object.keys(TCt).some(b=>f[b]!=null&&f[b]!==""&&!(Array.isArray(f[b])&&f[b].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(TCt).map(([b,w])=>{const S=f[b];return S==null||S===""||Array.isArray(S)&&S.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:w}),e.jsx("div",{className:"font-medium",children:Array.isArray(S)?S.join(", "):String(S)})]},b)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[f.email&&e.jsx("a",{href:`mailto:${f.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(z,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Reply"]})}),f.phone&&e.jsx("a",{href:`tel:${String(f.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(z,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(va,{className:"h-3.5 w-3.5"}),"Call"]})}),!v&&e.jsxs(z,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Mr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),y?e.jsx(z,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs(z,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(w0,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const MCt=s=>{if(!s)return"";const[t,n]=s.split(":"),r=parseInt(t,10),a=r>=12?"PM":"AM";return`${r>12?r-12:r||12}:${n} ${a}`},olr=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return!t||!n||!r?"":new Date(t,n-1,r).toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})},PCt=25;function llr({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var Ze;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=bg(),{data:o}=xae(),c=!!(o!=null&&o.hasVerifiedSes),d=ha(),{data:u=[]}=Q_(),[h,m]=_.useState([]),[p,f]=_.useState(!1),[g,v]=_.useState("all"),[y,b]=_.useState([]),[w,S]=_.useState([]),[C,E]=_.useState(""),[P,M]=_.useState([]),[I,D]=_.useState(""),[F,q]=_.useState(""),[G,V]=_.useState(""),[H,K]=_.useState("platform"),[Z,oe]=_.useState(!1),[re,ae]=_.useState(0),[J,te]=_.useState(!1),ce=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,ve=olr(n.event_date),me=n.start_time?`${MCt(n.start_time)}${n.end_time?` – ${MCt(n.end_time)}`:""}`:"",he=[ve,me].filter(Boolean).join(" · ");_.useEffect(()=>{s&&(q(a?`You're invited: Open House at ${n.property_address}`:`Take a virtual tour of ${n.property_address}`),V(a?`I'm hosting an open house at ${n.property_address}${ve?` on ${ve}`:""}${me?` from ${me}`:""}. I'd love for you to stop by — tap below to RSVP so I can save you a spot.`:`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.`),S([]),b([]),M([]),E(""),v("all"),ae(0),K(c?"ses":i?"gmail":"platform"),h.length===0&&ge())},[s,n.id,i,c]);const ge=async()=>{if(d){f(!0);try{const $e=[];let nt=0;for(;;){const{data:Ge,error:Je}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, tags:innercircle_contact_tags(relationship_type_id)").eq("owner_user_id",d).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).order("id",{ascending:!0}).range(nt,nt+1e3-1);if(Je)throw Je;const ut=Ge||[];if($e.push(...ut),ut.length<1e3)break;nt+=1e3}m($e.map(Ge=>({id:Ge.id,first_name:Ge.first_name,last_name:Ge.last_name,email:Ge.email,tagIds:(Ge.tags||[]).map(Je=>Je.relationship_type_id)})))}catch{ne.error("Failed to load contacts")}finally{f(!1)}}},Ee=$e=>`${$e.first_name} ${$e.last_name||""}`.trim(),Ne=_.useMemo(()=>{const $e=I.trim().toLowerCase();return $e?h.filter(Xe=>`${Ee(Xe)} ${Xe.email||""}`.toLowerCase().includes($e)):h},[h,I]),Pe=_.useMemo(()=>{const $e={};return h.forEach(Xe=>Xe.tagIds.forEach(nt=>{$e[nt]=($e[nt]||0)+1})),$e},[h]),Oe=_.useMemo(()=>g==="all"?h:g==="tags"?y.length===0?[]:h.filter($e=>$e.tagIds.some(Xe=>y.includes(Xe))):h.filter($e=>w.includes($e.id)),[g,h,y,w]),ke=_.useMemo(()=>{const $e=new Set,Xe=[];return[...Oe.map(nt=>({email:nt.email,name:Ee(nt)})),...P].forEach(nt=>{const Ge=nt.email.toLowerCase();!nt.email||$e.has(Ge)||($e.add(Ge),Xe.push(nt))}),Xe},[Oe,P]),Ve=()=>{const $e=C.trim();if($e){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($e)){ne.error("Invalid email");return}M(Xe=>[...Xe,{email:$e,name:$e.split("@")[0]}]),E("")}},_e=$e=>$e.replace(/&/g,"&").replace(//g,">"),Ae=n.photo_url&&n.photo_url.includes("/storage/v1/object/public/")?n.photo_url.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":n.photo_url||"",Se=$e=>{const Xe=$e?`Hi ${_e($e)},`:"Hi there,",nt=[n.city,n.state].filter(Boolean).join(", "),Ge=_e(G).split(/\n\n+/).map(Je=>`

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

`).join("");return`
${Ae?``:""} ${a&&he?``:""}

${a?"You're Invited":"Virtual Open House"}

${_e(n.property_address)}

${nt?`

${_e(nt)}${n.zip?" "+_e(n.zip):""}

`:""}
 

When

${_e(he)}

${Xe}

${Ge}
${a?"RSVP for this Open House":"▶ Start Virtual Tour"}

Or copy this link:
${ce}

`},We=_.useMemo(()=>Se("Alex"),[G,n.id,Ae,a,he]),qe=async()=>{var $e;if(ke.length===0){ne.error("Add at least one recipient");return}oe(!0),ae(0);try{if(H==="gmail"&&i){let Xe=0;for(const nt of ke){const{data:Ge,error:Je}=await U.functions.invoke("gmail-send",{body:{to:nt.email,subject:F,body:Se(($e=nt.name)==null?void 0:$e.split(" ")[0])}});!Je&&(Ge!=null&&Ge.success)&&(Xe+=1),ae(Xe)}if(Xe===0)throw new Error("Gmail send failed");ne.success(`Sent to ${Xe} of ${ke.length} via Gmail`)}else{let Xe=0;for(let nt=0;nt{await navigator.clipboard.writeText(ce),te(!0),setTimeout(()=>te(!1),1500)};return e.jsx(Is,{open:s,onOpenChange:t,children:e.jsxs(Ls,{className:"sm:max-w-[900px] w-[calc(100vw-2rem)] max-h-[92vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Os,{className:"min-w-0",children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),a?"Invite to Open House":"Email Virtual Tour"]}),e.jsx(_r,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[1fr_380px] min-w-0",children:[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(Kc,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:ce}),e.jsxs(z,{variant:"ghost",size:"sm",onClick:Be,className:"shrink-0 h-7 gap-1",children:[J?e.jsx(Wr,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Sa,{className:"h-3.5 w-3.5"}),J?"Copied":"Copy"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Send from"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[c&&e.jsx(z,{type:"button",variant:H==="ses"?"default":"outline",size:"sm",onClick:()=>K("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx(z,{type:"button",variant:H==="gmail"?"default":"outline",size:"sm",onClick:()=>K("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx(z,{type:"button",variant:H==="platform"?"default":"outline",size:"sm",onClick:()=>K("platform"),className:"gap-1.5",children:"LevelUp"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:H==="ses"&&((Ze=o==null?void 0:o.verifiedEmails)!=null&&Ze[0])?e.jsxs(e.Fragment,{children:["Sending as ",e.jsx("span",{className:"font-medium",children:o.verifiedEmails[0]})," via your Mass Email setup"]}):H==="gmail"&&l?e.jsxs(e.Fragment,{children:["Sending as ",e.jsx("span",{className:"font-medium",children:l})]}):e.jsx(e.Fragment,{children:"Sending from the LevelUp notifications address with replies going to you"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(On,{className:"h-3.5 w-3.5"}),"Who should receive this?"]}),e.jsxs(Qr,{value:g,onValueChange:$e=>v($e),children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsx(Wt,{value:"all",children:"All contacts"}),e.jsx(Wt,{value:"tags",children:"By tag"}),e.jsx(Wt,{value:"select",children:"Pick people"})]}),e.jsx(Kt,{value:"all",className:"pt-3",children:e.jsx("div",{className:"rounded-lg border p-3 text-sm text-muted-foreground",children:p?"Loading contacts…":e.jsxs(e.Fragment,{children:["Everyone in your database with an email address — ",e.jsx("span",{className:"font-medium text-foreground",children:h.length.toLocaleString()})," contacts."]})})}),e.jsx(Kt,{value:"tags",className:"pt-3",children:e.jsx(Ki,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map($e=>{const Xe=y.includes($e.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted cursor-pointer",children:[e.jsx(za,{checked:Xe,onCheckedChange:()=>b(nt=>Xe?nt.filter(Ge=>Ge!==$e.id):[...nt,$e.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Ip,{className:"h-3 w-3 text-muted-foreground shrink-0"}),$e.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Pe[$e.id]||0})]},$e.id)}),u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No tags yet."})]})})}),e.jsxs(Kt,{value:"select",className:"pt-3 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:I,onChange:$e=>D($e.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(Ki,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[Ne.slice(0,300).map($e=>{const Xe=w.includes($e.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted cursor-pointer",children:[e.jsx(za,{checked:Xe,onCheckedChange:()=>S(nt=>Xe?nt.filter(Ge=>Ge!==$e.id):[...nt,$e.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:Ee($e)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:$e.email})]})]},$e.id)}),Ne.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:p?"Loading…":"No contacts found."})]})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(pe,{value:C,onChange:$e=>E($e.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Ve())}}),e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:Ve,children:"Add"})]}),P.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map($e=>e.jsxs(ze,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:$e.email}),e.jsx("button",{onClick:()=>M(Xe=>Xe.filter(nt=>nt.email!==$e.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(er,{className:"h-3 w-3"})})]},$e.email))})]}),e.jsx(fc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(pe,{id:"vt-subject",value:F,onChange:$e=>q($e.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vt-message",children:"Message"}),e.jsx(Ps,{id:"vt-message",value:G,onChange:$e=>V($e.target.value),rows:6,className:"resize-y"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Each email opens with a personal greeting using the contact's first name."})]})]}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(xa,{className:"h-3.5 w-3.5"}),"Preview"]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/20",children:e.jsx("iframe",{title:"Email preview",srcDoc:`${We}`,className:"w-full h-[420px] lg:h-[560px] border-0 bg-white",sandbox:""})})]})]}),e.jsxs("div",{className:Ct("flex flex-wrap items-center justify-between gap-3 pt-2 border-t"),children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:ke.length.toLocaleString()})," recipient",ke.length===1?"":"s",Z&&re>0&&e.jsxs("span",{children:[" · sent ",re]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(z,{variant:"outline",onClick:()=>t(!1),disabled:Z,children:"Cancel"}),e.jsxs(z,{onClick:qe,disabled:Z||ke.length===0||!F.trim(),className:"gap-2",children:[Z?e.jsx(bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"}),Z?"Sending...":`Send${ke.length?` to ${ke.length}`:""}`]})]})]})]})})}function clr({openHouseId:s}){const{data:t=[],isLoading:n}=uLs(s),r=mLs(s),a=pLs(s),i=t.filter(l=>l.checked_in_at).length;return e.jsxs("div",{className:"rounded-xl border border-border bg-card/50",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_v,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"RSVPs"}),e.jsx(ze,{variant:"secondary",className:"text-[11px]",children:t.length})]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i," checked in"]})]}),n?e.jsx("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading RSVPs…"}):t.length===0?e.jsxs("div",{className:"px-4 py-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No RSVPs yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send an invite to your database to start filling the list."})]}):e.jsx("ul",{className:"divide-y divide-border",children:t.map(l=>e.jsxs("li",{className:"flex items-center gap-3 px-4 py-3",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("span",{className:"text-sm font-medium truncate",children:[l.first_name,l.last_name].filter(Boolean).join(" ")}),l.checked_in_at&&e.jsxs(ze,{className:"text-[10px] gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs(ze,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(jj,{className:"h-3 w-3"}),l.working_with_agent_name||"Has an agent"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-xs text-muted-foreground flex-wrap",children:[l.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(on,{className:"h-3 w-3"}),l.email]}),l.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),l.phone]})]}),l.message&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:["“",l.message,"”"]})]}),e.jsx(z,{variant:l.checked_in_at?"secondary":"outline",size:"sm",className:"h-8 text-xs",onClick:()=>a.mutate({id:l.id,checkedIn:!l.checked_in_at}),children:l.checked_in_at?"Undo":"Check in"}),e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive","aria-label":"Delete RSVP",onClick:()=>r.mutate(l.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]},l.id))})]})}function dlr({summary:s,stats:t,search:n,onSearchChange:r,onCreate:a}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Guest Book"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-col items-start gap-2 sm:items-end",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(sn,{className:"h-4 w-4"}),"New Open House"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs hub-ink-muted",children:[e.jsx(lf,{className:"h-3.5 w-3.5",style:{color:"hsl(var(--hub-glow))"}}),"Every event gets a sign-in page & QR code"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Rr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(pe,{value:n,onChange:i=>r(i.target.value),placeholder:"Search by address, event name, or city...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide",children:t.map(i=>e.jsxs("button",{type:"button",onClick:i.onClick,disabled:!i.onClick,className:Ct("hub-glass min-w-[118px] shrink-0 rounded-xl px-4 py-3 text-left transition-all",i.onClick?"cursor-pointer hover:scale-[1.02]":"cursor-default opacity-80",i.active&&"ring-2 ring-white/50"),children:[e.jsx("div",{className:"text-lg font-bold leading-none",children:i.value}),e.jsx("div",{className:"mt-1.5 text-[11px] uppercase tracking-wide hub-ink-muted",children:i.label})]},i.key))})]})})}const LCt={buying:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",selling:"bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",neighbor:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",browsing:"bg-muted text-muted-foreground border-border"};function ulr({visitors:s,onExport:t,onShare:n}){if(!s.length)return e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/20 px-6 py-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10",children:e.jsx(On,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No sign-ins yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs text-muted-foreground",children:"Share the link or print the QR flyer so visitors can sign in from their phone."}),n&&e.jsxs(z,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:n,children:[e.jsx(sd,{className:"h-3.5 w-3.5"}),"Get the share link"]})]});const r=s.filter(a=>a.visitor_intent==="buying"&&!a.has_agent).length;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-foreground",children:[s.length," Visitor",s.length!==1?"s":""]}),r>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-orange-500/20 bg-orange-500/10 px-2 py-0.5 text-[11px] font-medium text-orange-700 dark:text-orange-300",children:[e.jsx(vu,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(d8e,{className:"h-7 text-xs",label:"Mail visitors",build:()=>({source:"guestbook",contactEmails:s.map(a=>(a.email||"").trim().toLowerCase()).filter(Boolean),name:"Open house thank-you",message:`Hi %FIRST_NAME%, Thank you for stopping by the open house! If you have any questions about the home or the neighborhood, I am always happy to help.`})}),e.jsxs(z,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(Ga,{className:"h-3 w-3"}),"Export CSV"]})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-auto rounded-xl border border-border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-muted/80 backdrop-blur",children:e.jsxs("tr",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Name"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold sm:table-cell",children:"Contact"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold md:table-cell",children:"Intent"}),e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Time"})]})}),e.jsx("tbody",{children:s.map(a=>{var o,c;const i=a.visitor_intent==="buying"&&!a.has_agent,l=LCt[a.visitor_intent||""]||LCt.browsing;return e.jsxs("tr",{className:Ct("border-t border-border/50 transition-colors hover:bg-muted/40",i&&"bg-orange-500/[0.06]"),children:[e.jsx("td",{className:"p-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:Ct("flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold",i?"bg-orange-500/15 text-orange-700 dark:text-orange-300":"bg-primary/10 text-primary"),children:((c=(o=a.first_name)==null?void 0:o[0])==null?void 0:c.toUpperCase())||"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate font-medium text-foreground",children:[a.first_name,a.last_name?` ${a.last_name}`:""]}),i&&e.jsx("div",{className:"text-[11px] font-medium text-orange-600 dark:text-orange-400",children:"Buyer · no agent"})]})]})}),e.jsxs("td",{className:"hidden p-2.5 text-muted-foreground sm:table-cell",children:[a.email&&e.jsx("div",{className:"max-w-[200px] truncate",children:a.email}),a.phone&&e.jsx("div",{className:"text-xs",children:a.phone}),a.visitor_address?e.jsx("div",{className:"max-w-[200px] truncate text-xs",children:a.visitor_address}):null]}),e.jsx("td",{className:"hidden p-2.5 md:table-cell",children:a.visitor_intent?e.jsx("span",{className:Ct("inline-flex rounded-full border px-2 py-0.5 text-[11px] font-medium capitalize",l),children:a.visitor_intent}):a.partial_signin?e.jsx("span",{className:"inline-flex rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2.5 text-xs text-muted-foreground",children:Ys(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const c3e="guestbook.relevelup.com";function hlr(){const{data:s,isLoading:t}=kPs(),n=SPs(),r=gOt(),a=CPs(),[i,l]=_.useState(!1),[o,c]=_.useState(null),[d,u]=_.useState(""),[h,m]=_.useState("all"),[p,f]=_.useState(!1),{user:g}=hs(),v=ha(),[y,b]=_.useState(null),[w,S]=_.useState(null),[C,E]=_.useState(!1),P=_.useRef(null),[M,I]=_.useState({property_address:"",city:"",state:"",zip:"",event_date:Ys(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),D=J=>{var ce;const te=(ce=J.target.files)==null?void 0:ce[0];if(te){if(te.size>5*1024*1024){la({title:"Photo must be under 5MB",variant:"destructive"});return}b(te),S(URL.createObjectURL(te))}},F=()=>{b(null),S(null),P.current&&(P.current.value="")},q=async()=>{if(!M.property_address){la({title:M.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let J;if(y&&g){E(!0);const ce=y.name.split(".").pop(),ve=`${v}/${Date.now()}.${ce}`,{error:me}=await U.storage.from("open-house-photos").upload(ve,y,{upsert:!0});if(me){la({title:"Photo upload failed",description:me.message,variant:"destructive"}),E(!1);return}const{data:he}=U.storage.from("open-house-photos").getPublicUrl(ve);J=he.publicUrl,E(!1)}const te=M.kind==="virtual"?{...M,start_time:void 0,end_time:void 0,photo_url:J}:{...M,photo_url:J};await n.mutateAsync(te),l(!1),I({property_address:"",city:"",state:"",zip:"",event_date:Ys(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),F()},G=J=>{navigator.clipboard.writeText(`https://${c3e}/${J}`),la({title:"Link copied!"})},V=Ys(new Date,"yyyy-MM-dd"),H=_.useMemo(()=>{const J=s??[],te=d.trim().toLowerCase(),ce=ke=>!te||[ke.property_address,ke.city,ke.state].filter(Boolean).join(" ").toLowerCase().includes(te),ve=J.filter(ce),me=ve.filter(ke=>ke.kind==="virtual"),he=ve.filter(ke=>ke.kind!=="virtual"),ge=he.filter(ke=>ke.event_date===V),Ee=he.filter(ke=>ke.event_date>V).sort((ke,Ve)=>ke.event_date.localeCompare(Ve.event_date)),Ne=he.filter(ke=>ke.event_dateVe.event_date.localeCompare(ke.event_date)),Pe=J.reduce((ke,Ve)=>ke+(Ve.visitor_count||0),0),Oe=J.reduce((ke,Ve)=>ke+(Ve.qr_scan_count||0),0);return{today:ge,upcoming:Ee,past:Ne,virtual:me,totalSignIns:Pe,totalScans:Oe}},[s,d,V]),K=H.today.length+H.upcoming.length,Z=K>0?`${K} upcoming · ${H.totalSignIns.toLocaleString()} total sign-ins`:`${H.totalSignIns.toLocaleString()} total sign-ins collected`,oe=J=>h==="all"||h===J,re=J=>m(te=>te===J?"all":J),ae=J=>e.jsx(mlr,{openHouse:J,isExpanded:o===J.id,onToggle:()=>c(o===J.id?null:J.id),onCopyLink:()=>G(J.slug||""),onToggleActive:()=>r.mutate({id:J.id,is_active:!J.is_active}),onDelete:()=>a.mutate(J.id),isToday:J.kind!=="virtual"&&J.event_date===V},J.id);return e.jsxs($s,{title:"Guest Book",children:[e.jsx(dl,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(dlr,{summary:Z,search:d,onSearchChange:u,onCreate:()=>l(!0),stats:[{key:"today",label:"Live Today",value:H.today.length,onClick:()=>re("today"),active:h==="today"},{key:"upcoming",label:"Upcoming",value:H.upcoming.length,onClick:()=>re("upcoming"),active:h==="upcoming"},{key:"virtual",label:"Virtual Tours",value:H.virtual.length,onClick:()=>re("virtual"),active:h==="virtual"},{key:"signins",label:"Total Sign-Ins",value:H.totalSignIns.toLocaleString()},{key:"scans",label:"Total QR Scans",value:H.totalScans.toLocaleString()}]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(Is,{open:i,onOpenChange:l,children:[e.jsx(rl,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Ls,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"Create Open House"}),e.jsx(_r,{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(ee,{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:()=>I(J=>({...J,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${M.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:()=>I(J=>({...J,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${M.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"})]})]})]}),M.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:()=>I(J=>({...J,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${M.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:()=>I(J=>({...J,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${M.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),M.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:()=>I(J=>({...J,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${M.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:()=>I(J=>({...J,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${M.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(ee,{children:M.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(pe,{value:M.property_address,onChange:J=>I(te=>({...te,property_address:J.target.value})),placeholder:M.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(ee,{children:"City"}),e.jsx(pe,{value:M.city,onChange:J=>I(te=>({...te,city:J.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:M.state,onChange:J=>I(te=>({...te,state:J.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:M.zip,onChange:J=>I(te=>({...te,zip:J.target.value})),placeholder:"78701"})]})]}),M.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(ee,{children:"Date"}),e.jsx(pe,{type:"date",value:M.event_date,onChange:J=>I(te=>({...te,event_date:J.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Start Time"}),e.jsx(pe,{type:"time",value:M.start_time,onChange:J=>I(te=>({...te,start_time:J.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"End Time"}),e.jsx(pe,{type:"time",value:M.end_time,onChange:J=>I(te=>({...te,end_time:J.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Welcome Message"}),e.jsx(Ps,{value:M.agent_greeting,onChange:J=>I(te=>({...te,agent_greeting:J.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:M.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:D,className:"hidden"}),w?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:w,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:F,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(er,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var J;return(J=P.current)==null?void 0:J.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(N0,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",M.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(z,{onClick:q,disabled:n.isPending||C,className:"w-full",children:C?"Uploading photo...":n.isPending?"Creating...":M.kind==="virtual"?"Create Virtual Open House":M.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(J=>e.jsx(be,{className:"animate-pulse",children:e.jsxs(_t,{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"})]})},J))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-8",children:[H.today.length>0&&oe("today")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(n$e,{title:"Happening Today",count:H.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:H.today.map(ae)})]}),H.upcoming.length>0&&oe("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(n$e,{title:"Upcoming",count:H.upcoming.length}),e.jsx("div",{className:"space-y-4",children:H.upcoming.map(ae)})]}),H.virtual.length>0&&oe("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(n$e,{title:"Virtual Tours",count:H.virtual.length}),e.jsx("div",{className:"space-y-4",children:H.virtual.map(ae)})]}),H.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>f(J=>!J),className:"flex w-full items-center justify-between rounded-xl border border-border bg-card px-4 py-3 text-left transition-colors hover:bg-muted/40",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[e.jsx(O_,{className:"h-4 w-4 text-muted-foreground"}),"Past Open Houses",e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:H.past.length})]}),p?e.jsx(h1,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(cl,{className:"h-4 w-4 text-muted-foreground"})]}),p&&e.jsx("div",{className:"space-y-4",children:H.past.map(ae)})]}),K===0&&H.virtual.length===0&&H.past.length===0&&e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Le,{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(lf,{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(z,{onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function n$e({title:s,count:t,accent:n}){return e.jsxs("div",{className:"flex items-center gap-2.5",children:[n&&e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-500"})]}),e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wide text-foreground",children:s}),e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:t}),e.jsx("div",{className:"h-px flex-1 bg-border"})]})}function mlr({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=xOt(t?s.id:void 0),{data:c}=rt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:M,error:I}=await U.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(I)throw I;const D=M.brokerages;return{...M,brokerage_name:(D==null?void 0:D.name)||null}},enabled:!!s.agent_id}),[d,u]=_.useState(!1),[h,m]=_.useState(!1),[p,f]=_.useState(!1),[g,v]=_.useState(!1),y=_.useRef(null),b=`https://${c3e}/${s.slug}`,w=M=>{if(!M)return"";const[I,D]=M.split(":"),F=parseInt(I),q=F>=12?"PM":"AM";return`${F>12?F-12:F||12}:${D} ${q}`},S=()=>{if(!(o!=null&&o.length))return;const M=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],I=o.map(V=>[V.first_name,V.last_name||"",V.email||"",V.phone||"",V.visitor_address||"",V.visitor_intent||"",V.wants_market_updates?"Yes":"No",(V.message||"").replace(/"/g,'""'),Ys(new Date(V.created_at),"MM/dd/yyyy h:mm a")]),D=[M,...I].map(V=>V.map(H=>`"${H}"`).join(",")).join(` `),F=new Blob([D],{type:"text/csv"}),q=URL.createObjectURL(F),G=document.createElement("a");G.href=q,G.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,G.click(),URL.revokeObjectURL(q)},C=_.useCallback(()=>{if(!y.current)return;const M=y.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),D=document.createElement("canvas");D.width=1024,D.height=1024;const F=D.getContext("2d"),q=new Image;q.onload=()=>{F==null||F.drawImage(q,0,0,1024,1024);const G=document.createElement("a");G.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,G.href=D.toDataURL("image/png"),G.click()},q.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I)))},[s.property_address]),E=_.useCallback(()=>{var Ae;if(!y.current)return;const M=y.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),D="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I))),F=Ys(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),q=s.start_time?`${w(s.start_time)}${s.end_time?" – "+w(s.end_time):""}`:"",G=[s.city,s.state].filter(Boolean).join(", "),V=s.agent_greeting||"Welcome! Please sign in below.",H=!!s.photo_url,K=!!c,Z=H||K,oe=H&&K,re=oe?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ae=oe?"28px":"34px",J=oe?"0.2in 0.75in":Z?"0.3in 0.75in":"0.4in 0.75in",te=Z?"0.15in":"0.3in",ce=Z?"0.15in":"0.3in",ve=oe?"14px 36px":"22px 44px",me=oe?"20px":"24px",he=Z?"0.2in":"0.35in",ge=oe?"1.8in":"2.4in",Ee=Z?"0.15in":"0.3in",Ne=oe?"140px":Z?"160px":"200px",Pe=oe?"16px":"24px",Oe=oe?"10px 20px":"16px 28px",ke=oe?"44px":"56px",Ve="0.15in",_e=window.open("","_blank");_e&&(_e.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${G?`
${G}${s.zip?" "+s.zip:""}
`:""}
Date
${F}
${q?`
Time
${q}
`:""}
${V}
${c?`
${c.avatar_url?`${c.name}`:`
${((Ae=c.name)==null?void 0:Ae.charAt(0))||"A"}
`}
Hosted By
${c.name}
${c.title?`
${c.title}
`:""} ${c.brokerage_name?`
${c.brokerage_name}
`:""} ${c.phone?`
${c.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),_e.document.close(),setTimeout(()=>{_e.focus(),_e.print()},500))},[s,b,c]),P=async()=>{v(!0);try{const{error:M}=await U.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(M)throw M;la({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(M){la({title:"Failed to send",description:M.message,variant:"destructive"})}finally{v(!1)}};return e.jsxs(be,{className:Ct("relative overflow-hidden transition-all",s.is_active?"border-border hover:border-primary/40 hover:shadow-md":"opacity-70",l&&"border-emerald-500/40 shadow-[0_0_0_1px_hsl(var(--primary)/0.06)]"),children:[e.jsx("span",{className:Ct("absolute inset-y-0 left-0 w-1",l?"bg-emerald-500":s.kind==="virtual"?"bg-purple-500/70":"bg-primary/40")}),e.jsx(_t,{className:"pb-3 pl-5",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Nt,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[l&&e.jsxs(ze,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(Nv,{className:"h-3 w-3"}),"Today"]}),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-500/10 text-purple-700 dark:text-purple-300 border-purple-500/20",children:[e.jsx(xa,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",children:[e.jsx(Ha,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(ze,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",children:[e.jsx(Oo,{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(oi,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(z,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(h1,{className:"h-4 w-4"}):e.jsx(cl,{className:"h-4 w-4"})})]}),e.jsxs(En,{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(Ha,{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(Zr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),Ys(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),w(s.start_time),s.end_time?` – ${w(s.end_time)}`:""]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(On,{className:"h-3.5 w-3.5 text-primary"}),s.visitor_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"signed in"})]}),s.qr_scan_count>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(lf,{className:"h-3.5 w-3.5 text-primary"}),s.qr_scan_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"scans"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,className:"h-8 gap-1.5 text-xs text-emerald-600 border-emerald-500/30 hover:bg-emerald-500/10 dark:text-emerald-400",children:[e.jsx(Nv,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(lf,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(sd,{className:"h-3.5 w-3.5"}),"Email Tour"]}):e.jsxs(e.Fragment,{children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>f(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Invite"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>window.open(`${b}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs",children:[e.jsx(xq,{className:"h-3.5 w-3.5"}),"Tablet Mode"]})]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Gc,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(ru,{children:[e.jsx(au,{asChild:!0,children:e.jsx(z,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(lb,{className:"h-4 w-4"})})}),e.jsxs(qd,{align:"end",className:"w-52",children:[e.jsxs(ua,{onClick:()=>window.open(b,"_blank"),children:[e.jsx(mr,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"?e.jsxs(ua,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(xa,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(ua,{onClick:()=>window.open(`https://${c3e}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(_v,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(ua,{onClick:a,children:[s.is_active?e.jsx(Yf,{className:"mr-2 h-4 w-4"}):e.jsx(xa,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(Iy,{}),e.jsxs(ua,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(Cn,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Le,{className:"pt-0",children:[e.jsx(fc,{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://",c3e,"/",s.slug]})]}),e.jsx(ulr,{visitors:o??[],onExport:S}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(clr,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(ilr,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(rlr,{openHouseId:s.id})})]}),e.jsx(Is,{open:d,onOpenChange:u,children:e.jsxs(Ls,{className:"sm:max-w-sm",children:[e.jsxs(Os,{children:[e.jsx(Rs,{children:"QR Code"}),e.jsx(_r,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:y,className:"bg-white p-4 rounded-xl",children:e.jsx(LN,{value:b,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:b}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(z,{variant:"outline",className:"flex-1",onClick:C,children:[e.jsx(Ga,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(z,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(eE,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(z,{variant:"default",className:"w-full",onClick:P,disabled:g,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),g?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(slr,{open:h,onOpenChange:m,openHouse:s}),e.jsx(llr,{open:p,onOpenChange:f,variant:s.kind==="virtual"?"tour":"rsvp",openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state,zip:s.zip,photo_url:s.photo_url,event_date:s.event_date,start_time:s.start_time,end_time:s.end_time}})]})}const plr=Gj({full_name:Jo().trim().min(2,"Please enter your name").max(120),email:Jo().trim().email("Please enter a valid email").max(200),brokerage:Jo().trim().min(2,"Please enter your brokerage").max(160)}),ICt=s=>s?s.replace(/<\s*(br|\/p|\/div|\/li)\s*\/?\s*>/gi,` `).replace(/<[^>]*>/g,"").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\n{2,}/g,` `).trim():"",flr=s=>{if(!s)return"";const t=s/(1024*1024);return t>=1?`${t.toFixed(1)} MB`:`${Math.max(1,Math.round(s/1024))} KB`};function xlr(){var S;const{slug:s}=Mi(),[t,n]=_.useState(!0),[r,a]=_.useState(null),[i,l]=_.useState([]),[o,c]=_.useState(!1),[d,u]=_.useState({full_name:"",email:"",brokerage:""}),[h,m]=_.useState(""),[p,f]=_.useState(!1),[g,v]=_.useState(!1);_.useEffect(()=>{let C=!0;return(async()=>{n(!0);const{data:E,error:P}=await U.functions.invoke("resource-kit-public",{body:{slug:s}});C&&(P||!(E!=null&&E.kit)?c(!0):(a(E.kit),l(E.files??[])),n(!1))})(),()=>{C=!1}},[s]);const y=async C=>{C.preventDefault(),m("");const E=plr.safeParse(d);if(!E.success){m(E.error.issues[0].message);return}f(!0);try{const{data:P,error:M}=await U.functions.invoke("resource-kit-unlock",{body:{slug:s,...E.data}});if(M)throw M;if(P!=null&&P.error)throw new Error("Something went wrong. Please try again.");l(P.files??[]),v(!0)}catch(P){m(P.message||"Something went wrong. Please try again.")}finally{f(!1)}};if(t)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6 pt-16",children:[e.jsx(ln,{className:"h-10 w-2/3 bg-white/10"}),e.jsx(ln,{className:"h-64 w-full bg-white/10"})]})});if(o||!r)return e.jsx("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center px-6 text-center",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-white",children:"This resource isn't available"}),e.jsx("p",{className:"mt-2 text-slate-400",children:"The link may have expired or been unpublished."})]})});const b=ICt(r.subheadline),w=(b||`Download ${r.name} — a free resource for real estate agents.`).replace(/\s*\n\s*/g," ").slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(dl,{children:[e.jsx("title",{children:`${r.headline} | LevelUp`.slice(0,60)}),e.jsx("meta",{name:"description",content:w}),e.jsx("link",{rel:"canonical",href:`${window.location.origin}/resources/${r.slug}`}),e.jsx("meta",{property:"og:title",content:r.headline}),e.jsx("meta",{property:"og:description",content:w}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`${window.location.origin}/resources/${r.slug}`}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),r.hero_image_url&&e.jsx("meta",{property:"og:image",content:r.hero_image_url}),r.hero_image_url&&e.jsx("meta",{name:"twitter:image",content:r.hero_image_url})]}),e.jsxs("div",{className:"pointer-events-none fixed inset-0 opacity-60",children:[e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/3 -right-32 h-96 w-96 rounded-full bg-sky-500/20 blur-3xl"})]}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-5 py-12 md:py-20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold tracking-tight mb-10",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"text-slate-500 font-medium",children:"· Free Agent Resource"})]}),e.jsxs("div",{className:"grid lg:grid-cols-[1.15fr_1fr] gap-10 lg:gap-14 items-start",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[12px] font-semibold text-amber-300",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Instant download"]}),e.jsx("h1",{className:"mt-5 text-4xl md:text-5xl font-black tracking-tight leading-[1.05]",children:r.headline}),b&&e.jsx("p",{className:"mt-5 text-lg text-slate-300 leading-relaxed max-w-xl whitespace-pre-line",children:b}),r.hero_image_url&&e.jsx("div",{className:"mt-8 overflow-hidden rounded-2xl border border-white/10 shadow-2xl",children:e.jsx("img",{src:r.hero_image_url,alt:r.name,loading:"lazy",className:"w-full h-56 md:h-72 object-cover"})}),((S=r.benefits)==null?void 0:S.length)>0&&e.jsx("ul",{className:"mt-8 space-y-3",children:r.benefits.map((C,E)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-200",children:[e.jsx(Mr,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsx("span",{className:"leading-relaxed",children:ICt(C)||C})]},E))}),i.length>0&&e.jsxs("div",{className:"mt-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-widest text-slate-400 font-semibold mb-3",children:"What's inside"}),e.jsx("div",{className:"space-y-2",children:i.map(C=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3",children:[e.jsx($r,{className:"h-4 w-4 text-slate-300 shrink-0"}),e.jsx("span",{className:"flex-1 text-sm text-slate-100 truncate",children:C.name}),e.jsx("span",{className:"text-[11px] text-slate-400",children:flr(C.file_size)}),g&&C.file_url?e.jsx(z,{asChild:!0,size:"sm",className:"h-8 rounded-full bg-amber-400 text-slate-900 hover:bg-amber-300",children:e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(Ga,{className:"h-3.5 w-3.5 mr-1"})," Download"]})}):e.jsx(Hl,{className:"h-3.5 w-3.5 text-slate-500"})]},C.id))})]})]}),e.jsx("div",{className:"lg:sticky lg:top-10",children:e.jsx("div",{className:"rounded-3xl border border-white/10 bg-white/[0.06] backdrop-blur p-6 md:p-8 shadow-2xl",children:g?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl bg-emerald-400/15 grid place-items-center",children:e.jsx(Mr,{className:"h-7 w-7 text-emerald-400"})}),e.jsx("h2",{className:"mt-4 text-xl font-bold",children:"You're all set"}),e.jsxs("p",{className:"mt-1.5 text-sm text-slate-300",children:["Your files are unlocked on this page and a copy is on the way to ",d.email,"."]}),e.jsx("div",{className:"mt-6 space-y-2 text-left",children:i.map(C=>C.file_url&&e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,className:"flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3 hover:bg-white/10 transition",children:[e.jsx(Ga,{className:"h-4 w-4 text-amber-400"}),e.jsx("span",{className:"text-sm truncate",children:C.name})]},C.id))}),e.jsxs("div",{className:"mt-7 rounded-2xl bg-slate-900/60 border border-white/10 p-5 text-left",children:[e.jsx("div",{className:"font-semibold",children:"Want the whole toolbox?"}),e.jsx("p",{className:"mt-1 text-sm text-slate-300",children:"LevelUp gives agents marketing, CRM, listing tools, and coaching in one place."}),e.jsx(z,{asChild:!0,className:"mt-4 w-full h-11 rounded-xl bg-white text-slate-900 font-bold hover:bg-slate-100",children:e.jsx("a",{href:"https://dashboard.relevelup.com/trial",children:"Try LevelUp Free"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Get instant access"}),e.jsx("p",{className:"mt-1.5 text-sm text-slate-300",children:"Tell us where to send it and the files unlock right here."}),e.jsxs("form",{onSubmit:y,className:"mt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"full_name",className:"text-slate-200",children:"Agent name"}),e.jsx(pe,{id:"full_name",value:d.full_name,onChange:C=>u({...d,full_name:C.target.value}),placeholder:"Jane Smith",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",className:"text-slate-200",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:d.email,onChange:C=>u({...d,email:C.target.value}),placeholder:"you@email.com",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"brokerage",className:"text-slate-200",children:"Brokerage"}),e.jsx(pe,{id:"brokerage",value:d.brokerage,onChange:C=>u({...d,brokerage:C.target.value}),placeholder:"Your brokerage",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),h&&e.jsx("p",{className:"text-sm text-red-300",children:h}),e.jsxs(z,{type:"submit",disabled:p,className:"w-full h-12 rounded-xl bg-amber-400 text-slate-900 font-bold hover:bg-amber-300",children:[p?"Unlocking…":r.cta_text,e.jsx(Da,{className:"h-4 w-4 ml-1.5"})]}),e.jsxs("p",{className:"flex items-start gap-2 text-[11px] leading-relaxed text-slate-400",children:[e.jsx(Ch,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),"By downloading, you agree to receive occasional emails from LevelUp about tools and resources for agents. Unsubscribe anytime."]})]})]})})})]})]})]})}Aat.workerSrc=Eat;const glr={signature:Mm,initials:yq,date_signed:gc,printed_name:Oo,text:gq},tis={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function sis(){return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"2-digit",day:"2-digit",year:"numeric"}).format(new Date)}function ylr(s,t){const n=document.createElement("canvas");n.width=600,n.height=t?200:140;const r=n.getContext("2d");return r.fillStyle="#12233f",r.font=`${t?84:64}px "Segoe Script", "Brush Script MT", "Snell Roundhand", cursive`,r.textAlign="center",r.textBaseline="middle",r.fillText(s,n.width/2,n.height/2+10),n.toDataURL("image/png")}function vlr(){var H,K,Z,oe;const{token:s}=Mi(),t=zn(),[n,r]=_.useState(!0),[a,i]=_.useState(null),[l,o]=_.useState(null),[c,d]=_.useState(null),[u,h]=_.useState(null),m=_.useRef(null),p=_.useRef([]),[f,g]=_.useState({}),[v,y]=_.useState({}),[b,w]=_.useState(null),[S,C]=_.useState(!1),[E,P]=_.useState(!1),[M,I]=_.useState(!1);_.useEffect(()=>{let re=!1;return r(!0),i(null),o(null),d(null),h(null),g({}),C(!1),(async()=>{var te;const{data:ae,error:J}=await U.functions.invoke("forms-sign-public",{body:{action:"load",token:s}});if(!re){if(J||ae!=null&&ae.error)i((ae==null?void 0:ae.error)||"This signing link could not be loaded.");else if(ae.state==="already_signed")d("signed");else{o(ae);const ce={};for(const ve of ae.fields||[])ve.field_kind==="printed_name"&&(ce[ve.id]={value:((te=ae.signer)==null?void 0:te.full_name)||""}),ve.field_kind==="date_signed"&&(ce[ve.id]={value:sis()});g(ce)}r(!1)}})(),()=>{re=!0}},[s]),_.useEffect(()=>{let re=!1;const ae=m.current;if(!(!(l!=null&&l.pdf_url)||!ae))return(async()=>{try{const te=await(await fetch(l.pdf_url)).arrayBuffer(),ce=await v6e({data:te}).promise;if(re)return;ae.innerHTML="",p.current=[];const ve=Math.min(ae.clientWidth-16||700,820);for(let me=1;me<=ce.numPages;me++){const he=await ce.getPage(me);if(re)return;const ge=he.getViewport({scale:1}),Ee=ve/ge.width,Ne=he.getViewport({scale:Ee*(window.devicePixelRatio||1)}),Pe=document.createElement("div");Pe.className="relative mx-auto shadow",Pe.style.width=`${ve}px`,Pe.style.height=`${ge.height*Ee}px`;const Oe=document.createElement("canvas");Oe.width=Math.floor(Ne.width),Oe.height=Math.floor(Ne.height),Oe.style.width="100%",Oe.style.height="100%",Oe.className="rounded-md border border-border bg-white",Pe.appendChild(Oe),ae.appendChild(Pe),p.current[me-1]=Pe;const ke=Oe.getContext("2d");ke&&await he.render({canvasContext:ke,viewport:Ne}).promise}re||g(me=>({...me}))}catch{re||i("The document could not be displayed.")}})(),()=>{re=!0}},[l==null?void 0:l.pdf_url]);const D=(l==null?void 0:l.fields)||[],F=D.filter(re=>{var ae,J;return re.is_required&&!((ae=f[re.id])!=null&&ae.value)&&!((J=f[re.id])!=null&&J.png)}),q=async()=>{if(!S){ne.error("Please agree to sign electronically first.");return}if(F.length){ne.error("Please complete every highlighted field.");return}P(!0);try{const{data:re,error:ae}=await U.functions.invoke("forms-sign-public",{body:{action:"submit",token:s,consent:!0,fields:D.filter(J=>f[J.id]).map(J=>{var te,ce;return{mapping_id:J.id,value:(te=f[J.id])==null?void 0:te.value,signature_png:(ce=f[J.id])==null?void 0:ce.png}})}});if(ae||re!=null&&re.error)throw new Error((re==null?void 0:re.error)||(ae==null?void 0:ae.message)||"Could not submit");re!=null&&re.next_token&&h({token:re.next_token,title:re.next_title??null}),d("signed"),window.scrollTo({top:0})}catch(re){ne.error((re==null?void 0:re.message)||"Could not finish signing")}finally{P(!1)}},G=async()=>{const re=window.prompt("Optional: tell the sender why you are declining.")??"";I(!0),await U.functions.invoke("forms-sign-public",{body:{action:"decline",token:s,reason:re}}),d("declined"),I(!1)},V=(re,ae)=>{g(J=>({...J,[re.id]:ae})),w(null)};return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):a?e.jsx(eue,{icon:e.jsx(Bd,{className:"h-8 w-8 text-destructive"}),title:"Link unavailable",body:a}):c==="declined"?e.jsx(eue,{icon:e.jsx(Bd,{className:"h-8 w-8 text-muted-foreground"}),title:"Document declined",body:"The sender has been notified that you declined to sign this document."}):c==="signed"&&u?e.jsx(eue,{icon:e.jsx(Mr,{className:"h-8 w-8 text-emerald-600"}),title:"Signed — one more to go",body:u.title?`Next up in this packet: ${u.title}. Your signature is saved and ready to reuse.`:"There is one more document in this packet. Your signature is saved and ready to reuse.",action:e.jsx(z,{className:"mt-5 bg-[#406E71] hover:bg-[#375d60]",onClick:()=>t(`/sign/${u.token}`),children:"Continue to the next document"})}):c==="signed"||(l==null?void 0:l.state)==="already_signed"?e.jsx(eue,{icon:e.jsx(Mr,{className:"h-8 w-8 text-emerald-600"}),title:"You're all set",body:"Thank you — your signature has been recorded. Once everyone has signed, the completed document is delivered to your agent automatically."}):e.jsxs("div",{className:"min-h-screen bg-slate-100 pb-40",children:[e.jsx("header",{className:"sticky top-0 z-20 border-b bg-[#2a4c64] px-4 py-3 text-white shadow-md",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.18em] opacity-70",children:"LevelUp Forms"}),e.jsx("h1",{className:"truncate text-base font-semibold",children:(H=l==null?void 0:l.envelope)==null?void 0:H.title}),e.jsxs("p",{className:"text-xs opacity-80",children:["Signing as ",(K=l==null?void 0:l.signer)==null?void 0:K.full_name]})]})}),((Z=l==null?void 0:l.envelope)==null?void 0:Z.message)&&e.jsx("div",{className:"mx-auto mt-4 max-w-3xl rounded-lg border bg-white px-4 py-3 text-sm text-slate-600 shadow-sm",children:l.envelope.message}),e.jsxs("div",{className:"mx-auto mt-4 max-w-3xl space-y-4 px-2",children:[e.jsx("div",{ref:m,className:"space-y-4"}),D.map(re=>{const ae=p.current[re.page_index];if(!ae)return null;const J=f[re.id],te=!!(J!=null&&J.png||J!=null&&J.value),ce=glr[re.field_kind];return e.jsx(DCt,{target:ae,children:e.jsx("button",{onClick:()=>w(re),className:`absolute flex items-center justify-center gap-1 rounded-sm border-2 transition-colors ${te?"border-emerald-500 bg-emerald-500/10":"animate-pulse border-[#406E71] bg-[#406E71]/15 hover:bg-[#406E71]/25"}`,style:{left:`${re.pos_x*100}%`,top:`${re.pos_y*100}%`,width:`${re.width*100}%`,height:`${re.height*100}%`},children:J!=null&&J.png?e.jsx("img",{src:J.png,alt:re.label||"Signature",className:"max-h-full max-w-full object-contain"}):J!=null&&J.value?e.jsx("span",{className:"truncate px-1 text-[10px] font-medium text-emerald-800",children:J.value}):e.jsxs("span",{className:"flex items-center gap-1 px-1 text-[10px] font-semibold text-[#2f5c60]",children:[e.jsx(ce,{className:"h-3 w-3"})," ",re.label||tis[re.field_kind]]})})},re.id)}),((l==null?void 0:l.data_overlays)||[]).map(re=>{const ae=p.current[re.page_index];return!ae||!re.value?null:e.jsx(DCt,{target:ae,children:e.jsx("div",{className:"pointer-events-none absolute flex items-center",style:{left:`${re.pos_x*100}%`,top:`${re.pos_y*100}%`,width:`${re.width*100}%`,height:`${re.height*100}%`},children:e.jsx("span",{className:"truncate px-0.5 text-[10px] text-slate-900",children:re.value})})},re.id)})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 z-30 border-t bg-white/95 px-4 py-3 shadow-[0_-4px_20px_rgba(0,0,0,0.08)] backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-3xl flex-col gap-2",children:[e.jsxs("label",{className:"flex items-start gap-2 text-xs text-slate-600",children:[e.jsx(za,{checked:S,onCheckedChange:re=>C(!!re),className:"mt-0.5"}),e.jsx("span",{children:l==null?void 0:l.consent_text})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(z,{className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",disabled:E||!S||F.length>0,onClick:q,children:[E?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Mm,{className:"mr-2 h-4 w-4"}),F.length>0?`${F.length} field${F.length===1?"":"s"} left`:"Finish signing"]}),e.jsx(z,{variant:"ghost",size:"sm",disabled:M,onClick:G,className:"text-muted-foreground",children:"Decline"})]})]})}),e.jsx(blr,{field:b,signerName:((oe=l==null?void 0:l.signer)==null?void 0:oe.full_name)||"",current:b?f[b.id]:void 0,adopted:v,onAdopt:(re,ae)=>{y(J=>({...J,[re]:ae})),g(J=>{var ce;const te={...J};for(const ve of D)ve.field_kind===re&&!((ce=te[ve.id])!=null&&ce.png)&&(te[ve.id]={png:ae});return te})},onClose:()=>w(null),onApply:V})]})}function eue({icon:s,title:t,body:n,action:r}){return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100 p-4",children:e.jsxs("div",{className:"w-full max-w-md rounded-2xl border bg-white p-8 text-center shadow-sm",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-slate-100",children:s}),e.jsx("h1",{className:"text-lg font-semibold",children:t}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:n}),r]})})}function DCt({target:s,children:t}){return pv.createPortal(t,s)}function blr({field:s,signerName:t,current:n,adopted:r,onAdopt:a,onClose:i,onApply:l}){const o=(s==null?void 0:s.field_kind)==="signature"||(s==null?void 0:s.field_kind)==="initials",c=(s==null?void 0:s.field_kind)==="initials"?"initials":"signature",[d,u]=_.useState(""),h=_.useRef(null),m=_.useRef(!1),[p,f]=_.useState("");_.useEffect(()=>{if(!s)return;f((n==null?void 0:n.value)||(s.field_kind==="printed_name"?t:s.field_kind==="date_signed"?sis():"")),u(s.field_kind==="initials"?t.split(" ").map(S=>S[0]).join(""):t);const w=h.current;if(w){const S=w.getContext("2d");S==null||S.clearRect(0,0,w.width,w.height)}},[s==null?void 0:s.id]);const g=w=>{const S=h.current;if(!S)return;m.current=!0,S.setPointerCapture(w.pointerId);const C=S.getContext("2d"),E=S.getBoundingClientRect();C.strokeStyle="#12233f",C.lineWidth=3,C.lineCap="round",C.beginPath(),C.moveTo((w.clientX-E.left)/E.width*S.width,(w.clientY-E.top)/E.height*S.height)},v=w=>{if(!m.current)return;const S=h.current;if(!S)return;const C=S.getContext("2d"),E=S.getBoundingClientRect();C.lineTo((w.clientX-E.left)/E.width*S.width,(w.clientY-E.top)/E.height*S.height),C.stroke()},y=()=>{m.current=!1},b=(w,S)=>{s&&(S&&o&&a(c,w),l(s,{png:w}))};return e.jsx(Wg,{open:!!s,onOpenChange:w=>!w&&i(),children:e.jsxs(gg,{side:"bottom",className:"mx-auto max-w-lg rounded-t-2xl",children:[e.jsx(Dy,{className:"text-left",children:e.jsx(Ry,{className:"text-base",children:(s==null?void 0:s.label)||(s?tis[s.field_kind]:"")})}),s&&o&&e.jsxs(Qr,{defaultValue:r[c]?"saved":"draw",className:"mt-3",children:[e.jsxs(Jr,{className:"grid w-full grid-cols-3",children:[e.jsx(Wt,{value:"draw",children:"Draw"}),e.jsx(Wt,{value:"type",children:"Type"}),e.jsx(Wt,{value:"saved",disabled:!r[c],children:"Saved"})]}),e.jsxs(Kt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:h,width:640,height:220,className:"h-40 w-full touch-none rounded-lg border bg-white",onPointerDown:g,onPointerMove:v,onPointerUp:y}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>{var S;const w=h.current;(S=w==null?void 0:w.getContext("2d"))==null||S.clearRect(0,0,w.width,w.height)},children:[e.jsx($U,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs(z,{size:"sm",className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>{const w=h.current;w&&b(w.toDataURL("image/png"),!0)},children:["Use this ",s.field_kind==="initials"?"initials":"signature"," everywhere"]})]})]}),e.jsxs(Kt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(pe,{value:d,onChange:w=>u(w.target.value),placeholder:"Type your name"}),d.trim()&&e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:'"Segoe Script","Brush Script MT",cursive'},children:d})}),e.jsx(z,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!d.trim(),onClick:()=>b(ylr(d.trim(),s.field_kind==="signature"),!0),children:"Use this everywhere"})]}),e.jsx(Kt,{value:"saved",className:"space-y-3 pt-3",children:r[c]&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white p-2",children:e.jsx("img",{src:r[c],alt:"Saved signature",className:"max-h-full object-contain"})}),e.jsxs(z,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>b(r[c],!1),children:["Use saved ",s.field_kind==="initials"?"initials":"signature"]})]})})]}),s&&!o&&e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx(pe,{value:p,onChange:w=>f(w.target.value),autoFocus:!0}),e.jsx(z,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!p.trim(),onClick:()=>l(s,{value:p.trim()}),children:"Apply"})]})]})})}const RCt="https://dashboard.relevelup.com/trial",_lr=["Full LevelUp Agent OS access","300+ marketing templates & AI tools","Cancel anytime — no risk"];function jZe({variant:s="full",className:t=""}){return s==="compact"?e.jsxs("div",{className:`rounded-2xl border border-amber-400/20 bg-gradient-to-br from-amber-500/10 to-transparent p-5 ${t}`,children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-widest text-amber-300",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Free trial"]}),e.jsx("h3",{className:"mt-3 text-lg font-bold text-white leading-snug",children:"Try LevelUp free"}),e.jsx("p",{className:"mt-2 text-sm text-slate-300 leading-relaxed",children:"Everything you just read — plus the tools to actually run it. Start your free trial today."}),e.jsxs("a",{href:RCt,className:"mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-amber-400 px-4 py-2.5 text-sm font-bold text-slate-950 transition hover:bg-amber-300",children:["Start free trial ",e.jsx(Da,{className:"h-4 w-4"})]})]}):e.jsxs("section",{className:`relative overflow-hidden rounded-3xl border border-amber-400/20 bg-gradient-to-br from-amber-500/15 via-slate-900 to-slate-900 p-8 md:p-12 ${t}`,children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-16 h-64 w-64 rounded-full bg-amber-400/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[12px] font-semibold text-amber-300",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Free trial · no credit card hassle"]}),e.jsx("h2",{className:"mt-5 text-3xl md:text-4xl font-black tracking-tight text-white leading-[1.1]",children:"Ready to put this into action?"}),e.jsx("p",{className:"mt-4 max-w-xl text-slate-300 leading-relaxed",children:"LevelUp gives real estate agents the marketing, CRM, and AI tools to win more listings — all in one place. Take it for a spin free."}),e.jsx("ul",{className:"mt-6 grid gap-2 sm:grid-cols-3",children:_lr.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-200",children:[e.jsx(Wr,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsx("span",{children:n})]},n))}),e.jsxs("a",{href:RCt,className:"mt-8 inline-flex items-center gap-2 rounded-xl bg-amber-400 px-6 py-3 text-base font-bold text-slate-950 transition hover:bg-amber-300",children:["Start your free trial ",e.jsx(Da,{className:"h-5 w-5"})]})]})]})}const FCt=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t,n-1,r,12)))},wlr=s=>{const t=s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length;return Math.max(1,Math.round(t/220))};function jlr(){const[s,t]=_.useState([]),[n,r]=_.useState(!0),[a,i]=_.useState("all");_.useEffect(()=>{(async()=>{const{data:u}=await U.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, featured, published_at, content").eq("status","published").order("published_at",{ascending:!1}).limit(200);t(u||[]),r(!1)})()},[]);const l=["all",...Array.from(new Set(s.map(u=>u.category).filter(Boolean)))],o=a==="all"?s:s.filter(u=>u.category===a),[c,...d]=o;return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(dl,{children:[e.jsx("title",{children:"The LevelUp Blog | Real Estate Growth Insights"}),e.jsx("meta",{name:"description",content:"Strategies, systems, and stories from the founder of LevelUp — helping real estate agents win more listings and build a business they love."}),e.jsx("link",{rel:"canonical",href:`${window.location.origin}/blog`}),e.jsx("meta",{property:"og:title",content:"The LevelUp Blog"}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:description",content:"Strategies, systems, and stories from the founder of LevelUp for real estate agents."}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsxs("div",{className:"pointer-events-none fixed inset-0 opacity-60",children:[e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/3 -right-32 h-96 w-96 rounded-full bg-sky-500/20 blur-3xl"})]}),e.jsxs("div",{className:"relative mx-auto max-w-6xl px-5 py-12 md:py-16",children:[e.jsxs(or,{to:"/",className:"flex items-center gap-2 text-sm font-bold tracking-tight",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"font-medium text-slate-500",children:"· Blog"})]}),e.jsxs("header",{className:"mt-10 max-w-3xl",children:[e.jsxs("h1",{className:"text-4xl font-black leading-[1.05] tracking-tight md:text-6xl",children:["Ideas that move your ",e.jsx("span",{className:"text-amber-400",children:"real estate business"})," forward."]}),e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:"Strategies, systems, and honest lessons from the founder of LevelUp — written for agents who want to grow on purpose."})]}),l.length>2&&e.jsx("div",{className:"mt-8 flex flex-wrap gap-2",children:l.map(u=>e.jsx("button",{onClick:()=>i(u),className:`rounded-full border px-4 py-1.5 text-sm font-medium transition ${a===u?"border-amber-400/40 bg-amber-400/15 text-amber-200":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:u==="all"?"All articles":u},u))}),n?e.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[0,1,2].map(u=>e.jsx(ln,{className:"h-72 w-full bg-white/10"},u))}):o.length===0?e.jsx("p",{className:"mt-16 text-slate-400",children:"No articles published yet — check back soon."}):e.jsxs(e.Fragment,{children:[c&&e.jsxs(or,{to:`/blog/${c.slug}`,className:"group mt-12 grid gap-8 overflow-hidden rounded-3xl border border-white/10 bg-white/5 p-6 transition hover:border-amber-400/30 md:grid-cols-2 md:p-8",children:[c.cover_image_url&&e.jsx("div",{className:"overflow-hidden rounded-2xl",children:e.jsx("img",{src:c.cover_image_url,alt:c.title,className:"h-56 w-full object-cover transition duration-500 group-hover:scale-105 md:h-72"})}),e.jsxs("div",{className:"flex flex-col justify-center",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-400",children:[c.category&&e.jsx(ze,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:c.category}),e.jsx("span",{children:FCt(c.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," ",wlr(c.content)," min read"]})]}),e.jsx("h2",{className:"mt-4 text-2xl font-bold leading-tight md:text-3xl",children:c.title}),c.excerpt&&e.jsx("p",{className:"mt-3 leading-relaxed text-slate-300",children:c.excerpt}),e.jsxs("span",{className:"mt-5 inline-flex items-center gap-2 text-sm font-semibold text-amber-300",children:["Read article ",e.jsx(Da,{className:"h-4 w-4 transition group-hover:translate-x-1"})]})]})]}),d.length>0&&e.jsx("div",{className:"mt-8 grid gap-6 md:grid-cols-3",children:d.map(u=>e.jsxs(or,{to:`/blog/${u.slug}`,className:"group flex flex-col overflow-hidden rounded-2xl border border-white/10 bg-white/5 transition hover:border-amber-400/30",children:[u.cover_image_url?e.jsx("img",{src:u.cover_image_url,alt:u.title,loading:"lazy",className:"h-44 w-full object-cover transition duration-500 group-hover:scale-105"}):e.jsx("div",{className:"h-44 w-full bg-gradient-to-br from-amber-500/20 to-slate-900"}),e.jsxs("div",{className:"flex flex-1 flex-col p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[u.category&&e.jsx("span",{className:"text-amber-300",children:u.category}),e.jsx("span",{children:FCt(u.published_at)})]}),e.jsx("h3",{className:"mt-2 text-lg font-bold leading-snug",children:u.title}),u.excerpt&&e.jsx("p",{className:"mt-2 line-clamp-3 text-sm leading-relaxed text-slate-400",children:u.excerpt}),e.jsxs("span",{className:"mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-amber-300",children:["Read ",e.jsx(Da,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},u.id))})]}),e.jsx(jZe,{className:"mt-16"}),e.jsxs("footer",{className:"mt-14 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(or,{to:"/",className:"hover:text-slate-300",children:"Home"})]})]})]})}const Nlr=s=>(s||"LevelUp Member").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),klr=s=>{const[t,n]=s.split("T"),[r,a,i]=t.split("-").map(Number);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(r,a-1,i,Number((n||"12").slice(0,2))||12)))};function Slr({postId:s,allowComments:t}){const{user:n}=hs(),[r,a]=_.useState([]),[i,l]=_.useState(!0),[o,c]=_.useState(""),[d,u]=_.useState(null),[h,m]=_.useState(""),[p,f]=_.useState(!1),g=_.useCallback(async()=>{l(!0);const{data:C,error:E}=await U.from("blog_comments").select("id, post_id, user_id, parent_id, body, created_at").eq("post_id",s).eq("is_hidden",!1).order("created_at",{ascending:!0});if(E){l(!1);return}const P=C||[],M=[...new Set(P.map(I=>I.user_id))];if(M.length){const{data:I}=await U.from("profiles").select("id, name, avatar_url").in("id",M),D=new Map((I||[]).map(F=>[F.id,F]));P.forEach(F=>{F.author=D.get(F.user_id)})}a(P),l(!1)},[s]);_.useEffect(()=>{g()},[g]);const v=async(C,E)=>{if(!n){ne.error("Sign in to comment");return}if(!C.trim())return;f(!0);const{error:P}=await U.from("blog_comments").insert({post_id:s,user_id:n.id,parent_id:E,body:C.trim()});if(f(!1),P){ne.error(P.message);return}c(""),m(""),u(null),ne.success("Comment posted"),g()},y=async C=>{const{error:E}=await U.from("blog_comments").delete().eq("id",C);if(E){ne.error(E.message);return}g()},b=r.filter(C=>!C.parent_id),w=C=>r.filter(E=>E.parent_id===C),S=({c:C,nested:E=!1})=>{var P,M,I;return e.jsxs("div",{className:`flex gap-3 ${E?"ml-10 mt-4":"mt-6"}`,children:[e.jsxs(ja,{className:"h-9 w-9 shrink-0",children:[e.jsx(xi,{src:((P=C.author)==null?void 0:P.avatar_url)||void 0}),e.jsx(Na,{className:"bg-white/10 text-xs text-white",children:Nlr((M=C.author)==null?void 0:M.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:((I=C.author)==null?void 0:I.name)||"LevelUp Member"}),e.jsx("span",{className:"text-xs text-slate-500",children:klr(C.created_at)})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[15px] leading-relaxed text-slate-300",children:C.body}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[!E&&n&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-400 hover:text-amber-300",onClick:()=>{u(d===C.id?null:C.id),m("")},children:[e.jsx(IQ,{className:"h-3 w-3"})," Reply"]}),(n==null?void 0:n.id)===C.user_id&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-500 hover:text-red-400",onClick:()=>y(C.id),children:[e.jsx(Cn,{className:"h-3 w-3"})," Delete"]})]}),d===C.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ps,{value:h,onChange:D=>m(D.target.value),placeholder:"Write a reply…",className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(z,{size:"sm",disabled:p,onClick:()=>v(h,C.id),children:[p&&e.jsx(bt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"})," Post reply"]}),e.jsx(z,{size:"sm",variant:"ghost",className:"text-slate-400",onClick:()=>u(null),children:"Cancel"})]})]}),w(C.id).map(D=>e.jsx(S,{c:D,nested:!0},D.id))]})]})};return e.jsxs("section",{id:"comments",className:"mt-14 border-t border-white/10 pt-10",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-xl font-bold text-white",children:[e.jsx(Bu,{className:"h-5 w-5 text-amber-400"}),"Discussion ",r.length>0&&e.jsxs("span",{className:"text-slate-500",children:["(",r.length,")"]})]}),t?n?e.jsxs("div",{className:"mt-5 space-y-3",children:[e.jsx(Ps,{value:o,onChange:C=>c(C.target.value),placeholder:"Share your take with the LevelUp community…",rows:4,className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs(z,{disabled:p||!o.trim(),onClick:()=>v(o,null),children:[p&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"})," Post comment"]})]}):e.jsxs("div",{className:"mt-5 rounded-xl border border-white/10 bg-white/5 p-5 text-sm text-slate-300",children:[e.jsx(or,{to:"/auth",className:"font-semibold text-amber-300 hover:underline",children:"Sign in"})," ","to join the conversation — comments are open to all LevelUp members."]}):e.jsx("p",{className:"mt-4 text-sm text-slate-400",children:"Comments are closed on this article."}),i?e.jsxs("div",{className:"mt-8 flex items-center gap-2 text-sm text-slate-400",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading comments…"]}):b.length===0?e.jsx("p",{className:"mt-8 text-sm text-slate-500",children:"No comments yet — be the first."}):e.jsx("div",{className:"mt-2",children:b.map(C=>e.jsx(S,{c:C},C.id))})]})}const OCt=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t,n-1,r,12)))},Clr=s=>Math.max(1,Math.round(s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length/220));function Alr(){var h;const{slug:s=""}=Mi(),[t,n]=_.useState(null),[r,a]=_.useState([]),[i,l]=_.useState(!0);_.useEffect(()=>{(async()=>{l(!0);const{data:m}=await U.from("blog_posts").select("*").eq("slug",s).eq("status","published").maybeSingle();if(n(m||null),l(!1),m){U.rpc("increment_blog_post_views",{_slug:s});const{data:p}=await U.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, published_at, content").eq("status","published").neq("slug",s).order("published_at",{ascending:!1}).limit(3);a(p||[])}})()},[s]);const o=typeof window<"u"?`${window.location.origin}/blog/${s}`:"",c=async m=>{const p=encodeURIComponent((t==null?void 0:t.title)||"LevelUp"),f=encodeURIComponent(o),g={facebook:`https://www.facebook.com/sharer/sharer.php?u=${f}`,linkedin:`https://www.linkedin.com/sharing/share-offsite/?url=${f}`,twitter:`https://twitter.com/intent/tweet?url=${f}&text=${p}`,email:`mailto:?subject=${p}&body=${f}`};if(m==="copy"){await navigator.clipboard.writeText(o),ne.success("Link copied");return}if(m==="native"&&navigator.share){try{await navigator.share({title:t==null?void 0:t.title,url:o})}catch{}return}window.open(g[m],"_blank","noopener,width=640,height=560")};if(i)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 pt-16",children:[e.jsx(ln,{className:"h-12 w-3/4 bg-white/10"}),e.jsx(ln,{className:"h-64 w-full bg-white/10"}),e.jsx(ln,{className:"h-40 w-full bg-white/10"})]})});if(!t)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-950 px-6 text-center",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-white",children:"Article not found"}),e.jsx("p",{className:"mt-2 text-slate-400",children:"It may have been unpublished or moved."}),e.jsx(or,{to:"/blog",className:"mt-5 inline-block font-semibold text-amber-300 hover:underline",children:"Back to the blog"})]})});const d=(t.seo_title||t.title).slice(0,60),u=(t.seo_description||t.excerpt||t.title).slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(dl,{children:[e.jsx("title",{children:`${d} | LevelUp`}),e.jsx("meta",{name:"description",content:u}),e.jsx("link",{rel:"canonical",href:o}),e.jsx("meta",{property:"og:type",content:"article"}),e.jsx("meta",{property:"og:title",content:t.title}),e.jsx("meta",{property:"og:description",content:u}),e.jsx("meta",{property:"og:url",content:o}),t.cover_image_url&&e.jsx("meta",{property:"og:image",content:t.cover_image_url}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),t.cover_image_url&&e.jsx("meta",{name:"twitter:image",content:t.cover_image_url}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"BlogPosting",headline:t.title,description:u,image:t.cover_image_url||void 0,datePublished:t.published_at,author:{"@type":"Person",name:t.author_name},publisher:{"@type":"Organization",name:"LevelUp"},mainEntityOfPage:o})})]}),e.jsx("div",{className:"pointer-events-none fixed inset-0 opacity-50",children:e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"})}),e.jsxs("div",{className:"relative mx-auto max-w-6xl px-5 py-10 md:py-14",children:[e.jsxs(or,{to:"/blog",className:"inline-flex items-center gap-2 text-sm font-medium text-slate-400 hover:text-white",children:[e.jsx(ka,{className:"h-4 w-4"})," All articles"]}),e.jsxs("div",{className:"mt-8 grid gap-12 lg:grid-cols-[minmax(0,1fr)_300px]",children:[e.jsxs("article",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-slate-400",children:[t.category&&e.jsx(ze,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:t.category}),e.jsx("span",{children:OCt(t.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," ",Clr(t.content)," min read"]})]}),e.jsx("h1",{className:"mt-4 text-3xl font-black leading-[1.1] tracking-tight md:text-5xl",children:t.title}),t.excerpt&&e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:t.excerpt}),e.jsxs("div",{className:"mt-7 flex items-center gap-3 border-y border-white/10 py-4",children:[e.jsxs(ja,{className:"h-11 w-11",children:[e.jsx(xi,{src:t.author_avatar_url||void 0}),e.jsx(Na,{className:"bg-amber-400/20 text-amber-200",children:t.author_name.split(" ").map(m=>m[0]).slice(0,2).join("")})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:t.author_name}),e.jsx("div",{className:"text-xs text-slate-400",children:t.author_title})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>c("copy"),title:"Copy link",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(Oc,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("facebook"),title:"Share on Facebook",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(of,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("linkedin"),title:"Share on LinkedIn",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(fg,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("twitter"),title:"Share on X",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(bJ,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("email"),title:"Share by email",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("native"),title:"Share",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white md:hidden",children:e.jsx(sd,{className:"h-4 w-4"})})]})]}),t.cover_image_url&&e.jsx("img",{src:t.cover_image_url,alt:t.title,className:"mt-8 w-full rounded-2xl border border-white/10 object-cover"}),e.jsx("div",{className:"blog-content prose prose-invert mt-10 max-w-none prose-headings:font-bold prose-headings:tracking-tight prose-a:text-amber-300 prose-img:rounded-2xl prose-video:rounded-2xl",dangerouslySetInnerHTML:{__html:t.content}}),((h=t.tags)==null?void 0:h.length)>0&&e.jsx("div",{className:"mt-10 flex flex-wrap gap-2",children:t.tags.map(m=>e.jsxs("span",{className:"rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs text-slate-300",children:["#",m]},m))}),e.jsx(jZe,{className:"mt-14"}),e.jsx(Slr,{postId:t.id,allowComments:t.allow_comments})]}),e.jsxs("aside",{className:"space-y-6 lg:sticky lg:top-8 lg:self-start",children:[e.jsx(jZe,{variant:"compact"}),r.length>0&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/5 p-5",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-widest text-slate-400",children:"Keep reading"}),e.jsx("div",{className:"mt-4 space-y-4",children:r.map(m=>e.jsxs(or,{to:`/blog/${m.slug}`,className:"group block",children:[e.jsx("div",{className:"text-sm font-semibold leading-snug text-slate-100 group-hover:text-amber-300",children:m.title}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:OCt(m.published_at)})]},m.id))})]})]})]}),e.jsxs("footer",{className:"mt-16 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(or,{to:"/blog",className:"hover:text-slate-300",children:"Blog"})]})]})]})}const Elr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,Tlr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,nis=s=>s.match(Elr),Mlr=(s,t)=>t?"https://www.youtube-nocookie.com/embed/videoseries?list=":s?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",Plr=s=>s.searchParams.has("v")?{id:s.searchParams.get("v")}:s.hostname==="youtu.be"||s.pathname.includes("shorts")||s.pathname.includes("live")?{id:s.pathname.split("/").pop()}:s.searchParams.has("list")?{id:s.searchParams.get("list"),isPlaylist:!0}:null,Llr=s=>{var t;const{url:n,allowFullscreen:r,autoplay:a,ccLanguage:i,ccLoadPolicy:l,controls:o,disableKBcontrols:c,enableIFrameApi:d,endTime:u,interfaceLanguage:h,ivLoadPolicy:m,loop:p,modestBranding:f,nocookie:g,origin:v,playlist:y,progressBarColor:b,startAt:w,rel:S}=s;if(!nis(n))return null;if(n.includes("/embed/"))return n;const C=new URL(n),{id:E,isPlaylist:P}=(t=Plr(C))!==null&&t!==void 0?t:{};if(!E)return null;const M=new URL(`${Mlr(g,P)}${E}`);return C.searchParams.has("t")&&M.searchParams.set("start",C.searchParams.get("t").replaceAll("s","")),r===!1&&M.searchParams.set("fs","0"),a&&M.searchParams.set("autoplay","1"),i&&M.searchParams.set("cc_lang_pref",i),l&&M.searchParams.set("cc_load_policy","1"),o||M.searchParams.set("controls","0"),c&&M.searchParams.set("disablekb","1"),d&&M.searchParams.set("enablejsapi","1"),u&&M.searchParams.set("end",u.toString()),h&&M.searchParams.set("hl",h),m&&M.searchParams.set("iv_load_policy",m.toString()),p&&M.searchParams.set("loop","1"),f&&M.searchParams.set("modestbranding","1"),v&&M.searchParams.set("origin",v),y&&M.searchParams.set("playlist",y),w&&M.searchParams.set("start",w.toString()),b&&M.searchParams.set("color",b),S!==void 0&&M.searchParams.set("rel",S.toString()),M.toString()},Ilr=P0.create({name:"youtube",addOptions(){return{addPasteHandler:!0,allowFullscreen:!0,autoplay:!1,ccLanguage:void 0,ccLoadPolicy:void 0,controls:!0,disableKBcontrols:!1,enableIFrameApi:!1,endTime:0,height:480,interfaceLanguage:void 0,ivLoadPolicy:0,loop:!1,modestBranding:!1,HTMLAttributes:{},inline:!1,nocookie:!1,origin:"",playlist:"",progressBarColor:void 0,width:640,rel:1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},start:{default:0},width:{default:this.options.width},height:{default:this.options.height}}},parseHTML(){return[{tag:"div[data-youtube-video] iframe"}]},addCommands(){return{setYoutubeVideo:s=>({commands:t})=>nis(s.src)?t.insertContent({type:this.name,attrs:s}):!1}},addPasteRules(){return this.options.addPasteHandler?[CKs({find:Tlr,type:this.type,getAttributes:s=>({src:s.input})})]:[]},renderHTML({HTMLAttributes:s}){const t=Llr({url:s.src,allowFullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,controls:this.options.controls,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,nocookie:this.options.nocookie,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,startAt:s.start||0,rel:this.options.rel});return s.src=t,["div",{"data-youtube-video":""},["iframe",cp(this.options.HTMLAttributes,{width:this.options.width,height:this.options.height,allowfullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,rel:this.options.rel},s)]]}}),Dlr=P0.create({name:"videoEmbed",group:"block",atom:!0,draggable:!0,addAttributes(){return{src:{default:null},poster:{default:null}}},parseHTML(){return[{tag:"video[src]"}]},renderHTML({HTMLAttributes:s}){return["video",cp(s,{controls:"true",playsinline:"true",preload:"metadata",class:"w-full rounded-xl"})]}}),ny=({onClick:s,active:t,title:n,children:r,disabled:a})=>e.jsx(z,{type:"button",variant:t?"secondary":"ghost",size:"sm",className:"h-8 w-8 p-0",title:n,disabled:a,onClick:s,children:r});function Rlr({content:s,onChange:t,placeholder:n="Write your article…"}){const[r,a]=_.useState(!1),[i,l]=_.useState(""),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(!1),p=_.useRef(null),f=_.useRef(null),g=ULe({extensions:[qLe.configure({heading:{levels:[2,3,4]}}),Tas,HLe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),kUt.configure({HTMLAttributes:{class:"rounded-xl w-full"}}),GLe.configure({types:["heading","paragraph"]}),Ilr.configure({width:960,height:540,HTMLAttributes:{class:"w-full aspect-video rounded-xl"}}),Dlr],content:s||"",editorProps:{attributes:{class:"prose prose-slate dark:prose-invert max-w-none min-h-[420px] focus:outline-none px-4 py-4"}},onUpdate:({editor:w})=>t(w.getHTML())});_.useEffect(()=>{g&&s!==g.getHTML()&&g.commands.setContent(s||"",!1)},[s]);const v=_.useCallback(async(w,S)=>{var D;const{data:C}=await U.auth.getUser(),E=(D=C.user)==null?void 0:D.id;if(!E)return ne.error("You must be signed in"),null;const P=w.name.split(".").pop()||(S==="image"?"jpg":"mp4"),M=`${E}/blog/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${P}`,{error:I}=await U.storage.from("email-assets").upload(M,w,{cacheControl:"31536000",upsert:!1});return I?(ne.error(`Upload failed: ${I.message}`),null):U.storage.from("email-assets").getPublicUrl(M).data.publicUrl},[]),y=async(w,S)=>{if(!w||!g)return;m(!0);const C=await v(w,S);m(!1),C&&(S==="image"?g.chain().focus().setImage({src:C}).run():g.chain().focus().insertContent({type:"videoEmbed",attrs:{src:C}}).run())};if(!g)return null;const b=g;return e.jsxs("div",{className:"rounded-xl border bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 border-b bg-muted/40 px-2 py-1.5 sticky top-0 z-10",children:[e.jsx(ny,{title:"Bold",active:b.isActive("bold"),onClick:()=>b.chain().focus().toggleBold().run(),children:e.jsx(HA,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Italic",active:b.isActive("italic"),onClick:()=>b.chain().focus().toggleItalic().run(),children:e.jsx(KA,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Underline",active:b.isActive("underline"),onClick:()=>b.chain().focus().toggleUnderline().run(),children:e.jsx(b7,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(ny,{title:"Heading",active:b.isActive("heading",{level:2}),onClick:()=>b.chain().focus().toggleHeading({level:2}).run(),children:e.jsx(a7,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Subheading",active:b.isActive("heading",{level:3}),onClick:()=>b.chain().focus().toggleHeading({level:3}).run(),children:e.jsx(WU,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Bullet list",active:b.isActive("bulletList"),onClick:()=>b.chain().focus().toggleBulletList().run(),children:e.jsx(My,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Numbered list",active:b.isActive("orderedList"),onClick:()=>b.chain().focus().toggleOrderedList().run(),children:e.jsx(bj,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Quote",active:b.isActive("blockquote"),onClick:()=>b.chain().focus().toggleBlockquote().run(),children:e.jsx(wj,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Code block",active:b.isActive("codeBlock"),onClick:()=>b.chain().focus().toggleCodeBlock().run(),children:e.jsx(GA,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(ny,{title:"Align left",active:b.isActive({textAlign:"left"}),onClick:()=>b.chain().focus().setTextAlign("left").run(),children:e.jsx(QM,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Align center",active:b.isActive({textAlign:"center"}),onClick:()=>b.chain().focus().setTextAlign("center").run(),children:e.jsx(XM,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Align right",active:b.isActive({textAlign:"right"}),onClick:()=>b.chain().focus().setTextAlign("right").run(),children:e.jsx(JM,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(ny,{title:"Link",active:b.isActive("link"),onClick:()=>{l(b.getAttributes("link").href||""),a(!0)},children:e.jsx(Kc,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Insert image",disabled:h,onClick:()=>{var w;return(w=p.current)==null?void 0:w.click()},children:e.jsx(N0,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Upload video",disabled:h,onClick:()=>{var w;return(w=f.current)==null?void 0:w.click()},children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Embed YouTube / Vimeo",onClick:()=>{u(""),c(!0)},children:e.jsx(jq,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Divider",onClick:()=>b.chain().focus().setHorizontalRule().run(),children:e.jsx(gN,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(ny,{title:"Undo",onClick:()=>b.chain().focus().undo().run(),children:e.jsx(nE,{className:"h-4 w-4"})}),e.jsx(ny,{title:"Redo",onClick:()=>b.chain().focus().redo().run(),children:e.jsx(tE,{className:"h-4 w-4"})}),h&&e.jsxs("span",{className:"ml-2 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"})," Uploading…"]})]}),e.jsx($Le,{editor:g,"data-placeholder":n}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:w=>{var S;y((S=w.target.files)==null?void 0:S[0],"image"),w.target.value=""}}),e.jsx("input",{ref:f,type:"file",accept:"video/*",className:"hidden",onChange:w=>{var S;y((S=w.target.files)==null?void 0:S[0],"video"),w.target.value=""}}),e.jsx(Is,{open:r,onOpenChange:a,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Insert link"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"URL"}),e.jsx(pe,{value:i,onChange:w=>l(w.target.value),placeholder:"https://…"})]}),e.jsxs(hr,{children:[e.jsx(z,{variant:"outline",onClick:()=>{b.chain().focus().unsetLink().run(),a(!1)},children:"Remove link"}),e.jsx(z,{onClick:()=>{i.trim()&&b.chain().focus().extendMarkRange("link").setLink({href:i.trim(),target:"_blank"}).run(),a(!1)},children:"Apply"})]})]})}),e.jsx(Is,{open:o,onOpenChange:c,children:e.jsxs(Ls,{children:[e.jsx(Os,{children:e.jsx(Rs,{children:"Embed a video"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"YouTube or Vimeo URL"}),e.jsx(pe,{value:d,onChange:w=>u(w.target.value),placeholder:"https://youtube.com/watch?v=…"})]}),e.jsx(hr,{children:e.jsx(z,{onClick:()=>{const w=d.trim();if(w){if(/vimeo\.com/i.test(w)){const S=w.split("/").filter(Boolean).pop();b.chain().focus().insertContent(`
`).run()}else b.commands.setYoutubeVideo({src:w});c(!1)}},children:"Embed"})})]})})]})}const tue=s=>s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,80),Flr=()=>({title:"",slug:"",excerpt:"",content:"",cover_image_url:null,category:"",tags:[],author_name:"Jeremy Collins",author_title:"Founder, LevelUp",status:"draft",featured:!1,allow_comments:!0});function Olr(){const{user:s}=hs(),[t,n]=_.useState([]),[r,a]=_.useState(!0),[i,l]=_.useState(null),[o,c]=_.useState(!1),[d,u]=_.useState(""),[h,m]=_.useState(""),[p,f]=_.useState(!1),g=_.useRef(null),[v,y]=_.useState([]),b=async()=>{a(!0);const{data:F,error:q}=await U.from("blog_posts").select("*").order("created_at",{ascending:!1});q&&ne.error(q.message),n(F||[]),a(!1)},w=async()=>{const{data:F}=await U.from("blog_comments").select("id, body, created_at, is_hidden, user_id, post_id").order("created_at",{ascending:!1}).limit(200),q=F||[],G=[...new Set(q.map(re=>re.user_id))],V=[...new Set(q.map(re=>re.post_id))],[{data:H},{data:K}]=await Promise.all([G.length?U.from("profiles").select("id, name, email").in("id",G):Promise.resolve({data:[]}),V.length?U.from("blog_posts").select("id, title, slug").in("id",V):Promise.resolve({data:[]})]),Z=new Map((H||[]).map(re=>[re.id,re])),oe=new Map((K||[]).map(re=>[re.id,re]));y(q.map(re=>({...re,author:Z.get(re.user_id),post:oe.get(re.post_id)})))};_.useEffect(()=>{b(),w()},[]);const S=_.useMemo(()=>t.filter(F=>F.title.toLowerCase().includes(d.toLowerCase())),[t,d]),C=async F=>{if(!F||!s)return;f(!0);const q=F.name.split(".").pop()||"jpg",G=`${s.id}/blog/cover-${Date.now()}.${q}`,{error:V}=await U.storage.from("email-assets").upload(G,F);if(f(!1),V){ne.error(V.message);return}const H=U.storage.from("email-assets").getPublicUrl(G).data.publicUrl;l(K=>({...K||{},cover_image_url:H}))},E=async F=>{if(!i)return;const q=(i.title||"").trim();if(!q){ne.error("Give the article a title");return}const G=tue(i.slug||q),V=F===void 0?i.status||"draft":F?"published":"draft";c(!0);const H={title:q,slug:G,excerpt:i.excerpt||null,content:i.content||"",cover_image_url:i.cover_image_url||null,category:i.category||null,tags:i.tags||[],author_name:i.author_name||"Jeremy Collins",author_title:i.author_title||"Founder, LevelUp",author_avatar_url:i.author_avatar_url||null,status:V,featured:!!i.featured,allow_comments:i.allow_comments!==!1,seo_title:i.seo_title||null,seo_description:i.seo_description||null,published_at:V==="published"?i.published_at||new Date().toISOString():i.published_at||null};let K;if(i.id)({error:K}=await U.from("blog_posts").update(H).eq("id",i.id));else{H.created_by=(s==null?void 0:s.id)||null;const Z=await U.from("blog_posts").insert(H).select().single();K=Z.error,Z.data&&l(Z.data)}if(c(!1),K){ne.error(K.message);return}ne.success(V==="published"?"Published":"Saved"),b()},P=async F=>{if(!confirm("Delete this article and its comments?"))return;const{error:q}=await U.from("blog_posts").delete().eq("id",F);if(q){ne.error(q.message);return}ne.success("Deleted"),(i==null?void 0:i.id)===F&&l(null),b()},M=async F=>{const q=F.status==="published"?"draft":"published",{error:G}=await U.from("blog_posts").update({status:q,published_at:q==="published"?F.published_at||new Date().toISOString():F.published_at}).eq("id",F.id);if(G){ne.error(G.message);return}b()},I=async F=>{const{error:q}=await U.from("blog_comments").update({is_hidden:!F.is_hidden}).eq("id",F.id);if(q){ne.error(q.message);return}w()},D=async F=>{const{error:q}=await U.from("blog_comments").delete().eq("id",F);if(q){ne.error(q.message);return}w()};return i?e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(z,{variant:"ghost",onClick:()=>l(null),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back to articles"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[i.slug&&i.status==="published"&&e.jsx(z,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/blog/${i.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(mr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs(z,{variant:"outline",disabled:o,onClick:()=>E(!1),children:[o&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"})," Save draft"]}),e.jsxs(z,{disabled:o,onClick:()=>E(!0),children:[o&&e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"})," Publish"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(pe,{value:i.title||"",onChange:F=>l({...i,title:F.target.value}),placeholder:"Article title",className:"h-14 border-0 bg-transparent px-0 text-3xl font-bold shadow-none focus-visible:ring-0"}),e.jsx(Ps,{value:i.excerpt||"",onChange:F=>l({...i,excerpt:F.target.value}),placeholder:"Short excerpt shown on the blog index and social previews…",rows:2}),e.jsx(Rlr,{content:i.content||"",onChange:F=>l(q=>({...q||{},content:F}))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{children:e.jsxs(Le,{className:"space-y-4 pt-6",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Cover image"}),i.cover_image_url?e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("img",{src:i.cover_image_url,alt:"cover",className:"h-36 w-full rounded-lg object-cover"}),e.jsx(z,{variant:"outline",size:"sm",className:"w-full",onClick:()=>l({...i,cover_image_url:null}),children:"Remove"})]}):e.jsxs(z,{variant:"outline",className:"mt-2 w-full",disabled:p,onClick:()=>{var F;return(F=g.current)==null?void 0:F.click()},children:[p?e.jsx(bt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(N0,{className:"mr-2 h-4 w-4"}),"Upload cover"]}),e.jsx("input",{ref:g,type:"file",accept:"image/*",className:"hidden",onChange:F=>{var q;C((q=F.target.files)==null?void 0:q[0]),F.target.value=""}})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"URL slug"}),e.jsx(pe,{className:"mt-1",value:i.slug||"",onChange:F=>l({...i,slug:F.target.value}),onBlur:F=>l({...i,slug:tue(F.target.value||i.title||"")}),placeholder:tue(i.title||"")||"my-article"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["/blog/",i.slug||tue(i.title||"")||"…"]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsx(pe,{className:"mt-1",value:i.category||"",onChange:F=>l({...i,category:F.target.value}),placeholder:"e.g. Lead Generation"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tags"}),e.jsx("div",{className:"mt-1 flex gap-2",children:e.jsx(pe,{value:h,onChange:F=>m(F.target.value),placeholder:"Add a tag and press Enter",onKeyDown:F=>{F.key==="Enter"&&h.trim()&&(F.preventDefault(),l({...i,tags:[...i.tags||[],h.trim()]}),m(""))}})}),(i.tags||[]).length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:(i.tags||[]).map((F,q)=>e.jsxs(ze,{variant:"secondary",className:"cursor-pointer",onClick:()=>l({...i,tags:(i.tags||[]).filter((G,V)=>V!==q)}),children:[F," ×"]},`${F}-${q}`))})]}),e.jsx(fc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"featured",children:"Featured article"}),e.jsx(mn,{id:"featured",checked:!!i.featured,onCheckedChange:F=>l({...i,featured:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"comments",children:"Allow comments"}),e.jsx(mn,{id:"comments",checked:i.allow_comments!==!1,onCheckedChange:F=>l({...i,allow_comments:F})})]})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"Author"}),e.jsx(pe,{value:i.author_name||"",placeholder:"Author name",onChange:F=>l({...i,author_name:F.target.value})}),e.jsx(pe,{value:i.author_title||"",placeholder:"Author title",onChange:F=>l({...i,author_title:F.target.value})}),e.jsx(pe,{value:i.author_avatar_url||"",placeholder:"Author photo URL (optional)",onChange:F=>l({...i,author_avatar_url:F.target.value})})]})}),e.jsx(be,{children:e.jsxs(Le,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"SEO"}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"SEO title"}),e.jsx(pe,{className:"mt-1",maxLength:60,value:i.seo_title||"",onChange:F=>l({...i,seo_title:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Meta description"}),e.jsx(Ps,{className:"mt-1",maxLength:160,rows:3,value:i.seo_description||"",onChange:F=>l({...i,seo_description:F.target.value})})]})]})})]})]})]}):e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Blog"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Founder articles published publicly at ",e.jsx("a",{className:"underline",href:"/blog",target:"_blank",rel:"noreferrer",children:"/blog"})]})]}),e.jsxs(z,{onClick:()=>l(Flr()),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," New article"]})]}),e.jsxs(Qr,{defaultValue:"articles",children:[e.jsxs(Jr,{children:[e.jsxs(Wt,{value:"articles",children:["Articles (",t.length,")"]}),e.jsxs(Wt,{value:"comments",children:["Comments (",v.length,")"]})]}),e.jsxs(Kt,{value:"articles",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Rr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",value:d,onChange:F=>u(F.target.value),placeholder:"Search articles…"})]}),r?e.jsxs("div",{className:"flex items-center gap-2 py-10 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):S.length===0?e.jsx(be,{children:e.jsx(Le,{className:"py-12 text-center text-sm text-muted-foreground",children:"No articles yet. Write your first one."})}):S.map(F=>e.jsx(be,{className:"transition hover:border-primary/30",children:e.jsxs(Le,{className:"flex flex-wrap items-center gap-4 py-4",children:[F.cover_image_url?e.jsx("img",{src:F.cover_image_url,alt:"",className:"h-14 w-20 rounded-md object-cover"}):e.jsx("div",{className:"h-14 w-20 rounded-md bg-muted"}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>l(F),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:F.title}),F.featured&&e.jsx(Ia,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ze,{variant:F.status==="published"?"default":"secondary",children:F.status}),F.category&&e.jsx("span",{children:F.category}),e.jsxs("span",{children:[F.view_count," views"]}),e.jsxs("span",{children:["/blog/",F.slug]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(z,{variant:"ghost",size:"sm",title:"Toggle publish",onClick:()=>M(F),children:F.status==="published"?e.jsx(Yf,{className:"h-4 w-4"}):e.jsx(xa,{className:"h-4 w-4"})}),F.status==="published"&&e.jsx(z,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx("a",{href:`/blog/${F.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(mr,{className:"h-4 w-4"})})}),e.jsx(z,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>P(F.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})},F.id))]}),e.jsx(Kt,{value:"comments",className:"mt-4 space-y-3",children:v.length===0?e.jsx(be,{children:e.jsx(Le,{className:"py-12 text-center text-sm text-muted-foreground",children:"No comments yet."})}):v.map(F=>{var q,G,V;return e.jsx(be,{children:e.jsxs(Le,{className:"flex flex-wrap items-start gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-semibold",children:[((q=F.author)==null?void 0:q.name)||((G=F.author)==null?void 0:G.email)||"Member",e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["on “",((V=F.post)==null?void 0:V.title)||"article","”"]})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm text-muted-foreground",children:F.body})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[F.is_hidden&&e.jsx(ze,{variant:"secondary",children:"hidden"}),e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>I(F),children:F.is_hidden?e.jsx(xa,{className:"h-4 w-4"}):e.jsx(Yf,{className:"h-4 w-4"})}),e.jsx(z,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>D(F.id),children:e.jsx(Cn,{className:"h-4 w-4"})})]})]})},F.id)})})]})]})}const zlr=["What was it like working together?","What moment stood out the most?","Would you recommend me to a friend?"],Y5="#16283a",zCt="#f7f5f1";function ris(s){var F,q,G,V,H;const t=s.accentColor||"#c9a24b",n=(F=s.videoPrompts)!=null&&F.length?s.videoPrompts:zlr,r=((q=s.agent)==null?void 0:q.name)||"Your agent",a=((V=(G=s.agent)==null?void 0:G.name)==null?void 0:V.split(" ")[0])||"them",[i,l]=_.useState("none"),[o,c]=_.useState(s.recipientName||""),[d,u]=_.useState(5),[h,m]=_.useState(0),[p,f]=_.useState(""),[g,v]=_.useState(!1),[y,b]=_.useState(!1),[w,S]=_.useState(null),C=_.useCallback(()=>{U.functions.invoke("review-public",{body:{action:"clicked",...s.payloadBase}}).catch(()=>{})},[s.payloadBase]),E=_.useCallback(()=>{C(),s.googleReviewLink&&window.open(s.googleReviewLink,"_blank","noopener")},[C,s.googleReviewLink]),P=s.protectionThreshold??3,M=!!s.protectionEnabled&&d<=P,I=!!s.googleReviewLink&&!(M&&s.hideGoogleBelowThreshold),D=_.useCallback(async(K,Z)=>{if(!o.trim()){S("Please add your name first.");return}v(!0),S(null);try{const oe={action:"submit",...s.payloadBase,reviewer_name:o,rating:d,review_text:p||void 0,is_private:!!Z};if(K){const J=K.type||"video/webm",{data:te,error:ce}=await U.functions.invoke("review-public",{body:{action:"video_upload_url",...s.payloadBase,video_type:J}});if(ce||!(te!=null&&te.path)||!(te!=null&&te.token))throw new Error((te==null?void 0:te.error)||(ce==null?void 0:ce.message)||"Could not start the video upload");const{error:ve}=await U.storage.from(te.bucket||"agent-uploads").uploadToSignedUrl(te.path,te.token,K,{contentType:J});if(ve)throw new Error(`Video upload failed: ${ve.message}`);oe.video_path=te.path,oe.video_type=J}const{data:re,error:ae}=await U.functions.invoke("review-public",{body:oe});if(ae||re!=null&&re.error)throw new Error((re==null?void 0:re.error)||(ae==null?void 0:ae.message)||"Something went wrong");b(!0)}catch(oe){S(oe.message)}finally{v(!1)}},[s.payloadBase,o,d,p]);return y?e.jsx("div",{className:"min-h-screen flex items-center justify-center p-5 sm:p-6",style:{background:zCt},children:e.jsxs("div",{className:"text-center max-w-md w-full",children:[e.jsx("div",{className:"w-16 h-16 sm:w-20 sm:h-20 rounded-full mx-auto mb-5 sm:mb-6 flex items-center justify-center",style:{background:`${t}1f`},children:e.jsx(Mr,{className:"h-9 w-9 sm:h-10 sm:w-10",style:{color:t}})}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-serif mb-3",style:{color:Y5},children:s.thankYouTitle||"Thank you!"}),e.jsx("p",{className:"text-slate-600 leading-relaxed",children:s.thankYouMessage||`Your words mean the world to ${a}. We truly appreciate you taking the time.`}),s.ctaUrl&&e.jsxs("a",{href:s.ctaUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 mt-8 px-7 py-3.5 rounded-full font-semibold transition-transform hover:scale-[1.03]",style:{background:t,color:Y5},children:[s.ctaLabel||"Visit my website"," ",e.jsx(Da,{className:"h-4 w-4"})]})]})}):e.jsxs("div",{className:"min-h-screen",style:{background:zCt},children:[e.jsxs("header",{className:"relative overflow-hidden",style:{background:Y5},children:[s.heroImageUrl&&e.jsx("img",{src:s.heroImageUrl,alt:"",className:"absolute inset-0 w-full h-full object-cover opacity-25"}),e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(circle at 50% 0%, ${t}33, transparent 62%)`}}),e.jsxs("div",{className:"relative max-w-2xl mx-auto px-4 sm:px-6 pt-12 sm:pt-14 pb-14 sm:pb-16 text-center",children:[((H=s.agent)==null?void 0:H.avatar_url)&&e.jsx("img",{src:s.agent.avatar_url,alt:r,className:"w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover mx-auto mb-5 shadow-2xl",style:{border:`3px solid ${t}`}}),e.jsx("p",{className:"uppercase tracking-[0.25em] sm:tracking-[0.3em] text-[10px] sm:text-[11px] mb-3",style:{color:t},children:"Client Experience"}),e.jsx("h1",{className:"text-3xl sm:text-4xl md:text-5xl font-serif text-white leading-tight break-words",children:s.headline||`Share your experience with ${r}`}),e.jsx("p",{className:"text-white/70 mt-4 leading-relaxed max-w-lg mx-auto text-sm sm:text-base",children:s.subheadline||"Thank you for your trust. It takes less than 60 seconds — and it helps other families find the right agent."})]}),e.jsx("div",{className:"h-px w-full",style:{background:`linear-gradient(90deg,transparent,${t},transparent)`}})]}),e.jsxs("main",{className:"relative z-10 max-w-2xl mx-auto px-4 -mt-9 pb-[max(4rem,env(safe-area-inset-bottom))]",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-xl border border-slate-200/70 px-4 sm:px-6 py-6 sm:py-7 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-4",children:"How was your experience?"}),e.jsx("div",{className:"flex justify-center gap-1 sm:gap-1.5",onMouseLeave:()=>m(0),children:[1,2,3,4,5].map(K=>e.jsx("button",{onClick:()=>u(K),onMouseEnter:()=>m(K),"aria-label":`${K} stars`,className:"p-0.5 transition-transform hover:scale-125 active:scale-95",children:e.jsx(Ia,{className:"h-9 w-9 sm:h-10 sm:w-10 transition-colors",style:{fill:K<=(h||d)?t:"transparent",color:K<=(h||d)?t:"#cbd5e1"}})},K))})]}),i==="none"&&M&&e.jsxs("div",{className:"grid gap-4 mt-6",children:[e.jsxs("div",{className:"bg-white rounded-3xl p-6 shadow-xl border border-slate-200/70 text-center",children:[e.jsx("h2",{className:"text-2xl font-serif",style:{color:Y5},children:s.privateFeedbackTitle||`How can ${a} make this right?`}),e.jsx("p",{className:"text-sm text-slate-600 mt-2 leading-relaxed",children:s.privateFeedbackMessage||`Your honest feedback goes straight to ${a} in private so it can be addressed personally.`})]}),e.jsx(WZ,{accent:t,icon:e.jsx(Mm,{className:"h-6 w-6 text-slate-600"}),title:`Share feedback privately with ${a}`,subtitle:"Only they will see it",badge:"Private",onClick:()=>l("private")}),I&&e.jsx(WZ,{accent:t,icon:e.jsx(Ia,{className:"h-6 w-6",style:{color:t}}),title:"Post a public Google review",subtitle:"You're always welcome to share your experience publicly",onClick:E})]}),i==="none"&&!M&&e.jsxs("div",{className:"grid gap-4 mt-6",children:[I&&e.jsx(WZ,{accent:t,icon:e.jsx(Ia,{className:"h-6 w-6",style:{color:t}}),title:"Leave a Google review",subtitle:`Takes 30 seconds — helps others find ${a}`,badge:"Most helpful",onClick:E}),e.jsx(WZ,{accent:t,icon:e.jsx(Xr,{className:"h-6 w-6",style:{color:t}}),title:"Record a quick video",subtitle:"60 seconds, right from your phone",onClick:()=>l("video")}),e.jsx(WZ,{accent:t,icon:e.jsx(Mm,{className:"h-6 w-6 text-slate-600"}),title:"Write a note",subtitle:"A few kind words go a long way",onClick:()=>l("write")})]}),i!=="none"&&e.jsxs("div",{className:"bg-white rounded-3xl p-6 sm:p-8 shadow-xl border border-slate-200/70 space-y-6 mt-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your name"}),e.jsx(pe,{value:o,onChange:K=>c(K.target.value),placeholder:"Jane Smith",className:"mt-1.5 h-11"})]}),i==="write"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your review"}),e.jsx(Ps,{value:p,onChange:K=>f(K.target.value),rows:6,placeholder:"Share a few words about your experience...",className:"mt-1.5"}),e.jsxs("div",{className:"rounded-2xl p-4 mt-4",style:{background:`${t}12`},children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2",style:{color:Y5},children:"Need a nudge?"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(K=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(wj,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),K]},K))})]})]}),i==="private"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"What could have been better?"}),e.jsx(Ps,{value:p,onChange:K=>f(K.target.value),rows:6,placeholder:"Tell them what happened...",className:"mt-1.5"}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:"This message is private. It will not appear on any public page or website."})]}),i==="video"&&e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-2xl p-4 mb-5",style:{background:`${t}12`},children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2",style:{color:Y5},children:"Not sure what to say? Try these"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(K=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(wj,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),K]},K))})]}),e.jsx(YE,{maxDurationSeconds:60,showBackgroundPicker:!1,onRecordingComplete:K=>D(K),onError:K=>S(K)})]}),w&&e.jsx("p",{className:"text-sm text-red-600",children:w}),e.jsxs("div",{className:"flex flex-col-reverse sm:flex-row gap-2 sm:gap-3 sm:items-center",children:[e.jsxs(z,{variant:"ghost",onClick:()=>l("none"),disabled:g,className:"text-slate-500",children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Back"]}),i==="write"&&e.jsxs(z,{onClick:()=>D(),disabled:g||!o.trim()||!p.trim(),className:"flex-1 h-12 rounded-full font-semibold hover:opacity-90",style:{background:Y5,color:"#fff"},children:[g?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Send my review"]}),i==="private"&&e.jsxs(z,{onClick:()=>D(void 0,!0),disabled:g||!o.trim()||!p.trim(),className:"flex-1 h-12 rounded-full font-semibold hover:opacity-90",style:{background:Y5,color:"#fff"},children:[g?e.jsx(bt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Send privately"]})]}),i==="video"&&g&&e.jsxs("p",{className:"text-sm text-slate-500 flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4 animate-spin"})," Uploading your video…"]})]}),e.jsx("p",{className:"text-center text-xs text-slate-400 mt-8",children:i==="private"?`Your feedback goes only to ${r}.`:`Your review is shared publicly with ${r}'s permission.`})]})]})}function WZ({accent:s,icon:t,title:n,subtitle:r,badge:a,onClick:i}){return e.jsx("button",{onClick:i,className:Ct("group bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200 text-left","transition-all hover:shadow-xl hover:-translate-y-0.5"),style:{borderColor:void 0},children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center shrink-0 transition-transform group-hover:scale-110",style:{background:`${s}1f`},children:t}),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-semibold",style:{color:Y5},children:n}),a&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full font-semibold",style:{background:`${s}26`,color:Y5},children:a})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:r})]}),e.jsx(Da,{className:"h-5 w-5 text-slate-300 group-hover:translate-x-1 transition-transform"})]})})}function Blr(){const{token:s}=Mi(),[t,n]=_.useState(null),[r,a]=_.useState(null),[i,l]=_.useState(!0);return _.useEffect(()=>{(async()=>{const{data:o}=await U.rpc("get_review_request_by_token",{_token:s});n(o),l(!1)})()},[s]),_.useEffect(()=>{var o;(o=t==null?void 0:t.agent)!=null&&o.name&&(async()=>{const{data:c}=await U.rpc("get_review_page_style_for_token",{_token:s});c&&a(c)})()},[t,s]),i?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):t?e.jsx(ris,{agent:t.agent,googleReviewLink:t.google_review_link,recipientName:t.recipient_name,headline:r==null?void 0:r.headline,subheadline:r==null?void 0:r.subheadline,accentColor:r==null?void 0:r.accent_color,heroImageUrl:r==null?void 0:r.hero_image_url,videoPrompts:r==null?void 0:r.video_prompts,thankYouTitle:r==null?void 0:r.thank_you_title,thankYouMessage:r==null?void 0:r.thank_you_message,ctaLabel:r==null?void 0:r.cta_label,ctaUrl:r==null?void 0:r.cta_url,protectionEnabled:r==null?void 0:r.protection_enabled,protectionThreshold:r==null?void 0:r.protection_threshold,hideGoogleBelowThreshold:r==null?void 0:r.hide_google_below_threshold,privateFeedbackTitle:r==null?void 0:r.private_feedback_title,privateFeedbackMessage:r==null?void 0:r.private_feedback_message,payloadBase:{token:s||""}}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600 text-center",children:"This review link is invalid or has expired."})})}function sue({rating:s,size:t="h-4 w-4"}){return e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx(Ia,{className:Ct(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function $lr(){var d,u;const{slug:s}=Mi(),[t,n]=_.useState(null),[r,a]=_.useState(!0);_.useEffect(()=>{(async()=>{const{data:h}=await U.rpc("get_public_reviews_page",{_slug:s});n(h),a(!1)})()},[s]);const i=_.useMemo(()=>{var h;return((h=t==null?void 0:t.agent)==null?void 0:h.name)??""},[t]);if(_.useEffect(()=>{var m;if(!t)return;document.title=`Reviews for ${i}`;const h=document.createElement("script");return h.type="application/ld+json",h.text=JSON.stringify({"@context":"https://schema.org","@type":"RealEstateAgent",name:i,image:(m=t.agent)==null?void 0:m.avatar_url,aggregateRating:t.stats.total_reviews>0?{"@type":"AggregateRating",ratingValue:t.stats.avg_rating,reviewCount:t.stats.total_reviews}:void 0}),document.head.appendChild(h),()=>{document.head.removeChild(h)}},[t,i]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-[#406E71]"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600",children:"This reviews page isn't available."})});const l=t.reviews.filter(h=>h.source==="video"&&h.video_url),o=t.reviews.filter(h=>h.source==="google"),c=t.reviews.filter(h=>h.source==="video"&&!h.video_url);return e.jsxs("div",{className:"min-h-screen bg-[#f7f5f1]",children:[e.jsxs("header",{className:"bg-[#2a4c64] text-white py-12 sm:py-16 px-4 sm:px-6 text-center",children:[((d=t.agent)==null?void 0:d.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:i,className:"w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover mx-auto mb-5 border-4 border-[#c9a24b]/60 shadow-xl"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-serif break-words",children:i}),((u=t.agent)==null?void 0:u.title)&&e.jsx("p",{className:"text-white/70 mt-1 text-sm sm:text-base",children:t.agent.title}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1 mt-5",children:[e.jsx(sue,{rating:Math.round(t.stats.avg_rating),size:"h-5 w-5 sm:h-6 sm:w-6"}),e.jsx("span",{className:"text-xl sm:text-2xl font-semibold",children:t.stats.avg_rating}),e.jsxs("span",{className:"text-white/60 text-sm sm:text-base",children:["· ",t.stats.total_reviews," review",t.stats.total_reviews!==1?"s":""]})]}),t.settings.intro_text&&e.jsx("p",{className:"max-w-xl mx-auto mt-5 text-white/80 leading-relaxed text-sm sm:text-base",children:t.settings.intro_text}),e.jsx("a",{href:`/reviews/${t.settings.slug}/new`,className:"inline-flex items-center justify-center gap-2 mt-7 sm:mt-8 w-full sm:w-auto max-w-xs px-7 py-3.5 rounded-full bg-[#c9a24b] text-[#16283a] font-semibold shadow-lg transition-transform hover:scale-[1.03]",children:"Leave a review"})]}),e.jsxs("main",{className:"max-w-4xl mx-auto px-4 py-10 sm:py-12 space-y-12 sm:space-y-14",children:[l.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6 flex items-center gap-2",children:[e.jsx(Xr,{className:"h-6 w-6 text-[#c9a24b]"})," Video testimonials"]}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:l.map(h=>e.jsxs("figure",{className:"bg-white rounded-2xl overflow-hidden shadow-sm border border-slate-200",children:[e.jsx("video",{src:h.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full aspect-video bg-black"}),e.jsxs("figcaption",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-[#2a4c64]",children:h.reviewer_name}),h.rating&&e.jsx(sue,{rating:h.rating})]}),h.review_text&&e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:h.review_text})]})]},h.id))})]}),o.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6",children:"Google reviews"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:o.map(h=>{var m,p;return e.jsxs("blockquote",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.rating&&e.jsx(sue,{rating:h.rating}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-[#406E71] bg-[#406E71]/10 px-2 py-1 rounded-full",children:[e.jsx(eA,{className:"h-3.5 w-3.5"})," Verified Google review"]})]}),h.review_text&&e.jsxs("p",{className:"text-slate-700 leading-relaxed flex-1",children:['"',h.review_text,'"']}),e.jsxs("footer",{className:"mt-4 text-sm font-medium text-[#2a4c64]",children:["— ",h.reviewer_name]}),h.reply_text&&e.jsxs("div",{className:"mt-4 pl-4 border-l-2 border-[#c9a24b]/50 bg-[#f7f5f1] rounded-r-lg p-3",children:[e.jsxs("p",{className:"text-xs font-semibold text-[#2a4c64] flex items-center gap-1 mb-1",children:[e.jsx(tJ,{className:"h-3.5 w-3.5"})," Response from ",(p=(m=t.agent)==null?void 0:m.name)==null?void 0:p.split(" ")[0]]}),e.jsx("p",{className:"text-sm text-slate-600",children:h.reply_text})]})]},h.id)})})]}),c.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6",children:"Kind words"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:c.map(h=>e.jsxs("blockquote",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200",children:[h.rating&&e.jsx(sue,{rating:h.rating}),h.review_text&&e.jsxs("p",{className:"text-slate-700 leading-relaxed mt-3",children:['"',h.review_text,'"']}),e.jsxs("footer",{className:"mt-4 text-sm font-medium text-[#2a4c64]",children:["— ",h.reviewer_name]})]},h.id))})]})]})]})}function Ulr(){const{slug:s}=Mi(),[t,n]=_.useState(null),[r,a]=_.useState(!0);return _.useEffect(()=>{(async()=>{const{data:i}=await U.rpc("get_public_review_intake",{_slug:s});n(i),a(!1)})()},[s]),_.useEffect(()=>{var i;(i=t==null?void 0:t.agent)!=null&&i.name&&(document.title=`Leave a review for ${t.agent.name}`)},[t]),r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(bt,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):t?e.jsx(ris,{agent:t.agent,googleReviewLink:t.google_review_link,headline:t.headline,subheadline:t.subheadline,accentColor:t.accent_color,heroImageUrl:t.hero_image_url,videoPrompts:t.video_prompts,thankYouTitle:t.thank_you_title,thankYouMessage:t.thank_you_message,ctaLabel:t.cta_label,ctaUrl:t.cta_url,protectionEnabled:t.protection_enabled,protectionThreshold:t.protection_threshold,hideGoogleBelowThreshold:t.hide_google_below_threshold,privateFeedbackTitle:t.private_feedback_title,privateFeedbackMessage:t.private_feedback_message,payloadBase:{slug:s||""}}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600 text-center",children:"This review page isn't accepting reviews right now."})})}const qlr=[{tag:"{{client_first_name}}",label:"Client's first name"},{tag:"{{agent_name}}",label:"Your name"},{tag:"{{property_address}}",label:"Property address"},{tag:"{{review_link}}",label:"Review link"}],r$e=[{key:"closing_day",name:"Closing Day Celebration",description:"Warm and celebratory — best sent the day of closing.",subject:"Congratulations on closing, {{client_first_name}}!",emailBody:`Congratulations on closing today, {{client_first_name}}! It was an absolute honor helping you through this, and I'm so happy for you. If you have 60 seconds, would you share a few words (or a quick video) about how the experience went? It helps other families find the right agent — and it would truly mean a lot to me.`,smsBody:"Congrats again on closing, {{client_first_name}}! It was an honor. If you have 60 seconds, would you leave me a quick review? {{review_link}} — {{agent_name}}"},{key:"short_casual",name:"Short & Casual",description:"Ten-second read. Highest response rate on mobile.",subject:"Quick favor, {{client_first_name}}?",emailBody:`Hey {{client_first_name}} — quick favor! Would you mind sharing a short note or 60-second video about how things went? It takes less than a minute and helps more than you know. Thank you!`,smsBody:"Hey {{client_first_name}}, it's {{agent_name}} — quick favor? A 60-second review would mean a lot: {{review_link}}"},{key:"luxury",name:"Luxury & High-Touch",description:"Refined and discreet — for high-end clientele.",subject:"Thank you for your trust, {{client_first_name}}",emailBody:`{{client_first_name}}, thank you for trusting me with your recent transaction. Discretion and white-glove service are the standards I hold myself to, and your feedback tells me whether I met them. If you're willing, I would be grateful for a brief review of your experience.`,smsBody:"{{client_first_name}}, thank you again for your trust. If you're willing, I'd be grateful for a brief review of your experience: {{review_link}} — {{agent_name}}"},{key:"past_client",name:"Past Client Reconnect",description:"For clients from 3–12 months ago.",subject:"Hope you are loving the house, {{client_first_name}}",emailBody:`Hi {{client_first_name}}, I hope you're settled in and loving {{property_address}}! I'm updating my client stories and would love to include yours. Would you share a couple of sentences — or a quick video — about what working together was like?`,smsBody:"Hi {{client_first_name}}, {{agent_name}} here — hope you're loving the house! I'm updating my client stories and would love to include yours: {{review_link}}"}];function a$e(s,t){return s.replace(/\{\{\s*client_first_name\s*\}\}/g,t.client_first_name||"there").replace(/\{\{\s*agent_name\s*\}\}/g,t.agent_name||"your agent").replace(/\{\{\s*property_address\s*\}\}/g,t.property_address||"your new home").replace(/\{\{\s*review_link\s*\}\}/g,t.review_link||"")}const Vlr=[{key:"onyx",label:"Onyx & Gold",base:"#0F172A",accent:"#D4AF37"},{key:"navy",label:"Classic Navy",base:"#2a4c64",accent:"#B8965A"},{key:"noir",label:"Modern Noir",base:"#111111",accent:"#F5F5F5"}],Hlr=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)}`},Glr=s=>{const t=s.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t,r=parseInt(n,16);return Number.isNaN(r)?{r:15,g:23,b:42}:{r:r>>16&255,g:r>>8&255,b:r&255}},zI=(s,t)=>{const{r:n,g:r,b:a}=Glr(s);return`rgba(${n},${r},${a},${t})`},Wlr=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}),Klr=(s,t,n,r,a,i)=>{const l=Math.max(a/t.naturalWidth,i/t.naturalHeight),o=a/l,c=i/l;s.drawImage(t,(t.naturalWidth-o)/2,(t.naturalHeight-c)/2,o,c,n,r,a,i)},d3e=(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()}…`},BCt=(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{const a=r*.45;s.beginPath();for(let i=0;i<10;i+=1){const l=i%2===0?r:a,o=Math.PI/5*i-Math.PI/2,c=t+Math.cos(o)*l,d=n+Math.sin(o)*l;i===0?s.moveTo(c,d):s.lineTo(c,d)}s.closePath(),s.fill()},Zlr=s=>{const t=new Date,n=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=l=>{var o;return((o=n.find(c=>c.type===l))==null?void 0:o.value)??"01"},a=new Date(`${r("year")}-${r("month")}-${r("day")}T00:00:00Z`);return a.setUTCDate(a.getUTCDate()+1),`${a.toISOString().slice(0,10)}T10:00`};function Xlr({review:s,open:t,onOpenChange:n}){var ae;const r=zn(),{data:a}=NLe(),{data:i=[]}=Qtt(),{timezone:l}=MW(),o=Lqt(),[c,d]=_.useState(!1),[u,h]=_.useState(null),[m,p]=_.useState(null),[f,g]=_.useState("brand"),[v,y]=_.useState(""),[b,w]=_.useState(!1),[S,C]=_.useState([]),E=_.useMemo(()=>({key:"brand",label:"My Brand Kit",base:(a==null?void 0:a.brandColor)||"#2a4c64",accent:(a==null?void 0:a.accentColor)||"#B8965A"}),[a==null?void 0:a.brandColor,a==null?void 0:a.accentColor]),P=_.useMemo(()=>[E,...Vlr],[E]),M=P.find(J=>J.key===f)||E,I=Hlr(a==null?void 0:a.phone),D=(s==null?void 0:s.rating)??5,F=((ae=s==null?void 0:s.reviewer_name)==null?void 0:ae.trim())||"A happy client",q=((s==null?void 0:s.review_text)||"").trim();_.useEffect(()=>{t||(p(null),w(!1),h(null))},[t]),_.useEffect(()=>{t&&C(i.map(J=>J.id))},[t,i.length]),_.useEffect(()=>{if(!t||!s||b)return;const J=I?`call or text ${I}`:"send me a message",te=q.length>220?`${q.slice(0,217).trim()}…`:q,ce=["⭐️⭐️⭐️⭐️⭐️ Client love!",te?`"${te}"`:"",`Thank you, ${F} — this is exactly why I do what I do.`,`Thinking about buying or selling? ${J} and let's talk.`,"#ClientReview #ClientAppreciation #RealEstate #Testimonial"].filter(Boolean);y(ce.join(` `))},[t,s==null?void 0:s.id,b,I]);const G=_.useCallback(async()=>{if(s){d(!0);try{const J=document.createElement("canvas");J.width=1080,J.height=1080;const te=J.getContext("2d");if(!te)throw new Error("Canvas unavailable");const ce=te.createLinearGradient(0,0,1080,1080);ce.addColorStop(0,M.base),ce.addColorStop(1,zI(M.base,.86)),te.fillStyle=ce,te.fillRect(0,0,1080,1080),te.save();const ve=te.createRadialGradient(880,180,40,880,180,520);ve.addColorStop(0,zI(M.accent,.22)),ve.addColorStop(1,zI(M.accent,0)),te.fillStyle=ve,te.fillRect(0,0,1080,1080),te.restore(),te.fillStyle=M.accent,te.fillRect(72,96,72,3),te.font="600 22px Arial, sans-serif",te.textBaseline="middle";let me=164;const he=s.source==="google"?"GOOGLE REVIEW":s.source==="video"?"CLIENT VIDEO REVIEW":"CLIENT REVIEW";for(const Ae of he)te.fillText(Ae,me,98),me+=te.measureText(Ae).width+8;te.fillStyle=M.accent;for(let Ae=0;Ae=ge.length-2||Ae===30))break}Pe.length===0&&(te.font="500 30px Georgia, serif",Pe=BCt(te,ge,900,10),Ne=30),te.fillStyle="#F8FAFC",te.font=`500 ${Ne}px Georgia, serif`;let Oe=400;Pe.forEach(Ae=>{te.fillText(Ae,90,Oe),Oe+=Ne*1.35}),te.fillStyle=M.accent,te.fillRect(90,Oe+30,56,3),te.fillStyle="rgba(248,250,252,0.92)",te.font="600 30px Arial, sans-serif",te.fillText(d3e(te,`— ${F}`,860),168,Oe+16);const ke=te.createLinearGradient(0,880,0,1080);ke.addColorStop(0,zI(M.base,.96)),ke.addColorStop(1,M.base),te.fillStyle=ke,te.fillRect(0,880,1080,200),te.fillStyle=M.accent,te.fillRect(0,880,1080,3);const Ve=(a==null?void 0:a.name)||"Agent";te.save(),te.beginPath(),te.arc(124,980,60,0,Math.PI*2),te.closePath(),te.fillStyle=zI(M.accent,.18),te.fill(),te.lineWidth=6,te.strokeStyle=M.accent,te.stroke(),te.clip();let _e=!1;if(a!=null&&a.headshotUrl)try{const Ae=await Wlr(a.headshotUrl);Klr(te,Ae,64,920,120,120),_e=!0}catch{_e=!1}_e||(te.fillStyle=M.accent,te.font="700 48px Arial, sans-serif",te.textAlign="center",te.textBaseline="middle",te.fillText(Ve.charAt(0).toUpperCase(),124,982)),te.restore(),te.textAlign="left",te.textBaseline="alphabetic",te.fillStyle="#F8FAFC",te.font="600 38px Georgia, serif",te.fillText(d3e(te,Ve,I?430:820),212,970),a!=null&&a.brokerageName&&(te.fillStyle=M.accent,te.font="600 20px Arial, sans-serif",te.fillText(d3e(te,a.brokerageName.toUpperCase(),I?430:820),212,1008)),I&&(te.textAlign="right",te.fillStyle=zI(M.accent,.9),te.font="600 16px Arial, sans-serif",te.fillText("CALL · TEXT",1016,958),te.fillStyle="#F8FAFC",te.font="600 38px Arial, sans-serif",te.fillText(I,1016,1008)),p(J.toDataURL("image/png"))}catch(J){console.error("Generate review graphic error",J),ne.error("Could not generate graphic")}finally{d(!1)}}},[s,M,a,I,q,D,F]);_.useEffect(()=>{if(!t||!s)return;const J=setTimeout(()=>{G()},250);return()=>clearTimeout(J)},[t,s==null?void 0:s.id,f,a==null?void 0:a.brandColor,a==null?void 0:a.name]);const V=async()=>{var ge;if(!m)throw new Error("No graphic yet");const{data:J}=await U.auth.getUser(),te=(ge=J.user)==null?void 0:ge.id;if(!te)throw new Error("Not signed in");const ce=await(await fetch(m)).blob(),ve=`review-social/${te}/${crypto.randomUUID()}.png`,{error:me}=await U.storage.from("agent-uploads").upload(ve,ce,{contentType:"image/png",upsert:!0});if(me)throw me;const{data:he}=U.storage.from("agent-uploads").getPublicUrl(ve);return{uid:te,publicUrl:he.publicUrl}},H=()=>{if(!m)return;const J=document.createElement("a");J.href=m,J.download=`review-${(s==null?void 0:s.id)||"graphic"}.png`,J.click(),ne.success("Downloaded!")},K=async()=>{try{await navigator.clipboard.writeText(v),ne.success("Caption copied")}catch{ne.error("Copy not supported in this browser")}},Z=async()=>{if(m){h("studio");try{const{publicUrl:J}=await V();sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:J,mediaType:"image",caption:v,source:"other",sourceRef:s==null?void 0:s.id})),n(!1),r("/social-studio"),ne.success("Draft ready in Social Studio")}catch(J){console.error("Push to Social Studio failed",J),ne.error("Could not send to Social Studio")}finally{h(null)}}},oe=async J=>{if(m){if(S.length===0){ne.error("Choose at least one account to post to.");return}h(J);try{const{uid:te,publicUrl:ce}=await V(),ve=J==="schedule"?REe(Zlr(l),l).toISOString():null,{data:me,error:he}=await U.from("social_posts").insert({user_id:te,caption:v.trim()||null,media_type:"image",media_urls:[ce],source:"other",status:J==="schedule"?"scheduled":"publishing",scheduled_for:ve,timezone:l}).select("id").single();if(he)throw he;const ge=i.filter(Ne=>S.includes(Ne.id)).map(Ne=>({post_id:me.id,user_id:te,social_account_id:Ne.id,platform:Ne.platform,caption_override:null,status:"pending"})),{error:Ee}=await U.from("social_post_targets").insert(ge);if(Ee)throw Ee;if(J==="now"){const{data:Ne,error:Pe}=await U.functions.invoke("social-publish-post",{body:{post_id:me.id}});if(Pe)throw Pe;const Oe=Ne==null?void 0:Ne.status;Oe==="failed"?ne.error("Publishing failed. Check the Queue tab in Social Studio."):Oe==="partial"?ne.warning("Some accounts failed. Check the Queue tab to retry."):ne.success("Posted to your accounts.")}else ne.success("Scheduled for tomorrow at 10:00 AM");o(),n(!1)}catch(te){console.error("Review post failed",te),ne.error(te instanceof Error?te.message:"Could not create the post")}finally{h(null)}}},re=J=>C(te=>te.includes(J)?te.filter(ce=>ce!==J):[...te,J]);return e.jsx(Is,{open:t,onOpenChange:n,children:e.jsx(Ls,{className:"!max-w-[900px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex max-h-[calc(100vh-2rem)] flex-col",children:[e.jsxs(Os,{className:"shrink-0 border-b px-5 pb-3 pt-5 text-left",children:[e.jsx(Rs,{className:"text-lg",children:"Share this review"}),e.jsx(_r,{children:"A branded 1080×1080 post in your colors — schedule it or send it straight to Social Studio."})]}),e.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Colors"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(J=>e.jsxs("button",{type:"button",onClick:()=>g(J.key),className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs transition ${f===J.key?"border-primary ring-2 ring-primary/25":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("span",{className:"flex",children:[e.jsx("span",{className:"h-3.5 w-3.5 rounded-l-full",style:{background:J.base}}),e.jsx("span",{className:"h-3.5 w-3.5 rounded-r-full",style:{background:J.accent}})]}),J.label]},J.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"relative mx-auto flex aspect-square w-full max-w-[360px] items-center justify-center overflow-hidden rounded-lg",style:{background:M.base},children:[m?e.jsx("img",{src:m,alt:"Review graphic preview",className:"h-full w-full object-cover"}):e.jsx("div",{className:"text-xs text-white/70",children:"Preparing preview…"}),c&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/60 text-white/90",children:[e.jsx(bt,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Designing your post…"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Post text"}),e.jsxs(z,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:K,children:[e.jsx(Sa,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Ps,{value:v,onChange:J=>{y(J.target.value),w(!0)},rows:11,className:"min-h-[220px] text-sm",placeholder:"Your caption…"}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Post to"}),i.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No social accounts connected yet — you can still download the graphic or open Social Studio."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map(J=>{const te=rC(J.platform),ce=S.includes(J.id);return e.jsxs("button",{type:"button",onClick:()=>re(J.id),className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs transition ${ce?"border-primary bg-primary/10":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs(ja,{className:"h-5 w-5",children:[e.jsx(xi,{src:J.profile_picture_url??void 0}),e.jsx(Na,{className:"text-[10px]",children:te.label.charAt(0)})]}),J.page_name||J.platform_username||te.label]},J.id)})})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-5 pb-5 pt-3",children:[e.jsx(z,{variant:"ghost",size:"sm",onClick:()=>n(!1),children:"Not now"}),e.jsxs(z,{variant:"outline",size:"sm",onClick:H,disabled:!m,className:"gap-1.5",children:[e.jsx(Ga,{className:"h-3.5 w-3.5"})," Download"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:Z,disabled:!m||u!==null,className:"gap-1.5",children:[u==="studio"?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Open in Social Studio"]}),e.jsxs(z,{variant:"outline",size:"sm",onClick:()=>void oe("schedule"),disabled:!m||u!==null||i.length===0,className:"gap-1.5",children:[u==="schedule"?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ud,{className:"h-3.5 w-3.5"}),"Schedule tomorrow 10 AM"]}),e.jsxs(z,{size:"sm",onClick:()=>void oe("now"),disabled:!m||u!==null||i.length===0,className:"gap-1.5",children:[u==="now"?e.jsx(bt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Fr,{className:"h-3.5 w-3.5"}),"Post now"]})]})]})})})}function $Ct({rating:s,size:t="h-4 w-4"}){return e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx(Ia,{className:Ct(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function UCt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function Qlr(){var Fs,cn,lr,Tn,Yn;const{user:s,rolesLoading:t}=hs(),[n,r]=_.useState([]),[a,i]=_.useState([]),[l,o]=_.useState(!0),[c,d]=_.useState({slug:"",intro_text:"",is_published:!1,show_google_reviews:!0,show_video_reviews:!0,headline:"",subheadline:"",accent_color:"#c9a24b",hero_image_url:"",video_prompts:"",thank_you_title:"",thank_you_message:"",cta_label:"",cta_url:"",allow_public_submissions:!0,protection_enabled:!1,protection_threshold:3,hide_google_below_threshold:!1,private_feedback_title:"",private_feedback_message:"",widget_enabled:!1,widget_layout:"carousel",widget_theme:"light",widget_accent:"",widget_title:""}),[u,h]=_.useState(!1),[m,p]=_.useState(!1),[f,g]=_.useState(""),[v,y]=_.useState("email"),[b,w]=_.useState(null),[S,C]=_.useState({}),[E,P]=_.useState(""),[M,I]=_.useState(""),[D,F]=_.useState(""),[q,G]=_.useState("closing_day"),[V,H]=_.useState(!1),[K,Z]=_.useState(null),[oe,re]=_.useState(null),[ae,J]=_.useState(""),[te,ce]=_.useState(!1),[ve,me]=_.useState(!1),[he,ge]=_.useState(!1),[Ee,Ne]=_.useState(null),Pe=Ee?Ee.connected:null,[Oe,ke]=Gl(),Ve=_.useRef(!1),_e=_.useCallback(async()=>{const{data:fs,error:wn}=await U.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(wn||fs!=null&&fs.error){Ne({connected:!1,email:null,apiAccessPending:!1,hasRefreshToken:!1,connectedAt:null,locations:[]});return}Ne(fs)},[]),Ae=_.useCallback(async()=>{if(!s)return;o(!0);const[{data:fs},{data:wn},{data:As}]=await Promise.all([U.from("review_responses").select("*").eq("user_id",s.id).order("is_pinned",{ascending:!1}).order("created_at",{ascending:!1}),U.from("review_requests").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(100),U.from("agent_review_page_settings").select("*").eq("user_id",s.id).maybeSingle()]);if(r(fs??[]),i(wn??[]),_e(),As){const Ss=Array.isArray(As.video_prompts)?As.video_prompts:[];d({id:As.id,slug:As.slug??"",intro_text:As.intro_text??"",is_published:As.is_published,show_google_reviews:As.show_google_reviews,show_video_reviews:As.show_video_reviews,headline:As.headline??"",subheadline:As.subheadline??"",accent_color:As.accent_color??"#c9a24b",hero_image_url:As.hero_image_url??"",video_prompts:Ss.join(` `),thank_you_title:As.thank_you_title??"",thank_you_message:As.thank_you_message??"",cta_label:As.cta_label??"",cta_url:As.cta_url??"",allow_public_submissions:As.allow_public_submissions??!0,protection_enabled:As.protection_enabled??!1,protection_threshold:As.protection_threshold??3,hide_google_below_threshold:As.hide_google_below_threshold??!1,private_feedback_title:As.private_feedback_title??"",private_feedback_message:As.private_feedback_message??"",widget_enabled:As.widget_enabled??!1,widget_layout:As.widget_layout??"carousel",widget_theme:As.widget_theme??"light",widget_accent:As.widget_accent??"",widget_title:As.widget_title??""})}else{const{data:Ss}=await U.from("profiles").select("name").eq("id",s.id).single(),pr=UCt((Ss==null?void 0:Ss.name)??"");d(hn=>({...hn,slug:hn.slug||pr}))}o(!1)},[s,_e]);_.useEffect(()=>{Ae()},[Ae]),_.useEffect(()=>{if(Ve.current)return;const fs=Oe.get("google"),wn=Oe.get("google_error");if(!fs&&!wn)return;if(Ve.current=!0,wn)ne.error(wn==="access_denied"?"Google connection was cancelled":wn==="invalid_state"?"That connection link expired — please try again":wn==="not_configured"?"Google Business credentials are not configured yet":wn==="missing_business_permission"?"Google didn't give us access to your Business Profile. Connect again and tick the Business Profile box on Google's screen.":`Google connection failed: ${wn}`,wn==="missing_business_permission"?{duration:1e4}:void 0);else{const Ss=Number(Oe.get("locations")??0);ne.success(Oe.get("google_pending")?"Google connected — review access is still pending Google approval":`Google Business Profile connected${Ss?` (${Ss} location${Ss>1?"s":""})`:""}`)}const As=new URLSearchParams(Oe);["google","google_error","google_pending","locations"].forEach(Ss=>As.delete(Ss)),ke(As,{replace:!0}),_e()},[Oe,ke,_e]);const Se=async()=>{ge(!0);const{data:fs,error:wn}=await U.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/apps/reviews"}});if(wn||fs!=null&&fs.error||!(fs!=null&&fs.authUrl))return ge(!1),ne.error((fs==null?void 0:fs.error)||(wn==null?void 0:wn.message)||"Could not start Google connection");window.location.href=fs.authUrl},We=async()=>{const{error:fs}=await U.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(fs)return ne.error("Could not disconnect");ne.success("Google Business Profile disconnected"),_e()},[qe,Be]=_.useState(!1),Ze=async()=>{Be(!0);const{data:fs,error:wn}=await U.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(Be(!1),wn||fs!=null&&fs.error)return ne.error((fs==null?void 0:fs.error)||(wn==null?void 0:wn.message)||"Could not check Google");(fs==null?void 0:fs.success)===!1||!(fs!=null&&fs.locationsCount)?ne.error((fs==null?void 0:fs.message)||"No business locations were found on this Google account.",{duration:1e4}):ne.success(fs.message),_e()},$e=_.useMemo(()=>{const fs=n.filter(Pn=>Pn.status!=="hidden"),wn=fs.filter(Pn=>Pn.rating),As=wn.length?wn.reduce((Pn,Gs)=>Pn+(Gs.rating??0),0)/wn.length:0,Ss=a.filter(Pn=>["sent","reminded","clicked"].includes(Pn.status)).length,pr=a.filter(Pn=>Pn.status==="completed").length,hn=a.length?Math.round(pr/a.length*100):0;return{avg:Math.round(As*10)/10,total:fs.length,pending:Ss,responseRate:hn,newCount:n.filter(Pn=>Pn.status==="new").length}},[n,a]),Xe=async(fs,wn)=>{const{error:As}=await U.from("review_responses").update({status:wn}).eq("id",fs);if(As)return ne.error(As.message);r(Ss=>Ss.map(pr=>pr.id===fs?{...pr,status:wn}:pr))},nt=async fs=>{const{error:wn}=await U.from("review_responses").update({is_pinned:!fs.is_pinned}).eq("id",fs.id);if(wn)return ne.error(wn.message);r(As=>As.map(Ss=>Ss.id===fs.id?{...Ss,is_pinned:!fs.is_pinned}:Ss))},Ge=async fs=>{const wn=!fs.in_widget,{error:As}=await U.from("review_responses").update({in_widget:wn}).eq("id",fs.id);if(As)return ne.error(As.message);r(Ss=>Ss.map(pr=>pr.id===fs.id?{...pr,in_widget:wn}:pr))},Je=async()=>{if(!s)return;if(!c.slug)return ne.error("Choose a slug for your page");h(!0);const fs={user_id:s.id,slug:UCt(c.slug),intro_text:c.intro_text||null,is_published:c.is_published,show_google_reviews:c.show_google_reviews,show_video_reviews:c.show_video_reviews,headline:c.headline||null,subheadline:c.subheadline||null,accent_color:c.accent_color||null,hero_image_url:c.hero_image_url||null,video_prompts:c.video_prompts.split(` `).map(As=>As.trim()).filter(Boolean),thank_you_title:c.thank_you_title||null,thank_you_message:c.thank_you_message||null,cta_label:c.cta_label||null,cta_url:c.cta_url||null,allow_public_submissions:c.allow_public_submissions,protection_enabled:c.protection_enabled,protection_threshold:c.protection_threshold,hide_google_below_threshold:c.hide_google_below_threshold,private_feedback_title:c.private_feedback_title||null,private_feedback_message:c.private_feedback_message||null,widget_enabled:c.widget_enabled,widget_layout:c.widget_layout,widget_theme:c.widget_theme,widget_accent:c.widget_accent||null,widget_title:c.widget_title||null},{error:wn}=c.id?await U.from("agent_review_page_settings").update(fs).eq("id",c.id):await U.from("agent_review_page_settings").insert(fs);if(h(!1),wn)return ne.error(wn.message.includes("unique")?"That slug is taken — try another":wn.message);ne.success(c.is_published?"Your reviews page is live":"Settings saved"),Ae()},ut=async()=>{const wn=f.split(` `).map(Pn=>Pn.trim()).filter(Boolean).map(Pn=>{const[Gs,an,tr]=Pn.split(",").map(Lr=>Lr.trim());return{name:Gs,email:an,phone:tr}}).filter(Pn=>Pn.email||Pn.phone);if(wn.length===0)return ne.error("Add at least one recipient (Name, email, phone — one per line)");if(v!=="email"&&!wn.some(Pn=>Pn.phone))return ne.error("Add a mobile number for each person you want to text");H(!0);const{data:As,error:Ss}=await U.functions.invoke("review-request-send",{body:{recipients:wn,channel:v,message:E||void 0,subject:M||void 0,sms_body:D||void 0}});if(H(!1),Ss||As!=null&&As.error)return ne.error((As==null?void 0:As.error)||(Ss==null?void 0:Ss.message)||"Send failed");const pr=(As.results??[]).filter(Pn=>Pn.ok&&Pn.emailed).length;if(v!=="email"){const Pn=As.prepared??[];if(Pn.length===0)return ne.error("No mobile numbers to text");pr>0&&ne.success(`${pr} email${pr!==1?"s":""} sent — now send your texts`),C({}),w(Pn),p(!1),g(""),Ae();return}const hn=(As.results??[]).filter(Pn=>Pn.ok).length;ne.success(`${hn} review request${hn!==1?"s":""} sent`),p(!1),g(""),Ae()},lt=fs=>{const wn=navigator.userAgent,Ss=/iPhone|iPad|iPod/.test(wn)||/Macintosh/.test(wn)&&navigator.maxTouchPoints>1?"&":"?";return`sms:${fs.phone}${Ss}body=${encodeURIComponent(fs.body)}`},qt=fs=>C(wn=>({...wn,[fs]:!0})),zt=async()=>{if(!(!K||!ae.trim())){if(ce(!0),K.source==="google"){const{data:fs,error:wn}=await U.functions.invoke("google-reviews-sync",{body:{action:"reply",review_id:K.id,text:ae.trim()}});if(wn||fs!=null&&fs.error)return ce(!1),ne.error((fs==null?void 0:fs.error)||(wn==null?void 0:wn.message)||"Reply failed")}else{const{error:fs}=await U.from("review_responses").update({reply_text:ae.trim(),replied_at:new Date().toISOString()}).eq("id",K.id);if(fs)return ce(!1),ne.error(fs.message)}ce(!1),ne.success("Reply posted"),Z(null),J(""),Ae()}},Zt=async()=>{me(!0);const{data:fs,error:wn}=await U.functions.invoke("google-reviews-sync",{body:{action:"sync_mine"}});if(me(!1),wn||fs!=null&&fs.error)return ne.error((fs==null?void 0:fs.error)||(wn==null?void 0:wn.message)||"Sync failed");if(fs!=null&&fs.needsReconnect)return ne.error("Your Google connection expired — click Connect Google to reconnect");ne.success(`Synced ${(fs==null?void 0:fs.synced)??0} reviews`),Ae()},ms=n.filter(fs=>fs.in_widget&&!fs.is_private&&(fs.status==="approved"||fs.status==="featured")),It=`